@orangecatai/adgen-canvas 0.0.9 → 0.0.10

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.
@@ -1,17 +1,17 @@
1
- import{$ as Qg,A as qg,B as AA,C as GE,D as UE,E as jd,F as Yl,G as qd,H as Jd,I as Vl,J as WE,K as YE,L as VE,M as Ba,N as Fa,O as $E,P as LA,Q as Ni,R as Oa,S as $l,U as KE,W as XE,X as ZE,Y as Qd,Z as jE,_ as Jg,a as FE,aa as em,b as Ri,ba as qE,c as Cn,ca as eh,d as OE,da as Bi,e as He,ea as JE,f as zE,fa as za,g as le,ga as QE,h as _a,ha as Bo,i as kn,ia as th,j as Hl,ja as ey,k as Gl,ka as tm,l as Da,la as oh,m as Ul,ma as ty,n as Ra,na as oy,o as HE,oa as ny,p as Zg,pa as Kl,q as Sn,r as Mn,s as Rr,t as po,u as sr,v as Na,w as Xd,x as jg,y as Wl,z as Zd}from"./chunk-UX5BMIBN.js";import{a as C}from"./chunk-WHNMS6DF.js";import{M as Xg}from"./chunk-MSBJ7C4T.js";import{c as BE}from"./chunk-3PELD44J.js";import{b as RE,c as NE,d as A}from"./chunk-SRAX5OIU.js";import xQ,{useEffect as gA}from"react";import{DEFAULT_UI_OPTIONS as hA,isShallowEqual as EQ}from"@orangecatai/common";import l6 from"clsx";import jZ from"lodash.throttle";import nr,{useContext as Li}from"react";import{flushSync as wo}from"react-dom";import qZ from"roughjs/bin/rough";import{nanoid as Ex}from"nanoid";import{clamp as c6,pointFrom as de,pointDistance as Ti,vector as d6,pointRotateRads as yx,vectorFromPoint as wx,vectorSubtract as m6,vectorDot as p6,vectorNormalize as u6}from"@orangecatai/math";import{COLOR_PALETTE as JZ,CODES as g6,shouldResizeFromCenter as h6,shouldMaintainAspectRatio as Cd,shouldRotateWithDiscreteAngle as f6,isArrowKey as wg,KEYS as oe,APP_NAME as QZ,CURSOR_TYPE as st,DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT as ej,DEFAULT_VERTICAL_ALIGN as b6,DRAGGING_THRESHOLD as x6,ELEMENT_SHIFT_TRANSLATE_AMOUNT as tj,ELEMENT_TRANSLATE_AMOUNT as E6,EVENT as ue,FRAME_STYLE as on,IMAGE_MIME_TYPES as oj,IMAGE_RENDER_TIMEOUT as nj,LINE_CONFIRM_THRESHOLD as vx,MAX_ALLOWED_FILE_BYTES as y6,MIME_TYPES as Jn,MQ_RIGHT_SIDEBAR_MIN_WIDTH as rj,POINTER_BUTTON as Ci,ROUNDNESS as vg,SCROLL_TIMEOUT as ij,TAP_TWICE_TIMEOUT as aj,TEXT_TO_CENTER_SNAP_THRESHOLD as sj,THEME as Ig,TOUCH_CTX_MENU_TIMEOUT as lj,VERTICAL_ALIGN as cj,YOUTUBE_STATES as Tg,ZOOM_STEP as dj,POINTER_EVENTS as Sl,TOOL_TYPE as Qn,supportsResizeObserver as mj,DEFAULT_COLLISION_THRESHOLD as w6,DEFAULT_TEXT_ALIGN as pj,ARROW_TYPE as ki,DEFAULT_REDUCED_GLOBAL_ALPHA as uj,isLocalLink as gj,normalizeLink as Ix,toValidURL as hj,getGridPoint as Zt,getLineHeight as v6,debounce as I6,distance as Ml,getFontString as Tx,getNearestScrollableContainer as fj,isInputLike as T6,isToolIcon as bj,isWritableElement as kd,sceneCoordsToViewportCoords as Cg,tupleToCoors as Cx,viewportCoordsToSceneCoords as ot,wrapEvent as xj,updateObject as kx,updateActiveTool as er,isTransparent as Ej,easeToValuesRAF as yj,muteFSAbortError as wj,isTestEnv as cP,isDevEnv as dP,easeOut as vj,updateStable as Sd,addEventListener as gt,normalizeEOL as Ij,getDateTime as C6,isShallowEqual as k6,arrayToMap as kg,applyDarkModeFilter as Tj,randomInteger as Cj,CLASSES as Sx,Emitter as Ta,MINIMUM_ARROW_SIZE as kj,DOUBLE_TAP_POSITION_THRESHOLD as Sj,BIND_MODE_TIMEOUT as Mj,invariant as tr,getFeatureFlag as Ar,createUserAgentDescriptor as mP,getFormFactor as Pj,deriveStylesPanelMode as Dg,isIOS as Aj,isBrave as Lj,isSafari as _j,loadDesktopUIModePreference as Dj,setDesktopUIMode as Rj,isSelectionLikeTool as Sg,oneOf as S6}from"@orangecatai/common";import{getObservedAppState as Nj,getCommonBounds as Pl,getElementAbsoluteCoords as Mg,bindOrUnbindBindingElements as M6,fixBindingsAfterDeletion as Bj,getHoveredElementForBinding as wn,isBindingEnabled as Md,shouldEnableBindingForPointerEvent as Fj,updateBoundElements as Pg,LinearElementEditor as Me,newElementWith as Si,newFrameElement as P6,newFreeDrawElement as Oj,newEmbeddableElement as A6,newMagicFrameElement as L6,newIframeElement as zj,newArrowElement as Hj,newElement as Gj,newImageElement as Mx,newLinearElement as Uj,newTextElement as _6,refreshTextDimensions as Wj,deepCopyElement as D6,duplicateElements as Px,hasBoundTextElement as R6,isArrowElement as Al,isBindingElement as or,isBindingElementType as Yj,isBoundToContainer as Ax,isFrameLikeElement as jt,isImageElement as Mi,isEmbeddableElement as Lr,isInitializedImageElement as Pd,isLinearElement as ao,isLinearElementType as Vj,isUsingAdaptiveRadius as $j,isIframeElement as Ll,isIframeLikeElement as Lx,isMagicFrameElement as _x,isTextBindableContainer as N6,isElbowArrow as vo,isFlowchartNodeElement as Kj,isBindableElement as Dx,isTextElement as vn,getNormalizedDimensions as Xj,isElementCompletelyInViewport as Rx,isElementInViewport as B6,isInvisiblySmallElement as F6,getCornerRadius as Zj,isPathALoop as O6,createSrcDoc as z6,embeddableURLValidator as Nx,maybeParseEmbedSrc as jj,getEmbedLink as Ag,getInitializedImageElements as qj,normalizeSVG as H6,updateImageCache as Jj,getBoundTextElement as Bx,getContainerCenter as Fx,getContainerElement as G6,isValidTextContainer as Qj,redrawTextBoundingBox as eq,hasBoundingBox as tq,getFrameChildren as Ox,isCursorInFrame as U6,addElementsToFrame as zx,replaceAllElementsInFrame as oq,removeElementsFromFrame as nq,getElementsInResizingFrame as Hx,getElementsInNewFrame as rq,getContainingFrame as Gx,elementOverlapsWithFrame as iq,updateFrameMembershipOfSelectedElements as W6,isElementInFrame as Y6,getFrameLikeTitle as aq,getElementsOverlappingFrame as sq,filterElementsEligibleAsFrameChildren as lq,hitElementBoundText as cq,hitElementBoundingBoxOnly as dq,hitElementItself as Ad,getVisibleSceneBounds as mq,FlowChartCreator as pq,FlowChartNavigator as uq,getLinkDirectionFromKey as V6,cropElement as gq,wrapText as hq,isElementLink as Ux,parseElementLinkFromURL as fq,isMeasureTextSupported as bq,normalizeText as xq,measureText as $6,getLineHeightInPx as Eq,getApproxMinLineWidth as yq,getApproxMinLineHeight as wq,getMinTextElementWidth as vq,ShapeCache as Ld,getRenderOpacity as Iq,editGroupForSelectedElement as Tq,getElementsInGroup as Ca,getSelectedGroupIdForElement as Cq,getSelectedGroupIds as kq,isElementInGroup as K6,isSelectedViaGroup as Sq,selectGroupsForSelectedElements as nn,syncInvalidIndices as pP,syncMovedIndices as X6,excludeElementsInFramesFromSelection as Mq,getSelectionStateForElements as Pq,makeNextSelectedElementIds as Oe,getResizeOffsetXY as Aq,getResizeArrowDirection as Lq,transformElements as _q,getCursorForResizingElement as Z6,getElementWithTransformHandleType as j6,getTransformHandleTypeFromCoords as q6,dragNewElement as J6,dragSelectedElements as Dq,getDragOffsetXY as Rq,isNonDeletedElement as Q6,Scene as eP,Store as Nq,CaptureUpdateAction as so,hitElementBoundingBox as Bq,isLineElement as Wx,isSimpleArrow as Yx,StoreDelta as tP,positionElementsOnGrid as oP,calculateFixedPointForNonElbowArrowBinding as nP,bindOrUnbindBindingElement as Fq,mutateElement as Lg,getElementBounds as rP,doBoundsIntersect as Oq,isPointInElement as zq,maxBindingDistance_simple as Vx,convertToExcalidrawElements as iP,getSnapOutlineMidPoint as $x,handleFocusPointDrag as Hq,handleFocusPointHover as Gq,handleFocusPointPointerDown as Uq,handleFocusPointPointerUp as Wq,maybeHandleArrowPointlikeDrag as _g,getUncroppedWidthAndHeight as Yq}from"@orangecatai/element";import{KEYS as Mh,MOBILE_ACTION_BUTTON_BG as YA,updateActiveTool as VA}from"@orangecatai/common";import{getNonDeletedElements as Ph}from"@orangecatai/element";import{fixBindingsAfterDeletion as $A}from"@orangecatai/element";import{LinearElementEditor as nv}from"@orangecatai/element";import{newElementWith as wm}from"@orangecatai/element";import{getContainerElement as rv}from"@orangecatai/element";import{isBoundToContainer as Em,isElbowArrow as KA,isFrameLikeElement as XA}from"@orangecatai/element";import{getFrameChildren as ZA}from"@orangecatai/element";import{getElementsInGroup as Ah,selectGroupsForSelectedElements as jA}from"@orangecatai/element";import{CaptureUpdateAction as ym}from"@orangecatai/element";import{isDevEnv as NA}from"@orangecatai/common";import{atom as Ce,createStore as _A}from"jotai";import{createIsolation as DA}from"jotai-scope";var ry=DA();var{useAtom:ae,useSetAtom:Pn,useAtomValue:Ha,useStore:CQ}=ry,iy=ry.Provider,Et=_A();var RA=RE({"./locales/ar-SA.json":()=>import("./locales/ar-SA-NXDWD63E.js"),"./locales/az-AZ.json":()=>import("./locales/az-AZ-MXSORGZV.js"),"./locales/bg-BG.json":()=>import("./locales/bg-BG-O6MV2KSF.js"),"./locales/bn-BD.json":()=>import("./locales/bn-BD-T2VJNT7N.js"),"./locales/bn-IN.json":()=>import("./locales/bn-IN-MMW2ORAC.js"),"./locales/ca-ES.json":()=>import("./locales/ca-ES-MKBCGNOG.js"),"./locales/cs-CZ.json":()=>import("./locales/cs-CZ-V77HGUP7.js"),"./locales/da-DK.json":()=>import("./locales/da-DK-I5RFNTM4.js"),"./locales/de-CH.json":()=>import("./locales/de-CH-WLRDEVBV.js"),"./locales/de-DE.json":()=>import("./locales/de-DE-DTI4WUSC.js"),"./locales/el-GR.json":()=>import("./locales/el-GR-ZXDJ2OS4.js"),"./locales/en.json":()=>import("./locales/en-RQF5X6GM.js"),"./locales/es-ES.json":()=>import("./locales/es-ES-DYQHAD43.js"),"./locales/eu-ES.json":()=>import("./locales/eu-ES-QDSYU5Y3.js"),"./locales/fa-IR.json":()=>import("./locales/fa-IR-26LZG4PM.js"),"./locales/fi-FI.json":()=>import("./locales/fi-FI-6YS4KDE4.js"),"./locales/fr-FR.json":()=>import("./locales/fr-FR-BRLLPTZC.js"),"./locales/gl-ES.json":()=>import("./locales/gl-ES-OKUZTLYG.js"),"./locales/he-IL.json":()=>import("./locales/he-IL-26MGYIU7.js"),"./locales/hi-IN.json":()=>import("./locales/hi-IN-Q4ZOGTP2.js"),"./locales/hu-HU.json":()=>import("./locales/hu-HU-P2OXPSN5.js"),"./locales/id-ID.json":()=>import("./locales/id-ID-2EIKXYN6.js"),"./locales/it-IT.json":()=>import("./locales/it-IT-4CFKVXI2.js"),"./locales/ja-JP.json":()=>import("./locales/ja-JP-MAND2Z4V.js"),"./locales/kaa.json":()=>import("./locales/kaa-HQRTCXTJ.js"),"./locales/kab-KAB.json":()=>import("./locales/kab-KAB-JKIKKTGH.js"),"./locales/kk-KZ.json":()=>import("./locales/kk-KZ-HXQ63ZFC.js"),"./locales/km-KH.json":()=>import("./locales/km-KH-PKL3LSGX.js"),"./locales/ko-KR.json":()=>import("./locales/ko-KR-KXLREZX3.js"),"./locales/ku-TR.json":()=>import("./locales/ku-TR-MJ4IER3X.js"),"./locales/lt-LT.json":()=>import("./locales/lt-LT-H6WFQ6FJ.js"),"./locales/lv-LV.json":()=>import("./locales/lv-LV-GOCK6SJW.js"),"./locales/mr-IN.json":()=>import("./locales/mr-IN-IXVLDMEQ.js"),"./locales/my-MM.json":()=>import("./locales/my-MM-YG6MYTTD.js"),"./locales/nb-NO.json":()=>import("./locales/nb-NO-XGWJISD2.js"),"./locales/nl-NL.json":()=>import("./locales/nl-NL-XVDVCPNC.js"),"./locales/nn-NO.json":()=>import("./locales/nn-NO-EMX5MJX5.js"),"./locales/oc-FR.json":()=>import("./locales/oc-FR-ROEINTVO.js"),"./locales/pa-IN.json":()=>import("./locales/pa-IN-ZYN6SUDY.js"),"./locales/percentages.json":()=>import("./locales/percentages-5DKR754L.js"),"./locales/pl-PL.json":()=>import("./locales/pl-PL-6VTG7PHC.js"),"./locales/pt-BR.json":()=>import("./locales/pt-BR-5YFKRR5G.js"),"./locales/pt-PT.json":()=>import("./locales/pt-PT-GEIXXZ67.js"),"./locales/ro-RO.json":()=>import("./locales/ro-RO-E2P6TFZI.js"),"./locales/ru-RU.json":()=>import("./locales/ru-RU-YBIIY43T.js"),"./locales/si-LK.json":()=>import("./locales/si-LK-673C2CI2.js"),"./locales/sk-SK.json":()=>import("./locales/sk-SK-CKZHQ4AP.js"),"./locales/sl-SI.json":()=>import("./locales/sl-SI-557H2GWM.js"),"./locales/sv-SE.json":()=>import("./locales/sv-SE-XOPKKDWS.js"),"./locales/ta-IN.json":()=>import("./locales/ta-IN-XBH7DQI3.js"),"./locales/th-TH.json":()=>import("./locales/th-TH-TOCWH3R4.js"),"./locales/tr-TR.json":()=>import("./locales/tr-TR-GXW6CYY5.js"),"./locales/uk-UA.json":()=>import("./locales/uk-UA-IJKTNUDG.js"),"./locales/uz-UZ.json":()=>import("./locales/uz-UZ-TBZZEA4V.js"),"./locales/vi-VN.json":()=>import("./locales/vi-VN-MULSGNVB.js"),"./locales/zh-CN.json":()=>import("./locales/zh-CN-MVX3E32U.js"),"./locales/zh-HK.json":()=>import("./locales/zh-HK-JNU5RLIE.js"),"./locales/zh-TW.json":()=>import("./locales/zh-TW-LENVCA6T.js")});var BA=85,An={code:"en",label:"English"},Ua=[An,...[{code:"ar-SA",label:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",rtl:!0},{code:"bg-BG",label:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438"},{code:"ca-ES",label:"Catal\xE0"},{code:"cs-CZ",label:"\u010Cesky"},{code:"de-DE",label:"Deutsch"},{code:"el-GR",label:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC"},{code:"es-ES",label:"Espa\xF1ol"},{code:"eu-ES",label:"Euskara"},{code:"fa-IR",label:"\u0641\u0627\u0631\u0633\u06CC",rtl:!0},{code:"fi-FI",label:"Suomi"},{code:"fr-FR",label:"Fran\xE7ais"},{code:"gl-ES",label:"Galego"},{code:"he-IL",label:"\u05E2\u05D1\u05E8\u05D9\u05EA",rtl:!0},{code:"hi-IN",label:"\u0939\u093F\u0928\u094D\u0926\u0940"},{code:"hu-HU",label:"Magyar"},{code:"id-ID",label:"Bahasa Indonesia"},{code:"it-IT",label:"Italiano"},{code:"ja-JP",label:"\u65E5\u672C\u8A9E"},{code:"kab-KAB",label:"Taqbaylit"},{code:"kk-KZ",label:"\u049A\u0430\u0437\u0430\u049B \u0442\u0456\u043B\u0456"},{code:"ko-KR",label:"\uD55C\uAD6D\uC5B4"},{code:"ku-TR",label:"Kurd\xEE"},{code:"lt-LT",label:"Lietuvi\u0173"},{code:"lv-LV",label:"Latvie\u0161u"},{code:"my-MM",label:"Burmese"},{code:"nb-NO",label:"Norsk bokm\xE5l"},{code:"nl-NL",label:"Nederlands"},{code:"nn-NO",label:"Norsk nynorsk"},{code:"oc-FR",label:"Occitan"},{code:"pa-IN",label:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40"},{code:"pl-PL",label:"Polski"},{code:"pt-BR",label:"Portugu\xEAs Brasileiro"},{code:"pt-PT",label:"Portugu\xEAs"},{code:"ro-RO",label:"Rom\xE2n\u0103"},{code:"ru-RU",label:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"sk-SK",label:"Sloven\u010Dina"},{code:"sv-SE",label:"Svenska"},{code:"sl-SI",label:"Sloven\u0161\u010Dina"},{code:"tr-TR",label:"T\xFCrk\xE7e"},{code:"uk-UA",label:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430"},{code:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{code:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{code:"vi-VN",label:"Ti\u1EBFng Vi\u1EC7t"},{code:"mr-IN",label:"\u092E\u0930\u093E\u0920\u0940"}].filter(e=>BE[e.code]>=BA).sort((e,t)=>e.label>t.label?1:-1)],nm="__test__";NA()&&Ua.unshift({code:nm,label:"test language"},{code:`${nm}.rtl`,label:"\u202Atest language (rtl)\u202C",rtl:!0});var Ga=An,om={},rm=async e=>{if(Ga=e,document.documentElement.dir=Ga.rtl?"rtl":"ltr",document.documentElement.lang=Ga.code,e.code.startsWith(nm))om={};else try{om=await RA(`./locales/${Ga.code}.json`)}catch(t){console.error(`Failed to load language ${e.code}:`,t.message),om=Xg}Et.set(sy,e.code)},lr=()=>Ga,ay=(e,t)=>{for(let o=0;o<t.length;++o){let n=t[o];if(e[n]===void 0)return;e=e[n]}if(typeof e=="string")return e},f=(e,t,o)=>{if(Ga.code.startsWith(nm))return`\u202A[[${t?`${e}(${JSON.stringify(t).slice(1,-1)})`:e}]]\u202C`;let n=e.split("."),r=ay(om,n)||ay(Xg,n)||o;if(r===void 0){let i=`Can't find translation for ${e}`;if(C.PROD)return console.warn(i),"";throw new Error(i)}if(t)for(let i in t)r=r.replace(`{{${i}}}`,String(t[i]));return r},sy=Ce(An.code),Ge=()=>{let e=Ha(sy);return{t:f,langCode:e}};import FA from"clsx";import Lt from"react";import{THEME as OA}from"@orangecatai/common";import{Fragment as Ue,jsx as b,jsxs as H}from"react/jsx-runtime";var cn=e=>"var(--icon-fill-color)",ly=e=>e===OA.LIGHT?"#fff":"#1e1e1e",R=(e,t=512)=>{let{width:o=512,height:n=o,mirror:r,style:i,...a}=typeof t=="number"?{width:t}:t;return b("svg",{"aria-hidden":"true",focusable:"false",role:"img",viewBox:`0 0 ${o} ${n}`,className:FA({"rtl-mirror":r}),style:i,...a,children:typeof e=="string"?b("path",{fill:"currentColor",d:e}):e})},K={width:24,height:24,fill:"none",strokeWidth:2,stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"},fe={width:20,height:20,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"},HQ=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("rect",{x:3,y:8,width:18,height:4,rx:1}),b("line",{x1:12,y1:8,x2:12,y2:21}),b("path",{d:"M19 12v7a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-7"}),b("path",{d:"M7.5 8a2.5 2.5 0 0 1 0 -5a4.8 8 0 0 1 4.5 5a4.8 8 0 0 1 4.5 -5a2.5 2.5 0 0 1 0 5"})]}),K),im=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0"}),b("path",{d:"M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0"}),b("line",{x1:"3",y1:"6",x2:"3",y2:"19"}),b("line",{x1:"12",y1:"6",x2:"12",y2:"19"}),b("line",{x1:"21",y1:"6",x2:"21",y2:"19"})]}),K),cy=R(H("svg",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),b("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),K),dy=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"12",cy:"12",r:"1"}),b("circle",{cx:"12",cy:"19",r:"1"}),b("circle",{cx:"12",cy:"5",r:"1"})]}),K),my=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),b("path",{d:"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),b("path",{d:"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"})]}),K),py=R(H("svg",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M9 4v6l-2 4v2h10v-2l-2 -4v-6"}),b("line",{x1:"12",y1:"16",x2:"12",y2:"21"}),b("line",{x1:"8",y1:"4",x2:"16",y2:"4"})]}),K),nh=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 5m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M19 8m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M5 11m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M15 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M6.5 9.5l3.5 -3"}),b("path",{d:"M14 5.5l3 1.5"}),b("path",{d:"M18.5 10l-2.5 7"}),b("path",{d:"M13.5 17.5l-7 -5"})]}),K),Fi=R(H("g",{children:[b("path",{d:"M13.542 8.542H6.458a2.5 2.5 0 0 0-2.5 2.5v3.75a2.5 2.5 0 0 0 2.5 2.5h7.084a2.5 2.5 0 0 0 2.5-2.5v-3.75a2.5 2.5 0 0 0-2.5-2.5Z",stroke:"currentColor",strokeWidth:"1.25"}),b("path",{d:"M10 13.958a1.042 1.042 0 1 0 0-2.083 1.042 1.042 0 0 0 0 2.083Z",stroke:"currentColor",strokeWidth:"1.25"}),b("mask",{id:"UnlockedIcon",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:6,y:1,width:9,height:9,children:b("path",{stroke:"none",d:"M6.399 9.561V5.175c0-.93.401-1.823 1.116-2.48a3.981 3.981 0 0 1 2.693-1.028c1.01 0 1.98.37 2.694 1.027.715.658 1.116 1.55 1.116 2.481",fill:"#fff"})}),b("g",{mask:"url(#UnlockedIcon)",children:b("path",{stroke:"none",d:"M5.149 9.561v1.25h2.5v-1.25h-2.5Zm5.06-7.894V.417v1.25Zm2.559 3.508v1.25h2.5v-1.25h-2.5ZM7.648 8.51V5.175h-2.5V8.51h2.5Zm0-3.334c0-.564.243-1.128.713-1.561L6.668 1.775c-.959.883-1.52 2.104-1.52 3.4h2.5Zm.713-1.561a2.732 2.732 0 0 1 1.847-.697v-2.5c-1.31 0-2.585.478-3.54 1.358L8.36 3.614Zm1.847-.697c.71 0 1.374.26 1.847.697l1.694-1.839a5.231 5.231 0 0 0-3.54-1.358v2.5Zm1.847.697c.47.433.713.997.713 1.561h2.5c0-1.296-.56-2.517-1.52-3.4l-1.693 1.839Z",fill:"currentColor"})})]}),fe),Wa=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M13.542 8.542H6.458a2.5 2.5 0 0 0-2.5 2.5v3.75a2.5 2.5 0 0 0 2.5 2.5h7.084a2.5 2.5 0 0 0 2.5-2.5v-3.75a2.5 2.5 0 0 0-2.5-2.5Z"}),b("path",{d:"M10 13.958a1.042 1.042 0 1 0 0-2.083 1.042 1.042 0 0 0 0 2.083Z"}),b("path",{d:"M6.667 8.333V5.417C6.667 3.806 8.159 2.5 10 2.5c1.841 0 3.333 1.306 3.333 2.917v2.916"})]}),fe),uy=R(b("g",{fill:"currentColor",children:b("path",{d:"M12 2a5 5 0 0 1 5 5v3a3 3 0 0 1 3 3v6a3 3 0 0 1 -3 3h-10a3 3 0 0 1 -3 -3v-6a3 3 0 0 1 3 -3v-3a5 5 0 0 1 5 -5m0 12a2 2 0 0 0 -1.995 1.85l-.005 .15a2 2 0 1 0 2 -2m0 -10a3 3 0 0 0 -3 3v3h6v-3a3 3 0 0 0 -3 -3"})}),{width:24,height:24}),gy=R(H(Ue,{children:[b("path",{d:"M38.5 83.5c-14-2-17.833-10.473-21-22.5C14.333 48.984 12 22 12 12.5",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"}),b("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m12.005 10.478 7.905 14.423L6 25.75l6.005-15.273Z",fill:"currentColor"}),b("path",{d:"M12.005 10.478c1.92 3.495 3.838 7 7.905 14.423m-7.905-14.423c3.11 5.683 6.23 11.368 7.905 14.423m0 0c-3.68.226-7.35.455-13.91.85m13.91-.85c-5.279.33-10.566.647-13.91.85m0 0c1.936-4.931 3.882-9.86 6.005-15.273M6 25.75c2.069-5.257 4.135-10.505 6.005-15.272",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"})]}),{width:41,height:94,fill:"none"}),hy=R(H(Ue,{children:[b("path",{d:"M18.026 1.232c-5.268 13.125-5.548 33.555 3.285 42.311 8.823 8.75 33.31 12.304 42.422 13.523",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"}),b("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m72.181 59.247-13.058-10-2.948 13.62 16.006-3.62Z",fill:"currentColor"}),b("path",{d:"M72.181 59.247c-3.163-2.429-6.337-4.856-13.058-10m13.058 10c-5.145-3.936-10.292-7.882-13.058-10m0 0c-.78 3.603-1.563 7.196-2.948 13.62m2.948-13.62c-1.126 5.168-2.24 10.346-2.948 13.62m0 0c5.168-1.166 10.334-2.343 16.006-3.62m-16.006 3.62c5.51-1.248 11.01-2.495 16.006-3.62",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"})]}),{width:85,height:71,fill:"none"}),fy=R(H(Ue,{children:[b("path",{d:"M1 77c14-2 31.833-11.973 35-24 3.167-12.016-6-35-9.5-43.5",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"}),b("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m24.165 1.093-2.132 16.309 13.27-4.258-11.138-12.05Z",fill:"currentColor"}),b("path",{d:"M24.165 1.093c-.522 3.953-1.037 7.916-2.132 16.309m2.131-16.309c-.835 6.424-1.68 12.854-2.13 16.308m0 0c3.51-1.125 7.013-2.243 13.27-4.257m-13.27 4.257c5.038-1.608 10.08-3.232 13.27-4.257m0 0c-3.595-3.892-7.197-7.777-11.14-12.05m11.14 12.05c-3.837-4.148-7.667-8.287-11.14-12.05",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"})]}),{width:38,height:78,fill:"none"}),GQ=R(b("g",{fill:"currentColor",children:b("path",{d:"M39.9 32.889a.326.326 0 0 0-.279-.056c-2.094-3.083-4.774-6-7.343-8.833l-.419-.472a.212.212 0 0 0-.056-.139.586.586 0 0 0-.167-.111l-.084-.083-.056-.056c-.084-.167-.28-.278-.475-.167-.782.39-1.507.973-2.206 1.528-.92.722-1.842 1.445-2.708 2.25a8.405 8.405 0 0 0-.977 1.028c-.14.194-.028.361.14.444-.615.611-1.23 1.223-1.843 1.861a.315.315 0 0 0-.084.223c0 .083.056.166.111.194l1.09.833v.028c1.535 1.528 4.244 3.611 7.12 5.861.418.334.865.667 1.284 1 .195.223.39.473.558.695.084.11.28.139.391.055.056.056.14.111.196.167a.398.398 0 0 0 .167.056.255.255 0 0 0 .224-.111.394.394 0 0 0 .055-.167c.029 0 .028.028.056.028a.318.318 0 0 0 .224-.084l5.082-5.528a.309.309 0 0 0 0-.444Zm-14.63-1.917a.485.485 0 0 0 .111.14c.586.5 1.2 1 1.843 1.555l-2.569-1.945-.251-.166c-.056-.028-.112-.084-.168-.111l-.195-.167.056-.056.055-.055.112-.111c.866-.861 2.346-2.306 3.1-3.028-.81.805-2.43 3.167-2.095 3.944Zm8.767 6.89-2.122-1.612a44.713 44.713 0 0 0-2.625-2.5c1.145.861 2.122 1.611 2.262 1.75 1.117.972 1.06.806 1.815 1.445l.921.666a1.06 1.06 0 0 1-.251.25Zm.558.416-.056-.028c.084-.055.168-.111.252-.194l-.196.222ZM1.089 5.75c.055.361.14.722.195 1.056.335 1.833.67 3.5 1.284 4.75l.252.944c.084.361.223.806.363.917 1.424 1.25 3.602 3.11 5.947 4.889a.295.295 0 0 0 .363 0s0 .027.028.027a.254.254 0 0 0 .196.084.318.318 0 0 0 .223-.084c2.988-3.305 5.221-6.027 6.813-8.305.112-.111.14-.278.14-.417.111-.111.195-.25.307-.333.111-.111.111-.306 0-.39l-.028-.027c0-.055-.028-.139-.084-.167-.698-.666-1.2-1.138-1.731-1.638-.922-.862-1.871-1.75-3.881-3.75l-.028-.028c-.028-.028-.056-.056-.112-.056-.558-.194-1.703-.389-3.127-.639C6.087 2.223 3.21 1.723.614.944c0 0-.168 0-.196.028l-.083.084c-.028.027-.056.055-.224.11h.056-.056c.028.167.028.278.084.473 0 .055.112.5.112.555l.782 3.556Zm15.496 3.278-.335-.334c.084.112.196.195.335.334Zm-3.546 4.666-.056.056c0-.028.028-.056.056-.056Zm-2.038-10c.168.167.866.834 1.033.973-.726-.334-2.54-1.167-3.379-1.445.838.167 1.983.334 2.346.472ZM1.424 2.306c.419.722.754 3.222 1.089 5.666-.196-.778-.335-1.555-.503-2.278-.251-1.277-.503-2.416-.838-3.416.056 0 .14 0 .252.028Zm-.168-.584c-.112 0-.223-.028-.307-.028 0-.027 0-.055-.028-.055.14 0 .223.028.335.083Zm-1.089.222c0-.027 0-.027 0 0ZM39.453 1.333c.028-.11-.558-.61-.363-.639.42-.027.42-.666 0-.666-.558.028-1.144.166-1.675.25-.977.194-1.982.389-2.96.61-2.205.473-4.383.973-6.561 1.557-.67.194-1.424.333-2.066.666-.224.111-.196.333-.084.472-.056.028-.084.028-.14.056-.195.028-.363.056-.558.083-.168.028-.252.167-.224.334 0 .027.028.083.028.11-1.173 1.556-2.485 3.195-3.909 4.945-1.396 1.611-2.876 3.306-4.356 5.056-4.719 5.5-10.052 11.75-15.943 17.25a.268.268 0 0 0 0 .389c.028.027.056.055.084.055-.084.084-.168.14-.252.222-.056.056-.084.111-.084.167a.605.605 0 0 0-.111.139c-.112.111-.112.305.028.389.111.11.307.11.39-.028.029-.028.029-.056.056-.056a.44.44 0 0 1 .615 0c.335.362.67.723.977 1.028l-.698-.583c-.112-.111-.307-.083-.39.028-.113.11-.085.305.027.389l7.427 6.194c.056.056.112.056.196.056s.14-.028.195-.084l.168-.166c.028.027.083.027.111.027.084 0 .14-.027.196-.083 10.052-10.055 18.15-17.639 27.42-24.417.083-.055.111-.166.111-.25.112 0 .196-.083.251-.194 1.704-5.194 2.039-9.806 2.15-12.083v-.028c0-.028.028-.056.028-.083.028-.056.028-.084.028-.084a1.626 1.626 0 0 0-.111-1.028ZM21.472 9.5c.446-.5.893-1.028 1.34-1.5-2.876 3.778-7.65 9.583-14.408 16.5 4.607-5.083 9.242-10.333 13.068-15ZM5.193 35.778h.084-.084Zm3.462 3.194c-.027-.028-.027-.028 0-.028v.028Zm4.16-3.583c.224-.25.448-.472.699-.722 0 0 0 .027.028.027-.252.223-.475.445-.726.695Zm1.146-1.111c.14-.14.279-.334.446-.5l.028-.028c1.648-1.694 3.351-3.389 5.082-5.111l.028-.028c.419-.333.921-.694 1.368-1.028a379.003 379.003 0 0 0-6.952 6.695ZM24.794 6.472c-.921 1.195-1.954 2.778-2.82 4.028-2.736 3.944-11.532 13.583-11.727 13.75a1976.983 1976.983 0 0 1-8.042 7.639l-.167.167c-.14-.167-.14-.417.028-.556C14.49 19.861 22.03 10.167 25.074 5.917c-.084.194-.14.36-.28.555Zm4.83 5.695c-1.116-.64-1.646-1.64-1.34-2.611l.084-.334c.028-.083.084-.194.14-.277.307-.5.754-.917 1.257-1.167.027 0 .055 0 .083-.028-.028-.056-.028-.139-.028-.222.028-.167.14-.278.335-.278.335 0 1.369.306 1.76.639.111.083.223.194.335.305.14.167.363.445.474.667.056.028.112.306.196.445.056.222.111.472.084.694-.028.028 0 .194-.028.194a2.668 2.668 0 0 1-.363 1.028c-.028.028-.028.056-.056.084l-.028.027c-.14.223-.335.417-.53.556-.643.444-1.369.583-2.095.389 0 0-.195-.084-.28-.111Zm8.154-.834a39.098 39.098 0 0 1-.893 3.167c0 .028-.028.083 0 .111-.056 0-.084.028-.14.056-2.206 1.61-4.356 3.305-6.506 5.028 1.843-1.64 3.686-3.306 5.613-4.945.558-.5.949-1.139 1.06-1.861l.28-1.667v-.055c.14-.334.67-.195.586.166Z",fill:"currentColor"})}),{width:40,height:40,fill:"none"}),Oi=R(H("g",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 6l4.153 11.793a0.365 .365 0 0 0 .331 .207a0.366 .366 0 0 0 .332 -.207l2.184 -4.793l4.787 -1.994a0.355 .355 0 0 0 .213 -.323a0.355 .355 0 0 0 -.213 -.323l-11.787 -4.36z"}),b("path",{d:"M13.5 13.5l4.5 4.5"})]}),{fill:"none",width:22,height:22,strokeWidth:1.25}),Nr=R(H("g",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,children:[b("path",{d:"M4.028 13.252c-.657 -.972 -1.028 -2.078 -1.028 -3.252c0 -3.866 4.03 -7 9 -7s9 3.134 9 7s-4.03 7 -9 7c-1.913 0 -3.686 -.464 -5.144 -1.255"}),b("path",{d:"M5 15m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M5 17c0 1.42 .316 2.805 1 4"})]}),{fill:"none",width:22,height:22,strokeWidth:1.25}),Ya=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})]}),K),Va=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10.5 20.4l-6.9 -6.9c-.781 -.781 -.781 -2.219 0 -3l6.9 -6.9c.781 -.781 2.219 -.781 3 0l6.9 6.9c.781 .781 .781 2.219 0 3l-6.9 6.9c-.781 .781 -2.219 .781 -3 0z"})]}),K),$a=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"12",cy:"12",r:"9"})]}),K),am=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),b("line",{x1:"15",y1:"16",x2:"19",y2:"12"}),b("line",{x1:"15",y1:"8",x2:"19",y2:"12"})]}),K),Ka=R(b("path",{d:"M4.167 10h11.666",strokeWidth:"1.5"}),fe),by=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M20 17v-12c0 -1.121 -.879 -2 -2 -2s-2 .879 -2 2v12l2 2l2 -2z"}),b("path",{d:"M16 7h4"}),b("path",{d:"M18 19h-13a2 2 0 1 1 0 -4h4a2 2 0 1 0 0 -4h-3"})]}),K),Ln=R(H("g",{strokeWidth:"1.25",children:[b("path",{clipRule:"evenodd",d:"m7.643 15.69 7.774-7.773a2.357 2.357 0 1 0-3.334-3.334L4.31 12.357a3.333 3.333 0 0 0-.977 2.357v1.953h1.953c.884 0 1.732-.352 2.357-.977Z"}),b("path",{d:"m11.25 5.417 3.333 3.333"})]}),fe),_n=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"20",x2:"7",y2:"20"}),b("line",{x1:"14",y1:"20",x2:"21",y2:"20"}),b("line",{x1:"6.9",y1:"15",x2:"13.8",y2:"15"}),b("line",{x1:"10.2",y1:"6.3",x2:"16",y2:"20"}),b("polyline",{points:"5 20 11 4 13 4 20 20"})]}),K),xy=R(H("g",{stroke:"currentColor",strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 7v-2h13v2"}),b("path",{d:"M10 5v14"}),b("path",{d:"M12 19h-4"}),b("path",{d:"M15 13v-1h6v1"}),b("path",{d:"M18 12v7"}),b("path",{d:"M17 19h2"})]}),K),Xa=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M12.5 6.667h.01"}),b("path",{d:"M4.91 2.625h10.18a2.284 2.284 0 0 1 2.285 2.284v10.182a2.284 2.284 0 0 1-2.284 2.284H4.909a2.284 2.284 0 0 1-2.284-2.284V4.909a2.284 2.284 0 0 1 2.284-2.284Z"}),b("path",{d:"m3.333 12.5 3.334-3.333c.773-.745 1.726-.745 2.5 0l4.166 4.166"}),b("path",{d:"m11.667 11.667.833-.834c.774-.744 1.726-.744 2.5 0l1.667 1.667"})]}),fe),sm=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M19 20h-10.5l-4.21 -4.3a1 1 0 0 1 0 -1.41l10 -10a1 1 0 0 1 1.41 0l5 5a1 1 0 0 1 0 1.41l-9.2 9.3"}),b("path",{d:"M18 13.3l-6.3 -6.3"})]}),K),rh=R(b("path",{strokeWidth:"1.25",d:"M10 4.167v11.666M4.167 10h11.666"}),fe),ih=R(b("path",{d:"M5 10h10",strokeWidth:"1.25"}),fe),Ey=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M21 21l-6 -6"}),b("path",{d:"M3.268 12.043a7.017 7.017 0 0 0 6.634 4.957a7.012 7.012 0 0 0 7.043 -6.131a7 7 0 0 0 -5.314 -7.672a7.021 7.021 0 0 0 -8.241 4.403"}),b("path",{d:"M3 4v4h4"})]}),K),Ht=R(b("path",{strokeWidth:"1.25",d:"M3.333 5.833h13.334M8.333 9.167v5M11.667 9.167v5M4.167 5.833l.833 10c0 .92.746 1.667 1.667 1.667h6.666c.92 0 1.667-.746 1.667-1.667l.833-10M7.5 5.833v-2.5c0-.46.373-.833.833-.833h3.334c.46 0 .833.373.833.833v2.5"}),fe),Za=R(H("g",{strokeWidth:"1.5",children:[b("polyline",{points:"12 16 18 10 12 4"}),b("polyline",{points:"8 4 2 10 8 16"})]}),fe),Xl=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M14.375 6.458H8.958a2.5 2.5 0 0 0-2.5 2.5v5.417a2.5 2.5 0 0 0 2.5 2.5h5.417a2.5 2.5 0 0 0 2.5-2.5V8.958a2.5 2.5 0 0 0-2.5-2.5Z"}),b("path",{clipRule:"evenodd",d:"M11.667 3.125c.517 0 .986.21 1.325.55.34.338.55.807.55 1.325v1.458H8.333c-.485 0-.927.185-1.26.487-.343.312-.57.75-.609 1.24l-.005 5.357H5a1.87 1.87 0 0 1-1.326-.55 1.87 1.87 0 0 1-.549-1.325V5c0-.518.21-.987.55-1.326.338-.34.807-.549 1.325-.549h6.667Z"})]}),fe),Zl=R(b("path",{clipRule:"evenodd",d:"M10 2.5h.328a6.25 6.25 0 0 0 6.6 10.372A7.5 7.5 0 1 1 10 2.493V2.5Z",stroke:"currentColor"}),fe),jl=R(b("g",{stroke:"currentColor",strokeLinejoin:"round",children:b("path",{d:"M10 12.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM10 4.167V2.5M14.167 5.833l1.166-1.166M15.833 10H17.5M14.167 14.167l1.166 1.166M10 15.833V17.5M5.833 14.167l-1.166 1.166M5 10H3.333M5.833 5.833 4.667 4.667"})}),{...fe,strokeWidth:1.5}),yy=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"6",x2:"20",y2:"6"}),b("line",{x1:"4",y1:"12",x2:"20",y2:"12"}),b("line",{x1:"4",y1:"18",x2:"20",y2:"18"})]}),K),zi=R(b("path",{strokeWidth:"1.25",d:"M3.333 14.167v1.666c0 .92.747 1.667 1.667 1.667h10c.92 0 1.667-.746 1.667-1.667v-1.666M5.833 9.167 10 13.333l4.167-4.166M10 3.333v10"}),fe),ja=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"12",cy:"12",r:"9"}),b("line",{x1:"12",y1:"17",x2:"12",y2:"17.01"}),b("path",{d:"M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"})]}),K),wy=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"12",cy:"12",r:"9"}),b("line",{x1:"12",y1:"17",x2:"12",y2:"17.01"}),b("path",{d:"M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"})]}),K),ah=R(b("path",{strokeWidth:"1.25",d:"M9.167 5.833H5.833c-1.254 0-2.5 1.282-2.5 2.5v5.834c0 1.283 1.252 2.5 2.5 2.5h5.834c1.251 0 2.5-1.25 2.5-2.5v-3.334M8.333 11.667l8.334-8.334M12.5 3.333h4.167V7.5"}),fe),lm=R(b("path",{d:"M7.5 15.833c-3.583 1.167-3.583-2.083-5-2.5m10 4.167v-2.917c0-.833.083-1.166-.417-1.666 2.334-.25 4.584-1.167 4.584-5a3.833 3.833 0 0 0-1.084-2.667 3.5 3.5 0 0 0-.083-2.667s-.917-.25-2.917 1.084a10.25 10.25 0 0 0-5.166 0C5.417 2.333 4.5 2.583 4.5 2.583a3.5 3.5 0 0 0-.083 2.667 3.833 3.833 0 0 0-1.084 2.667c0 3.833 2.25 4.75 4.584 5-.5.5-.5 1-.417 1.666V17.5",strokeWidth:"1.25"}),fe),vy=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M7.5 10.833a.833.833 0 1 0 0-1.666.833.833 0 0 0 0 1.666ZM12.5 10.833a.833.833 0 1 0 0-1.666.833.833 0 0 0 0 1.666ZM6.25 6.25c2.917-.833 4.583-.833 7.5 0M5.833 13.75c2.917.833 5.417.833 8.334 0"}),b("path",{d:"M12.917 14.167c0 .833 1.25 2.5 1.666 2.5 1.25 0 2.361-1.39 2.917-2.5.556-1.39.417-4.861-1.25-9.584-1.214-.846-2.5-1.116-3.75-1.25l-.833 2.084M7.083 14.167c0 .833-1.13 2.5-1.526 2.5-1.191 0-2.249-1.39-2.778-2.5-.529-1.39-.397-4.861 1.19-9.584 1.157-.846 2.318-1.116 3.531-1.25l.833 2.084"})]}),fe),Iy=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 4l11.733 16h4.267l-11.733 -16z"}),b("path",{d:"M4 20l6.768 -6.768m2.46 -2.46l6.772 -6.772"})]}),K),cm=R(b("polyline",{fill:"none",stroke:"currentColor",points:"20 6 9 17 4 12"}),{width:24,height:24}),ql=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M8.333 11.667a2.917 2.917 0 0 0 4.167 0l3.333-3.334a2.946 2.946 0 1 0-4.166-4.166l-.417.416"}),b("path",{d:"M11.667 8.333a2.917 2.917 0 0 0-4.167 0l-3.333 3.334a2.946 2.946 0 0 0 4.166 4.166l.417-.416"})]}),fe),Ty=R("M433.941 129.941l-83.882-83.882A48 48 0 0 0 316.118 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h352c26.51 0 48-21.49 48-48V163.882a48 48 0 0 0-14.059-33.941zM224 416c-35.346 0-64-28.654-64-64 0-35.346 28.654-64 64-64s64 28.654 64 64c0 35.346-28.654 64-64 64zm96-304.52V212c0 6.627-5.373 12-12 12H76c-6.627 0-12-5.373-12-12V108c0-6.627 5.373-12 12-12h228.52c3.183 0 6.235 1.264 8.485 3.515l3.48 3.48A11.996 11.996 0 0 1 320 111.48z",{width:448,height:512}),Cy=R("M252 54L203 8a28 27 0 00-20-8H28C12 0 0 12 0 27v195c0 15 12 26 28 26h204c15 0 28-11 28-26V73a28 27 0 00-8-19zM130 213c-21 0-37-16-37-36 0-19 16-35 37-35 20 0 37 16 37 35 0 20-17 36-37 36zm56-169v56c0 4-4 6-7 6H44c-4 0-7-2-7-6V42c0-4 3-7 7-7h133l4 2 3 2a7 7 0 012 5z M296 201l87 95-188 205-78 9c-10 1-19-8-18-20l9-84zm141-14l-41-44a31 31 0 00-46 0l-38 41 87 95 38-42c13-14 13-36 0-50z",{width:448,height:512}),qa=R(b("path",{d:"m9.257 6.351.183.183H15.819c.34 0 .727.182 1.051.506.323.323.505.708.505 1.05v5.819c0 .316-.183.7-.52 1.035-.337.338-.723.522-1.037.522H4.182c-.352 0-.74-.181-1.058-.5-.318-.318-.499-.705-.499-1.057V5.182c0-.351.181-.736.5-1.054.32-.321.71-.503 1.057-.503H6.53l2.726 2.726Z",strokeWidth:"1.25"}),fe),UQ=R("M384 112v352c0 26.51-21.49 48-48 48H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h80c0-35.29 28.71-64 64-64s64 28.71 64 64h80c26.51 0 48 21.49 48 48zM192 40c-13.255 0-24 10.745-24 24s10.745 24 24 24 24-10.745 24-24-10.745-24-24-24m96 114v-20a6 6 0 0 0-6-6H102a6 6 0 0 0-6 6v20a6 6 0 0 0 6 6h180a6 6 0 0 0 6-6z",{width:384,height:512}),WQ=R("M204.3 5C104.9 24.4 24.8 104.3 5.2 203.4c-37 187 131.7 326.4 258.8 306.7 41.2-6.4 61.4-54.6 42.5-91.7-23.1-45.4 9.9-98.4 60.9-98.4h79.7c35.8 0 64.8-29.6 64.9-65.3C511.5 97.1 368.1-26.9 204.3 5zM96 320c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm32-128c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128-64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128 64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32z"),dm=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 16l1.465 1.638a2 2 0 1 1 -3.015 .099l1.55 -1.737z"}),b("path",{d:"M13.737 9.737c2.299 -2.3 3.23 -5.095 2.081 -6.245c-1.15 -1.15 -3.945 -.217 -6.244 2.082c-2.3 2.299 -3.231 5.095 -2.082 6.244c1.15 1.15 3.946 .218 6.245 -2.081z"}),b("path",{d:"M7.492 11.818c.362 .362 .768 .676 1.208 .934l6.895 4.047c1.078 .557 2.255 -.075 3.692 -1.512c1.437 -1.437 2.07 -2.614 1.512 -3.692c-.372 -.718 -1.72 -3.017 -4.047 -6.895a6.015 6.015 0 0 0 -.934 -1.208"})]}),K),ky=R(b("g",{strokeWidth:1.5,children:b("path",{d:"M6 18l12 -12"})}),K),mm=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15 8h.01"}),b("path",{d:"M12 20h-5a3 3 0 0 1 -3 -3v-10a3 3 0 0 1 3 -3h10a3 3 0 0 1 3 3v5"}),b("path",{d:"M4 15l4 -4c.928 -.893 2.072 -.893 3 0l4 4"}),b("path",{d:"M14 14l1 -1c.617 -.593 1.328 -.793 2.009 -.598"}),b("path",{d:"M19 16v6"}),b("path",{d:"M22 19l-3 3l-3 -3"})]}),K),Sy=R("M216 0h80c13.3 0 24 10.7 24 24v168h87.7c17.8 0 26.7 21.5 14.1 34.1L269.7 378.3c-7.5 7.5-19.8 7.5-27.3 0L90.1 226.1c-12.6-12.6-3.7-34.1 14.1-34.1H192V24c0-13.3 10.7-24 24-24zm296 376v112c0 13.3-10.7 24-24 24H24c-13.3 0-24-10.7-24-24V376c0-13.3 10.7-24 24-24h146.7l49 49c20.1 20.1 52.5 20.1 72.6 0l49-49H488c13.3 0 24 10.7 24 24zm-124 88c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20zm64 0c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20z",{width:512,height:512}),YQ=R("M416 208H272V64c0-17.67-14.33-32-32-32h-32c-17.67 0-32 14.33-32 32v144H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h144v144c0 17.67 14.33 32 32 32h32c17.67 0 32-14.33 32-32V304h144c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z",{width:448,height:512}),VQ=R("M416 208H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h384c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z",{width:448,height:512}),My=R("M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"),$Q=R("M16 132h416c8.837 0 16-7.163 16-16V76c0-8.837-7.163-16-16-16H16C7.163 60 0 67.163 0 76v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16z"),sh=R(b("path",{d:"M7.5 10.833 4.167 7.5 7.5 4.167M4.167 7.5h9.166a3.333 3.333 0 0 1 0 6.667H12.5",strokeWidth:"1.25"}),fe),lh=R(b("path",{d:"M12.5 10.833 15.833 7.5 12.5 4.167M15.833 7.5H6.667a3.333 3.333 0 1 0 0 6.667H7.5",strokeWidth:"1.25"}),fe),Py=R("M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zM262.655 90c-54.497 0-89.255 22.957-116.549 63.758-3.536 5.286-2.353 12.415 2.715 16.258l34.699 26.31c5.205 3.947 12.621 3.008 16.665-2.122 17.864-22.658 30.113-35.797 57.303-35.797 20.429 0 45.698 13.148 45.698 32.958 0 14.976-12.363 22.667-32.534 33.976C247.128 238.528 216 254.941 216 296v4c0 6.627 5.373 12 12 12h56c6.627 0 12-5.373 12-12v-1.333c0-28.462 83.186-29.647 83.186-106.667 0-58.002-60.165-102-116.531-102zM256 338c-25.365 0-46 20.635-46 46 0 25.364 20.635 46 46 46s46-20.636 46-46c0-25.365-20.635-46-46-46z",{mirror:!0}),Ay=R(b("path",{d:"M5 12.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM15 7.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM15 17.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM7.25 8.917l5.5-2.834M7.25 11.083l5.5 2.834",strokeWidth:"1.5"}),fe),KQ=R("M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"),XQ=R("M16 5l-1.42 1.42-1.59-1.59V16h-1.98V4.83L9.42 6.42 8 5l4-4 4 4zm4 5v11c0 1.1-.9 2-2 2H6c-1.11 0-2-.9-2-2V10c0-1.11.89-2 2-2h3v2H6v11h12V10h-3V8h3c1.1 0 2 .89 2 2z",{width:24,height:24}),ZQ=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 9h-1a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-8a2 2 0 0 0 -2 -2h-1"}),b("path",{d:"M12 14v-11"}),b("path",{d:"M9 6l3 -3l3 3"})]}),K),jQ=R(H(Ue,{children:[b("path",{fill:"currentColor",d:"M40 5.6v6.1l-4.1.7c-8.9 1.4-16.5 6.9-20.6 15C13 32 10.9 43 12.4 43c.4 0 2.4-1.3 4.4-3 5-3.9 12.1-7 18.2-7.7l5-.6v12.8l11.2-11.3L62.5 22 51.2 10.8 40-.5v6.1zm10.2 22.6L44 34.5v-6.8l-6.9.6c-3.9.3-9.8 1.7-13.2 3.1-3.5 1.4-6.5 2.4-6.7 2.2-.9-1 3-7.5 6.4-10.8C28 18.6 34.4 16 40.1 16c3.7 0 3.9-.1 3.9-3.2V9.5l6.2 6.3 6.3 6.2-6.3 6.2z"}),b("path",{stroke:"currentColor",fill:"currentColor",d:"M0 36v20h48v-6.2c0-6 0-6.1-2-4.3-1.1 1-2 2.9-2 4.2V52H4V34c0-17.3-.1-18-2-18s-2 .7-2 20z"})]}),{width:64,height:64}),qQ=R(b("path",{stroke:"currentColor",strokeWidth:"40",fill:"currentColor",d:"M148 560a318 318 0 0 0 522 110 316 316 0 0 0 0-450 316 316 0 0 0-450 0c-11 11-21 22-30 34v4h47c25 0 46 21 46 46s-21 45-46 45H90c-13 0-25-6-33-14-9-9-14-20-14-33V156c0-25 20-45 45-45s45 20 45 45v32l1 1a401 401 0 0 1 623 509l212 212a42 42 0 0 1-59 59L698 757A401 401 0 0 1 65 570a42 42 0 0 1 83-10z"}),{width:1024}),Ly=H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 10l0 10"}),b("path",{d:"M12 10l4 4"}),b("path",{d:"M12 10l-4 4"}),b("path",{d:"M4 4l16 0"})]}),_y=H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 5l0 14"}),b("path",{d:"M16 9l-4 -4"}),b("path",{d:"M8 9l4 -4"})]}),ch=R(_y,K),dh=R(_y,{...K,style:{transform:"rotate(180deg)"}}),mh=R(Ly,K),ph=R(Ly,{...K,style:{transform:"rotate(180deg)"}}),uh=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M3.333 3.333h13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M13.542 6.458h-.417c-.92 0-1.667.747-1.667 1.667v7.083c0 .92.746 1.667 1.667 1.667h.417c.92 0 1.666-.746 1.666-1.667V8.125c0-.92-.746-1.667-1.666-1.667ZM6.875 6.458h-.417c-.92 0-1.666.747-1.666 1.667v3.75c0 .92.746 1.667 1.666 1.667h.417c.92 0 1.667-.746 1.667-1.667v-3.75c0-.92-.747-1.667-1.667-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),gh=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M3.333 16.667h13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M6.875 3.125h-.417c-.92 0-1.666.746-1.666 1.667v7.083c0 .92.746 1.667 1.666 1.667h.417c.92 0 1.667-.746 1.667-1.667V4.792c0-.92-.747-1.667-1.667-1.667ZM13.542 5.817h-.417c-.92 0-1.667.747-1.667 1.667v4.391c0 .92.746 1.667 1.667 1.667h.417c.92 0 1.666-.746 1.666-1.667V7.484c0-.92-.746-1.667-1.666-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),hh=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M3.333 3.333v13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M15.208 4.792H8.125c-.92 0-1.667.746-1.667 1.666v.417c0 .92.747 1.667 1.667 1.667h7.083c.92 0 1.667-.747 1.667-1.667v-.417c0-.92-.746-1.666-1.667-1.666ZM12.516 11.458H8.125c-.92 0-1.667.746-1.667 1.667v.417c0 .92.747 1.666 1.667 1.666h4.391c.92 0 1.667-.746 1.667-1.666v-.417c0-.92-.746-1.667-1.667-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),fh=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M16.667 3.333v13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M11.875 4.792H4.792c-.92 0-1.667.746-1.667 1.666v.417c0 .92.746 1.667 1.667 1.667h7.083c.92 0 1.667-.747 1.667-1.667v-.417c0-.92-.746-1.666-1.667-1.666ZM11.683 11.458H7.292c-.92 0-1.667.746-1.667 1.667v.417c0 .92.746 1.666 1.667 1.666h4.39c.921 0 1.667-.746 1.667-1.666v-.417c0-.92-.746-1.667-1.666-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),Dy=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M16.667 3.333v13.334M3.333 3.333v13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M14.375 10.208v-.416c0-.92-.746-1.667-1.667-1.667H7.292c-.92 0-1.667.746-1.667 1.667v.416c0 .92.746 1.667 1.667 1.667h5.416c.92 0 1.667-.746 1.667-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),Ry=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M3.333 3.333h13.334M3.333 16.667h13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M10.208 5.625h-.416c-.92 0-1.667.746-1.667 1.667v5.416c0 .92.746 1.667 1.667 1.667h.416c.92 0 1.667-.746 1.667-1.667V7.292c0-.92-.746-1.667-1.667-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),bh=R(H("g",{stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M1.667 10h2.916",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M8.333 10h3.334",strokeLinejoin:"round"}),b("path",{d:"M15.417 10h2.916",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M6.875 4.792h-.417c-.92 0-1.666.746-1.666 1.666v7.084c0 .92.746 1.666 1.666 1.666h.417c.92 0 1.667-.746 1.667-1.666V6.458c0-.92-.747-1.666-1.667-1.666ZM13.542 6.458h-.417c-.92 0-1.667.747-1.667 1.667v3.75c0 .92.746 1.667 1.667 1.667h.417c.92 0 1.666-.746 1.666-1.667v-3.75c0-.92-.746-1.667-1.666-1.667Z"})]}),fe),xh=R(H("g",{stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M10 18.333v-2.916",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M10 11.667V8.333",strokeLinejoin:"round"}),b("path",{d:"M10 4.583V1.667",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M4.792 13.125v.417c0 .92.746 1.666 1.666 1.666h7.084c.92 0 1.666-.746 1.666-1.666v-.417c0-.92-.746-1.667-1.666-1.667H6.458c-.92 0-1.666.746-1.666 1.667ZM6.458 6.458v.417c0 .92.747 1.667 1.667 1.667h3.75c.92 0 1.667-.747 1.667-1.667v-.417c0-.92-.746-1.666-1.667-1.666h-3.75c-.92 0-1.667.746-1.667 1.666Z"})]}),fe),pm=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"9",cy:"7",r:"4"}),b("path",{d:"M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"}),b("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"}),b("path",{d:"M21 21v-2a4 4 0 0 0 -3 -3.85"})]}),K),JQ=R("M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm115.7 272l-176 101c-15.8 8.8-35.7-2.5-35.7-21V152c0-18.4 19.8-29.8 35.7-21l176 107c16.4 9.2 16.4 32.9 0 42z"),Ny=R("M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm96 328c0 8.8-7.2 16-16 16H176c-8.8 0-16-7.2-16-16V176c0-8.8 7.2-16 16-16h160c8.8 0 16 7.2 16 16v160z"),Fo=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",children:b("path",{d:"M15 5 5 15M5 5l10 10"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),QQ=R("M464 0c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48H176c-26.51 0-48-21.49-48-48V48c0-26.51 21.49-48 48-48h288M176 416c-44.112 0-80-35.888-80-80V128H48c-26.51 0-48 21.49-48 48v288c0 26.51 21.49 48 48 48h288c26.51 0 48-21.49 48-48v-48H176z",{mirror:!0}),eee=R("M11.553 22.894a.998.998 0 00.894 0s3.037-1.516 5.465-4.097C19.616 16.987 21 14.663 21 12V5a1 1 0 00-.649-.936l-8-3a.998.998 0 00-.702 0l-8 3A1 1 0 003 5v7c0 2.663 1.384 4.987 3.088 6.797 2.428 2.581 5.465 4.097 5.465 4.097zm-1.303-8.481l6.644-6.644a.856.856 0 111.212 1.212l-7.25 7.25a.856.856 0 01-1.212 0l-3.75-3.75a.856.856 0 111.212-1.212l3.144 3.144z",{width:24}),tee=R("M369.9 97.9L286 14C277 5 264.8-.1 252.1-.1H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V131.9c0-12.7-5.1-25-14.1-34zM332.1 128H256V51.9l76.1 76.1zM48 464V48h160v104c0 13.3 10.7 24 24 24h104v288H48zm32-48h224V288l-23.5-23.5c-4.7-4.7-12.3-4.7-17 0L176 352l-39.5-39.5c-4.7-4.7-12.3-4.7-17 0L80 352v64zm48-240c-26.5 0-48 21.5-48 48s21.5 48 48 48 48-21.5 48-48-21.5-48-48-48z",{width:384,height:512}),Eh=Lt.memo(({theme:e})=>R(H(Ue,{children:[b("path",{d:"M25 26H111V111H25",fill:cn(e)}),b("path",{d:"M25 111C25 80.2068 25 49.4135 25 26M25 26C48.6174 26 72.2348 26 111 26H25ZM25 26C53.3671 26 81.7343 26 111 26H25ZM111 26C111 52.303 111 78.606 111 111V26ZM111 26C111 51.2947 111 76.5893 111 111V26ZM111 111C87.0792 111 63.1585 111 25 111H111ZM111 111C87.4646 111 63.9293 111 25 111H111ZM25 111C25 81.1514 25 51.3028 25 26V111Z",stroke:cn(e),strokeWidth:"2"}),b("path",{d:"M100 100H160V160H100",fill:cn(e)}),b("path",{d:"M100 160C100 144.106 100 128.211 100 100M100 100C117.706 100 135.412 100 160 100H100ZM100 100C114.214 100 128.428 100 160 100H100ZM160 100C160 120.184 160 140.369 160 160V100ZM160 100C160 113.219 160 126.437 160 160V100ZM160 160C145.534 160 131.068 160 100 160H160ZM160 160C143.467 160 126.934 160 100 160H160ZM100 160C100 143.661 100 127.321 100 100V160Z",stroke:cn(e),strokeWidth:"2"}),H("g",{fill:ly(e),stroke:cn(e),strokeWidth:"6",children:[b("rect",{x:"2.5",y:"2.5",width:"30",height:"30"}),b("rect",{x:"2.5",y:"149.5",width:"30",height:"30"}),b("rect",{x:"147.5",y:"149.5",width:"30",height:"30"}),b("rect",{x:"147.5",y:"2.5",width:"30",height:"30"})]})]}),{width:182,height:182,mirror:!0})),yh=Lt.memo(({theme:e})=>R(H(Ue,{children:[b("path",{d:"M25 26H111V111H25",fill:cn(e)}),b("path",{d:"M25 111C25 80.2068 25 49.4135 25 26M25 26C48.6174 26 72.2348 26 111 26H25ZM25 26C53.3671 26 81.7343 26 111 26H25ZM111 26C111 52.303 111 78.606 111 111V26ZM111 26C111 51.2947 111 76.5893 111 111V26ZM111 111C87.0792 111 63.1585 111 25 111H111ZM111 111C87.4646 111 63.9293 111 25 111H111ZM25 111C25 81.1514 25 51.3028 25 26V111Z",stroke:cn(e),strokeWidth:"2"}),b("path",{d:"M100 100H160V160H100",fill:cn(e)}),b("path",{d:"M100 160C100 144.106 100 128.211 100 100M100 100C117.706 100 135.412 100 160 100H100ZM100 100C114.214 100 128.428 100 160 100H100ZM160 100C160 120.184 160 140.369 160 160V100ZM160 100C160 113.219 160 126.437 160 160V100ZM160 160C145.534 160 131.068 160 100 160H160ZM160 160C143.467 160 126.934 160 100 160H160ZM100 160C100 143.661 100 127.321 100 100V160Z",stroke:cn(e),strokeWidth:"2"}),H("g",{fill:ly(e),stroke:cn(e),strokeWidth:"6",children:[b("rect",{x:"2.5",y:"2.5",width:"30",height:"30"}),b("rect",{x:"78.5",y:"149.5",width:"30",height:"30"}),b("rect",{x:"147.5",y:"149.5",width:"30",height:"30"}),b("rect",{x:"147.5",y:"78.5",width:"30",height:"30"}),b("rect",{x:"105.5",y:"2.5",width:"30",height:"30"}),b("rect",{x:"2.5",y:"102.5",width:"30",height:"30"})]})]}),{width:182,height:182,mirror:!0})),By=R(b("g",{strokeWidth:1.25,children:b("path",{d:"M5.879 2.625h8.242a3.27 3.27 0 0 1 3.254 3.254v8.242a3.27 3.27 0 0 1-3.254 3.254H5.88a3.27 3.27 0 0 1-3.254-3.254V5.88A3.27 3.27 0 0 1 5.88 2.626l-.001-.001ZM4.518 16.118l7.608-12.83m.198 13.934 5.051-9.897M2.778 9.675l9.348-6.387m-7.608 12.83 12.857-8.793"})}),fe),Fy=R(H(Ue,{children:[b("path",{d:"M5.879 2.625h8.242a3.254 3.254 0 0 1 3.254 3.254v8.242a3.254 3.254 0 0 1-3.254 3.254H5.88a3.254 3.254 0 0 1-3.254-3.254V5.88a3.254 3.254 0 0 1 3.254-3.254Z",stroke:"currentColor",strokeWidth:"1.25"}),b("mask",{id:"FillHachureIcon",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:2,y:2,width:16,height:16,children:b("path",{d:"M5.879 2.625h8.242a3.254 3.254 0 0 1 3.254 3.254v8.242a3.254 3.254 0 0 1-3.254 3.254H5.88a3.254 3.254 0 0 1-3.254-3.254V5.88a3.254 3.254 0 0 1 3.254-3.254Z",fill:"currentColor",stroke:"currentColor",strokeWidth:"1.25"})}),b("g",{mask:"url(#FillHachureIcon)",children:b("path",{d:"M2.258 15.156 15.156 2.258M7.324 20.222 20.222 7.325m-20.444 5.35L12.675-.222m-8.157 18.34L17.416 5.22",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),fe),Oy=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",children:[b("path",{d:"M5.879 2.625h8.242a3.254 3.254 0 0 1 3.254 3.254v8.242a3.254 3.254 0 0 1-3.254 3.254H5.88a3.254 3.254 0 0 1-3.254-3.254V5.88a3.254 3.254 0 0 1 3.254-3.254Z",stroke:"currentColor",strokeWidth:"1.25"}),b("mask",{id:"FillCrossHatchIcon",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:-1,y:-1,width:22,height:22,children:b("path",{d:"M2.426 15.044 15.044 2.426M7.383 20 20 7.383M0 12.617 12.617 0m-7.98 17.941L17.256 5.324m-2.211 12.25L2.426 4.956M20 12.617 7.383 0m5.234 20L0 7.383m17.941 7.98L5.324 2.745",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),b("g",{mask:"url(#FillCrossHatchIcon)",children:b("path",{d:"M14.121 2H5.88A3.879 3.879 0 0 0 2 5.879v8.242A3.879 3.879 0 0 0 5.879 18h8.242A3.879 3.879 0 0 0 18 14.121V5.88A3.879 3.879 0 0 0 14.121 2Z",fill:"currentColor"})})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),zy=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",children:b("path",{d:"M4.91 2.625h10.18a2.284 2.284 0 0 1 2.285 2.284v10.182a2.284 2.284 0 0 1-2.284 2.284H4.909a2.284 2.284 0 0 1-2.284-2.284V4.909a2.284 2.284 0 0 1 2.284-2.284Z",stroke:"currentColor",strokeWidth:"1.25"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),{...fe,fill:"currentColor"}),wh=R(b(Ue,{children:b("path",{d:"M4.167 10h11.666",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),fe),Hy=R(b("path",{d:"M5 10h10",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),fe),Gy=R(b("path",{d:"M5 10h10",stroke:"currentColor",strokeWidth:"3.75",strokeLinecap:"round",strokeLinejoin:"round"}),fe),oee=Lt.memo(({theme:e})=>R(b("path",{d:"M6 10H34",stroke:cn(e),strokeWidth:2,fill:"none",strokeLinecap:"round"}),{width:40,height:20})),Uy=R(H("g",{strokeWidth:"2",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 12h2"}),b("path",{d:"M17 12h2"}),b("path",{d:"M11 12h2"})]}),K),Wy=R(H("g",{strokeWidth:"2",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 12v.01"}),b("path",{d:"M8 12v.01"}),b("path",{d:"M12 12v.01"}),b("path",{d:"M16 12v.01"}),b("path",{d:"M20 12v.01"})]}),K),Yy=R(b("path",{d:"M2.5 12.038c1.655-.885 5.9-3.292 8.568-4.354 2.668-1.063.101 2.821 1.32 3.104 1.218.283 5.112-1.814 5.112-1.814",strokeWidth:"1.25"}),fe),Vy=R(b("path",{d:"M2.5 12.563c1.655-.886 5.9-3.293 8.568-4.355 2.668-1.062.101 2.822 1.32 3.105 1.218.283 5.112-1.814 5.112-1.814m-13.469 2.23c2.963-1.586 6.13-5.62 7.468-4.998 1.338.623-1.153 4.11-.132 5.595 1.02 1.487 6.133-1.43 6.133-1.43",strokeWidth:"1.25"}),fe),$y=R(b("path",{d:"M2.5 11.936c1.737-.879 8.627-5.346 10.42-5.268 1.795.078-.418 5.138.345 5.736.763.598 3.53-1.789 4.235-2.147M2.929 9.788c1.164-.519 5.47-3.28 6.987-3.114 1.519.165 1 3.827 2.121 4.109 1.122.281 3.839-2.016 4.606-2.42",strokeWidth:"1.25"}),fe),Ky=R(H("svg",{strokeWidth:"1.5",children:[b("path",{d:"M3.33334 9.99998V6.66665C3.33334 6.04326 3.33403 4.9332 3.33539 3.33646C4.95233 3.33436 6.06276 3.33331 6.66668 3.33331H10"}),b("path",{d:"M13.3333 3.33331V3.34331"}),b("path",{d:"M16.6667 3.33331V3.34331"}),b("path",{d:"M16.6667 6.66669V6.67669"}),b("path",{d:"M16.6667 10V10.01"}),b("path",{d:"M3.33334 13.3333V13.3433"}),b("path",{d:"M16.6667 13.3333V13.3433"}),b("path",{d:"M3.33334 16.6667V16.6767"}),b("path",{d:"M6.66666 16.6667V16.6767"}),b("path",{d:"M10 16.6667V16.6767"}),b("path",{d:"M13.3333 16.6667V16.6767"}),b("path",{d:"M16.6667 16.6667V16.6767"})]}),fe),Xy=R(H("g",{strokeWidth:"1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 12v-4a4 4 0 0 1 4 -4h4"}),b("line",{x1:"16",y1:"4",x2:"16",y2:"4.01"}),b("line",{x1:"20",y1:"4",x2:"20",y2:"4.01"}),b("line",{x1:"20",y1:"8",x2:"20",y2:"8.01"}),b("line",{x1:"20",y1:"12",x2:"20",y2:"12.01"}),b("line",{x1:"4",y1:"16",x2:"4",y2:"16.01"}),b("line",{x1:"20",y1:"16",x2:"20",y2:"16.01"}),b("line",{x1:"4",y1:"20",x2:"4",y2:"20.01"}),b("line",{x1:"8",y1:"20",x2:"8",y2:"20.01"}),b("line",{x1:"12",y1:"20",x2:"12",y2:"20.01"}),b("line",{x1:"16",y1:"20",x2:"16",y2:"20.01"}),b("line",{x1:"20",y1:"20",x2:"20",y2:"20.01"})]}),K),Zy=Lt.memo(({flip:e=!1})=>R(H("g",{transform:e?"translate(24, 0) scale(-1, 1)":"",stroke:"currentColor",opacity:.3,strokeWidth:2,children:[b("path",{d:"M12 12l-9 0"}),b("path",{d:"M21 9l-6 6"}),b("path",{d:"M21 15l-6 -6"})]}),K)),jy=Lt.memo(({flip:e=!1})=>R(H("g",{transform:e?"translate(40, 0) scale(-1, 1)":"",stroke:"currentColor",strokeWidth:2,fill:"none",children:[b("path",{d:"M34 10H6M34 10L27 5M34 10L27 15"}),b("path",{d:"M27.5 5L34.5 10L27.5 15"})]}),{width:40,height:20})),qy=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"currentColor",transform:e?"translate(40, 0) scale(-1, 1)":"",children:[b("path",{d:"M32 10L6 10",strokeWidth:2}),b("circle",{r:"4",transform:"matrix(-1 0 0 1 30 10)"})]}),{width:40,height:20})),Jy=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"none",transform:e?"translate(40, 0) scale(-1, 1)":"",strokeWidth:2,children:[b("path",{d:"M26 10L6 10"}),b("circle",{r:"4",transform:"matrix(-1 0 0 1 30 10)"})]}),{width:40,height:20})),Qy=Lt.memo(({flip:e=!1})=>R(b("g",{transform:e?"translate(40, 0) scale(-1, 1)":"",children:b("path",{d:"M34 10H5.99996M34 10L34 5M34 10L34 15",stroke:"currentColor",strokeWidth:2,fill:"none"})}),{width:40,height:20})),ew=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"currentColor",transform:e?"translate(40, 0) scale(-1, 1)":"",children:[b("path",{d:"M32 10L6 10",strokeWidth:2}),b("path",{d:"M27.5 5.5L34.5 10L27.5 14.5L27.5 5.5"})]}),{width:40,height:20})),tw=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"none",transform:e?"translate(40, 0) scale(-1, 1)":"",strokeWidth:2,strokeLinejoin:"round",children:[b("path",{d:"M6,9.5H27"}),b("path",{d:"M27,5L34,10L27,14Z",fill:"none"})]}),{width:40,height:20})),ow=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"currentColor",transform:e?"translate(40, 0) scale(-1, 1)":"",strokeLinejoin:"round",strokeWidth:2,children:[b("path",{d:"M6,9.5H20"}),b("path",{d:"M27,5L34,10L27,14L20,9.5Z"})]}),{width:40,height:20})),nw=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"none",transform:e?"translate(40, 0) scale(-1, 1)":"",strokeLinejoin:"round",strokeWidth:2,children:[b("path",{d:"M6,9.5H20"}),b("path",{d:"M27,5L34,10L27,14L20,9.5Z"})]}),{width:40,height:20})),rw=Lt.memo(({flip:e=!1})=>R(b("g",{stroke:"currentColor",fill:"none",transform:e?"":"translate(40, 0) scale(-1, 1)",strokeLinejoin:"round",strokeWidth:2,children:b("path",{d:"M34,10 H6 M15,10 L7,5 M15,10 L7,15"})}),{width:40,height:20})),iw=Lt.memo(({flip:e=!1})=>R(b("g",{stroke:"currentColor",fill:"none",transform:e?"":"translate(40, 0) scale(-1, 1)",strokeLinejoin:"round",strokeWidth:2,children:b("path",{d:"M34,10 H6 M15,10 L15,15 L15,5"})}),{width:40,height:20})),aw=Lt.memo(({flip:e=!1})=>R(b("g",{stroke:"currentColor",fill:"none",transform:e?"":"translate(40, 0) scale(-1, 1)",strokeLinejoin:"round",strokeWidth:2,children:b("path",{d:"M34,10 H6 M15,10 L15,16 L15,4 M15,10 L7,5 M15,10 L7,15"})}),{width:40,height:20})),sw=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",children:b("path",{d:"M14.167 6.667a3.333 3.333 0 0 0-3.334-3.334H9.167a3.333 3.333 0 0 0 0 6.667h1.666a3.333 3.333 0 0 1 0 6.667H9.167a3.333 3.333 0 0 1-3.334-3.334",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),lw=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",children:b("path",{d:"M5 16.667V3.333L10 15l5-11.667v13.334",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),cw=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",children:b("path",{d:"M5.833 3.333v13.334h8.334",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),dw=R(b(Ue,{children:b("path",{d:"m1.667 3.333 6.666 13.334M8.333 3.333 1.667 16.667M11.667 3.333v13.334h6.666",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),fe),Hi=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 7v-2h13v2"}),b("path",{d:"M10 5v14"}),b("path",{d:"M12 19h-4"}),b("path",{d:"M15 13v-1h6v1"}),b("path",{d:"M18 12v7"}),b("path",{d:"M17 19h2"})]}),K),mw=R(b(Ue,{children:H("g",{stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M7 12h10"}),b("path",{d:"M7 5v14"}),b("path",{d:"M17 5v14"}),b("path",{d:"M15 19h4"}),b("path",{d:"M15 5h4"}),b("path",{d:"M5 19h4"}),b("path",{d:"M5 5h4"})]})}),K),Jl=R(b(Ue,{children:b("g",{stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",children:b("path",{d:"M5.833 16.667v-10a3.333 3.333 0 0 1 3.334-3.334h1.666a3.333 3.333 0 0 1 3.334 3.334v10M5.833 10.833h8.334"})})}),fe),vh=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M7 8l-4 4l4 4"}),b("path",{d:"M17 8l4 4l-4 4"}),b("path",{d:"M14 4l-4 16"})]}),K),um=vh,pw=R(H("g",{stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"8",x2:"20",y2:"8"}),b("line",{x1:"4",y1:"12",x2:"12",y2:"12"}),b("line",{x1:"4",y1:"16",x2:"16",y2:"16"})]}),K),uw=R(H("g",{stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"8",x2:"20",y2:"8"}),b("line",{x1:"8",y1:"12",x2:"16",y2:"12"}),b("line",{x1:"6",y1:"16",x2:"18",y2:"16"})]}),K),gw=R(H("g",{stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"8",x2:"20",y2:"8"}),b("line",{x1:"10",y1:"12",x2:"20",y2:"12"}),b("line",{x1:"8",y1:"16",x2:"20",y2:"16"})]}),K),hw=Lt.memo(({theme:e})=>R(H("g",{strokeWidth:"1.5",stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"4",x2:"20",y2:"4"}),b("rect",{x:"9",y:"8",width:"6",height:"12",rx:"2"})]}),K)),fw=Lt.memo(({theme:e})=>R(H("g",{strokeWidth:"2",stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"20",x2:"20",y2:"20"}),b("rect",{x:"9",y:"4",width:"6",height:"12",rx:"2"})]}),K)),bw=Lt.memo(({theme:e})=>R(H("g",{strokeWidth:"1.5",stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"12",x2:"9",y2:"12"}),b("line",{x1:"15",y1:"12",x2:"20",y2:"12"}),b("rect",{x:"9",y:"6",width:"6",height:"12",rx:"2"})]}),K)),gm=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M21 19h-18l9 -15"}),b("path",{d:"M20.615 15.171h.015"}),b("path",{d:"M19.515 11.771h.015"}),b("path",{d:"M17.715 8.671h.015"}),b("path",{d:"M15.415 5.971h.015"})]}),K),xw=R(b("path",{d:"M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zM393.4 288H328v112c0 8.8-7.2 16-16 16h-48c-8.8 0-16-7.2-16-16V288h-65.4c-14.3 0-21.4-17.2-11.3-27.3l105.4-105.4c6.2-6.2 16.4-6.2 22.6 0l105.4 105.4c10.1 10.1 2.9 27.3-11.3 27.3z",fill:"currentColor"}),{width:640,height:512}),nee=R(b("path",{d:"M480 416C497.7 416 512 430.3 512 448C512 465.7 497.7 480 480 480H150.6C133.7 480 117.4 473.3 105.4 461.3L25.37 381.3C.3786 356.3 .3786 315.7 25.37 290.7L258.7 57.37C283.7 32.38 324.3 32.38 349.3 57.37L486.6 194.7C511.6 219.7 511.6 260.3 486.6 285.3L355.9 416H480zM265.4 416L332.7 348.7L195.3 211.3L70.63 336L150.6 416L265.4 416z"})),Ja=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 13v-7.5a1.5 1.5 0 0 1 3 0v6.5"}),b("path",{d:"M11 5.5v-2a1.5 1.5 0 1 1 3 0v8.5"}),b("path",{d:"M14 5.5a1.5 1.5 0 0 1 3 0v6.5"}),b("path",{d:"M17 7.5a1.5 1.5 0 0 1 3 0v8.5a6 6 0 0 1 -6 6h-2h.208a6 6 0 0 1 -5.012 -2.7a69.74 69.74 0 0 1 -.196 -.3c-.312 -.479 -1.407 -2.388 -3.286 -5.728a1.5 1.5 0 0 1 .536 -2.022a1.867 1.867 0 0 1 2.28 .28l1.47 1.47"})]}),K),Ih=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2"}),b("path",{d:"M7 11l5 5l5 -5"}),b("path",{d:"M12 4l0 12"})]}),K),Qa=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 8m0 2a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2z"}),b("path",{d:"M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2"})]}),K),Ew=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M7 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"}),b("path",{d:"M17 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"}),b("path",{d:"M9.15 14.85l8.85 -10.85"}),b("path",{d:"M6 4l8.85 10.85"})]}),K),yw=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"}),b("path",{d:"M12 17l0 .01"}),b("path",{d:"M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"})]}),K),ree=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M7 4v16l13 -8z"})]}),K),iee=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M17 4h-10a3 3 0 0 0 -3 3v10a3 3 0 0 0 3 3h10a3 3 0 0 0 3 -3v-10a3 3 0 0 0 -3 -3z",strokeWidth:"0",fill:"currentColor"})]}),K),ww=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 12l5 5l10 -10"})]}),K),hm=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10.24 3.957l-8.422 14.06a1.989 1.989 0 0 0 1.7 2.983h16.845a1.989 1.989 0 0 0 1.7 -2.983l-8.423 -14.06a1.989 1.989 0 0 0 -3.4 0z"}),b("path",{d:"M12 9v4"}),b("path",{d:"M12 17h.01"})]}),K),vw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M11 7l6 6"}),b("path",{d:"M4 16l11.7 -11.7a1 1 0 0 1 1.4 0l2.6 2.6a1 1 0 0 1 0 1.4l-11.7 11.7h-4v-4z"})]}),K),Ql=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 3l-4 7h8z"}),b("path",{d:"M17 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"}),b("path",{d:"M4 14m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z"})]}),K),Dn=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 7l16 0"}),b("path",{d:"M4 17l16 0"}),b("path",{d:"M7 4l0 16"}),b("path",{d:"M17 4l0 16"})]}),K),Iw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),b("circle",{cx:"8.5",cy:"8.5",r:"1.5",fill:"currentColor",stroke:"none"}),b("path",{d:"M3 16l5-5c.928-.893 2.072-.893 3 0l5 5"}),b("path",{d:"M14 14l1-1c.928-.893 2.072-.893 3 0l3 3"}),b("path",{d:"M17.5 4.5l0 3m-1.5-1.5l3 0",strokeWidth:"1.5",strokeLinecap:"round"})]}),K),es=R(b("path",{fill:"currentColor",d:"M407.48,111.18C335.587,108.103 269.573,152.338 245.08,220C220.587,152.338 154.573,108.103 82.68,111.18C80.285,168.229 107.577,222.632 154.74,254.82C178.908,271.419 193.35,298.951 193.27,328.27L193.27,379.13L296.9,379.13L296.9,328.27C296.816,298.953 311.255,271.42 335.42,254.82C382.596,222.644 409.892,168.233 407.48,111.18Z"})),Tw=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4"}),b("path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4"})]}),K),Cw=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 10l-2 1l8 4l8 -4l-2 -1"}),b("path",{d:"M4 15l8 4l8 -4"}),b("path",{d:"M12 4v7"}),b("path",{d:"M15 8l-3 3l-3 -3"})]}),K),Br=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M4.16602 10H15.8327"}),b("path",{d:"M12.5 13.3333L15.8333 10"}),b("path",{d:"M12.5 6.66666L15.8333 9.99999"})]}),fe),Rn=R(H("g",{fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",transform:"rotate(90 10 10)",children:[b("path",{clipRule:"evenodd",d:"m9.644 13.69 7.774-7.773a2.357 2.357 0 0 0-3.334-3.334l-7.773 7.774L8 12l1.643 1.69Z"}),b("path",{d:"m13.25 3.417 3.333 3.333M10 10l2-2M5 15l3-3M2.156 17.894l1-1M5.453 19.029l-.144-1.407M2.377 11.887l.866 1.118M8.354 17.273l-1.194-.758M.953 14.652l1.408.13"})]}),20),Gi=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z"}),b("path",{d:"M6 21l15 -15l-3 -3l-15 15l3 3"}),b("path",{d:"M15 6l3 3"}),b("path",{d:"M9 3a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2"}),b("path",{d:"M19 13a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2"})]}),K),aee=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z"}),b("path",{d:"M6 21l15 -15l-3 -3l-15 15l3 3"}),b("path",{d:"M15 6l3 3"}),b("path",{d:"M9 3a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2"}),b("path",{d:"M19 13a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2"})]}),K),see=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M11.217 19.384a3.501 3.501 0 0 0 6.783 -1.217v-5.167l-6 -3.35"}),b("path",{d:"M5.214 15.014a3.501 3.501 0 0 0 4.446 5.266l4.34 -2.534v-6.946"}),b("path",{d:"M6 7.63c-1.391 -.236 -2.787 .395 -3.534 1.689a3.474 3.474 0 0 0 1.271 4.745l4.263 2.514l6 -3.348"}),b("path",{d:"M12.783 4.616a3.501 3.501 0 0 0 -6.783 1.217v5.067l6 3.45"}),b("path",{d:"M18.786 8.986a3.501 3.501 0 0 0 -4.446 -5.266l-4.34 2.534v6.946"}),b("path",{d:"M18 16.302c1.391 .236 2.787 -.395 3.534 -1.689a3.474 3.474 0 0 0 -1.271 -4.745l-4.308 -2.514l-5.955 3.42"})]}),K),kw=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2"}),b("path",{d:"M4 16v2a2 2 0 0 0 2 2h2"}),b("path",{d:"M16 4h2a2 2 0 0 1 2 2v2"}),b("path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2"})]}),K),ts=R(H("g",{stroke:"currentColor",fill:"none",strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0"}),b("path",{d:"M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6"})]}),K),Sw=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10.585 10.587a2 2 0 0 0 2.829 2.828"}),b("path",{d:"M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87"}),b("path",{d:"M3 3l18 18"})]}),K),Mw=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15.5 13a3.5 3.5 0 0 0 -3.5 3.5v1a3.5 3.5 0 0 0 7 0v-1.8"}),b("path",{d:"M8.5 13a3.5 3.5 0 0 1 3.5 3.5v1a3.5 3.5 0 0 1 -7 0v-1.8"}),b("path",{d:"M17.5 16a3.5 3.5 0 0 0 0 -7h-.5"}),b("path",{d:"M19 9.3v-2.8a3.5 3.5 0 0 0 -7 0"}),b("path",{d:"M6.5 16a3.5 3.5 0 0 1 0 -7h.5"}),b("path",{d:"M5 9.3v-2.8a3.5 3.5 0 0 1 7 0v10"})]}),K),Pw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15.5 13a3.5 3.5 0 0 0 -3.5 3.5v1a3.5 3.5 0 0 0 7 0v-1.8"}),b("path",{d:"M8.5 13a3.5 3.5 0 0 1 3.5 3.5v1a3.5 3.5 0 0 1 -7 0v-1.8"}),b("path",{d:"M17.5 16a3.5 3.5 0 0 0 0 -7h-.5"}),b("path",{d:"M19 9.3v-2.8a3.5 3.5 0 0 0 -7 0"}),b("path",{d:"M6.5 16a3.5 3.5 0 0 1 0 -7h.5"}),b("path",{d:"M5 9.3v-2.8a3.5 3.5 0 0 1 7 0v10"})]}),K),ko=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"}),b("path",{d:"M21 21l-6 -6"})]}),K),Aw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M20.984 12.53a9 9 0 1 0 -7.552 8.355"}),b("path",{d:"M12 7v5l3 3"}),b("path",{d:"M19 16l-2 3h4l-2 3"})]}),K),Lw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 8l0 4l2 2"}),b("path",{d:"M3.05 11a9 9 0 1 1 .5 4m-.5 5v-5h5"})]}),K),_w=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M9 2m0 3a3 3 0 0 1 3 -3h0a3 3 0 0 1 3 3v5a3 3 0 0 1 -3 3h0a3 3 0 0 1 -3 -3z"}),b("path",{d:"M5 10a7 7 0 0 0 14 0"}),b("path",{d:"M8 21l8 0"}),b("path",{d:"M12 17l0 4"})]}),K),Dw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 3l18 18"}),b("path",{d:"M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1"}),b("path",{d:"M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85"}),b("path",{d:"M8 21l8 0"}),b("path",{d:"M12 17l0 4"})]}),K),ec=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M13 3l0 7l6 0l-8 11l0 -7l-6 0l8 -11"})]}),K),Rw=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 8m0 1a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-6a1 1 0 0 1 -1 -1z"}),b("path",{d:"M12 20v.01"}),b("path",{d:"M16 20v.01"}),b("path",{d:"M8 20v.01"}),b("path",{d:"M4 20v.01"}),b("path",{d:"M4 16v.01"}),b("path",{d:"M4 12v.01"}),b("path",{d:"M4 8v.01"}),b("path",{d:"M4 4v.01"}),b("path",{d:"M8 4v.01"}),b("path",{d:"M12 4v.01"}),b("path",{d:"M16 4v.01"}),b("path",{d:"M20 4v.01"}),b("path",{d:"M20 8v.01"}),b("path",{d:"M20 12v.01"}),b("path",{d:"M20 16v.01"}),b("path",{d:"M20 20v.01"})]}),K),Nw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 3v18"}),b("path",{d:"M19 21v-18"}),b("path",{d:"M5 7h14"}),b("path",{d:"M5 15h14"}),b("path",{d:"M8 13v4"}),b("path",{d:"M11 13v4"}),b("path",{d:"M16 13v4"}),b("path",{d:"M14 5v4"}),b("path",{d:"M11 5v4"}),b("path",{d:"M8 5v4"}),b("path",{d:"M3 21h18"})]}),K),Bw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 12l18 0"}),b("path",{d:"M7 16l10 0l-10 5l0 -5"}),b("path",{d:"M7 8l10 0l-10 -5l0 5"})]}),K),Fw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 3l0 18"}),b("path",{d:"M16 7l0 10l5 0l-5 -10"}),b("path",{d:"M8 7l0 10l-5 0l5 -10"})]}),K),Th=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v2a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z"}),b("path",{d:"M19 6h1a2 2 0 0 1 2 2a5 5 0 0 1 -5 5l-5 0v2"}),b("path",{d:"M10 15m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"})]}),K),os=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15 15m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0"}),b("path",{d:"M22 22l-3 -3"}),b("path",{d:"M6 18h-1a2 2 0 0 1 -2 -2v-1"}),b("path",{d:"M3 11v-1"}),b("path",{d:"M3 6v-1a2 2 0 0 1 2 -2h1"}),b("path",{d:"M10 3h1"}),b("path",{d:"M15 3h1a2 2 0 0 1 2 2v1"})]}),K),Ow=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),b("path",{d:"M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4"}),b("path",{d:"M4 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75"}),b("path",{d:"M10 15l2 6l2 -6"}),b("path",{d:"M20 15h-1a2 2 0 0 0 -2 2v2a2 2 0 0 0 2 2h1v-3"})]}),K),zw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),b("path",{d:"M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4"}),b("path",{d:"M20 15h-1a2 2 0 0 0 -2 2v2a2 2 0 0 0 2 2h1v-3"}),b("path",{d:"M5 18h1.5a1.5 1.5 0 0 0 0 -3h-1.5v6"}),b("path",{d:"M11 21v-6l3 6v-6"})]}),K),Hw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 13v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a2 2 0 0 0 6 0v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a8 8 0 0 1 -16 0"}),b("path",{d:"M4 8l5 0"}),b("path",{d:"M15 8l4 0"})]}),K),Gw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 14c.83 .642 2.077 1.017 3.5 1c1.423 .017 2.67 -.358 3.5 -1c.83 -.642 2.077 -1.017 3.5 -1c1.423 -.017 2.67 .358 3.5 1"}),b("path",{d:"M8 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"}),b("path",{d:"M12 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"}),b("path",{d:"M3 10h14v5a6 6 0 0 1 -6 6h-2a6 6 0 0 1 -6 -6v-5z"}),b("path",{d:"M16.746 16.726a3 3 0 1 0 .252 -5.555"})]}),K),Uw=R(H("g",{stroke:"currentColor",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 5a1 1 0 0 1 1-1h16a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-16a1 1 0 0 1-1-1v-10zM7 20h10M9 16v4M15 16v4"})]}),{...K,strokeWidth:1.5}),lee=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2"}),b("path",{d:"M21 12h-13l3 -3"}),b("path",{d:"M11 15l-3 -3"})]}),K),Ww=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M2 8a4 4 0 0 1 4 -4h12a4 4 0 0 1 4 4v8a4 4 0 0 1 -4 4h-12a4 4 0 0 1 -4 -4v-8z"}),b("path",{d:"M10 9l5 3l-5 3z"})]}),K),Yw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 6h18"}),b("path",{d:"M3 12h18"}),b("path",{d:"M3 18h18"}),b("path",{d:"M6 3v18"}),b("path",{d:"M12 3v18"}),b("path",{d:"M18 3v18"})]}),K),Vw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M17 3m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"}),b("path",{d:"M3 17m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"}),b("path",{d:"M17 5c-6.627 0 -12 5.373 -12 12"})]}),K),ns=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 18l12 -12"}),b("path",{d:"M18 10v-4h-4"})]}),K),rs=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4,19L10,19C11.097,19 12,18.097 12,17L12,9C12,7.903 12.903,7 14,7L21,7"}),b("path",{d:"M18 4l3 3l-3 3"})]}),K),is=R(H("g",{children:[b("path",{d:"M16,12L20,9L16,6"}),b("path",{d:"M6 20c0 -6.075 4.925 -11 11 -11h3"})]}),K),fm=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 9l6 6l6 -6"})]}),K),$w=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 15l6 -6l6 6"})]}),K),Kw=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 15l6 -6l6 6"})]}),K),Ch=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 5v10a1 1 0 0 0 1 1h10"}),b("path",{d:"M5 8h10a1 1 0 0 1 1 1v10"})]}),K),bm=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 5m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M19 5m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M5 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M19 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M5 7l0 10"}),b("path",{d:"M7 5l10 0"}),b("path",{d:"M7 19l10 0"}),b("path",{d:"M19 7l0 10"})]}),K),cee=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 11v8a1 1 0 0 0 1 1h8m-9 -14v-1a1 1 0 0 1 1 -1h1m5 0h2m5 0h1a1 1 0 0 1 1 1v1m0 5v2m0 5v1a1 1 0 0 1 -1 1h-1"}),b("path",{d:"M4 12h7a1 1 0 0 1 1 1v7"})]}),K),Xw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M14 6m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 6l8 0"}),b("path",{d:"M16 6l4 0"}),b("path",{d:"M8 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 12l2 0"}),b("path",{d:"M10 12l10 0"}),b("path",{d:"M17 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 18l11 0"}),b("path",{d:"M19 18l1 0"})]}),K),Zw=R(H("g",{strokeWidth:1,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 10l4 -4 L6 14l8 -8 L6 18l12 -12 L10 18l8 -8 L14 18l4 -4"})]}),K),jw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 20h4l10.5 -10.5a2.828 2.828 0 1 0 -4 -4l-10.5 10.5v4"}),b("path",{d:"M13.5 6.5l4 4"})]}),K),dee=R(H("g",{strokeWidth:1,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M11 7l-5 5l5 5"}),b("path",{d:"M17 7l-5 5l5 5"})]}),K),qw=R(H("g",{strokeWidth:"1.75",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"}),b("path",{d:"M15 4l0 16"})]}),K),mee=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1"})]}),K),pee=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 4l18 0"}),b("path",{d:"M4 4v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-10"}),b("path",{d:"M12 16l0 4"}),b("path",{d:"M9 20l6 0"}),b("path",{d:"M8 12l3 -3l2 2l3 -3"})]}),K),Jw=b("div",{style:{width:"1rem",height:"1rem"}}),Qw=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("polyline",{points:"9 6 15 12 9 18"})]}),K),ev=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M14 6m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 6l8 0"}),b("path",{d:"M16 6l4 0"}),b("path",{d:"M8 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 12l2 0"}),b("path",{d:"M10 12l10 0"}),b("path",{d:"M17 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 18l11 0"}),b("path",{d:"M19 18l1 0"})]}),K);import tv from"clsx";import Sh,{useEffect as GA,useRef as ov,useState as UA}from"react";import{isPromiseLike as WA}from"@orangecatai/common";import zA from"react";import{jsx as kh}from"react/jsx-runtime";var HA=({size:e="1em",circleWidth:t=8,synchronized:o=!1,className:n=""})=>{let i=-(zA.useRef(Date.now()).current%1600);return kh("div",{className:`Spinner ${n}`,children:kh("svg",{viewBox:"0 0 100 100",style:{width:e,height:e,"--spinner-delay":o?`${i}ms`:0},children:kh("circle",{cx:"50",cy:"50",r:50-t/2,strokeWidth:t,fill:"none",strokeMiterlimit:"10"})})})},Gt=HA;import{jsx as tc,jsxs as oc}from"react/jsx-runtime";var ne=Sh.forwardRef(({size:e="medium",visible:t=!0,className:o="",...n},r)=>{let{id:i}=qe(),a=Sh.useRef(null);Sh.useImperativeHandle(r,()=>a.current);let s=`ToolIcon_size_${e}`,[l,c]=UA(!1),m=ov(!0),p=async u=>{let h="onClick"in n&&n.onClick?.(u);if(WA(h))try{c(!0),await h}catch(g){if(g instanceof Ra)console.warn(g);else throw g}finally{m.current&&c(!1)}};GA(()=>(m.current=!0,()=>{m.current=!1}),[]);let d=ov(null);if(n.type==="button"||n.type==="icon"||n.type==="submit"){let u=n.type==="icon"?"button":n.type;return oc("button",{className:tv("ToolIcon_type_button",s,o,t&&!n.hidden?"ToolIcon_type_button--show":"ToolIcon_type_button--hide",{ToolIcon:!n.hidden,"ToolIcon--selected":n.selected,"ToolIcon--plain":n.type==="icon"}),style:n.style,"data-testid":n["data-testid"],hidden:n.hidden,title:n.title,"aria-label":n["aria-label"],type:u,onClick:p,ref:a,disabled:l||n.isLoading||!!n.disabled,children:[(n.icon||n.label)&&oc("div",{className:"ToolIcon__icon","aria-hidden":"true","aria-disabled":!!n.disabled,children:[n.icon||n.label,n.keyBindingLabel&&tc("span",{className:"ToolIcon__keybinding",children:n.keyBindingLabel}),n.isLoading&&tc(Gt,{})]}),n.showAriaLabel&&oc("div",{className:"ToolIcon__label",children:[n["aria-label"]," ",l&&tc(Gt,{})]}),n.children]})}return oc("label",{className:tv("ToolIcon",o),title:n.title,onPointerDown:u=>{d.current=u.pointerType||null,n.onPointerDown?.({pointerType:u.pointerType||null})},onPointerUp:()=>{requestAnimationFrame(()=>{d.current=null})},children:[tc("input",{className:`ToolIcon_type_radio ${s}`,type:"radio",name:n.name,"aria-label":n["aria-label"],"aria-keyshortcuts":n["aria-keyshortcuts"],"data-testid":n["data-testid"],id:`${i}-${n.id}`,onChange:()=>{n.onChange?.({pointerType:d.current})},checked:n.checked,ref:a}),oc("div",{className:"ToolIcon__icon",children:[n.icon,n.keyBindingLabel&&tc("span",{className:"ToolIcon__keybinding",children:n.keyBindingLabel})]})]})});ne.displayName="ToolButton";var xm=[],W=e=>(xm=xm.concat(e),e);import{jsx as JA}from"react/jsx-runtime";var qA=(e,t,o)=>{let n=new Set(le(e.filter(m=>XA(m)),t).map(m=>m.id)),r={},i=o.scene.getNonDeletedElementsMap(),a=new Set;for(let m of n){let p=ZA(e,m);for(let d of p)if(!a.has(d.id)){if(Em(d)){let u=rv(d,i);u&&(r[u.id]=!0)}else r[d.id]=!0;a.add(d.id)}}let s=!0,l=e.map(m=>{if(t.selectedElementIds[m.id]){let p=Em(m)?rv(m,i):null;return m.frameId&&n.has(m.frameId)?(s=!1,r[m.id]=!0,m):p?.frameId&&n.has(p?.frameId)?m:(m.boundElements&&m.boundElements.forEach(d=>{let u=o.scene.getNonDeletedElementsMap().get(d.id);u&&KA(u)&&o.scene.mutateElement(u,{startBinding:m.id===u.startBinding?.elementId?null:u.startBinding,endBinding:m.id===u.endBinding?.elementId?null:u.endBinding})}),wm(m,{isDeleted:!0}))}return m.frameId&&n.has(m.frameId)?(s=!1,Em(m)||(r[m.id]=!0),wm(m,{frameId:null})):Em(m)&&t.selectedElementIds[m.containerId]?wm(m,{isDeleted:!0}):m}),c=t.editingGroupId;if(s&&t.editingGroupId){let m=Ah(l,t.editingGroupId).filter(p=>!p.isDeleted);if(m.length>1)m[0]&&(r[m[0].id]=!0);else{c=null,m[0]&&(r[m[0].id]=!0);let p=m[0];if(p){let d=p.groupIds.findIndex(h=>h===t.editingGroupId),u=p.groupIds[d+1];if(u){let h=Ah(l,u).filter(g=>!g.isDeleted);h.length>1&&(c=u,h.forEach(g=>{r[g.id]=!0}))}}}}return{elements:l,appState:{...t,...jA({selectedElementIds:r,editingGroupId:c},l,t,null)}}},iv=(e,t)=>{if(e.editingGroupId){let o=Ah(Ph(t),e.editingGroupId);if(o.length)return{...e,selectedElementIds:{[o[0].id]:!0}}}return e},nc=W({name:"deleteSelectedElements",label:"labels.delete",icon:Ht,trackEvent:{category:"element",action:"delete"},perform:(e,t,o,n)=>{if(t.selectedLinearElement?.isEditing){let{elementId:a,selectedPointsIndices:s}=t.selectedLinearElement,l=n.scene.getNonDeletedElementsMap(),c=nv.getElement(a,l);if(!c||s==null)return!1;if(s.length>=c.points.length){let m=e.map(d=>d.id===c.id?wm(d,{isDeleted:!0}):d),p=iv(t,m);return{elements:m,appState:{...p,selectedLinearElement:null},captureUpdate:ym.IMMEDIATELY}}return nv.deletePoints(c,n,s),{elements:e,appState:{...t,selectedLinearElement:{...t.selectedLinearElement,selectedPointsIndices:s?.[0]>0?[s[0]-1]:[0]}},captureUpdate:ym.IMMEDIATELY}}let{elements:r,appState:i}=qA(e,t,n);return $A(r,r.filter(a=>a.isDeleted)),i=iv(i,r),{elements:r,appState:{...i,activeTool:VA(t,{type:n.state.preferredSelectionTool.type}),multiElement:null,newElement:null,activeEmbeddable:null,selectedLinearElement:null},captureUpdate:He(Ph(e),t)?ym.IMMEDIATELY:ym.EVENTUALLY}},keyTest:(e,t,o)=>(e.key===Mh.BACKSPACE||e.key===Mh.DELETE)&&!e[Mh.CTRL_OR_CMD],PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>{let r=_t()==="mobile";return JA(ne,{type:"button",icon:Ht,title:f("labels.delete"),"aria-label":f("labels.delete"),onClick:()=>o(null),disabled:!He(Ph(e),t),style:{...r&&t.openPopup!=="compactOtherProperties"?YA:{}}})}});import{KEYS as as,CODES as ss,isDarwin as vm}from"@orangecatai/common";import{moveOneLeft as QA,moveOneRight as eL,moveAllLeft as tL,moveAllRight as oL}from"@orangecatai/element";import{CaptureUpdateAction as Im}from"@orangecatai/element";import{isDarwin as av}from"@orangecatai/common";var G=e=>e.replace(/\b(Opt(?:ion)?|Alt)\b/i,av?f("keys.option"):f("keys.alt")).replace(/\bShift\b/i,f("keys.shift")).replace(/\b(Enter|Return)\b/i,f("keys.enter")).replace(/\b(Ctrl|Cmd|Command|CtrlOrCmd)\b/gi,av?f("keys.cmd"):f("keys.ctrl")).replace(/\b(Esc(?:ape)?)\b/i,f("keys.escape")).replace(/\b(Space(?:bar)?)\b/i,f("keys.spacebar")).replace(/\b(Del(?:ete)?)\b/i,f("keys.delete"));import{jsx as Tm}from"react/jsx-runtime";var Lh=W({name:"sendBackward",label:"labels.sendBackward",keywords:["move down","zindex","layer"],icon:dh,trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:QA(e,t,n.scene),appState:t,captureUpdate:Im.IMMEDIATELY}),keyPriority:40,keyTest:e=>e[as.CTRL_OR_CMD]&&!e.shiftKey&&e.code===ss.BRACKET_LEFT,PanelComponent:({updateData:e,appState:t})=>Tm("button",{type:"button",className:"zIndexButton",onClick:()=>e(null),title:`${f("labels.sendBackward")} \u2014 ${G("CtrlOrCmd+[")}`,children:dh})}),_h=W({name:"bringForward",label:"labels.bringForward",keywords:["move up","zindex","layer"],icon:ch,trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:eL(e,t,n.scene),appState:t,captureUpdate:Im.IMMEDIATELY}),keyPriority:40,keyTest:e=>e[as.CTRL_OR_CMD]&&!e.shiftKey&&e.code===ss.BRACKET_RIGHT,PanelComponent:({updateData:e,appState:t})=>Tm("button",{type:"button",className:"zIndexButton",onClick:()=>e(null),title:`${f("labels.bringForward")} \u2014 ${G("CtrlOrCmd+]")}`,children:ch})}),Dh=W({name:"sendToBack",label:"labels.sendToBack",keywords:["move down","zindex","layer"],icon:ph,trackEvent:{category:"element"},perform:(e,t)=>({elements:tL(e,t),appState:t,captureUpdate:Im.IMMEDIATELY}),keyTest:e=>vm?e[as.CTRL_OR_CMD]&&e.altKey&&e.code===ss.BRACKET_LEFT:e[as.CTRL_OR_CMD]&&e.shiftKey&&e.code===ss.BRACKET_LEFT,PanelComponent:({updateData:e,appState:t})=>Tm("button",{type:"button",className:"zIndexButton",onClick:()=>e(null),title:`${f("labels.sendToBack")} \u2014 ${vm?G("CtrlOrCmd+Alt+["):G("CtrlOrCmd+Shift+[")}`,children:ph})}),Rh=W({name:"bringToFront",label:"labels.bringToFront",keywords:["move up","zindex","layer"],icon:mh,trackEvent:{category:"element"},perform:(e,t)=>({elements:oL(e,t),appState:t,captureUpdate:Im.IMMEDIATELY}),keyTest:e=>vm?e[as.CTRL_OR_CMD]&&e.altKey&&e.code===ss.BRACKET_RIGHT:e[as.CTRL_OR_CMD]&&e.shiftKey&&e.code===ss.BRACKET_RIGHT,PanelComponent:({updateData:e,appState:t})=>Tm("button",{type:"button",className:"zIndexButton",onClick:o=>e(null),title:`${f("labels.bringToFront")} \u2014 ${vm?G("CtrlOrCmd+Alt+]"):G("CtrlOrCmd+Shift+]")}`,children:mh})});import{getNonDeletedElements as nL}from"@orangecatai/element";import{LinearElementEditor as rL}from"@orangecatai/element";import{isLinearElement as iL,isTextElement as aL}from"@orangecatai/element";import{arrayToMap as sL,KEYS as sv}from"@orangecatai/common";import{selectGroupsForSelectedElements as lL}from"@orangecatai/element";import{CaptureUpdateAction as cL}from"@orangecatai/element";var Nh=W({name:"selectAll",label:"labels.selectAll",icon:Rw,trackEvent:{category:"canvas"},viewMode:!1,perform:(e,t,o,n)=>{if(t.selectedLinearElement?.isEditing)return!1;let r=e.filter(i=>!i.isDeleted&&!(aL(i)&&i.containerId)&&!i.locked).reduce((i,a)=>(i[a.id]=!0,i),{});return{appState:{...t,...lL({editingGroupId:null,selectedElementIds:r},nL(e),t,n),selectedLinearElement:Object.keys(r).length===1&&iL(e[0])?new rL(e[0],sL(e)):null},captureUpdate:cL.IMMEDIATELY}},keyTest:e=>e[sv.CTRL_OR_CMD]&&e.key===sv.A});import{DEFAULT_GRID_SIZE as lv,KEYS as cv,MOBILE_ACTION_BUTTON_BG as dL,arrayToMap as dv}from"@orangecatai/common";import{getNonDeletedElements as mv}from"@orangecatai/element";import{LinearElementEditor as mL}from"@orangecatai/element";import{getSelectedElements as pL,getSelectionStateForElements as uL}from"@orangecatai/element";import{syncMovedIndices as gL}from"@orangecatai/element";import{duplicateElements as hL}from"@orangecatai/element";import{CaptureUpdateAction as pv}from"@orangecatai/element";import{jsx as fL}from"react/jsx-runtime";var Bh=W({name:"duplicateSelection",label:"labels.duplicateSelection",icon:Xl,trackEvent:{category:"element"},perform:(e,t,o,n)=>{if(t.selectedElementsAreBeingDragged)return!1;if(t.selectedLinearElement?.isEditing)try{let a=mL.duplicateSelectedPoints(t,n.scene);return{elements:e,appState:a,captureUpdate:pv.IMMEDIATELY}}catch{return!1}let{duplicatedElements:r,elementsWithDuplicates:i}=hL({type:"in-place",elements:e,idsOfElementsToDuplicate:dv(pL(e,t,{includeBoundTextElement:!0,includeElementsInFrames:!0})),appState:t,randomizeSeed:!0,overrides:({origElement:a,origIdToDuplicateId:s})=>{let l=a.frameId&&s.get(a.frameId);return{x:a.x+lv/2,y:a.y+lv/2,frameId:l??a.frameId}}});if(n.props.onDuplicate&&i){let a=n.props.onDuplicate(i,e);a&&(i=a)}return{elements:gL(i,dv(r)),appState:{...t,...uL(r,mv(i),t)},captureUpdate:pv.IMMEDIATELY}},keyTest:e=>e[cv.CTRL_OR_CMD]&&e.key===cv.D,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>{let r=_t()==="mobile";return fL(ne,{type:"button",icon:Xl,title:`${f("labels.duplicateSelection")} \u2014 ${G("CtrlOrCmd+D")}`,"aria-label":f("labels.duplicateSelection"),onClick:()=>o(null),disabled:!He(mv(e),t),style:{...r&&t.openPopup!=="compactOtherProperties"?dL:{}}})}});import{pointFrom as fD}from"@orangecatai/math";import{useEffect as af,useMemo as bD,useRef as sf,useState as xD}from"react";import{DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE as ED,DEFAULT_ELEMENT_BACKGROUND_PICKS as yD,DEFAULT_ELEMENT_STROKE_COLOR_PALETTE as wD,DEFAULT_ELEMENT_STROKE_PICKS as vD,ARROW_TYPE as Uo,DEFAULT_FONT_FAMILY as ID,DEFAULT_FONT_SIZE as TD,FONT_FAMILY as CD,ROUNDNESS as Gm,STROKE_WIDTH as lf,VERTICAL_ALIGN as zm,KEYS as hs,randomInteger as kD,arrayToMap as df,getFontFamilyString as SD,getLineHeight as MD,isTransparent as PD,reduceToCommonValue as AD,invariant as mf,FONT_SIZES as Hm}from"@orangecatai/common";import{canBecomePolygon as LD,getNonDeletedElements as o2}from"@orangecatai/element";import{bindBindingElement as Jv,calculateFixedPointForElbowArrowBinding as Qv,updateBoundElements as _D}from"@orangecatai/element";import{LinearElementEditor as Yi}from"@orangecatai/element";import{newElementWith as kt}from"@orangecatai/element";import{getBoundTextElement as $r,redrawTextBoundingBox as hc}from"@orangecatai/element";import{isArrowElement as Um,isBoundToContainer as DD,isElbowArrow as n2,isLinearElement as cf,isLineElement as e2,isTextElement as uo,isUsingAdaptiveRadius as RD}from"@orangecatai/element";import{hasStrokeColor as ND}from"@orangecatai/element";import{updateElbowArrowPoints as BD,CaptureUpdateAction as St,toggleLinePolygonState as FD}from"@orangecatai/element";import{deriveStylesPanelMode as OD}from"@orangecatai/common";import{isDevEnv as bL}from"@orangecatai/common";var xL=new Set(["command_palette","export"]),ge=(e,t,o,n)=>{try{if(typeof window>"u"||C.VITE_WORKER_ID||C.VITE_APP_ENABLE_TRACKING!=="true"||!xL.has(e)||bL())return;C.PROD||console.info("trackEvent",{category:e,action:t,label:o,value:n}),window.sa_event&&window.sa_event(t,{category:e,label:o,value:n})}catch(r){console.error("error during analytics",r)}};import vL from"clsx";import EL from"clsx";import{forwardRef as yL}from"react";import{jsx as wL}from"react/jsx-runtime";var ls=yL((e,t)=>{let{title:o,className:n,testId:r,active:i,standalone:a,icon:s,onClick:l}=e;return wL("button",{type:"button",ref:t,title:o,"data-testid":r,className:EL(n,{standalone:a,active:i}),onClick:l,style:e.style,children:s},o)});import{Fragment as TL,jsx as Fh,jsxs as IL}from"react/jsx-runtime";var Oo=e=>Fh(TL,{children:e.options.map(t=>e.type==="button"?Fh(ls,{icon:t.icon,title:t.text,testId:t.testId,active:t.active??e.value===t.value,onClick:o=>e.onClick(t.value,o)},t.text):IL("label",{className:vL({active:e.value===t.value}),title:t.text,children:[Fh("input",{type:"radio",name:e.group,onChange:()=>e.onChange(t.value),checked:e.value===t.value,"data-testid":t.testId}),t.icon]},t.text))});import{Popover as _v}from"radix-ui";import Dv from"clsx";import{useRef as Rv,useEffect as k_}from"react";import{COLOR_OUTLINE_CONTRAST_THRESHOLD as Av,COLOR_PALETTE as Nv,isColorDark as Lv,isWritableElement as S_}from"@orangecatai/common";import{jsx as CL}from"react/jsx-runtime";var Cm=()=>CL("div",{style:{width:1,height:"1rem",backgroundColor:"var(--default-border-color)",margin:"0 auto"}});import{useEffect as AL,useRef as LL}from"react";import{createPortal as _L}from"react-dom";import{EVENT as Or,KEYS as DL,rgbToHex as RL}from"@orangecatai/common";import uv from"react";var Oh=uv.createContext(null),ye=()=>uv.useContext(Oh);import{useState as kL,useLayoutEffect as gv}from"react";import{THEME as SL}from"@orangecatai/common";var km=e=>{let[t,o]=kL(null),n=we(),{theme:r}=ye(),{container:i}=qe();return gv(()=>{t&&(t.className="",t.classList.add("excalidraw",...e?.className?.split(/\s+/)||[]),t.classList.toggle("excalidraw--mobile",n.formFactor==="phone"),t.classList.toggle("theme--dark",r===SL.DARK))},[t,r,n.formFactor,e?.className]),gv(()=>{let a=e?.parentSelector?i?.querySelector(e.parentSelector):document.body;if(!a)return;let s=document.createElement("div");return a.appendChild(s),o(s),()=>{a.removeChild(s)}},[i,e?.parentSelector]),t};import{useEffect as ML}from"react";import{EVENT as Sm}from"@orangecatai/common";function cs(e,t,o){ML(()=>{function n(r){let i=r;if(!e.current)return;let a=o?.(i,e.current);if(a===!0)return;if(a===!1)return t(i);e.current.contains(i.target)||!document.documentElement.contains(i.target)||i.target.closest("[data-radix-portal]")||i.target===document.documentElement&&document.body.style.pointerEvents==="none"||i.target.closest("[data-prevent-outside-click]")||t(i)}return document.addEventListener(Sm.POINTER_DOWN,n),document.addEventListener(Sm.TOUCH_START,n),()=>{document.removeEventListener(Sm.POINTER_DOWN,n),document.removeEventListener(Sm.TOUCH_START,n)}},[e,t,o])}import{useRef as PL}from"react";var Fr=e=>{let t=PL(e);return Object.assign(t.current,e),t.current};import{jsx as NL}from"react/jsx-runtime";var zr=Ce(null),hv=({onCancel:e,onChange:t,onSelect:o,colorPickerType:n})=>{let r=km({className:"excalidraw-eye-dropper-backdrop",parentSelector:".excalidraw-eye-dropper-container"}),i=ye(),a=Hr(),s=Qe(),l=le(a,i),c=Fr({app:s,onCancel:e,onChange:t,onSelect:o,selectedElements:l}),{container:m}=qe();AL(()=>{let d=p.current;if(!d||!s.canvas||!r)return;let u=!1,h=s.canvas.getContext("2d"),g=({clientX:k,clientY:L})=>{let S=h.getImageData((k-i.offsetLeft)*window.devicePixelRatio,(L-i.offsetTop)*window.devicePixelRatio,1,1).data;return RL(S[0],S[1],S[2])},E=({clientX:k,clientY:L,altKey:S})=>{d.style.top=`${L+20}px`,d.style.left=`${k+20}px`;let _=g({clientX:k,clientY:L});u&&c.onChange(n,_,c.selectedElements,{altKey:S}),d.style.background=_},w=()=>{c.onCancel()},x=(k,L)=>{c.onSelect(k,L)},y=k=>{u=!0,k.stopImmediatePropagation()},v=k=>{u=!1,m?.focus(),k.stopImmediatePropagation(),k.preventDefault(),x(g(k),k)},I=k=>{k.key===DL.ESCAPE&&(k.preventDefault(),k.stopImmediatePropagation(),w())};return r.tabIndex=-1,r.focus(),E({clientX:c.app.lastViewportPosition.x,clientY:c.app.lastViewportPosition.y,altKey:!1}),r.addEventListener(Or.KEYDOWN,I),r.addEventListener(Or.POINTER_DOWN,y),r.addEventListener(Or.POINTER_UP,v),window.addEventListener("pointermove",E,{passive:!0}),window.addEventListener(Or.BLUR,w),()=>{u=!1,r.removeEventListener(Or.KEYDOWN,I),r.removeEventListener(Or.POINTER_DOWN,y),r.removeEventListener(Or.POINTER_UP,v),window.removeEventListener("pointermove",E),window.removeEventListener(Or.BLUR,w)}},[c,s.canvas,r,n,m,i.offsetLeft,i.offsetTop]);let p=LL(null);return cs(p,()=>{e()},d=>!!d.target.closest(".excalidraw-eye-dropper-trigger, .excalidraw-eye-dropper-backdrop")),r?_L(NL("div",{ref:p,className:"excalidraw-eye-dropper-preview"}),r):null};import{Popover as zh}from"radix-ui";import zL from"clsx";import HL from"react";import{isInteractive as GL}from"@orangecatai/common";import BL from"react";import FL from"clsx";import{jsx as OL}from"react/jsx-runtime";var ut=BL.forwardRef(({children:e,padding:t,className:o,style:n},r)=>OL("div",{className:FL("Island",o),style:{"--padding":t,...n},ref:r,children:e}));import{jsx as Hh,jsxs as UL}from"react/jsx-runtime";var cr=HL.forwardRef(({className:e,container:t,children:o,style:n,onClose:r,onKeyDown:i,onFocusOutside:a,onPointerLeave:s,onPointerDownOutside:l,preventAutoFocusOnTouch:c=!1},m)=>{let p=we(),d=p.formFactor==="phone"&&!p.isLandscape;return Hh(zh.Portal,{container:t,children:UL(zh.Content,{ref:m,className:zL("focus-visible-none",e),"data-prevent-outside-click":!0,side:d?"bottom":"right",align:d?"center":"start",alignOffset:-16,sideOffset:20,collisionBoundary:t??void 0,style:{zIndex:"var(--zIndex-ui-styles-popup)",marginLeft:p.formFactor==="phone"?"0.5rem":void 0},onPointerLeave:s,onKeyDown:i,onFocusOutside:a,onPointerDownOutside:l,onOpenAutoFocus:u=>{c&&p.isTouchScreen&&u.preventDefault()},onCloseAutoFocus:u=>{u.stopPropagation(),u.preventDefault(),t&&!GL(document.activeElement)&&t.focus(),r()},children:[Hh(ut,{padding:3,style:n,children:o}),Hh(zh.Arrow,{width:20,height:10,style:{fill:"var(--popup-bg-color)",filter:"drop-shadow(rgba(0, 0, 0, 0.05) 0px 3px 2px)"}})]})})});import{useState as WL,useCallback as Gh}from"react";var Mm=()=>document.querySelector(".excalidraw-wysiwyg"),Pm=()=>{let e=Mm();return e?{start:e.selectionStart,end:e.selectionEnd}:null},rc=e=>{setTimeout(()=>{let t=Mm();t&&(t.focus(),e&&(t.selectionStart=e.start,t.selectionEnd=e.end))},0)},ic=(e,t,o,n)=>{t&&n&&n();let r=t&&o?Pm():null;e(),t&&o&&rc(r)},fv=()=>{let[e,t]=WL(null),o=Gh(()=>{let i=Pm();t(i)},[]),n=Gh(()=>{setTimeout(()=>{let i=Mm();i&&(i.focus(),e&&(i.selectionStart=e.start,i.selectionEnd=e.end,t(null)))},0)},[e]),r=Gh(()=>{t(null)},[]);return{saveCaretPosition:o,restoreCaretPosition:n,clearSavedPosition:r,hasSavedPosition:!!e}},bv=(e=100)=>{let t=Mm();if(t){let o=t.onblur;t.onblur=null,setTimeout(()=>{t.onblur=o},e)}};import VL from"clsx";import{useCallback as $L,useEffect as Wh,useRef as Ev,useState as KL}from"react";import{KEYS as Yh,normalizeInputColor as XL}from"@orangecatai/common";import{MAX_CUSTOM_COLORS_USED_IN_CANVAS as YL}from"@orangecatai/common";var Gr=({palette:e,color:t})=>{if(!t)return null;for(let[o,n]of Object.entries(e))if(Array.isArray(n)){let r=n.indexOf(t);if(r>-1)return{colorName:o,shade:r}}else if(n===t)return{colorName:o,shade:null};return null},ac=[["q","w","e","r","t"],["a","s","d","f","g"],["z","x","c","v","b"]].flat(),Uh=({color:e,palette:t})=>!Object.values(t).flat().includes(e),xv=(e,t,o)=>{let n={elementBackground:"backgroundColor",elementStroke:"strokeColor"},r=e.filter(a=>{if(a.isDeleted)return!1;let s=a[n[t]];return Uh({color:s,palette:o})}),i=new Map;return r.forEach(a=>{let s=a[n[t]];i.has(s)?i.set(s,i.get(s)+1):i.set(s,1)}),[...i.entries()].sort((a,s)=>s[1]-a[1]).map(a=>a[0]).slice(0,YL)},zo=Ce(null);import{Fragment as ZL,jsx as Am,jsxs as yv}from"react/jsx-runtime";var wv=({color:e,onChange:t,label:o,colorPickerType:n,placeholder:r})=>{let i=we(),[a,s]=KL(e),[l,c]=ae(zo);Wh(()=>{s(e)},[e]);let m=$L(g=>{let E=g.toLowerCase(),w=XL(E);w&&t(w),s(E)},[t]),p=Ev(null),d=Ev(null);Wh(()=>{p.current&&p.current.focus()},[l]);let[u,h]=ae(zr);return Wh(()=>()=>{h(null)},[h]),yv("div",{className:"color-picker__input-label",children:[Am("div",{className:"color-picker__input-hash",children:"#"}),Am("input",{ref:l==="hex"?p:void 0,style:{border:0,padding:0},spellCheck:!1,className:"color-picker-input","aria-label":o,onChange:g=>{m(g.target.value)},value:(a||"").replace(/^#/,""),onBlur:()=>{s(e)},tabIndex:-1,onFocus:()=>c("hex"),onKeyDown:g=>{g.key!==Yh.TAB&&(g.key===Yh.ESCAPE&&d.current?.focus(),g.stopPropagation())},placeholder:r}),i.formFactor!=="phone"&&yv(ZL,{children:[Am("div",{style:{width:"1px",height:"1.25rem",backgroundColor:"var(--default-border-color)"}}),Am("div",{ref:d,className:VL("excalidraw-eye-dropper-trigger",{selected:u}),onClick:()=>h(g=>g?null:{keepOpenOnAlt:!1,onSelect:E=>t(E),colorPickerType:n}),title:`${f("labels.eyeDropper")} \u2014 ${Yh.I.toLocaleUpperCase()} or ${G("Alt")} `,children:vw})]})]})};import Xh,{useEffect as Zh,useImperativeHandle as h_,useState as f_}from"react";import{EVENT as Sv}from"@orangecatai/common";import{DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX as b_,DEFAULT_ELEMENT_STROKE_COLOR_INDEX as x_,KEYS as E_}from"@orangecatai/common";import QL from"clsx";import{useEffect as e_,useRef as t_}from"react";import{isColorDark as jL}from"@orangecatai/common";import{jsxs as JL}from"react/jsx-runtime";var qL=({color:e,keyLabel:t,isShade:o=!1})=>JL("div",{className:"color-picker__button__hotkey-label",style:{color:jL(e)?"#fff":"#000"},children:[o&&"\u21E7",t]}),ds=qL;import{jsx as Vh,jsxs as o_}from"react/jsx-runtime";var vv=({colors:e,color:t,onChange:o,label:n})=>{let[r,i]=ae(zo),a=t_(null);return e_(()=>{a.current&&a.current.focus()},[t,r]),Vh("div",{className:"color-picker-content--default",children:e.map((s,l)=>o_("button",{ref:t===s?a:void 0,tabIndex:-1,type:"button",className:QL("color-picker__button color-picker__button--large has-outline",{active:t===s,"is-transparent":s==="transparent"||!s}),onClick:()=>{o(s),i("custom")},title:s,"aria-label":n,style:{"--swatch-color":s},children:[Vh("div",{className:"color-picker__button-outline"}),Vh(ds,{color:s,keyLabel:l+1})]},l))})};import n_ from"clsx";import{useEffect as r_,useRef as i_}from"react";import{jsx as $h,jsxs as s_}from"react/jsx-runtime";var a_=({palette:e,color:t,onChange:o,activeShade:n,showHotKey:r=!0})=>{let i=Gr({color:t,palette:e}),[a,s]=ae(zo),l=i_(null);return r_(()=>{l.current&&a==="baseColors"&&l.current.focus()},[i?.colorName,a]),$h("div",{className:"color-picker-content--default",children:Object.entries(e).map(([c,m],p)=>{let d=(Array.isArray(m)?m[n]:m)||"transparent",u=ac[p],h=f(`colors.${c.replace(/\d+/,"")}`,null,"");return s_("button",{ref:i?.colorName===c?l:void 0,tabIndex:-1,type:"button",className:n_("color-picker__button color-picker__button--large has-outline",{active:i?.colorName===c,"is-transparent":d==="transparent"||!d}),onClick:()=>{o(d),s("baseColors")},title:`${h}${d.startsWith("#")?` ${d}`:""} \u2014 ${u}`,"aria-label":`${h} \u2014 ${u}`,style:d?{"--swatch-color":d}:void 0,"data-testid":`color-${c}`,children:[$h("div",{className:"color-picker__button-outline"}),r&&$h(ds,{color:d,keyLabel:u})]},c)})})},Iv=a_;import{jsx as c_}from"react/jsx-runtime";var l_=({children:e})=>c_("div",{className:"color-picker__heading",children:e}),ms=l_;import d_ from"clsx";import{useEffect as m_,useRef as p_}from"react";import{jsx as sc,jsxs as Tv}from"react/jsx-runtime";var Cv=({color:e,onChange:t,palette:o,showHotKey:n})=>{let r=Gr({color:e||"transparent",palette:o}),[i,a]=ae(zo),s=p_(null);if(m_(()=>{s.current&&i==="shades"&&s.current.focus()},[r,i]),r){let{colorName:l,shade:c}=r,m=o[l];if(Array.isArray(m))return sc("div",{className:"color-picker-content--default shades",children:m.map((p,d)=>Tv("button",{ref:d===c&&i==="shades"?s:void 0,tabIndex:-1,type:"button",className:d_("color-picker__button color-picker__button--large has-outline",{active:d===c}),"aria-label":"Shade",title:`${l} - ${d+1}`,style:p?{"--swatch-color":p}:void 0,onClick:()=>{t(p),a("shades")},children:[sc("div",{className:"color-picker__button-outline"}),n&&sc(ds,{color:p,keyLabel:d+1,isShade:!0})]},d))})}return Tv("div",{className:"color-picker-content--default",style:{position:"relative"},tabIndex:-1,children:[sc("button",{type:"button",tabIndex:-1,className:"color-picker__button color-picker__button--large color-picker__button--no-focus-visible"}),sc("div",{tabIndex:-1,style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",fontSize:"0.75rem"},children:f("colorPicker.noShades")})]})};import{COLORS_PER_ROW as ps,COLOR_PALETTE as u_,KEYS as lc}from"@orangecatai/common";var Kh=(e,t,o)=>{let n=Math.ceil(o/ps);switch(t=t??-1,e){case"ArrowLeft":{let r=t-1;return r<0?o-1:r}case"ArrowRight":return(t+1)%o;case"ArrowDown":{let r=t+ps;return r>=o?t%ps:r}case"ArrowUp":{let r=t-ps,i=r<0?ps*n+r:r;return i>=o?void 0:i}}},g_=({e,colorObj:t,onChange:o,palette:n,customColors:r,setActiveColorPickerSection:i,activeShade:a})=>{if(t?.shade!=null&&["Digit1","Digit2","Digit3","Digit4","Digit5"].includes(e.code)&&e.shiftKey){let s=Number(e.code.slice(-1))-1;return o(n[t.colorName][s]),i("shades"),!0}if(["1","2","3","4","5"].includes(e.key)&&r[Number(e.key)-1])return o(r[Number(e.key)-1]),i("custom"),!0;if(ac.includes(e.key)){let s=ac.indexOf(e.key),l=Object.keys(n)[s],c=n[l],m=Array.isArray(c)?c[a]:c;return o(m),i("baseColors"),!0}return!1},kv=({event:e,activeColorPickerSection:t,palette:o,color:n,onChange:r,customColors:i,setActiveColorPickerSection:a,updateData:s,activeShade:l,onEyeDropperToggle:c,onEscape:m})=>{if(e[lc.CTRL_OR_CMD])return!1;if(e.key===lc.ESCAPE)return m(e),!0;if(e.key===lc.ALT)return c(!0),!0;if(e.key===lc.I)return c(),!0;let p=Gr({color:n,palette:o});if(e.key===lc.TAB){let d={custom:!!i.length,baseColors:!0,shades:p?.shade!=null,hex:!0},u=Object.entries(d).reduce((x,[y,v])=>(v&&x.push(y),x),[]),h=u.indexOf(t),g=e.shiftKey?-1:1,E=h+g>u.length-1?0:h+g<0?u.length-1:h+g,w=u[E];return w&&a(w),w==="custom"?r(i[0]):w==="baseColors"&&(Object.entries(o).find(([y,v])=>Array.isArray(v)?v.includes(n):v===n?y:null)||r(u_.black)),e.preventDefault(),e.stopPropagation(),!0}if(g_({e,colorObj:p,onChange:r,palette:o,customColors:i,setActiveColorPickerSection:a,activeShade:l}))return!0;if(t==="shades"&&p){let{shade:d}=p,u=Kh(e.key,d,ps);if(u!==void 0)return r(o[p.colorName][u]),!0}if(t==="baseColors"&&p){let{colorName:d}=p,u=Object.keys(o),h=u.indexOf(d),g=Kh(e.key,h,u.length);if(g!==void 0){let E=u[g],w=o[E];return r(Array.isArray(w)?w[l]:w),!0}}if(t==="custom"){let d=n!=null?i.indexOf(n):0,u=Kh(e.key,d,i.length);if(u!==void 0){let h=i[u];return r(h),!0}}return!1};import{jsx as Ur,jsxs as Lm}from"react/jsx-runtime";var Mv=Xh.forwardRef(({color:e,onChange:t,type:o,elements:n,palette:r,updateData:i,children:a,showTitle:s,onEyeDropperToggle:l,onEscape:c,showHotKey:m=!0},p)=>{let d=s?o==="elementStroke"?f("labels.stroke"):o==="elementBackground"?f("labels.background"):null:null,[u]=Xh.useState(()=>o==="canvasBackground"?[]:xv(n,o,r)),[h,g]=ae(zo),E=Gr({color:e,palette:r});Zh(()=>{if(!h){let v=!!e&&Uh({color:e,palette:r}),I=v&&!u.includes(e);g(I?null:v?"custom":E?.shade!=null?"shades":"baseColors")}},[h,e,r,g,E,u]);let[w,x]=f_(E?.shade??(o==="elementBackground"?b_:x_));Zh(()=>{E?.shade!=null&&x(E.shade);let v=I=>{I.key===E_.ALT&&l(!1)};return document.addEventListener(Sv.KEYUP,v,{capture:!0}),()=>{document.removeEventListener(Sv.KEYUP,v,{capture:!0})}},[E,l]);let y=Xh.useRef(null);return h_(p,()=>y.current),Zh(()=>{y?.current?.focus()},[]),Ur("div",{role:"dialog","aria-modal":"true","aria-label":f("labels.colorPicker"),children:Lm("div",{ref:y,onKeyDown:v=>{kv({event:v,activeColorPickerSection:h,palette:r,color:e,onChange:t,onEyeDropperToggle:l,customColors:u,setActiveColorPickerSection:g,updateData:i,activeShade:w,onEscape:c})&&(v.preventDefault(),v.stopPropagation())},className:"color-picker-content properties-content",tabIndex:-1,children:[d&&Ur("div",{className:"color-picker__title",children:d}),!!u.length&&Lm("div",{children:[Ur(ms,{children:f("colorPicker.mostUsedCustomColors")}),Ur(vv,{colors:u,color:e,label:f("colorPicker.mostUsedCustomColors"),onChange:t})]}),Lm("div",{children:[Ur(ms,{children:f("colorPicker.colors")}),Ur(Iv,{color:e,palette:r,onChange:t,activeShade:w,showHotKey:m})]}),Lm("div",{children:[Ur(ms,{children:f("colorPicker.shades")}),Ur(Cv,{color:e,onChange:t,palette:r,showHotKey:m})]}),a]})})});import y_ from"clsx";import{COLOR_OUTLINE_CONTRAST_THRESHOLD as w_,DEFAULT_CANVAS_BACKGROUND_PICKS as v_,DEFAULT_ELEMENT_BACKGROUND_PICKS as I_,DEFAULT_ELEMENT_STROKE_PICKS as T_,isColorDark as C_}from"@orangecatai/common";import{jsx as jh}from"react/jsx-runtime";var Pv=({onChange:e,type:t,activeColor:o,topPicks:n})=>{let r;return t==="elementStroke"&&(r=T_),t==="elementBackground"&&(r=I_),t==="canvasBackground"&&(r=v_),n&&(r=n),r?jh("div",{className:"color-picker__top-picks",children:r.map(i=>jh("button",{className:y_("color-picker__button",{active:i===o,"is-transparent":i==="transparent"||!i,"has-outline":!C_(i,w_)}),style:{"--swatch-color":i},type:"button",title:i,onClick:()=>e(i),"data-testid":`color-top-pick-${i}`,children:jh("div",{className:"color-picker__button-outline"})},i))}):(console.error("Invalid type for TopPicks"),null)};import{jsx as Ho,jsxs as _m}from"react/jsx-runtime";var M_=({type:e,color:t,onChange:o,label:n,elements:r,palette:i=Nv,updateData:a,getOpenPopup:s,appState:l})=>{let{container:c}=qe(),m=_t(),p=m!=="full",d=m==="mobile",[,u]=ae(zo),[h,g]=ae(zr),E=_m("div",{children:[Ho(ms,{children:f("colorPicker.hexCode")}),Ho(wv,{color:t||"",label:n,onChange:y=>{o(y)},colorPickerType:e,placeholder:f("colorPicker.color")})]}),w=Rv(null),x=()=>{w.current?.focus()};return Ho(cr,{container:c,style:{maxWidth:"13rem"},preventAutoFocusOnTouch:!!l.editingTextElement,onFocusOutside:y=>{S_(y.target)||x(),y.preventDefault()},onPointerDownOutside:y=>{h&&y.preventDefault()},onClose:()=>{s()===e&&a({openPopup:null}),u(null),l.editingTextElement&&setTimeout(()=>{let y=document.querySelector(".excalidraw-wysiwyg");y&&y.focus()},0)},children:i?Ho(Mv,{ref:w,palette:i,color:t,onChange:y=>{let v=l.editingTextElement?Pm():null;o(y),l.editingTextElement&&v&&rc(v)},onEyeDropperToggle:y=>{g(v=>y?(v=v||{keepOpenOnAlt:!0,onSelect:o,colorPickerType:e},v.keepOpenOnAlt=!0,v):y===!1||v?null:{keepOpenOnAlt:!1,onSelect:o,colorPickerType:e})},onEscape:y=>{h?g(null):a({openPopup:null})},type:e,elements:r,updateData:a,showTitle:p,showHotKey:!d,children:E}):E})},P_=({label:e,color:t,type:o,mode:n="background",onToggle:r,editingTextElement:i})=>{let a=_t(),s=a!=="full",l=a==="mobile",c=m=>{m.preventDefault(),m.stopPropagation(),i&&bv(),r()};return _m(_v.Trigger,{type:"button",className:Dv("color-picker__button active-color properties-trigger",{"is-transparent":!t||t==="transparent","has-outline":!t||!Lv(t,Av),"compact-sizing":s,"mobile-border":l}),"aria-label":e,style:t?{"--swatch-color":t}:void 0,title:o==="elementStroke"?f("labels.showStroke"):f("labels.showBackground"),"data-openpopup":o,onClick:c,children:[Ho("div",{className:"color-picker__button-outline",children:!t&&ky}),s&&t&&n==="stroke"&&Ho("div",{className:"color-picker__button-background",children:Ho("span",{style:{color:t&&Lv(t,Av)?"#fff":"#111"},children:Zw})})]})},cc=({type:e,color:t,onChange:o,label:n,elements:r,palette:i=Nv,topPicks:a,updateData:s,appState:l})=>{let c=Rv(l.openPopup);k_(()=>{c.current=l.openPopup},[l.openPopup]);let p=_t()!=="full";return Ho("div",{children:_m("div",{role:"dialog","aria-modal":"true",className:Dv("color-picker-container",{"color-picker-container--no-top-picks":p}),children:[!p&&Ho(Pv,{activeColor:t,onChange:o,type:e,topPicks:a}),!p&&Ho(Cm,{}),_m(_v.Root,{open:l.openPopup===e,onOpenChange:d=>{d&&s({openPopup:e})},children:[Ho(P_,{color:t,label:n,type:e,mode:e==="elementStroke"?"stroke":"background",editingTextElement:!!l.editingTextElement,onToggle:()=>{l.openPopup===e?s({openPopup:null}):l.openPopup?s({openPopup:e}):s({openPopup:e})}}),l.openPopup===e&&Ho(M_,{type:e,color:t,onChange:o,label:n,elements:r,palette:i,updateData:s,getOpenPopup:()=>c.current,appState:l})]})]})})};import{Popover as oD}from"radix-ui";import nD from"clsx";import rD,{useCallback as iD,useMemo as aD}from"react";import{FONT_FAMILY as ef}from"@orangecatai/common";import K_,{useMemo as Vr,useState as X_,useRef as zv,useEffect as Hv,useCallback as Gv}from"react";import{arrayToList as Z_,debounce as j_,FONT_FAMILY as Ui,getFontFamilyString as q_}from"@orangecatai/common";import A_ from"clsx";import L_ from"react";import{jsx as __,jsxs as D_}from"react/jsx-runtime";var Dm=L_.forwardRef(({className:e,placeholder:t,onChange:o},n)=>D_("div",{className:A_("QuickSearch__wrapper",e),children:[ko,__("input",{ref:n,className:"QuickSearch__input",type:"text",placeholder:t,onChange:r=>o(r.target.value.trim().toLowerCase())})]}));import R_ from"clsx";import{Children as N_}from"react";import{jsx as Bv}from"react/jsx-runtime";var Rm=({className:e,placeholder:t,children:o})=>{let n=!N_.count(o);return Bv("div",{className:R_("ScrollableList__wrapper",e),role:"menu",children:n?Bv("div",{className:"empty",children:t}):o})};import{jsx as B_,jsxs as F_}from"react/jsx-runtime";var Fv=({children:e,className:t="",style:o,title:n})=>F_("div",{className:`dropdown-menu-group ${t}`,style:o,children:[n&&B_("p",{className:"dropdown-menu-group-title",children:n}),e]}),dc=Fv;Fv.displayName="DropdownMenuGroup";import{THEME as V_}from"@orangecatai/common";import{DropdownMenu as $_}from"radix-ui";import O_,{useContext as z_}from"react";import{composeEventHandlers as H_}from"@orangecatai/common";var qh=O_.createContext({}),Wr=(e="",t=!1,o=!1)=>`dropdown-menu-item dropdown-menu-item-base ${e} ${t?"dropdown-menu-item--selected":""} ${o?"dropdown-menu-item--hovered":""}`.trim(),Nm=e=>{let t=z_(qh);return H_(e,o=>{t.onSelect?.(o)})};import{jsx as G_}from"react/jsx-runtime";var mc=({children:e,...t})=>G_("span",{...t,style:{textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap",...t.style},children:e});import{Fragment as W_,jsx as pc,jsxs as Y_}from"react/jsx-runtime";var U_=({textStyle:e,icon:t,shortcut:o,children:n,badge:r})=>{let i=we();return Y_(W_,{children:[t&&pc("div",{className:"dropdown-menu-item__icon",children:t}),pc("div",{style:e,className:"dropdown-menu-item__text",children:pc(mc,{children:n})}),r&&pc("div",{className:"dropdown-menu-item__badge",children:r}),o&&i.formFactor!=="phone"&&pc("div",{className:"dropdown-menu-item__shortcut",children:o})]})},Yr=U_;import{jsx as Bm}from"react/jsx-runtime";var Jh=({icon:e,badge:t,value:o,children:n,shortcut:r,className:i,selected:a,onSelect:s,...l})=>{let c=Nm(s);return Bm($_.Item,{className:"radix-menu-item",onSelect:c,asChild:!0,children:Bm("button",{...l,value:o,className:Wr(i,a),title:l.title??l["aria-label"],children:Bm(Yr,{icon:e,shortcut:r,badge:t,children:n})})})};Jh.displayName="DropdownMenuItem";var us={GREEN:"green",RED:"red",BLUE:"blue"},Fm=({type:e=us.BLUE,children:t})=>{let{theme:o}=Go(),n={display:"inline-flex",marginLeft:"auto",padding:"2px 4px",borderRadius:6,fontSize:9,fontFamily:"Cascadia, monospace",border:o===V_.LIGHT?"1.5px solid white":"none"};switch(e){case us.GREEN:Object.assign(n,{backgroundColor:"var(--background-color-badge)",color:"var(--color-badge)"});break;case us.RED:Object.assign(n,{backgroundColor:"pink",color:"darkred"});break;case us.BLUE:default:Object.assign(n,{background:"var(--color-promo)",color:"var(--color-surface-lowest)"})}return Bm("div",{className:"DropDownMenuItemBadge",style:n,children:t})};Fm.displayName="DropdownMenuItemBadge";Jh.Badge=Fm;var Jt=Jh;import{KEYS as gs}from"@orangecatai/common";var Ov=({event:e,inputRef:t,hoveredFont:o,filteredFonts:n,onClose:r,onSelect:i,onHover:a})=>{if(!e[gs.CTRL_OR_CMD]&&e.shiftKey&&e.key.toLowerCase()===gs.F)return t.current?.focus(),!0;if(e.key===gs.ESCAPE)return r(),!0;if(e.key===gs.ENTER)return o?.value&&i(o.value),!0;if(e.key===gs.ARROW_DOWN)return o?.next?a(o.next.value):n[0]?.value&&a(n[0].value),!0;if(e.key===gs.ARROW_UP)return o?.prev?a(o.prev.value):n[n.length-1]?.value&&a(n[n.length-1].value),!0};import{jsx as dr,jsxs as Q_}from"react/jsx-runtime";var J_=e=>{switch(e){case Ui.Excalifont:case Ui.Virgil:return Ln;case Ui.Nunito:case Ui.Helvetica:return Jl;case Ui["Lilita One"]:return mw;case Ui["Comic Shanns"]:case Ui.Cascadia:return um;default:return Jl}},Uv=K_.memo(({selectedFontFamily:e,hoveredFontFamily:t,onSelect:o,onHover:n,onLeave:r,onOpen:i,onClose:a})=>{let{container:s}=qe(),l=Qe(),{fonts:c}=l,{showDeprecatedFonts:m}=Nn(),p=_t(),[d,u]=X_(""),h=zv(null),g=Vr(()=>Array.from(Mn.registered.entries()).filter(([T,{metadata:M}])=>!M.private&&!M.fallback).map(([T,{metadata:M,fontFaces:N}])=>{let O={value:T,icon:J_(T),text:N[0]?.fontFace?.family??"Unknown"};return M.deprecated&&Object.assign(O,{deprecated:M.deprecated,badge:{type:us.RED,placeholder:f("fontList.badge.old")}}),O}).sort((T,M)=>T.text.toLowerCase()>M.text.toLowerCase()?1:-1),[]),E=Vr(()=>new Set(c.getSceneFamilies()),[e]),w=Vr(()=>g.filter(T=>E.has(T.value)),[g,E]),x=Vr(()=>g.filter(T=>!E.has(T.value)&&(m||!T.deprecated)),[g,E,m]),y=Vr(()=>Z_([...w,...x].filter(T=>T.text?.toLowerCase().includes(d))),[w,x,d]),v=Vr(()=>{let T;return t?T=y.find(M=>M.value===t):e&&(T=y.find(M=>M.value===e)),!T&&d&&(y[0]?.value?n(y[0].value):r()),T},[t,e,d,y,n,r]),I=Gv(T=>{let M=null;if(l.state.editingTextElement){let N=document.querySelector(".excalidraw-wysiwyg");N&&(M={start:N.selectionStart,end:N.selectionEnd})}o(T),l.state.editingTextElement&&M&&setTimeout(()=>{let N=document.querySelector(".excalidraw-wysiwyg");N&&M&&(N.focus(),N.selectionStart=M.start,N.selectionEnd=M.end)},0)},[o,l.state.editingTextElement]),k=Gv(T=>{Ov({event:T,inputRef:h,hoveredFont:v,filteredFonts:y,onSelect:I,onHover:n,onClose:a})&&(T.preventDefault(),T.stopPropagation())},[v,y,I,n,a]);Hv(()=>(i(),()=>{a()}),[]);let L=Vr(()=>y.filter(T=>E.has(T.value)),[y,E]),S=Vr(()=>y.filter(T=>!E.has(T.value)),[y,E]),_=({font:T,order:M})=>{let N=zv(null),O=T.value===v?.value,B=T.value===e;return Hv(()=>{O&&(M===0?N.current?.scrollIntoView?.({block:"end"}):N.current?.scrollIntoView?.({block:"nearest"}))},[O,M]),dr("button",{ref:N,type:"button",value:T.value,className:Wr("",B,O),title:T.text,tabIndex:B?0:-1,onClick:U=>{I(Number(U.currentTarget.value))},onMouseMove:()=>{v?.value!==T.value&&n(T.value)},children:dr(Yr,{icon:T.icon,badge:T.badge&&dr(Fm,{type:T.badge.type,children:T.badge.placeholder}),textStyle:{fontFamily:q_({fontFamily:T.value})},children:T.text})})},P=[];return L.length&&P.push(dr(dc,{title:f("fontList.sceneFonts"),children:L.map((T,M)=>dr(_,{font:T,order:M},T.value))},"group_1")),S.length&&P.push(dr(dc,{title:f("fontList.availableFonts"),children:S.map((T,M)=>dr(_,{font:T,order:M+L.length},T.value))},"group_2")),Q_(cr,{className:"properties-content",container:s,style:{width:"15rem"},onClose:()=>{a(),l.state.editingTextElement&&setTimeout(()=>{let T=document.querySelector(".excalidraw-wysiwyg");T&&T.focus()},0)},onPointerLeave:r,onKeyDown:k,preventAutoFocusOnTouch:!!l.state.editingTextElement,children:[p==="full"&&dr(Dm,{ref:h,placeholder:f("quickSearch.placeholder"),onChange:j_(u,20)}),dr(Rm,{className:"dropdown-menu fonts manual-hover",placeholder:f("fontList.empty"),children:P.length?P:null})]})},(e,t)=>e.selectedFontFamily===t.selectedFontFamily&&e.hoveredFontFamily===t.hoveredFontFamily);import{Popover as eD}from"radix-ui";import{MOBILE_ACTION_BUTTON_BG as tD}from"@orangecatai/common";import{jsx as Qh}from"react/jsx-runtime";var Wv=({selectedFontFamily:e,isOpened:t=!1,compactMode:o=!1})=>{let n=ve(),r=o?{...tD,width:"2rem",height:"2rem"}:{};return Qh(eD.Trigger,{asChild:!0,children:Qh("div",{"data-openpopup":"fontFamily",className:"properties-trigger",children:Qh(ls,{standalone:!0,icon:_n,title:f("labels.showFonts"),className:"properties-trigger",testId:"font-family-show-fonts",active:t,onClick:()=>{n(i=>({openPopup:i.openPopup==="fontFamily"?null:i.openPopup}))},style:{border:"none",...r}})})})};import{jsx as uc,jsxs as Yv}from"react/jsx-runtime";var Vv=[{value:ef.Excalifont,icon:Ln,text:f("labels.handDrawn"),testId:"font-family-hand-drawn"},{value:ef.Nunito,icon:Jl,text:f("labels.normal"),testId:"font-family-normal"},{value:ef["Comic Shanns"],icon:um,text:f("labels.code"),testId:"font-family-code"}],vae=new Set(Vv.map(e=>e.value));var $v=rD.memo(({isOpened:e,selectedFontFamily:t,hoveredFontFamily:o,onSelect:n,onHover:r,onLeave:i,onPopupChange:a,compactMode:s=!1})=>{let l=aD(()=>Vv,[]),c=iD(m=>{m&&n(m)},[n]);return Yv("div",{role:"dialog","aria-modal":"true",className:nD("FontPicker__container",{"FontPicker__container--compact":s}),children:[!s&&uc("div",{className:"buttonList",children:uc(Oo,{type:"button",options:l,value:t,onClick:c})}),!s&&uc(Cm,{}),Yv(oD.Root,{open:e,onOpenChange:a,children:[uc(Wv,{selectedFontFamily:t,isOpened:e,compactMode:s}),e&&uc(Uv,{selectedFontFamily:t,hoveredFontFamily:o,onSelect:c,onHover:r,onLeave:i,onOpen:()=>a(!0),onClose:()=>a(!1)})]})]})},(e,t)=>e.isOpened===t.isOpened&&e.selectedFontFamily===t.selectedFontFamily&&e.hoveredFontFamily===t.hoveredFontFamily);import{Popover as tf}from"radix-ui";import dD from"clsx";import Om,{useEffect as mD}from"react";import{isArrowKey as pD,KEYS as mr}from"@orangecatai/common";import{jsx as sD}from"react/jsx-runtime";var Bn=({className:e,icon:t,size:o="1em"})=>sD("span",{className:e,style:{width:o,height:"100%",margin:"0 0.5ex 0 0.5ex",display:"inline-flex",lineHeight:0,verticalAlign:"middle",flex:"0 0 auto"},children:t});import{Fragment as cD,jsx as Kv,jsxs as Xv}from"react/jsx-runtime";var lD=({label:e,open:t,openTrigger:o,children:n,className:r,showCollapsedIcon:i=!0})=>Xv(cD,{children:[Xv("div",{style:{cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center"},className:r,onClick:o,children:[e,i&&Kv(Bn,{icon:t?$w:fm})]}),t&&Kv("div",{style:{display:"flex",flexDirection:"column"},children:n})]}),gc=lD;import{jsx as Wi,jsxs as of}from"react/jsx-runtime";var uD=Ce(!1);function gD({options:e,value:t,label:o,onChange:n,onClose:r,numberOfOptionsToAlwaysShow:i=e.length}){let a=we(),{container:s}=qe(),l=g=>{let E=e.find(w=>w.keyBinding===g.key.toLowerCase());if(!(g.metaKey||g.altKey||g.ctrlKey)&&E)n(E.value),g.preventDefault();else if(g.key===mr.TAB){let w=e.findIndex(y=>y.value===t),x=g.shiftKey?(e.length+w-1)%e.length:(w+1)%e.length;n(e[x].value)}else if(pD(g.key)){let w=lr().rtl,x=e.findIndex(y=>y.value===t);if(x!==-1){let y=e.length,v=x;switch(g.key){case(w?mr.ARROW_LEFT:mr.ARROW_RIGHT):v=(x+1)%y;break;case(w?mr.ARROW_RIGHT:mr.ARROW_LEFT):v=(y+x-1)%y;break;case mr.ARROW_DOWN:{v=(x+(i??1))%y;break}case mr.ARROW_UP:{v=(y+x-(i??1))%y;break}}n(e[v].value)}g.preventDefault()}else(g.key===mr.ESCAPE||g.key===mr.ENTER)&&(g.preventDefault(),r());g.nativeEvent.stopImmediatePropagation(),g.stopPropagation()},[c,m]=ae(uD),p=Om.useMemo(()=>e.slice(0,i),[e,i]),d=Om.useMemo(()=>e.slice(i),[e,i]);mD(()=>{p.some(g=>g.value===t)||m(!0)},[t,p,m]);let u=g=>Wi("div",{className:"picker-content",children:g.map((E,w)=>of("button",{type:"button",className:dD("picker-option",{active:t===E.value}),onClick:x=>{n(E.value)},title:`${E.text} ${E.keyBinding&&`\u2014 ${E.keyBinding.toUpperCase()}`}`,"aria-label":E.text||"none","aria-keyshortcuts":E.keyBinding||void 0,ref:x=>{t===E.value&&setTimeout(()=>{x?.focus()},0)},children:[E.icon,E.keyBinding&&Wi("span",{className:"picker-keybinding",children:E.keyBinding})]},E.text))}),h=a.formFactor==="phone";return Wi(tf.Content,{side:h?"right":"bottom",align:"start",sideOffset:h?8:12,style:{zIndex:"var(--zIndex-ui-styles-popup)"},onKeyDown:l,collisionBoundary:s??void 0,children:of("div",{className:"picker",role:"dialog","aria-modal":"true","aria-label":o,children:[u(p),d.length>0&&Wi(gc,{label:f("labels.more_options"),open:c,openTrigger:()=>{m(g=>!g)},className:"picker-collapsible",children:u(d)})]})})}function nf({value:e,label:t,options:o,onChange:n,group:r="",numberOfOptionsToAlwaysShow:i}){let[a,s]=Om.useState(!1),l=Om.useRef(null);return Wi("div",{children:of(tf.Root,{open:a,onOpenChange:c=>s(c),children:[Wi(tf.Trigger,{name:r,type:"button","aria-label":t,onClick:()=>s(!a),ref:l,className:a?"active":"",children:o.find(c=>c.value===e)?.icon}),a&&Wi(gD,{options:o,value:e,label:t,onChange:n,onClose:()=>{s(!1)},numberOfOptionsToAlwaysShow:i})]})})}import Zv,{useEffect as hD}from"react";import{jsx as rf,jsxs as jv}from"react/jsx-runtime";var qv=({updateData:e,app:t,testId:o})=>{let n=Zv.useRef(null),r=Zv.useRef(null),i=t.scene.getSelectedElements(t.state),a=!0,s=i.at(0),c=i.reduce((m,p)=>(m!=null&&m!==p.opacity&&(a=!1),m==null||m>p.opacity?p.opacity:m),s?.opacity??null)??t.state.currentItemOpacity;return hD(()=>{if(n.current&&r.current){let m=n.current,p=r.current,d=m.offsetWidth,u=15,h=c/100*(d-u)+u/2;p.style.left=`${h}px`,m.style.background=`linear-gradient(to right, var(--color-slider-track) 0%, var(--color-slider-track) ${c}%, var(--button-bg) ${c}%, var(--button-bg) 100%)`}},[c]),jv("label",{className:"control-label",children:[f("labels.opacity"),jv("div",{className:"range-wrapper",children:[rf("input",{style:{"--color-slider-track":a?void 0:"var(--button-bg)"},ref:n,type:"range",min:"0",max:"100",step:"10",onChange:m=>{e(+m.target.value)},value:c,className:"range-input","data-testid":o}),rf("div",{className:"value-bubble",ref:r,children:c!==0?c:null}),rf("div",{className:"zero-label",children:"0"})]})]})};import{Fragment as hf,jsx as me,jsxs as eo}from"react/jsx-runtime";var r2=.1,fs=e=>{let t=OD(e.editorInterface);return{stylesPanelMode:t,isCompact:t!=="full",isMobile:t==="mobile"}},Qt=(e,t,o,n=!1)=>{let r=df(le(e,t,{includeBoundTextElement:n}));return e.map(i=>r.get(i.id)||i.id===t.editingTextElement?.id?o(i):i)},Yt=function(e,t,o,n,r){let i=t.state.editingTextElement,a=o2(e),s=null;if(i&&(s=o(i)),!s)if(He(a,t.state)){let c=t.scene.getSelectedElements(t.state),m=n===!0?c:c.filter(p=>n(p));s=AD(m,o)??(typeof r=="function"?r(!0):r)}else s=typeof r=="function"?r(!1):r;return s},zD=(e,t,o)=>DD(t)||!t.autoResize?t:o.mutateElement(t,{x:e.textAlign==="left"?e.x:e.x+(e.width-t.width)/(e.textAlign==="center"?2:1),y:e.y+(e.height-t.height)/2}),pf=(e,t,o,n,r)=>{let i=new Set,a=Qt(e,t,s=>{if(uo(s)){let l=n(s);i.add(l);let c=kt(s,{fontSize:l});return hc(c,o.scene.getContainerElement(s),o.scene),c=zD(s,c,o.scene),c}return s},!0);return le(e,t,{includeBoundTextElement:!0}).forEach(s=>{uo(s)&&_D(s,o.scene)}),{elements:a,appState:{...t,currentItemFontSize:i.size===1?[...i][0]:r??t.currentItemFontSize},captureUpdate:St.IMMEDIATELY}},HD=W({name:"changeStrokeColor",label:"labels.stroke",trackEvent:!1,perform:(e,t,o)=>({...o?.currentItemStrokeColor&&{elements:Qt(e,t,n=>ND(n.type)?kt(n,{strokeColor:o.currentItemStrokeColor}):n,!0)},appState:{...t,...o},captureUpdate:o?.currentItemStrokeColor?St.IMMEDIATELY:St.EVENTUALLY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let{stylesPanelMode:i}=fs(n);return eo(hf,{children:[i==="full"&&me("h3",{"aria-hidden":"true",children:f("labels.stroke")}),me(cc,{topPicks:vD,palette:wD,type:"elementStroke",label:f("labels.stroke"),color:Yt(e,n,a=>a.strokeColor,!0,a=>a?null:t.currentItemStrokeColor),onChange:a=>o({currentItemStrokeColor:a}),elements:e,appState:t,updateData:o})]})}}),GD=W({name:"changeBackgroundColor",label:"labels.changeBackground",trackEvent:!1,perform:(e,t,o,n)=>{if(!o?.currentItemBackgroundColor)return{appState:{...t,...o},captureUpdate:St.EVENTUALLY};let r,i=n.scene.getSelectedElements(t);if(!PD(o.currentItemBackgroundColor)&&i.every(s=>e2(s)&&LD(s.points))){let s=df(i);r=e.map(l=>s.has(l.id)&&e2(l)?kt(l,{backgroundColor:o.currentItemBackgroundColor,...FD(l,!0)}):l)}else r=Qt(e,t,s=>kt(s,{backgroundColor:o.currentItemBackgroundColor}));return{elements:r,appState:{...t,...o},captureUpdate:St.IMMEDIATELY}},PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let{stylesPanelMode:i}=fs(n);return eo(hf,{children:[i==="full"&&me("h3",{"aria-hidden":"true",children:f("labels.background")}),me(cc,{topPicks:yD,palette:ED,type:"elementBackground",label:f("labels.background"),color:Yt(e,n,a=>a.backgroundColor,!0,a=>a?null:t.currentItemBackgroundColor),onChange:a=>o({currentItemBackgroundColor:a}),elements:e,appState:t,updateData:o})]})}}),UD=W({name:"changeFillStyle",label:"labels.fill",trackEvent:!1,perform:(e,t,o,n)=>(ge("element","changeFillStyle",`${o} (${n.editorInterface.formFactor==="phone"?"mobile":"desktop"})`),{elements:Qt(e,t,r=>kt(r,{fillStyle:o})),appState:{...t,currentItemFillStyle:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>{let r=le(e,t),i=r.length>0&&r.every(a=>a.fillStyle==="zigzag");return eo("fieldset",{children:[me("legend",{children:f("labels.fill")}),me("div",{className:"buttonList",children:me(Oo,{type:"button",options:[{value:"hachure",text:`${i?f("labels.zigzag"):f("labels.hachure")} (${G("Alt-Click")})`,icon:i?By:Fy,active:i?!0:void 0,testId:"fill-hachure"},{value:"cross-hatch",text:f("labels.crossHatch"),icon:Oy,testId:"fill-cross-hatch"},{value:"solid",text:f("labels.solid"),icon:zy,testId:"fill-solid"}],value:Yt(e,n,a=>a.fillStyle,a=>a.hasOwnProperty("fillStyle"),a=>a?null:t.currentItemFillStyle),onClick:(a,s)=>{let l=s.altKey&&a==="hachure"&&r.every(c=>c.fillStyle==="hachure")?"zigzag":a;o(l)}})})]})}}),WD=W({name:"changeStrokeWidth",label:"labels.strokeWidth",trackEvent:!1,perform:(e,t,o)=>({elements:Qt(e,t,n=>kt(n,{strokeWidth:o})),appState:{...t,currentItemStrokeWidth:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>eo("fieldset",{children:[me("legend",{children:f("labels.strokeWidth")}),me("div",{className:"buttonList",children:me(Oo,{group:"stroke-width",options:[{value:lf.thin,text:f("labels.thin"),icon:wh,testId:"strokeWidth-thin"},{value:lf.bold,text:f("labels.bold"),icon:Hy,testId:"strokeWidth-bold"},{value:lf.extraBold,text:f("labels.extraBold"),icon:Gy,testId:"strokeWidth-extraBold"}],value:Yt(e,n,i=>i.strokeWidth,i=>i.hasOwnProperty("strokeWidth"),i=>i?null:t.currentItemStrokeWidth),onChange:i=>o(i)})})]})}),YD=W({name:"changeSloppiness",label:"labels.sloppiness",trackEvent:!1,perform:(e,t,o)=>({elements:Qt(e,t,n=>kt(n,{seed:kD(),roughness:o})),appState:{...t,currentItemRoughness:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>eo("fieldset",{children:[me("legend",{children:f("labels.sloppiness")}),me("div",{className:"buttonList",children:me(Oo,{group:"sloppiness",options:[{value:0,text:f("labels.architect"),icon:Yy},{value:1,text:f("labels.artist"),icon:Vy},{value:2,text:f("labels.cartoonist"),icon:$y}],value:Yt(e,n,i=>i.roughness,i=>i.hasOwnProperty("roughness"),i=>i?null:t.currentItemRoughness),onChange:i=>o(i)})})]})}),Sse=W({name:"changeStrokeStyle",label:"labels.strokeStyle",trackEvent:!1,perform:(e,t,o)=>({elements:Qt(e,t,n=>kt(n,{strokeStyle:o})),appState:{...t,currentItemStrokeStyle:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>eo("fieldset",{children:[me("legend",{children:f("labels.strokeStyle")}),me("div",{className:"buttonList",children:me(Oo,{group:"strokeStyle",options:[{value:"solid",text:f("labels.strokeStyle_solid"),icon:wh},{value:"dashed",text:f("labels.strokeStyle_dashed"),icon:Uy},{value:"dotted",text:f("labels.strokeStyle_dotted"),icon:Wy}],value:Yt(e,n,i=>i.strokeStyle,i=>i.hasOwnProperty("strokeStyle"),i=>i?null:t.currentItemStrokeStyle),onChange:i=>o(i)})})]})}),VD=W({name:"changeOpacity",label:"labels.opacity",trackEvent:!1,perform:(e,t,o)=>({elements:Qt(e,t,n=>kt(n,{opacity:o}),!0),appState:{...t,currentItemOpacity:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({app:e,updateData:t})=>me(qv,{updateData:t,app:e,testId:"opacity"})}),$D=W({name:"changeFontSize",label:"labels.fontSize",trackEvent:!1,perform:(e,t,o,n)=>pf(e,t,n,()=>(mf(o,"actionChangeFontSize: Expected a font size value"),o),o),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let{isCompact:i}=fs(n);return eo("fieldset",{children:[me("legend",{children:f("labels.fontSize")}),me("div",{className:"buttonList",children:me(Oo,{group:"font-size",options:[{value:Hm.sm,text:f("labels.small"),icon:sw,testId:"fontSize-small"},{value:Hm.md,text:f("labels.medium"),icon:lw,testId:"fontSize-medium"},{value:Hm.lg,text:f("labels.large"),icon:cw,testId:"fontSize-large"},{value:Hm.xl,text:f("labels.veryLarge"),icon:dw,testId:"fontSize-veryLarge"}],value:Yt(e,n,a=>{if(uo(a))return a.fontSize;let s=$r(a,n.scene.getNonDeletedElementsMap());return s?s.fontSize:null},a=>uo(a)||$r(a,n.scene.getNonDeletedElementsMap())!==null,a=>a?null:t.currentItemFontSize||TD),onChange:a=>{ic(()=>o(a),i,!!t.editingTextElement,r?.onPreventClose)}})})]})}}),uf=W({name:"decreaseFontSize",label:"labels.decreaseFontSize",icon:Hi,trackEvent:!1,perform:(e,t,o,n)=>pf(e,t,n,r=>Math.round(1/(1+r2)*r.fontSize)),keyTest:e=>e[hs.CTRL_OR_CMD]&&e.shiftKey&&(e.key===hs.CHEVRON_LEFT||e.key===hs.COMMA)}),gf=W({name:"increaseFontSize",label:"labels.increaseFontSize",icon:Hi,trackEvent:!1,perform:(e,t,o,n)=>pf(e,t,n,r=>Math.round(r.fontSize*(1+r2))),keyTest:e=>e[hs.CTRL_OR_CMD]&&e.shiftKey&&(e.key===hs.CHEVRON_RIGHT||e.key===hs.PERIOD)}),KD=W({name:"changeFontFamily",label:"labels.fontFamily",trackEvent:!1,perform:(e,t,o,n)=>{let{cachedElements:r,resetAll:i,resetContainers:a,...s}=o;if(i)return{elements:Qt(e,t,g=>{let E=r?.get(g.id);return E?kt(g,{...E}):g},!0),appState:{...t,...s},captureUpdate:St.NEVER};mf(o,"actionChangeFontFamily: value must be defined");let{currentItemFontFamily:l,currentHoveredFontFamily:c}=o,m=St.EVENTUALLY,p,d=!1;if(l)p=l,m=St.IMMEDIATELY;else if(c){p=c,m=St.EVENTUALLY;let h=le(e,t,{includeBoundTextElement:!0}).filter(g=>uo(g));if(h.length>200)d=!0;else{let g=0,E=0;for(;g<h.length&&E<5e3;){let w=h[g];E+=w?.originalText.length||0,g++}E>5e3&&(d=!0)}}let u={appState:{...t,...s},captureUpdate:m};if(p&&!d){let h=new Map,g=new Set,E=!1,w=Array.from(Mn.loadedFontsCache.values()),x=Object.entries(CD).find(([I,k])=>k===p)?.[0];c&&x&&w.some(I=>I.startsWith(x))&&(E=!0),Object.assign(u,{elements:Qt(e,t,I=>{if(uo(I)&&(I.fontFamily!==p||l)){let k=kt(I,{fontFamily:p,lineHeight:MD(p)}),L=r?.get(I.containerId||"")||{},S=n.scene.getContainerElement(I);return a&&S&&L&&n.scene.mutateElement(S,{...L}),E||(g=new Set([...g,...Array.from(k.originalText)])),h.set(k,S),k}return I},!0)});let y=`10px ${SD({fontFamily:p})}`,v=Array.from(g.values()).join();if(E||window.document.fonts.check(y,v))for(let[I,k]of h)hc(I,k,n.scene);else window.document.fonts.load(y,v).then(I=>{for(let[k,L]of h){let S=n.scene.getElement(k.id),_=L?n.scene.getElement(L.id):null;S&&hc(S,_,n.scene)}n.fonts.onLoaded(I)})}return u},PanelComponent:({elements:e,appState:t,app:o,updateData:n})=>{let r=sf(new Map),i=sf(null),[a,s]=xD({}),l=sf(!0),{stylesPanelMode:c,isCompact:m}=fs(o),p=bD(()=>{let d=(u,h)=>Yt(u,o,g=>{if(uo(g))return g.fontFamily;let E=$r(g,h);return E?E.fontFamily:null},g=>uo(g)||$r(g,h)!==null,g=>g?null:t.currentItemFontFamily||ID);return a.openPopup==="fontFamily"&&t.openPopup==="fontFamily"?d(Array.from(r.current?.values()??[]),r.current):!a.openPopup&&t.openPopup!=="fontFamily"?d(e,o.scene.getNonDeletedElementsMap()):i.current},[a.openPopup,t,e,o]);return af(()=>{i.current=p},[p]),af(()=>{Object.keys(a).length&&(n(a),s({}))},[a]),af(()=>(l.current=!1,()=>{l.current=!0}),[]),eo(hf,{children:[c==="full"&&me("legend",{children:f("labels.fontFamily")}),me($v,{isOpened:t.openPopup==="fontFamily",selectedFontFamily:p,hoveredFontFamily:t.currentHoveredFontFamily,compactMode:c!=="full",onSelect:d=>{ic(()=>{s({openPopup:null,currentHoveredFontFamily:null,currentItemFontFamily:d}),r.current.clear()},m,!!t.editingTextElement)},onHover:d=>{s({currentHoveredFontFamily:d,cachedElements:new Map(r.current),resetContainers:!0})},onLeave:()=>{s({currentHoveredFontFamily:null,cachedElements:new Map(r.current),resetAll:!0})},onPopupChange:d=>{if(d){r.current.clear();let{editingTextElement:u}=t;if(u?.type==="text"){let h=o.scene.getElement(u.id);r.current.set(u.id,kt(h||u,{},!0))}else{let h=le(e,t,{includeBoundTextElement:!0});for(let g of h)r.current.set(g.id,kt(g,{},!0))}s({...a,openPopup:"fontFamily"})}else{let u={currentHoveredFontFamily:null,cachedElements:new Map(r.current),resetAll:!0};s({...u}),r.current.clear(),m&&t.editingTextElement&&rc(null)}}})]})}}),XD=W({name:"changeTextAlign",label:"Change text alignment",trackEvent:!1,perform:(e,t,o,n)=>({elements:Qt(e,t,r=>{if(uo(r)){let i=kt(r,{textAlign:o});return hc(i,n.scene.getContainerElement(r),n.scene),i}return r},!0),appState:{...t,currentItemTextAlign:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let i=n.scene.getNonDeletedElementsMap(),{isCompact:a}=fs(n);return eo("fieldset",{children:[me("legend",{children:f("labels.textAlign")}),me("div",{className:"buttonList",children:me(Oo,{group:"text-align",options:[{value:"left",text:f("labels.left"),icon:pw,testId:"align-left"},{value:"center",text:f("labels.center"),icon:uw,testId:"align-horizontal-center"},{value:"right",text:f("labels.right"),icon:gw,testId:"align-right"}],value:Yt(e,n,s=>{if(uo(s))return s.textAlign;let l=$r(s,i);return l?l.textAlign:null},s=>uo(s)||$r(s,i)!==null,s=>s?null:t.currentItemTextAlign),onChange:s=>{ic(()=>o(s),a,!!t.editingTextElement,r?.onPreventClose)}})})]})}}),ZD=W({name:"changeVerticalAlign",label:"Change vertical alignment",trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:Qt(e,t,r=>{if(uo(r)){let i=kt(r,{verticalAlign:o});return hc(i,n.scene.getContainerElement(r),n.scene),i}return r},!0),appState:{...t},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let{isCompact:i}=fs(n);return me("fieldset",{children:me("div",{className:"buttonList",children:me(Oo,{group:"text-align",options:[{value:zm.TOP,text:f("labels.alignTop"),icon:me(hw,{theme:t.theme}),testId:"align-top"},{value:zm.MIDDLE,text:f("labels.centerVertically"),icon:me(bw,{theme:t.theme}),testId:"align-middle"},{value:zm.BOTTOM,text:f("labels.alignBottom"),icon:me(fw,{theme:t.theme}),testId:"align-bottom"}],value:Yt(e,n,a=>{if(uo(a)&&a.containerId)return a.verticalAlign;let s=$r(a,n.scene.getNonDeletedElementsMap());return s?s.verticalAlign:null},a=>uo(a)||$r(a,n.scene.getNonDeletedElementsMap())!==null,a=>a?null:zm.MIDDLE),onChange:a=>{ic(()=>o(a),i,!!t.editingTextElement,r?.onPreventClose)}})})})}}),Mse=W({name:"changeRoundness",label:"Change edge roundness",trackEvent:!1,perform:(e,t,o)=>({elements:Qt(e,t,n=>n2(n)?n:kt(n,{roundness:o==="round"?{type:RD(n.type)?Gm.ADAPTIVE_RADIUS:Gm.PROPORTIONAL_RADIUS}:null})),appState:{...t,currentItemRoundness:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,renderAction:r})=>{let a=_a(o2(e),t).some(s=>s.roundness?.type===Gm.LEGACY);return eo("fieldset",{children:[me("legend",{children:f("labels.edges")}),eo("div",{className:"buttonList",children:[me(Oo,{group:"edges",options:[{value:"sharp",text:f("labels.sharp"),icon:Ky},{value:"round",text:f("labels.round"),icon:Xy}],value:Yt(e,n,s=>a?null:s.roundness?"round":"sharp",s=>!Um(s)&&s.hasOwnProperty("roundness"),s=>s?null:t.currentItemRoundness),onChange:s=>o(s)}),r("togglePolygon")]})]})}}),t2=e=>[{value:null,text:f("labels.arrowhead_none"),keyBinding:"q",icon:me(Zy,{flip:e})},{value:"arrow",text:f("labels.arrowhead_arrow"),keyBinding:"w",icon:me(jy,{flip:e})},{value:"triangle",text:f("labels.arrowhead_triangle"),icon:me(ew,{flip:e}),keyBinding:"e"},{value:"triangle_outline",text:f("labels.arrowhead_triangle_outline"),icon:me(tw,{flip:e}),keyBinding:"r"},{value:"circle",text:f("labels.arrowhead_circle"),keyBinding:"a",icon:me(qy,{flip:e})},{value:"circle_outline",text:f("labels.arrowhead_circle_outline"),keyBinding:"s",icon:me(Jy,{flip:e})},{value:"diamond",text:f("labels.arrowhead_diamond"),icon:me(ow,{flip:e}),keyBinding:"d"},{value:"diamond_outline",text:f("labels.arrowhead_diamond_outline"),icon:me(nw,{flip:e}),keyBinding:"f"},{value:"bar",text:f("labels.arrowhead_bar"),keyBinding:"z",icon:me(Qy,{flip:e})},{value:"crowfoot_one",text:f("labels.arrowhead_crowfoot_one"),icon:me(iw,{flip:e}),keyBinding:"x"},{value:"crowfoot_many",text:f("labels.arrowhead_crowfoot_many"),icon:me(rw,{flip:e}),keyBinding:"c"},{value:"crowfoot_one_or_many",text:f("labels.arrowhead_crowfoot_one_or_many"),icon:me(aw,{flip:e}),keyBinding:"v"}],Pse=W({name:"changeArrowhead",label:"Change arrowheads",trackEvent:!1,perform:(e,t,o)=>(mf(o,"actionChangeArrowhead: value must be defined"),{elements:Qt(e,t,n=>{if(cf(n)){let{position:r,type:i}=o;if(r==="start")return kt(n,{startArrowhead:i});if(r==="end")return kt(n,{endArrowhead:i})}return n}),appState:{...t,[o.position==="start"?"currentItemStartArrowhead":"currentItemEndArrowhead"]:o.type},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>{let r=lr().rtl;return eo("fieldset",{children:[me("legend",{children:f("labels.arrowheads")}),eo("div",{className:"iconSelectList buttonList",children:[me(nf,{label:"arrowhead_start",options:t2(!r),value:Yt(e,n,i=>cf(i)&&Da(i.type)?i.startArrowhead:t.currentItemStartArrowhead,!0,i=>i?null:t.currentItemStartArrowhead),onChange:i=>o({position:"start",type:i}),numberOfOptionsToAlwaysShow:4}),me(nf,{label:"arrowhead_end",group:"arrowheads",options:t2(!!r),value:Yt(e,n,i=>cf(i)&&Da(i.type)?i.endArrowhead:t.currentItemEndArrowhead,!0,i=>i?null:t.currentItemEndArrowhead),onChange:i=>o({position:"end",type:i}),numberOfOptionsToAlwaysShow:4})]})]})}}),jD=W({name:"changeArrowProperties",label:"Change arrow properties",trackEvent:!1,perform:(e,t,o,n)=>!1,PanelComponent:({elements:e,appState:t,updateData:o,app:n,renderAction:r})=>eo("div",{className:"selected-shape-actions",children:[r("changeArrowhead"),r("changeArrowType")]})}),Ase=W({name:"changeArrowType",label:"Change arrow types",trackEvent:!1,perform:(e,t,o,n)=>{let r=Qt(e,t,s=>{if(!Um(s))return s;let l=n.scene.getNonDeletedElementsMap(),c=Yi.getPointAtIndexGlobalCoordinates(s,0,l),m=Yi.getPointAtIndexGlobalCoordinates(s,-1,l),p=kt(s,{x:o===Uo.elbow?c[0]:s.x,y:o===Uo.elbow?c[1]:s.y,roundness:o===Uo.round?{type:Gm.PROPORTIONAL_RADIUS}:null,elbowed:o===Uo.elbow,angle:o===Uo.elbow?0:s.angle,points:o===Uo.elbow||s.elbowed?[Yi.pointFromAbsoluteCoords({...s,x:c[0],y:c[1],angle:0},c,l),Yi.pointFromAbsoluteCoords({...s,x:c[0],y:c[1],angle:0},m,l)]:s.points});if(n2(p)){p.fixedSegments=null;let d=n.scene.getNonDeletedElementsMap();n.dismissLinearEditor();let u=Yi.getPointAtIndexGlobalCoordinates(p,0,d),h=Yi.getPointAtIndexGlobalCoordinates(p,-1,d),g=p.startBinding&&d.get(p.startBinding.elementId),E=p.endBinding&&d.get(p.endBinding.elementId),w=g&&p.startBinding?{...p.startBinding,...Qv(p,g,"start",d)}:null,x=E&&p.endBinding?{...p.endBinding,...Qv(p,E,"end",d)}:null;p={...p,startBinding:w,endBinding:x,...BD(p,d,{points:[u,h].map(y=>fD(y[0]-p.x,y[1]-p.y)),startBinding:w,endBinding:x,fixedSegments:null})}}else{let d=n.scene.getNonDeletedElementsMap();if(p.startBinding){let u=d.get(p.startBinding.elementId);u&&Jv(p,u,t.bindMode==="inside"?"inside":"orbit","start",n.scene)}if(p.endBinding){let u=d.get(p.endBinding.elementId);u&&Jv(p,u,t.bindMode==="inside"?"inside":"orbit","end",n.scene)}}return p}),i={...t,currentItemArrowType:o},a=t.selectedLinearElement?.elementId;if(a){let s=r.find(l=>l.id===a);s&&(i.selectedLinearElement=new Yi(s,df(e)))}return{elements:r,appState:i,captureUpdate:St.IMMEDIATELY}},PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>eo("fieldset",{children:[me("legend",{children:f("labels.arrowtypes")}),me("div",{className:"buttonList",children:me(Oo,{group:"arrowtypes",options:[{value:Uo.sharp,text:f("labels.arrowtype_sharp"),icon:ns,testId:"sharp-arrow"},{value:Uo.round,text:f("labels.arrowtype_round"),icon:is,testId:"round-arrow"},{value:Uo.elbow,text:f("labels.arrowtype_elbowed"),icon:rs,testId:"elbow-arrow"}],value:Yt(e,n,r=>Um(r)?r.elbowed?Uo.elbow:r.roundness?Uo.round:Uo.sharp:null,r=>Um(r),r=>r?null:t.currentItemArrowType),onChange:r=>o(r)})})]})});import{clamp as yf,roundToStep as n8}from"@orangecatai/math";import{DEFAULT_CANVAS_BACKGROUND_PICKS as r8,CURSOR_TYPE as p2,MAX_ZOOM as u2,MIN_ZOOM as g2,THEME as fc,ZOOM_STEP as wf,updateActiveTool as xs,CODES as On,KEYS as ur,viewportCoordsToSceneCoords as i8}from"@orangecatai/common";import{getElementAbsoluteCoords as c2,getNonDeletedElements as h2,getVisibleElements as a8}from"@orangecatai/element";import{newElementWith as s8}from"@orangecatai/element";import{getCommonBounds as f2}from"@orangecatai/element";import{CaptureUpdateAction as dn}from"@orangecatai/element";import{useEffect as qD}from"react";import{jsx as QD}from"react/jsx-runtime";var bs=()=>{let e=document.querySelector(".excalidraw-tooltip");if(e)return e;let t=document.createElement("div");return document.body.appendChild(t),t.classList.add("excalidraw-tooltip"),t},ff=(e,t,o="bottom")=>{let n=e.getBoundingClientRect(),r=window.innerWidth,i=window.innerHeight,a=5,s=t.left+t.width/2-n.width/2;s<0?s=a:s+n.width>=r&&(s=r-n.width-a);let l;o==="bottom"?(l=t.top+t.height+a,l+n.height>=i&&(l=t.top-n.height-a)):(l=t.top-n.height-a,l<0&&(l=t.top+t.height+a)),Object.assign(e.style,{top:`${l}px`,left:`${s}px`})},JD=(e,t,o,n)=>{t.classList.add("excalidraw-tooltip--visible"),t.style.minWidth=n?"50ch":"10ch",t.style.maxWidth=n?"50ch":"15ch",t.textContent=o;let r=e.getBoundingClientRect();ff(t,r)},Vt=({children:e,label:t,long:o=!1,style:n,disabled:r})=>(qD(()=>()=>bs().classList.remove("excalidraw-tooltip--visible"),[]),r?null:QD("div",{className:"excalidraw-tooltip-wrapper",onPointerEnter:i=>JD(i.currentTarget,bs(),t,o),onPointerLeave:()=>bs().classList.remove("excalidraw-tooltip--visible"),style:n,children:e}));import{CURSOR_TYPE as bf,MIME_TYPES as xf,THEME as a2}from"@orangecatai/common";var s2='<svg viewBox="0 0 24 24" stroke-width="1" width="28" height="28" xmlns="http://www.w3.org/2000/svg">',e8='<path d="M6.164 11.755a5.314 5.314 0 0 1-4.932-5.298 5.314 5.314 0 0 1 5.311-5.311 5.314 5.314 0 0 1 5.307 5.113l8.773 8.773a3.322 3.322 0 0 1 0 4.696l-.895.895a3.322 3.322 0 0 1-4.696 0l-8.868-8.868Z" style="fill:#fff"/>',l2='<path stroke="#1b1b1f" fill="#fff" d="m7.868 11.113 7.773 7.774a2.359 2.359 0 0 0 1.667.691 2.368 2.368 0 0 0 2.357-2.358c0-.625-.248-1.225-.69-1.667L11.201 7.78 9.558 9.469l-1.69 1.643v.001Zm10.273 3.606-3.333 3.333m-3.25-6.583 2 2m-7-7 3 3M3.664 3.625l1 1M2.529 6.922l1.407-.144m5.735-2.932-1.118.866M4.285 9.823l.758-1.194m1.863-6.207-.13 1.408"/>',t8=`data:${xf.svg},${encodeURIComponent(`${s2}${l2}</svg>`)}`,o8=`data:${xf.svg},${encodeURIComponent(`${s2}${e8}${l2}</svg>`)}`,So=e=>{e&&(e.style.cursor="")},Re=(e,t)=>{e&&(e.style.cursor=t)},Fn,i2,Ef=(e,t)=>{let n=()=>{let r=t===a2.DARK;Fn=document.createElement("canvas"),Fn.theme=t,Fn.height=20,Fn.width=20;let i=Fn.getContext("2d");i.lineWidth=1,i.beginPath(),i.arc(Fn.width/2,Fn.height/2,5,0,2*Math.PI),i.fillStyle=r?"#000":"#fff",i.fill(),i.strokeStyle=r?"#fff":"#000",i.stroke(),i2=Fn.toDataURL(xf.svg)};(!Fn||Fn.theme!==t)&&n(),Re(e,`url(${i2}) ${20/2} ${20/2}, auto`)},Mo=(e,t)=>{if(e)if(t.activeTool.type==="selection")So(e);else if(sr(t))e.style.cursor=bf.GRAB;else if(po(t))Ef(e,t.theme);else if(t.activeTool.type==="laser"){let o=t.theme===a2.LIGHT?t8:o8;e.style.cursor=`url(${o}), auto`}else["image","custom"].includes(t.activeTool.type)?t.activeTool.type!=="image"&&(e.style.cursor=bf.AUTO):e.style.cursor=bf.CROSSHAIR};var pr=({viewportX:e,viewportY:t,nextZoom:o},n)=>{let r=e-n.offsetLeft,i=t-n.offsetTop,a=n.zoom.value,s=n.scrollX+(r-r/a),l=n.scrollY+(i-i/a),c=-(r-r/o),m=-(i-i/o);return{scrollX:s+c,scrollY:l+m,zoom:{value:o}}};import{jsx as Es,jsxs as f8}from"react/jsx-runtime";var l8=W({name:"changeViewBackgroundColor",label:"labels.canvasBackground",trackEvent:!1,predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.changeViewBackgroundColor&&!t.viewModeEnabled,perform:(e,t,o)=>({appState:{...t,...o},captureUpdate:o?.viewBackgroundColor?dn.IMMEDIATELY:dn.EVENTUALLY}),PanelComponent:({elements:e,appState:t,updateData:o,appProps:n,data:r})=>Es(cc,{palette:null,topPicks:r8,label:f("labels.canvasBackground"),type:"canvasBackground",color:t.viewBackgroundColor,onChange:i=>o({viewBackgroundColor:i}),"data-testid":"canvas-background-picker",elements:e,appState:t,updateData:o})}),gr=W({name:"clearCanvas",label:"labels.clearCanvas",icon:Ht,trackEvent:{category:"canvas"},predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.clearCanvas&&!t.viewModeEnabled&&t.openDialog?.name!=="elementLinkSelector",perform:(e,t,o,n)=>(n.imageCache.clear(),{elements:e.map(r=>s8(r,{isDeleted:!0})),appState:{...Rr(),files:{},theme:t.theme,penMode:t.penMode,penDetected:t.penDetected,exportBackground:t.exportBackground,exportEmbedScene:t.exportEmbedScene,gridSize:t.gridSize,gridStep:t.gridStep,gridModeEnabled:t.gridModeEnabled,stats:t.stats,pasteDialog:t.pasteDialog,activeTool:t.activeTool.type==="image"?{...t.activeTool,type:n.state.preferredSelectionTool.type}:t.activeTool},captureUpdate:dn.IMMEDIATELY})}),Wm=W({name:"zoomIn",label:"buttons.zoomIn",viewMode:!0,icon:rh,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>({appState:{...t,...pr({viewportX:t.width/2+t.offsetLeft,viewportY:t.height/2+t.offsetTop,nextZoom:Cn(t.zoom.value+wf)},t),userToFollow:null},captureUpdate:dn.EVENTUALLY}),PanelComponent:({updateData:e,appState:t})=>Es(ne,{type:"button",className:"zoom-in-button zoom-button",icon:rh,title:`${f("buttons.zoomIn")} \u2014 ${G("CtrlOrCmd++")}`,"aria-label":f("buttons.zoomIn"),disabled:t.zoom.value>=u2,onClick:()=>{e(null)}}),keyTest:e=>(e.code===On.EQUAL||e.code===On.NUM_ADD)&&(e[ur.CTRL_OR_CMD]||e.shiftKey)}),Ym=W({name:"zoomOut",label:"buttons.zoomOut",icon:ih,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>({appState:{...t,...pr({viewportX:t.width/2+t.offsetLeft,viewportY:t.height/2+t.offsetTop,nextZoom:Cn(t.zoom.value-wf)},t),userToFollow:null},captureUpdate:dn.EVENTUALLY}),PanelComponent:({updateData:e,appState:t})=>Es(ne,{type:"button",className:"zoom-out-button zoom-button",icon:ih,title:`${f("buttons.zoomOut")} \u2014 ${G("CtrlOrCmd+-")}`,"aria-label":f("buttons.zoomOut"),disabled:t.zoom.value<=g2,onClick:()=>{e(null)}}),keyTest:e=>(e.code===On.MINUS||e.code===On.NUM_SUBTRACT)&&(e[ur.CTRL_OR_CMD]||e.shiftKey)}),Vm=W({name:"resetZoom",label:"buttons.resetZoom",icon:Ey,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>({appState:{...t,...pr({viewportX:t.width/2+t.offsetLeft,viewportY:t.height/2+t.offsetTop,nextZoom:Cn(1)},t),userToFollow:null},captureUpdate:dn.EVENTUALLY}),PanelComponent:({updateData:e,appState:t})=>Es(Vt,{label:f("buttons.resetZoom"),style:{height:"100%"},children:f8(ne,{type:"button",className:"reset-zoom-button zoom-button",title:f("buttons.resetZoom"),"aria-label":f("buttons.resetZoom"),onClick:()=>{e(null)},children:[(t.zoom.value*100).toFixed(0),"%"]})}),keyTest:e=>(e.code===On.ZERO||e.code===On.NUM_ZERO)&&(e[ur.CTRL_OR_CMD]||e.shiftKey)}),c8=(e,t,o=1)=>{let[n,r,i,a]=e,s=i-n,l=t.width/s,c=a-r,m=t.height/c,d=Math.min(l,m)*yf(o,.1,1);return Math.min(d,1)},d8=.8,m8=(e,t)=>e[0]<=t[2]&&e[2]>=t[0]&&e[1]<=t[3]&&e[3]>=t[1],p8=(e,t)=>[e[0]-t,e[1]-t,e[2]+t,e[3]+t],d2=(e,t)=>{let o=(e[0]+e[2])/2,n=(e[1]+e[3])/2;return Math.hypot(o-t.x,n-t.y)},m2=e=>[e[0],e[1],e[2],e[3]],u8=(e,t)=>{let o=h2(e);if(!o.length)return[];let n=a8(o),r=n.length?n:o,i=new Map(o.map(d=>[d.id,d])),a=i8({clientX:t.offsetLeft+t.width/2,clientY:t.offsetTop+t.height/2},t),s=r.reduce((d,u)=>{let h=m2(c2(u,i));return d?d2(h,a)<d2(d.bounds,a)?{element:u,bounds:h}:d:{element:u,bounds:h}},null);if(!s)return[];let l=Math.max(160/t.zoom.value,.12*Math.min(t.width,t.height)/t.zoom.value),c=new Map([[s.element.id,s.element]]),m=s.bounds,p=!0;for(;p;){p=!1;let d=p8(m,l);for(let u of r){if(c.has(u.id))continue;let h=m2(c2(u,i));m8(h,d)&&(c.set(u.id,u),m=f2([...c.values()]),p=!0)}}return[...c.values()]},b2=({bounds:e,appState:t,canvasOffsets:o,fitToViewport:n=!1,viewportZoomFactor:r=1,minZoom:i=-1/0,maxZoom:a=1/0})=>{r=yf(r,g2,u2);let[s,l,c,m]=e,p=(s+c)/2,d=(l+m)/2,u=o?.left??0,h=o?.top??0,g=o?.right??0,E=o?.bottom??0,w=t.width-u-g,x=t.height-h-E,y;if(n){let k=c-s,L=m-l;y=Math.min(w/k,x/L)*r}else y=c8(e,{width:w,height:x},r);let v=Cn(yf(n8(y,wf,"floor"),i,a)),I=FE({scenePoint:{x:p,y:d},viewportDimensions:{width:t.width,height:t.height},offsets:o,zoom:{value:v}});return{appState:{...t,scrollX:I.scrollX,scrollY:I.scrollY,zoom:{value:v}},captureUpdate:dn.EVENTUALLY}},ys=({canvasOffsets:e,targetElements:t,appState:o,fitToViewport:n,viewportZoomFactor:r,minZoom:i,maxZoom:a})=>{let s=f2(h2(t));return b2({canvasOffsets:e,bounds:s,appState:o,fitToViewport:n,viewportZoomFactor:r,minZoom:i,maxZoom:a})},ple=W({name:"zoomToFitSelectionInViewport",label:"labels.zoomToFitViewport",icon:os,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return ys({targetElements:r.length?r:e,appState:{...t,userToFollow:null},fitToViewport:!1,canvasOffsets:n.getEditorUIOffsets()})},keyTest:e=>e.code===On.TWO&&e.shiftKey&&!e.altKey&&!e[ur.CTRL_OR_CMD]}),ule=W({name:"zoomToFitSelection",label:"helpDialog.zoomToSelection",icon:os,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return ys({targetElements:r.length?r:e,appState:{...t,userToFollow:null},fitToViewport:!0,canvasOffsets:n.getEditorUIOffsets()})},keyTest:e=>e.code===On.THREE&&e.shiftKey&&!e.altKey&&!e[ur.CTRL_OR_CMD]}),g8=W({name:"zoomToFit",label:"helpDialog.zoomToFit",icon:os,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>ys({targetElements:e,appState:{...t,userToFollow:null},fitToViewport:!1,canvasOffsets:n.getEditorUIOffsets()}),keyTest:e=>e.code===On.ONE&&e.shiftKey&&!e.altKey&&!e[ur.CTRL_OR_CMD]}),h8=W({name:"scrollBackToContent",label:"buttons.scrollBackToContent",icon:os,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i=r.length?r:u8(e,t);return i.length?ys({targetElements:i,appState:{...t,userToFollow:null},fitToViewport:!0,viewportZoomFactor:d8,canvasOffsets:n.getEditorUIOffsets()}):!1},PanelComponent:({updateData:e})=>Es(Vt,{label:f("buttons.scrollBackToContent"),style:{height:"100%"},children:Es(ne,{type:"button",className:"scroll-back-to-content-button zoom-button",icon:os,title:f("buttons.scrollBackToContent"),"aria-label":f("buttons.scrollBackToContent"),onClick:()=>{e(null)}})})}),Vi=W({name:"toggleTheme",label:(e,t)=>t.theme===fc.DARK?"buttons.lightMode":"buttons.darkMode",keywords:["toggle","dark","light","mode","theme"],icon:(e,t)=>e.theme===fc.LIGHT?Zl:jl,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o)=>({appState:{...t,theme:o||(t.theme===fc.LIGHT?fc.DARK:fc.LIGHT)},captureUpdate:dn.EVENTUALLY}),keyTest:e=>e.altKey&&e.shiftKey&&e.code===On.D,predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.toggleTheme}),gle=W({name:"toggleEraserTool",label:"toolBar.eraser",trackEvent:{category:"toolbar"},perform:(e,t,o,n)=>{let r;return po(t)?r=xs(t,{...t.activeTool.lastActiveTool||{type:n.state.preferredSelectionTool.type},lastActiveToolBeforeEraser:null}):r=xs(t,{type:"eraser",lastActiveToolBeforeEraser:t.activeTool}),{appState:{...t,selectedElementIds:{},selectedGroupIds:{},activeEmbeddable:null,activeTool:r},captureUpdate:dn.IMMEDIATELY}},keyTest:e=>e.key===ur.E}),hle=W({name:"toggleLassoTool",label:"toolBar.lasso",icon:Nr,trackEvent:{category:"toolbar"},predicate:(e,t,o,n)=>n.state.preferredSelectionTool.type!=="lasso",perform:(e,t,o,n)=>{let r;return t.activeTool.type!=="lasso"?(r=xs(t,{type:"lasso",fromSelection:!1}),Re(n.interactiveCanvas,p2.CROSSHAIR)):r=xs(t,{type:"selection"}),{appState:{...t,selectedElementIds:{},selectedGroupIds:{},activeEmbeddable:null,activeTool:r},captureUpdate:dn.NEVER}}}),x2=W({name:"toggleHandTool",label:"toolBar.hand",trackEvent:{category:"toolbar"},icon:Ja,viewMode:!1,perform:(e,t,o,n)=>{let r;return sr(t)?r=xs(t,{...t.activeTool.lastActiveTool||{type:"selection"},lastActiveToolBeforeEraser:null}):(r=xs(t,{type:"hand",lastActiveToolBeforeEraser:t.activeTool}),Re(n.interactiveCanvas,p2.GRAB)),{appState:{...t,selectedElementIds:{},selectedGroupIds:{},activeEmbeddable:null,activeTool:r},captureUpdate:dn.IMMEDIATELY}},keyTest:e=>!e.altKey&&!e[ur.CTRL_OR_CMD]&&e.key===ur.H});import{updateActiveTool as E2}from"@orangecatai/common";import{CaptureUpdateAction as b8}from"@orangecatai/element";var x8=W({name:"setEmbeddableAsActiveTool",trackEvent:{category:"toolbar"},target:"Tool",label:"toolBar.embeddable",perform:(e,t,o,n)=>{let r=E2(t,{type:"embeddable"});return Mo(n.canvas,{...t,activeTool:r}),{elements:e,appState:{...t,activeTool:E2(t,{type:"embeddable"})},captureUpdate:b8.EVENTUALLY}}});import{pointFrom as y2}from"@orangecatai/math";import{bindOrUnbindBindingElement as E8}from"@orangecatai/element/binding";import{isValidPolygon as w2,LinearElementEditor as $m,newElementWith as vf}from"@orangecatai/element";import{isBindingElement as v2,isFreeDrawElement as I2,isLinearElement as T2,isLineElement as Km}from"@orangecatai/element";import{KEYS as If,arrayToMap as y8,invariant as C2,shouldRotateWithDiscreteAngle as w8,updateActiveTool as k2}from"@orangecatai/common";import{isPathALoop as v8}from"@orangecatai/element";import{isInvisiblySmallElement as Tf}from"@orangecatai/element";import{CaptureUpdateAction as S2}from"@orangecatai/element";import{jsx as I8}from"react/jsx-runtime";var to=W({name:"finalize",label:"",trackEvent:!1,perform:(e,t,o,n)=>{let r=e,{interactiveCanvas:i,focusContainer:a,scene:s}=n,l=s.getNonDeletedElementsMap();if(o&&t.selectedLinearElement){let{event:d,sceneCoords:u}=o,h=$m.getElement(t.selectedLinearElement.elementId,l);C2(h,"Arrow element should exist if selectedLinearElement is set"),C2(u,"sceneCoords should be defined if actionFinalize is called with event");let g=$m.handlePointerUp(d,t.selectedLinearElement,t,n.scene);if(v2(h)&&!t.selectedLinearElement.segmentMidPointHoveredCoords){let E=!!t.newElement,x=(E||!t.selectedLinearElement.selectedPointsIndices?[h.points.length-1]:t.selectedLinearElement.selectedPointsIndices).reduce((y,v)=>(y.set(v,{point:$m.pointFromAbsoluteCoords(h,y2(u.x-g.pointerOffset.x,u.y-g.pointerOffset.y),l)}),y),new Map)??new Map;E8(h,x,u.x-g.pointerOffset.x,u.y-g.pointerOffset.y,s,t,{newArrow:E,altKey:d.altKey,angleLocked:w8(d)})}else Km(h)&&t.selectedLinearElement?.isEditing&&!t.newElement&&!w2(h.points)&&s.mutateElement(h,{polygon:!1});if(g!==t.selectedLinearElement){h&&Tf(h)&&(r=r.map(w=>w.id===h.id?vf(w,{isDeleted:!0}):w));let E=t.activeTool?.locked;return{elements:h.points.length<2||Tf(h)?e.map(w=>w.id===h.id?vf(w,{isDeleted:!0}):w):r,appState:{...t,cursorButton:"up",selectedLinearElement:E?null:{...g,selectedPointsIndices:null,isEditing:!1,initialState:{...g.initialState,lastClickedPoint:-1},pointerOffset:{x:0,y:0}},selectionElement:null,suggestedBinding:null,newElement:null,multiElement:null},captureUpdate:S2.IMMEDIATELY}}}window.document.activeElement instanceof HTMLElement&&a();let c=null;if(t.multiElement)c=t.multiElement;else if(t.newElement?.type==="freedraw"||v2(t.newElement))c=t.newElement;else if(Object.keys(t.selectedElementIds).length===1){let d=l.get(Object.keys(t.selectedElementIds)[0]);d&&(c=d)}if(c){if(t.selectedLinearElement&&t.multiElement&&c.type!=="freedraw"&&t.lastPointerDownWith!=="touch"){let{points:d}=c,{lastCommittedPoint:u}=t.selectedLinearElement;(!u||d[d.length-1]!==u)&&s.mutateElement(c,{points:c.points.slice(0,-1)})}if(c&&Tf(c)&&(r=r.map(d=>d.id===c?.id?vf(d,{isDeleted:!0}):d)),T2(c)||I2(c)){if(v8(c.points,t.zoom.value)&&(Km(c)||I2(c))){let u=c.points,h=u[0],g=u.map((E,w)=>w===u.length-1?y2(h[0],h[1]):E);Km(c)?s.mutateElement(c,{points:g,polygon:!0}):s.mutateElement(c,{points:g})}Km(c)&&!w2(c.points)&&s.mutateElement(c,{polygon:!1})}}(!t.activeTool.locked&&t.activeTool.type!=="freedraw"||!c)&&So(i);let m;t.activeTool.type==="eraser"?m=k2(t,{...t.activeTool.lastActiveTool||{type:n.state.preferredSelectionTool.type},lastActiveToolBeforeEraser:null}):m=k2(t,{type:n.state.preferredSelectionTool.type});let p=c&&T2(c)?new $m(c,y8(r)):t.selectedLinearElement;return p=p&&{...p,isEditing:t.newElement?!1:p.isEditing,initialState:{...p.initialState,lastClickedPoint:-1,origin:null}},{elements:r,appState:{...t,cursorButton:"up",activeTool:(t.activeTool.locked||t.activeTool.type==="freedraw")&&c?t.activeTool:m,activeEmbeddable:null,newElement:null,selectionElement:null,multiElement:null,editingTextElement:null,startBoundElement:null,suggestedBinding:null,selectedElementIds:c&&!t.activeTool.locked&&t.activeTool.type!=="freedraw"?{...t.selectedElementIds,[c.id]:!0}:t.selectedElementIds,selectedLinearElement:p},captureUpdate:S2.IMMEDIATELY}},keyTest:(e,t)=>e.key===If.ESCAPE&&(t.selectedLinearElement?.isEditing||!t.newElement&&t.multiElement===null)||(e.key===If.ESCAPE||e.key===If.ENTER)&&t.multiElement!==null,PanelComponent:({appState:e,updateData:t,data:o})=>I8(ne,{type:"button",icon:My,title:f("buttons.done"),"aria-label":f("buttons.done"),onClick:t,visible:e.multiElement!=null,size:o?.size||"medium",style:{pointerEvents:"all"}})});import{KEYS as Ts,DEFAULT_EXPORT_PADDING as uR,EXPORT_SCALES as gR,THEME as Sf}from"@orangecatai/common";import{getNonDeletedElements as hR}from"@orangecatai/element";import{CaptureUpdateAction as un}from"@orangecatai/element";import T8 from"clsx";import{jsx as M2,jsxs as C8}from"react/jsx-runtime";var bc=({children:e,checked:t,onChange:o,className:n})=>C8("div",{className:T8("Checkbox",n,{"is-checked":t}),onClick:r=>{o(!t,r),r.currentTarget.querySelector(".Checkbox-box").focus()},children:[M2("button",{type:"button",className:"Checkbox-box",role:"checkbox","aria-checked":t,children:cm}),M2("div",{className:"Checkbox-label",children:e})]});import{THEME as xc}from"@orangecatai/common";import{jsx as Ec}from"react/jsx-runtime";var A2=e=>{let t=e.title||(e.value===xc.DARK?f("buttons.lightMode"):f("buttons.darkMode"));return Ec(ne,{type:"icon",icon:e.value===xc.LIGHT?P2.MOON:P2.SUN,title:t,"aria-label":t,onClick:()=>e.onChange(e.value===xc.DARK?xc.LIGHT:xc.DARK),"data-testid":"toggle-dark-mode"})},P2={SUN:Ec("svg",{width:"512",height:"512",className:"rtl-mirror",viewBox:"0 0 512 512",children:Ec("path",{fill:"currentColor",d:"M256 160c-52.9 0-96 43.1-96 96s43.1 96 96 96 96-43.1 96-96-43.1-96-96-96zm246.4 80.5l-94.7-47.3 33.5-100.4c4.5-13.6-8.4-26.5-21.9-21.9l-100.4 33.5-47.4-94.8c-6.4-12.8-24.6-12.8-31 0l-47.3 94.7L92.7 70.8c-13.6-4.5-26.5 8.4-21.9 21.9l33.5 100.4-94.7 47.4c-12.8 6.4-12.8 24.6 0 31l94.7 47.3-33.5 100.5c-4.5 13.6 8.4 26.5 21.9 21.9l100.4-33.5 47.3 94.7c6.4 12.8 24.6 12.8 31 0l47.3-94.7 100.4 33.5c13.6 4.5 26.5-8.4 21.9-21.9l-33.5-100.4 94.7-47.3c13-6.5 13-24.7.2-31.1zm-155.9 106c-49.9 49.9-131.1 49.9-181 0-49.9-49.9-49.9-131.1 0-181 49.9-49.9 131.1-49.9 181 0 49.9 49.9 49.9 131.1 0 181z"})}),MOON:Ec("svg",{width:"512",height:"512",className:"rtl-mirror",viewBox:"0 0 512 512",children:Ec("path",{fill:"currentColor",d:"M283.211 512c78.962 0 151.079-35.925 198.857-94.792 7.068-8.708-.639-21.43-11.562-19.35-124.203 23.654-238.262-71.576-238.262-196.954 0-72.222 38.662-138.635 101.498-174.394 9.686-5.512 7.25-20.197-3.756-22.23A258.156 258.156 0 0 0 283.211 0c-141.309 0-256 114.511-256 256 0 141.309 114.511 256 256 256z"})})};import{useState as k8}from"react";import{focusNearestParent as S8,KEYS as M8}from"@orangecatai/common";import{jsx as L2,jsxs as P8}from"react/jsx-runtime";var _2=e=>{let{id:t}=qe(),[o,n]=k8(e.value),r=a=>{e.ignoreFocus||S8(a.target);let s=a.target.value;s!==e.value&&e.onChange(s)},i=a=>{if(a.key===M8.ENTER){if(a.preventDefault(),a.nativeEvent.isComposing||a.keyCode===229)return;a.currentTarget.blur()}};return P8("div",{className:"ProjectName",children:[L2("label",{className:"ProjectName-label",htmlFor:"filename",children:`${e.label}:`}),L2("input",{type:"text",className:"TextInput",onBlur:r,onKeyDown:i,id:`${t}-filename`,value:o,onChange:a=>n(a.target.value)})]})};import{DEFAULT_EXPORT_PADDING as rR,DEFAULT_FILENAME as iR,IMAGE_MIME_TYPES as Z2,isFirefox as aR,MIME_TYPES as sR,cloneJSON as lR,SVG_DOCUMENT_PREAMBLE as cR}from"@orangecatai/common";import{getNonDeletedElements as dR}from"@orangecatai/element";import{isFrameLikeElement as mR}from"@orangecatai/element";import{getElementsOverlappingFrame as pR}from"@orangecatai/element";import{ALLOWED_PASTE_MIME_TYPES as G8,EXPORT_DATA_TYPES as vc,MIME_TYPES as Po,arrayToMap as U8,isMemberOf as W8,isPromiseLike as Y8,EVENT as jm}from"@orangecatai/common";import{mutateElement as V8}from"@orangecatai/element";import{deepCopyElement as $8}from"@orangecatai/element";import{isFrameLikeElement as K8,isInitializedImageElement as X8}from"@orangecatai/element";import{getContainingFrame as W2}from"@orangecatai/element";import{pointFrom as Kr}from"@orangecatai/math";import{COLOR_PALETTE as R2,DEFAULT_CHART_COLOR_INDEX as A8,getAllColorsSpecificShade as L8,DEFAULT_FONT_FAMILY as _8,DEFAULT_FONT_SIZE as N2,VERTICAL_ALIGN as D8,randomId as B2,isDevEnv as F2,FONT_SIZES as R8}from"@orangecatai/common";import{newTextElement as Xm,newLinearElement as wc,newElement as kf}from"@orangecatai/element";var mn=32,$e=12,Xr=256,O2=50,$i="NOT_SPREADSHEET",ws="VALID_SPREADSHEET",yc=e=>{let t=/^([-+]?)[$€£¥₩]?([-+]?)([\d.,]+)[%]?$/.exec(e);return t?parseFloat(`${(t[1]||t[2])+t[3]}`.replace(/,/g,"")):null},Cf=(e,t)=>e.slice(1).every(o=>yc(o[t])!==null),D2=e=>{let t=e[0].length;if(t>2)return{type:$i,reason:"More than 2 columns"};if(t===1){if(!Cf(e,0))return{type:$i,reason:"Value is not numeric"};let l=yc(e[0][0])===null,c=(l?e.slice(1):e).map(m=>yc(m[0]));return c.length<2?{type:$i,reason:"Less than two rows"}:{type:ws,spreadsheet:{title:l?e[0][0]:null,labels:null,values:c}}}let o=Cf(e,0),n=Cf(e,1);if(!o&&!n)return{type:$i,reason:"Value is not numeric"};let[r,i]=n?[0,1]:[1,0],a=yc(e[0][i])===null,s=a?e.slice(1):e;return s.length<2?{type:$i,reason:"Less than 2 rows"}:{type:ws,spreadsheet:{title:a?e[0][i]:null,labels:s.map(l=>l[r]),values:s.map(l=>yc(l[i]))}}},N8=e=>{let t=[];for(let o=0;o<e[0].length;o++){let n=[];for(let r=0;r<e.length;r++)n.push(e[r][o]);t.push(n)}return t},z2=e=>{let t=e.trim().split(`
1
+ import{$ as Qg,A as qg,B as AA,C as GE,D as UE,E as jd,F as Yl,G as qd,H as Jd,I as Vl,J as WE,K as YE,L as VE,M as Ba,N as Fa,O as $E,P as LA,Q as Ni,R as Oa,S as $l,U as KE,W as XE,X as ZE,Y as Qd,Z as jE,_ as Jg,a as FE,aa as em,b as Ri,ba as qE,c as Cn,ca as eh,d as OE,da as Bi,e as He,ea as JE,f as zE,fa as za,g as le,ga as QE,h as _a,ha as Bo,i as kn,ia as th,j as Hl,ja as ey,k as Gl,ka as tm,l as Da,la as oh,m as Ul,ma as ty,n as Ra,na as oy,o as HE,oa as ny,p as Zg,pa as Kl,q as Sn,r as Mn,s as Rr,t as po,u as sr,v as Na,w as Xd,x as jg,y as Wl,z as Zd}from"./chunk-EQ2VZGNJ.js";import{a as C}from"./chunk-LVSKSH7E.js";import{M as Xg}from"./chunk-MSBJ7C4T.js";import{c as BE}from"./chunk-3PELD44J.js";import{b as RE,c as NE,d as A}from"./chunk-SRAX5OIU.js";import xQ,{useEffect as gA}from"react";import{DEFAULT_UI_OPTIONS as hA,isShallowEqual as EQ}from"@orangecatai/common";import l6 from"clsx";import jZ from"lodash.throttle";import nr,{useContext as Li}from"react";import{flushSync as wo}from"react-dom";import qZ from"roughjs/bin/rough";import{nanoid as Ex}from"nanoid";import{clamp as c6,pointFrom as de,pointDistance as Ti,vector as d6,pointRotateRads as yx,vectorFromPoint as wx,vectorSubtract as m6,vectorDot as p6,vectorNormalize as u6}from"@orangecatai/math";import{COLOR_PALETTE as JZ,CODES as g6,shouldResizeFromCenter as h6,shouldMaintainAspectRatio as Cd,shouldRotateWithDiscreteAngle as f6,isArrowKey as wg,KEYS as oe,APP_NAME as QZ,CURSOR_TYPE as st,DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT as ej,DEFAULT_VERTICAL_ALIGN as b6,DRAGGING_THRESHOLD as x6,ELEMENT_SHIFT_TRANSLATE_AMOUNT as tj,ELEMENT_TRANSLATE_AMOUNT as E6,EVENT as ue,FRAME_STYLE as on,IMAGE_MIME_TYPES as oj,IMAGE_RENDER_TIMEOUT as nj,LINE_CONFIRM_THRESHOLD as vx,MAX_ALLOWED_FILE_BYTES as y6,MIME_TYPES as Jn,MQ_RIGHT_SIDEBAR_MIN_WIDTH as rj,POINTER_BUTTON as Ci,ROUNDNESS as vg,SCROLL_TIMEOUT as ij,TAP_TWICE_TIMEOUT as aj,TEXT_TO_CENTER_SNAP_THRESHOLD as sj,THEME as Ig,TOUCH_CTX_MENU_TIMEOUT as lj,VERTICAL_ALIGN as cj,YOUTUBE_STATES as Tg,ZOOM_STEP as dj,POINTER_EVENTS as Sl,TOOL_TYPE as Qn,supportsResizeObserver as mj,DEFAULT_COLLISION_THRESHOLD as w6,DEFAULT_TEXT_ALIGN as pj,ARROW_TYPE as ki,DEFAULT_REDUCED_GLOBAL_ALPHA as uj,isLocalLink as gj,normalizeLink as Ix,toValidURL as hj,getGridPoint as Zt,getLineHeight as v6,debounce as I6,distance as Ml,getFontString as Tx,getNearestScrollableContainer as fj,isInputLike as T6,isToolIcon as bj,isWritableElement as kd,sceneCoordsToViewportCoords as Cg,tupleToCoors as Cx,viewportCoordsToSceneCoords as ot,wrapEvent as xj,updateObject as kx,updateActiveTool as er,isTransparent as Ej,easeToValuesRAF as yj,muteFSAbortError as wj,isTestEnv as cP,isDevEnv as dP,easeOut as vj,updateStable as Sd,addEventListener as gt,normalizeEOL as Ij,getDateTime as C6,isShallowEqual as k6,arrayToMap as kg,applyDarkModeFilter as Tj,randomInteger as Cj,CLASSES as Sx,Emitter as Ta,MINIMUM_ARROW_SIZE as kj,DOUBLE_TAP_POSITION_THRESHOLD as Sj,BIND_MODE_TIMEOUT as Mj,invariant as tr,getFeatureFlag as Ar,createUserAgentDescriptor as mP,getFormFactor as Pj,deriveStylesPanelMode as Dg,isIOS as Aj,isBrave as Lj,isSafari as _j,loadDesktopUIModePreference as Dj,setDesktopUIMode as Rj,isSelectionLikeTool as Sg,oneOf as S6}from"@orangecatai/common";import{getObservedAppState as Nj,getCommonBounds as Pl,getElementAbsoluteCoords as Mg,bindOrUnbindBindingElements as M6,fixBindingsAfterDeletion as Bj,getHoveredElementForBinding as wn,isBindingEnabled as Md,shouldEnableBindingForPointerEvent as Fj,updateBoundElements as Pg,LinearElementEditor as Me,newElementWith as Si,newFrameElement as P6,newFreeDrawElement as Oj,newEmbeddableElement as A6,newMagicFrameElement as L6,newIframeElement as zj,newArrowElement as Hj,newElement as Gj,newImageElement as Mx,newLinearElement as Uj,newTextElement as _6,refreshTextDimensions as Wj,deepCopyElement as D6,duplicateElements as Px,hasBoundTextElement as R6,isArrowElement as Al,isBindingElement as or,isBindingElementType as Yj,isBoundToContainer as Ax,isFrameLikeElement as jt,isImageElement as Mi,isEmbeddableElement as Lr,isInitializedImageElement as Pd,isLinearElement as so,isLinearElementType as Vj,isUsingAdaptiveRadius as $j,isIframeElement as Ll,isIframeLikeElement as Lx,isMagicFrameElement as _x,isTextBindableContainer as N6,isElbowArrow as vo,isFlowchartNodeElement as Kj,isBindableElement as Dx,isTextElement as vn,getNormalizedDimensions as Xj,isElementCompletelyInViewport as Rx,isElementInViewport as B6,isInvisiblySmallElement as F6,getCornerRadius as Zj,isPathALoop as O6,createSrcDoc as z6,embeddableURLValidator as Nx,maybeParseEmbedSrc as jj,getEmbedLink as Ag,getInitializedImageElements as qj,normalizeSVG as H6,updateImageCache as Jj,getBoundTextElement as Bx,getContainerCenter as Fx,getContainerElement as G6,isValidTextContainer as Qj,redrawTextBoundingBox as eq,hasBoundingBox as tq,getFrameChildren as Ox,isCursorInFrame as U6,addElementsToFrame as zx,replaceAllElementsInFrame as oq,removeElementsFromFrame as nq,getElementsInResizingFrame as Hx,getElementsInNewFrame as rq,getContainingFrame as Gx,elementOverlapsWithFrame as iq,updateFrameMembershipOfSelectedElements as W6,isElementInFrame as Y6,getFrameLikeTitle as aq,getElementsOverlappingFrame as sq,filterElementsEligibleAsFrameChildren as lq,hitElementBoundText as cq,hitElementBoundingBoxOnly as dq,hitElementItself as Ad,getVisibleSceneBounds as mq,FlowChartCreator as pq,FlowChartNavigator as uq,getLinkDirectionFromKey as V6,cropElement as gq,wrapText as hq,isElementLink as Ux,parseElementLinkFromURL as fq,isMeasureTextSupported as bq,normalizeText as xq,measureText as $6,getLineHeightInPx as Eq,getApproxMinLineWidth as yq,getApproxMinLineHeight as wq,getMinTextElementWidth as vq,ShapeCache as Ld,getRenderOpacity as Iq,editGroupForSelectedElement as Tq,getElementsInGroup as Ca,getSelectedGroupIdForElement as Cq,getSelectedGroupIds as kq,isElementInGroup as K6,isSelectedViaGroup as Sq,selectGroupsForSelectedElements as nn,syncInvalidIndices as pP,syncMovedIndices as X6,excludeElementsInFramesFromSelection as Mq,getSelectionStateForElements as Pq,makeNextSelectedElementIds as Oe,getResizeOffsetXY as Aq,getResizeArrowDirection as Lq,transformElements as _q,getCursorForResizingElement as Z6,getElementWithTransformHandleType as j6,getTransformHandleTypeFromCoords as q6,dragNewElement as J6,dragSelectedElements as Dq,getDragOffsetXY as Rq,isNonDeletedElement as Q6,Scene as eP,Store as Nq,CaptureUpdateAction as lo,hitElementBoundingBox as Bq,isLineElement as Wx,isSimpleArrow as Yx,StoreDelta as tP,positionElementsOnGrid as oP,calculateFixedPointForNonElbowArrowBinding as nP,bindOrUnbindBindingElement as Fq,mutateElement as Lg,getElementBounds as rP,doBoundsIntersect as Oq,isPointInElement as zq,maxBindingDistance_simple as Vx,convertToExcalidrawElements as iP,getSnapOutlineMidPoint as $x,handleFocusPointDrag as Hq,handleFocusPointHover as Gq,handleFocusPointPointerDown as Uq,handleFocusPointPointerUp as Wq,maybeHandleArrowPointlikeDrag as _g,getUncroppedWidthAndHeight as Yq}from"@orangecatai/element";import{KEYS as Mh,MOBILE_ACTION_BUTTON_BG as YA,updateActiveTool as VA}from"@orangecatai/common";import{getNonDeletedElements as Ph}from"@orangecatai/element";import{fixBindingsAfterDeletion as $A}from"@orangecatai/element";import{LinearElementEditor as nv}from"@orangecatai/element";import{newElementWith as wm}from"@orangecatai/element";import{getContainerElement as rv}from"@orangecatai/element";import{isBoundToContainer as Em,isElbowArrow as KA,isFrameLikeElement as XA}from"@orangecatai/element";import{getFrameChildren as ZA}from"@orangecatai/element";import{getElementsInGroup as Ah,selectGroupsForSelectedElements as jA}from"@orangecatai/element";import{CaptureUpdateAction as ym}from"@orangecatai/element";import{isDevEnv as NA}from"@orangecatai/common";import{atom as Ce,createStore as _A}from"jotai";import{createIsolation as DA}from"jotai-scope";var ry=DA();var{useAtom:ae,useSetAtom:Pn,useAtomValue:Ha,useStore:CQ}=ry,iy=ry.Provider,xt=_A();var RA=RE({"./locales/ar-SA.json":()=>import("./locales/ar-SA-NXDWD63E.js"),"./locales/az-AZ.json":()=>import("./locales/az-AZ-MXSORGZV.js"),"./locales/bg-BG.json":()=>import("./locales/bg-BG-O6MV2KSF.js"),"./locales/bn-BD.json":()=>import("./locales/bn-BD-T2VJNT7N.js"),"./locales/bn-IN.json":()=>import("./locales/bn-IN-MMW2ORAC.js"),"./locales/ca-ES.json":()=>import("./locales/ca-ES-MKBCGNOG.js"),"./locales/cs-CZ.json":()=>import("./locales/cs-CZ-V77HGUP7.js"),"./locales/da-DK.json":()=>import("./locales/da-DK-I5RFNTM4.js"),"./locales/de-CH.json":()=>import("./locales/de-CH-WLRDEVBV.js"),"./locales/de-DE.json":()=>import("./locales/de-DE-DTI4WUSC.js"),"./locales/el-GR.json":()=>import("./locales/el-GR-ZXDJ2OS4.js"),"./locales/en.json":()=>import("./locales/en-RQF5X6GM.js"),"./locales/es-ES.json":()=>import("./locales/es-ES-DYQHAD43.js"),"./locales/eu-ES.json":()=>import("./locales/eu-ES-QDSYU5Y3.js"),"./locales/fa-IR.json":()=>import("./locales/fa-IR-26LZG4PM.js"),"./locales/fi-FI.json":()=>import("./locales/fi-FI-6YS4KDE4.js"),"./locales/fr-FR.json":()=>import("./locales/fr-FR-BRLLPTZC.js"),"./locales/gl-ES.json":()=>import("./locales/gl-ES-OKUZTLYG.js"),"./locales/he-IL.json":()=>import("./locales/he-IL-26MGYIU7.js"),"./locales/hi-IN.json":()=>import("./locales/hi-IN-Q4ZOGTP2.js"),"./locales/hu-HU.json":()=>import("./locales/hu-HU-P2OXPSN5.js"),"./locales/id-ID.json":()=>import("./locales/id-ID-2EIKXYN6.js"),"./locales/it-IT.json":()=>import("./locales/it-IT-4CFKVXI2.js"),"./locales/ja-JP.json":()=>import("./locales/ja-JP-MAND2Z4V.js"),"./locales/kaa.json":()=>import("./locales/kaa-HQRTCXTJ.js"),"./locales/kab-KAB.json":()=>import("./locales/kab-KAB-JKIKKTGH.js"),"./locales/kk-KZ.json":()=>import("./locales/kk-KZ-HXQ63ZFC.js"),"./locales/km-KH.json":()=>import("./locales/km-KH-PKL3LSGX.js"),"./locales/ko-KR.json":()=>import("./locales/ko-KR-KXLREZX3.js"),"./locales/ku-TR.json":()=>import("./locales/ku-TR-MJ4IER3X.js"),"./locales/lt-LT.json":()=>import("./locales/lt-LT-H6WFQ6FJ.js"),"./locales/lv-LV.json":()=>import("./locales/lv-LV-GOCK6SJW.js"),"./locales/mr-IN.json":()=>import("./locales/mr-IN-IXVLDMEQ.js"),"./locales/my-MM.json":()=>import("./locales/my-MM-YG6MYTTD.js"),"./locales/nb-NO.json":()=>import("./locales/nb-NO-XGWJISD2.js"),"./locales/nl-NL.json":()=>import("./locales/nl-NL-XVDVCPNC.js"),"./locales/nn-NO.json":()=>import("./locales/nn-NO-EMX5MJX5.js"),"./locales/oc-FR.json":()=>import("./locales/oc-FR-ROEINTVO.js"),"./locales/pa-IN.json":()=>import("./locales/pa-IN-ZYN6SUDY.js"),"./locales/percentages.json":()=>import("./locales/percentages-5DKR754L.js"),"./locales/pl-PL.json":()=>import("./locales/pl-PL-6VTG7PHC.js"),"./locales/pt-BR.json":()=>import("./locales/pt-BR-5YFKRR5G.js"),"./locales/pt-PT.json":()=>import("./locales/pt-PT-GEIXXZ67.js"),"./locales/ro-RO.json":()=>import("./locales/ro-RO-E2P6TFZI.js"),"./locales/ru-RU.json":()=>import("./locales/ru-RU-YBIIY43T.js"),"./locales/si-LK.json":()=>import("./locales/si-LK-673C2CI2.js"),"./locales/sk-SK.json":()=>import("./locales/sk-SK-CKZHQ4AP.js"),"./locales/sl-SI.json":()=>import("./locales/sl-SI-557H2GWM.js"),"./locales/sv-SE.json":()=>import("./locales/sv-SE-XOPKKDWS.js"),"./locales/ta-IN.json":()=>import("./locales/ta-IN-XBH7DQI3.js"),"./locales/th-TH.json":()=>import("./locales/th-TH-TOCWH3R4.js"),"./locales/tr-TR.json":()=>import("./locales/tr-TR-GXW6CYY5.js"),"./locales/uk-UA.json":()=>import("./locales/uk-UA-IJKTNUDG.js"),"./locales/uz-UZ.json":()=>import("./locales/uz-UZ-TBZZEA4V.js"),"./locales/vi-VN.json":()=>import("./locales/vi-VN-MULSGNVB.js"),"./locales/zh-CN.json":()=>import("./locales/zh-CN-MVX3E32U.js"),"./locales/zh-HK.json":()=>import("./locales/zh-HK-JNU5RLIE.js"),"./locales/zh-TW.json":()=>import("./locales/zh-TW-LENVCA6T.js")});var BA=85,An={code:"en",label:"English"},Ua=[An,...[{code:"ar-SA",label:"\u0627\u0644\u0639\u0631\u0628\u064A\u0629",rtl:!0},{code:"bg-BG",label:"\u0411\u044A\u043B\u0433\u0430\u0440\u0441\u043A\u0438"},{code:"ca-ES",label:"Catal\xE0"},{code:"cs-CZ",label:"\u010Cesky"},{code:"de-DE",label:"Deutsch"},{code:"el-GR",label:"\u0395\u03BB\u03BB\u03B7\u03BD\u03B9\u03BA\u03AC"},{code:"es-ES",label:"Espa\xF1ol"},{code:"eu-ES",label:"Euskara"},{code:"fa-IR",label:"\u0641\u0627\u0631\u0633\u06CC",rtl:!0},{code:"fi-FI",label:"Suomi"},{code:"fr-FR",label:"Fran\xE7ais"},{code:"gl-ES",label:"Galego"},{code:"he-IL",label:"\u05E2\u05D1\u05E8\u05D9\u05EA",rtl:!0},{code:"hi-IN",label:"\u0939\u093F\u0928\u094D\u0926\u0940"},{code:"hu-HU",label:"Magyar"},{code:"id-ID",label:"Bahasa Indonesia"},{code:"it-IT",label:"Italiano"},{code:"ja-JP",label:"\u65E5\u672C\u8A9E"},{code:"kab-KAB",label:"Taqbaylit"},{code:"kk-KZ",label:"\u049A\u0430\u0437\u0430\u049B \u0442\u0456\u043B\u0456"},{code:"ko-KR",label:"\uD55C\uAD6D\uC5B4"},{code:"ku-TR",label:"Kurd\xEE"},{code:"lt-LT",label:"Lietuvi\u0173"},{code:"lv-LV",label:"Latvie\u0161u"},{code:"my-MM",label:"Burmese"},{code:"nb-NO",label:"Norsk bokm\xE5l"},{code:"nl-NL",label:"Nederlands"},{code:"nn-NO",label:"Norsk nynorsk"},{code:"oc-FR",label:"Occitan"},{code:"pa-IN",label:"\u0A2A\u0A70\u0A1C\u0A3E\u0A2C\u0A40"},{code:"pl-PL",label:"Polski"},{code:"pt-BR",label:"Portugu\xEAs Brasileiro"},{code:"pt-PT",label:"Portugu\xEAs"},{code:"ro-RO",label:"Rom\xE2n\u0103"},{code:"ru-RU",label:"\u0420\u0443\u0441\u0441\u043A\u0438\u0439"},{code:"sk-SK",label:"Sloven\u010Dina"},{code:"sv-SE",label:"Svenska"},{code:"sl-SI",label:"Sloven\u0161\u010Dina"},{code:"tr-TR",label:"T\xFCrk\xE7e"},{code:"uk-UA",label:"\u0423\u043A\u0440\u0430\u0457\u043D\u0441\u044C\u043A\u0430"},{code:"zh-CN",label:"\u7B80\u4F53\u4E2D\u6587"},{code:"zh-TW",label:"\u7E41\u9AD4\u4E2D\u6587"},{code:"vi-VN",label:"Ti\u1EBFng Vi\u1EC7t"},{code:"mr-IN",label:"\u092E\u0930\u093E\u0920\u0940"}].filter(e=>BE[e.code]>=BA).sort((e,t)=>e.label>t.label?1:-1)],nm="__test__";NA()&&Ua.unshift({code:nm,label:"test language"},{code:`${nm}.rtl`,label:"\u202Atest language (rtl)\u202C",rtl:!0});var Ga=An,om={},rm=async e=>{if(Ga=e,document.documentElement.dir=Ga.rtl?"rtl":"ltr",document.documentElement.lang=Ga.code,e.code.startsWith(nm))om={};else try{om=await RA(`./locales/${Ga.code}.json`)}catch(t){console.error(`Failed to load language ${e.code}:`,t.message),om=Xg}xt.set(sy,e.code)},lr=()=>Ga,ay=(e,t)=>{for(let o=0;o<t.length;++o){let n=t[o];if(e[n]===void 0)return;e=e[n]}if(typeof e=="string")return e},f=(e,t,o)=>{if(Ga.code.startsWith(nm))return`\u202A[[${t?`${e}(${JSON.stringify(t).slice(1,-1)})`:e}]]\u202C`;let n=e.split("."),r=ay(om,n)||ay(Xg,n)||o;if(r===void 0){let i=`Can't find translation for ${e}`;if(C.PROD)return console.warn(i),"";throw new Error(i)}if(t)for(let i in t)r=r.replace(`{{${i}}}`,String(t[i]));return r},sy=Ce(An.code),Ge=()=>{let e=Ha(sy);return{t:f,langCode:e}};import FA from"clsx";import Lt from"react";import{THEME as OA}from"@orangecatai/common";import{Fragment as Ue,jsx as b,jsxs as H}from"react/jsx-runtime";var cn=e=>"var(--icon-fill-color)",ly=e=>e===OA.LIGHT?"#fff":"#1e1e1e",R=(e,t=512)=>{let{width:o=512,height:n=o,mirror:r,style:i,...a}=typeof t=="number"?{width:t}:t;return b("svg",{"aria-hidden":"true",focusable:"false",role:"img",viewBox:`0 0 ${o} ${n}`,className:FA({"rtl-mirror":r}),style:i,...a,children:typeof e=="string"?b("path",{fill:"currentColor",d:e}):e})},K={width:24,height:24,fill:"none",strokeWidth:2,stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"},fe={width:20,height:20,fill:"none",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round"},HQ=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("rect",{x:3,y:8,width:18,height:4,rx:1}),b("line",{x1:12,y1:8,x2:12,y2:21}),b("path",{d:"M19 12v7a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2v-7"}),b("path",{d:"M7.5 8a2.5 2.5 0 0 1 0 -5a4.8 8 0 0 1 4.5 5a4.8 8 0 0 1 4.5 -5a2.5 2.5 0 0 1 0 5"})]}),K),im=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 19a9 9 0 0 1 9 0a9 9 0 0 1 9 0"}),b("path",{d:"M3 6a9 9 0 0 1 9 0a9 9 0 0 1 9 0"}),b("line",{x1:"3",y1:"6",x2:"3",y2:"19"}),b("line",{x1:"12",y1:"6",x2:"12",y2:"19"}),b("line",{x1:"21",y1:"6",x2:"21",y2:"19"})]}),K),cy=R(H("svg",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"12",y1:"5",x2:"12",y2:"19"}),b("line",{x1:"5",y1:"12",x2:"19",y2:"12"})]}),K),dy=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"12",cy:"12",r:"1"}),b("circle",{cx:"12",cy:"19",r:"1"}),b("circle",{cx:"12",cy:"5",r:"1"})]}),K),my=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),b("path",{d:"M12 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"}),b("path",{d:"M19 12m-1 0a1 1 0 1 0 2 0a1 1 0 1 0 -2 0"})]}),K),py=R(H("svg",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M9 4v6l-2 4v2h10v-2l-2 -4v-6"}),b("line",{x1:"12",y1:"16",x2:"12",y2:"21"}),b("line",{x1:"8",y1:"4",x2:"16",y2:"4"})]}),K),nh=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 5m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M19 8m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M5 11m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M15 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M6.5 9.5l3.5 -3"}),b("path",{d:"M14 5.5l3 1.5"}),b("path",{d:"M18.5 10l-2.5 7"}),b("path",{d:"M13.5 17.5l-7 -5"})]}),K),Fi=R(H("g",{children:[b("path",{d:"M13.542 8.542H6.458a2.5 2.5 0 0 0-2.5 2.5v3.75a2.5 2.5 0 0 0 2.5 2.5h7.084a2.5 2.5 0 0 0 2.5-2.5v-3.75a2.5 2.5 0 0 0-2.5-2.5Z",stroke:"currentColor",strokeWidth:"1.25"}),b("path",{d:"M10 13.958a1.042 1.042 0 1 0 0-2.083 1.042 1.042 0 0 0 0 2.083Z",stroke:"currentColor",strokeWidth:"1.25"}),b("mask",{id:"UnlockedIcon",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:6,y:1,width:9,height:9,children:b("path",{stroke:"none",d:"M6.399 9.561V5.175c0-.93.401-1.823 1.116-2.48a3.981 3.981 0 0 1 2.693-1.028c1.01 0 1.98.37 2.694 1.027.715.658 1.116 1.55 1.116 2.481",fill:"#fff"})}),b("g",{mask:"url(#UnlockedIcon)",children:b("path",{stroke:"none",d:"M5.149 9.561v1.25h2.5v-1.25h-2.5Zm5.06-7.894V.417v1.25Zm2.559 3.508v1.25h2.5v-1.25h-2.5ZM7.648 8.51V5.175h-2.5V8.51h2.5Zm0-3.334c0-.564.243-1.128.713-1.561L6.668 1.775c-.959.883-1.52 2.104-1.52 3.4h2.5Zm.713-1.561a2.732 2.732 0 0 1 1.847-.697v-2.5c-1.31 0-2.585.478-3.54 1.358L8.36 3.614Zm1.847-.697c.71 0 1.374.26 1.847.697l1.694-1.839a5.231 5.231 0 0 0-3.54-1.358v2.5Zm1.847.697c.47.433.713.997.713 1.561h2.5c0-1.296-.56-2.517-1.52-3.4l-1.693 1.839Z",fill:"currentColor"})})]}),fe),Wa=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M13.542 8.542H6.458a2.5 2.5 0 0 0-2.5 2.5v3.75a2.5 2.5 0 0 0 2.5 2.5h7.084a2.5 2.5 0 0 0 2.5-2.5v-3.75a2.5 2.5 0 0 0-2.5-2.5Z"}),b("path",{d:"M10 13.958a1.042 1.042 0 1 0 0-2.083 1.042 1.042 0 0 0 0 2.083Z"}),b("path",{d:"M6.667 8.333V5.417C6.667 3.806 8.159 2.5 10 2.5c1.841 0 3.333 1.306 3.333 2.917v2.916"})]}),fe),uy=R(b("g",{fill:"currentColor",children:b("path",{d:"M12 2a5 5 0 0 1 5 5v3a3 3 0 0 1 3 3v6a3 3 0 0 1 -3 3h-10a3 3 0 0 1 -3 -3v-6a3 3 0 0 1 3 -3v-3a5 5 0 0 1 5 -5m0 12a2 2 0 0 0 -1.995 1.85l-.005 .15a2 2 0 1 0 2 -2m0 -10a3 3 0 0 0 -3 3v3h6v-3a3 3 0 0 0 -3 -3"})}),{width:24,height:24}),gy=R(H(Ue,{children:[b("path",{d:"M38.5 83.5c-14-2-17.833-10.473-21-22.5C14.333 48.984 12 22 12 12.5",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"}),b("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m12.005 10.478 7.905 14.423L6 25.75l6.005-15.273Z",fill:"currentColor"}),b("path",{d:"M12.005 10.478c1.92 3.495 3.838 7 7.905 14.423m-7.905-14.423c3.11 5.683 6.23 11.368 7.905 14.423m0 0c-3.68.226-7.35.455-13.91.85m13.91-.85c-5.279.33-10.566.647-13.91.85m0 0c1.936-4.931 3.882-9.86 6.005-15.273M6 25.75c2.069-5.257 4.135-10.505 6.005-15.272",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"})]}),{width:41,height:94,fill:"none"}),hy=R(H(Ue,{children:[b("path",{d:"M18.026 1.232c-5.268 13.125-5.548 33.555 3.285 42.311 8.823 8.75 33.31 12.304 42.422 13.523",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"}),b("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m72.181 59.247-13.058-10-2.948 13.62 16.006-3.62Z",fill:"currentColor"}),b("path",{d:"M72.181 59.247c-3.163-2.429-6.337-4.856-13.058-10m13.058 10c-5.145-3.936-10.292-7.882-13.058-10m0 0c-.78 3.603-1.563 7.196-2.948 13.62m2.948-13.62c-1.126 5.168-2.24 10.346-2.948 13.62m0 0c5.168-1.166 10.334-2.343 16.006-3.62m-16.006 3.62c5.51-1.248 11.01-2.495 16.006-3.62",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"})]}),{width:85,height:71,fill:"none"}),fy=R(H(Ue,{children:[b("path",{d:"M1 77c14-2 31.833-11.973 35-24 3.167-12.016-6-35-9.5-43.5",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"}),b("path",{fillRule:"evenodd",clipRule:"evenodd",d:"m24.165 1.093-2.132 16.309 13.27-4.258-11.138-12.05Z",fill:"currentColor"}),b("path",{d:"M24.165 1.093c-.522 3.953-1.037 7.916-2.132 16.309m2.131-16.309c-.835 6.424-1.68 12.854-2.13 16.308m0 0c3.51-1.125 7.013-2.243 13.27-4.257m-13.27 4.257c5.038-1.608 10.08-3.232 13.27-4.257m0 0c-3.595-3.892-7.197-7.777-11.14-12.05m11.14 12.05c-3.837-4.148-7.667-8.287-11.14-12.05",stroke:"currentColor",strokeWidth:2,strokeLinecap:"round"})]}),{width:38,height:78,fill:"none"}),GQ=R(b("g",{fill:"currentColor",children:b("path",{d:"M39.9 32.889a.326.326 0 0 0-.279-.056c-2.094-3.083-4.774-6-7.343-8.833l-.419-.472a.212.212 0 0 0-.056-.139.586.586 0 0 0-.167-.111l-.084-.083-.056-.056c-.084-.167-.28-.278-.475-.167-.782.39-1.507.973-2.206 1.528-.92.722-1.842 1.445-2.708 2.25a8.405 8.405 0 0 0-.977 1.028c-.14.194-.028.361.14.444-.615.611-1.23 1.223-1.843 1.861a.315.315 0 0 0-.084.223c0 .083.056.166.111.194l1.09.833v.028c1.535 1.528 4.244 3.611 7.12 5.861.418.334.865.667 1.284 1 .195.223.39.473.558.695.084.11.28.139.391.055.056.056.14.111.196.167a.398.398 0 0 0 .167.056.255.255 0 0 0 .224-.111.394.394 0 0 0 .055-.167c.029 0 .028.028.056.028a.318.318 0 0 0 .224-.084l5.082-5.528a.309.309 0 0 0 0-.444Zm-14.63-1.917a.485.485 0 0 0 .111.14c.586.5 1.2 1 1.843 1.555l-2.569-1.945-.251-.166c-.056-.028-.112-.084-.168-.111l-.195-.167.056-.056.055-.055.112-.111c.866-.861 2.346-2.306 3.1-3.028-.81.805-2.43 3.167-2.095 3.944Zm8.767 6.89-2.122-1.612a44.713 44.713 0 0 0-2.625-2.5c1.145.861 2.122 1.611 2.262 1.75 1.117.972 1.06.806 1.815 1.445l.921.666a1.06 1.06 0 0 1-.251.25Zm.558.416-.056-.028c.084-.055.168-.111.252-.194l-.196.222ZM1.089 5.75c.055.361.14.722.195 1.056.335 1.833.67 3.5 1.284 4.75l.252.944c.084.361.223.806.363.917 1.424 1.25 3.602 3.11 5.947 4.889a.295.295 0 0 0 .363 0s0 .027.028.027a.254.254 0 0 0 .196.084.318.318 0 0 0 .223-.084c2.988-3.305 5.221-6.027 6.813-8.305.112-.111.14-.278.14-.417.111-.111.195-.25.307-.333.111-.111.111-.306 0-.39l-.028-.027c0-.055-.028-.139-.084-.167-.698-.666-1.2-1.138-1.731-1.638-.922-.862-1.871-1.75-3.881-3.75l-.028-.028c-.028-.028-.056-.056-.112-.056-.558-.194-1.703-.389-3.127-.639C6.087 2.223 3.21 1.723.614.944c0 0-.168 0-.196.028l-.083.084c-.028.027-.056.055-.224.11h.056-.056c.028.167.028.278.084.473 0 .055.112.5.112.555l.782 3.556Zm15.496 3.278-.335-.334c.084.112.196.195.335.334Zm-3.546 4.666-.056.056c0-.028.028-.056.056-.056Zm-2.038-10c.168.167.866.834 1.033.973-.726-.334-2.54-1.167-3.379-1.445.838.167 1.983.334 2.346.472ZM1.424 2.306c.419.722.754 3.222 1.089 5.666-.196-.778-.335-1.555-.503-2.278-.251-1.277-.503-2.416-.838-3.416.056 0 .14 0 .252.028Zm-.168-.584c-.112 0-.223-.028-.307-.028 0-.027 0-.055-.028-.055.14 0 .223.028.335.083Zm-1.089.222c0-.027 0-.027 0 0ZM39.453 1.333c.028-.11-.558-.61-.363-.639.42-.027.42-.666 0-.666-.558.028-1.144.166-1.675.25-.977.194-1.982.389-2.96.61-2.205.473-4.383.973-6.561 1.557-.67.194-1.424.333-2.066.666-.224.111-.196.333-.084.472-.056.028-.084.028-.14.056-.195.028-.363.056-.558.083-.168.028-.252.167-.224.334 0 .027.028.083.028.11-1.173 1.556-2.485 3.195-3.909 4.945-1.396 1.611-2.876 3.306-4.356 5.056-4.719 5.5-10.052 11.75-15.943 17.25a.268.268 0 0 0 0 .389c.028.027.056.055.084.055-.084.084-.168.14-.252.222-.056.056-.084.111-.084.167a.605.605 0 0 0-.111.139c-.112.111-.112.305.028.389.111.11.307.11.39-.028.029-.028.029-.056.056-.056a.44.44 0 0 1 .615 0c.335.362.67.723.977 1.028l-.698-.583c-.112-.111-.307-.083-.39.028-.113.11-.085.305.027.389l7.427 6.194c.056.056.112.056.196.056s.14-.028.195-.084l.168-.166c.028.027.083.027.111.027.084 0 .14-.027.196-.083 10.052-10.055 18.15-17.639 27.42-24.417.083-.055.111-.166.111-.25.112 0 .196-.083.251-.194 1.704-5.194 2.039-9.806 2.15-12.083v-.028c0-.028.028-.056.028-.083.028-.056.028-.084.028-.084a1.626 1.626 0 0 0-.111-1.028ZM21.472 9.5c.446-.5.893-1.028 1.34-1.5-2.876 3.778-7.65 9.583-14.408 16.5 4.607-5.083 9.242-10.333 13.068-15ZM5.193 35.778h.084-.084Zm3.462 3.194c-.027-.028-.027-.028 0-.028v.028Zm4.16-3.583c.224-.25.448-.472.699-.722 0 0 0 .027.028.027-.252.223-.475.445-.726.695Zm1.146-1.111c.14-.14.279-.334.446-.5l.028-.028c1.648-1.694 3.351-3.389 5.082-5.111l.028-.028c.419-.333.921-.694 1.368-1.028a379.003 379.003 0 0 0-6.952 6.695ZM24.794 6.472c-.921 1.195-1.954 2.778-2.82 4.028-2.736 3.944-11.532 13.583-11.727 13.75a1976.983 1976.983 0 0 1-8.042 7.639l-.167.167c-.14-.167-.14-.417.028-.556C14.49 19.861 22.03 10.167 25.074 5.917c-.084.194-.14.36-.28.555Zm4.83 5.695c-1.116-.64-1.646-1.64-1.34-2.611l.084-.334c.028-.083.084-.194.14-.277.307-.5.754-.917 1.257-1.167.027 0 .055 0 .083-.028-.028-.056-.028-.139-.028-.222.028-.167.14-.278.335-.278.335 0 1.369.306 1.76.639.111.083.223.194.335.305.14.167.363.445.474.667.056.028.112.306.196.445.056.222.111.472.084.694-.028.028 0 .194-.028.194a2.668 2.668 0 0 1-.363 1.028c-.028.028-.028.056-.056.084l-.028.027c-.14.223-.335.417-.53.556-.643.444-1.369.583-2.095.389 0 0-.195-.084-.28-.111Zm8.154-.834a39.098 39.098 0 0 1-.893 3.167c0 .028-.028.083 0 .111-.056 0-.084.028-.14.056-2.206 1.61-4.356 3.305-6.506 5.028 1.843-1.64 3.686-3.306 5.613-4.945.558-.5.949-1.139 1.06-1.861l.28-1.667v-.055c.14-.334.67-.195.586.166Z",fill:"currentColor"})}),{width:40,height:40,fill:"none"}),Oi=R(H("g",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 6l4.153 11.793a0.365 .365 0 0 0 .331 .207a0.366 .366 0 0 0 .332 -.207l2.184 -4.793l4.787 -1.994a0.355 .355 0 0 0 .213 -.323a0.355 .355 0 0 0 -.213 -.323l-11.787 -4.36z"}),b("path",{d:"M13.5 13.5l4.5 4.5"})]}),{fill:"none",width:22,height:22,strokeWidth:1.25}),Nr=R(H("g",{stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:1.5,children:[b("path",{d:"M4.028 13.252c-.657 -.972 -1.028 -2.078 -1.028 -3.252c0 -3.866 4.03 -7 9 -7s9 3.134 9 7s-4.03 7 -9 7c-1.913 0 -3.686 -.464 -5.144 -1.255"}),b("path",{d:"M5 15m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M5 17c0 1.42 .316 2.805 1 4"})]}),{fill:"none",width:22,height:22,strokeWidth:1.25}),Ya=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("rect",{x:"4",y:"4",width:"16",height:"16",rx:"2"})]}),K),Va=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10.5 20.4l-6.9 -6.9c-.781 -.781 -.781 -2.219 0 -3l6.9 -6.9c.781 -.781 2.219 -.781 3 0l6.9 6.9c.781 .781 .781 2.219 0 3l-6.9 6.9c-.781 .781 -2.219 .781 -3 0z"})]}),K),$a=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"12",cy:"12",r:"9"})]}),K),am=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"5",y1:"12",x2:"19",y2:"12"}),b("line",{x1:"15",y1:"16",x2:"19",y2:"12"}),b("line",{x1:"15",y1:"8",x2:"19",y2:"12"})]}),K),Ka=R(b("path",{d:"M4.167 10h11.666",strokeWidth:"1.5"}),fe),by=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M20 17v-12c0 -1.121 -.879 -2 -2 -2s-2 .879 -2 2v12l2 2l2 -2z"}),b("path",{d:"M16 7h4"}),b("path",{d:"M18 19h-13a2 2 0 1 1 0 -4h4a2 2 0 1 0 0 -4h-3"})]}),K),Ln=R(H("g",{strokeWidth:"1.25",children:[b("path",{clipRule:"evenodd",d:"m7.643 15.69 7.774-7.773a2.357 2.357 0 1 0-3.334-3.334L4.31 12.357a3.333 3.333 0 0 0-.977 2.357v1.953h1.953c.884 0 1.732-.352 2.357-.977Z"}),b("path",{d:"m11.25 5.417 3.333 3.333"})]}),fe),_n=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"20",x2:"7",y2:"20"}),b("line",{x1:"14",y1:"20",x2:"21",y2:"20"}),b("line",{x1:"6.9",y1:"15",x2:"13.8",y2:"15"}),b("line",{x1:"10.2",y1:"6.3",x2:"16",y2:"20"}),b("polyline",{points:"5 20 11 4 13 4 20 20"})]}),K),xy=R(H("g",{stroke:"currentColor",strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 7v-2h13v2"}),b("path",{d:"M10 5v14"}),b("path",{d:"M12 19h-4"}),b("path",{d:"M15 13v-1h6v1"}),b("path",{d:"M18 12v7"}),b("path",{d:"M17 19h2"})]}),K),Xa=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M12.5 6.667h.01"}),b("path",{d:"M4.91 2.625h10.18a2.284 2.284 0 0 1 2.285 2.284v10.182a2.284 2.284 0 0 1-2.284 2.284H4.909a2.284 2.284 0 0 1-2.284-2.284V4.909a2.284 2.284 0 0 1 2.284-2.284Z"}),b("path",{d:"m3.333 12.5 3.334-3.333c.773-.745 1.726-.745 2.5 0l4.166 4.166"}),b("path",{d:"m11.667 11.667.833-.834c.774-.744 1.726-.744 2.5 0l1.667 1.667"})]}),fe),sm=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M19 20h-10.5l-4.21 -4.3a1 1 0 0 1 0 -1.41l10 -10a1 1 0 0 1 1.41 0l5 5a1 1 0 0 1 0 1.41l-9.2 9.3"}),b("path",{d:"M18 13.3l-6.3 -6.3"})]}),K),rh=R(b("path",{strokeWidth:"1.25",d:"M10 4.167v11.666M4.167 10h11.666"}),fe),ih=R(b("path",{d:"M5 10h10",strokeWidth:"1.25"}),fe),Ey=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M21 21l-6 -6"}),b("path",{d:"M3.268 12.043a7.017 7.017 0 0 0 6.634 4.957a7.012 7.012 0 0 0 7.043 -6.131a7 7 0 0 0 -5.314 -7.672a7.021 7.021 0 0 0 -8.241 4.403"}),b("path",{d:"M3 4v4h4"})]}),K),Ht=R(b("path",{strokeWidth:"1.25",d:"M3.333 5.833h13.334M8.333 9.167v5M11.667 9.167v5M4.167 5.833l.833 10c0 .92.746 1.667 1.667 1.667h6.666c.92 0 1.667-.746 1.667-1.667l.833-10M7.5 5.833v-2.5c0-.46.373-.833.833-.833h3.334c.46 0 .833.373.833.833v2.5"}),fe),Za=R(H("g",{strokeWidth:"1.5",children:[b("polyline",{points:"12 16 18 10 12 4"}),b("polyline",{points:"8 4 2 10 8 16"})]}),fe),Xl=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M14.375 6.458H8.958a2.5 2.5 0 0 0-2.5 2.5v5.417a2.5 2.5 0 0 0 2.5 2.5h5.417a2.5 2.5 0 0 0 2.5-2.5V8.958a2.5 2.5 0 0 0-2.5-2.5Z"}),b("path",{clipRule:"evenodd",d:"M11.667 3.125c.517 0 .986.21 1.325.55.34.338.55.807.55 1.325v1.458H8.333c-.485 0-.927.185-1.26.487-.343.312-.57.75-.609 1.24l-.005 5.357H5a1.87 1.87 0 0 1-1.326-.55 1.87 1.87 0 0 1-.549-1.325V5c0-.518.21-.987.55-1.326.338-.34.807-.549 1.325-.549h6.667Z"})]}),fe),Zl=R(b("path",{clipRule:"evenodd",d:"M10 2.5h.328a6.25 6.25 0 0 0 6.6 10.372A7.5 7.5 0 1 1 10 2.493V2.5Z",stroke:"currentColor"}),fe),jl=R(b("g",{stroke:"currentColor",strokeLinejoin:"round",children:b("path",{d:"M10 12.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM10 4.167V2.5M14.167 5.833l1.166-1.166M15.833 10H17.5M14.167 14.167l1.166 1.166M10 15.833V17.5M5.833 14.167l-1.166 1.166M5 10H3.333M5.833 5.833 4.667 4.667"})}),{...fe,strokeWidth:1.5}),yy=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"6",x2:"20",y2:"6"}),b("line",{x1:"4",y1:"12",x2:"20",y2:"12"}),b("line",{x1:"4",y1:"18",x2:"20",y2:"18"})]}),K),zi=R(b("path",{strokeWidth:"1.25",d:"M3.333 14.167v1.666c0 .92.747 1.667 1.667 1.667h10c.92 0 1.667-.746 1.667-1.667v-1.666M5.833 9.167 10 13.333l4.167-4.166M10 3.333v10"}),fe),ja=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"12",cy:"12",r:"9"}),b("line",{x1:"12",y1:"17",x2:"12",y2:"17.01"}),b("path",{d:"M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"})]}),K),wy=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"12",cy:"12",r:"9"}),b("line",{x1:"12",y1:"17",x2:"12",y2:"17.01"}),b("path",{d:"M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"})]}),K),ah=R(b("path",{strokeWidth:"1.25",d:"M9.167 5.833H5.833c-1.254 0-2.5 1.282-2.5 2.5v5.834c0 1.283 1.252 2.5 2.5 2.5h5.834c1.251 0 2.5-1.25 2.5-2.5v-3.334M8.333 11.667l8.334-8.334M12.5 3.333h4.167V7.5"}),fe),lm=R(b("path",{d:"M7.5 15.833c-3.583 1.167-3.583-2.083-5-2.5m10 4.167v-2.917c0-.833.083-1.166-.417-1.666 2.334-.25 4.584-1.167 4.584-5a3.833 3.833 0 0 0-1.084-2.667 3.5 3.5 0 0 0-.083-2.667s-.917-.25-2.917 1.084a10.25 10.25 0 0 0-5.166 0C5.417 2.333 4.5 2.583 4.5 2.583a3.5 3.5 0 0 0-.083 2.667 3.833 3.833 0 0 0-1.084 2.667c0 3.833 2.25 4.75 4.584 5-.5.5-.5 1-.417 1.666V17.5",strokeWidth:"1.25"}),fe),vy=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M7.5 10.833a.833.833 0 1 0 0-1.666.833.833 0 0 0 0 1.666ZM12.5 10.833a.833.833 0 1 0 0-1.666.833.833 0 0 0 0 1.666ZM6.25 6.25c2.917-.833 4.583-.833 7.5 0M5.833 13.75c2.917.833 5.417.833 8.334 0"}),b("path",{d:"M12.917 14.167c0 .833 1.25 2.5 1.666 2.5 1.25 0 2.361-1.39 2.917-2.5.556-1.39.417-4.861-1.25-9.584-1.214-.846-2.5-1.116-3.75-1.25l-.833 2.084M7.083 14.167c0 .833-1.13 2.5-1.526 2.5-1.191 0-2.249-1.39-2.778-2.5-.529-1.39-.397-4.861 1.19-9.584 1.157-.846 2.318-1.116 3.531-1.25l.833 2.084"})]}),fe),Iy=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 4l11.733 16h4.267l-11.733 -16z"}),b("path",{d:"M4 20l6.768 -6.768m2.46 -2.46l6.772 -6.772"})]}),K),cm=R(b("polyline",{fill:"none",stroke:"currentColor",points:"20 6 9 17 4 12"}),{width:24,height:24}),ql=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M8.333 11.667a2.917 2.917 0 0 0 4.167 0l3.333-3.334a2.946 2.946 0 1 0-4.166-4.166l-.417.416"}),b("path",{d:"M11.667 8.333a2.917 2.917 0 0 0-4.167 0l-3.333 3.334a2.946 2.946 0 0 0 4.166 4.166l.417-.416"})]}),fe),Ty=R("M433.941 129.941l-83.882-83.882A48 48 0 0 0 316.118 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h352c26.51 0 48-21.49 48-48V163.882a48 48 0 0 0-14.059-33.941zM224 416c-35.346 0-64-28.654-64-64 0-35.346 28.654-64 64-64s64 28.654 64 64c0 35.346-28.654 64-64 64zm96-304.52V212c0 6.627-5.373 12-12 12H76c-6.627 0-12-5.373-12-12V108c0-6.627 5.373-12 12-12h228.52c3.183 0 6.235 1.264 8.485 3.515l3.48 3.48A11.996 11.996 0 0 1 320 111.48z",{width:448,height:512}),Cy=R("M252 54L203 8a28 27 0 00-20-8H28C12 0 0 12 0 27v195c0 15 12 26 28 26h204c15 0 28-11 28-26V73a28 27 0 00-8-19zM130 213c-21 0-37-16-37-36 0-19 16-35 37-35 20 0 37 16 37 35 0 20-17 36-37 36zm56-169v56c0 4-4 6-7 6H44c-4 0-7-2-7-6V42c0-4 3-7 7-7h133l4 2 3 2a7 7 0 012 5z M296 201l87 95-188 205-78 9c-10 1-19-8-18-20l9-84zm141-14l-41-44a31 31 0 00-46 0l-38 41 87 95 38-42c13-14 13-36 0-50z",{width:448,height:512}),qa=R(b("path",{d:"m9.257 6.351.183.183H15.819c.34 0 .727.182 1.051.506.323.323.505.708.505 1.05v5.819c0 .316-.183.7-.52 1.035-.337.338-.723.522-1.037.522H4.182c-.352 0-.74-.181-1.058-.5-.318-.318-.499-.705-.499-1.057V5.182c0-.351.181-.736.5-1.054.32-.321.71-.503 1.057-.503H6.53l2.726 2.726Z",strokeWidth:"1.25"}),fe),UQ=R("M384 112v352c0 26.51-21.49 48-48 48H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h80c0-35.29 28.71-64 64-64s64 28.71 64 64h80c26.51 0 48 21.49 48 48zM192 40c-13.255 0-24 10.745-24 24s10.745 24 24 24 24-10.745 24-24-10.745-24-24-24m96 114v-20a6 6 0 0 0-6-6H102a6 6 0 0 0-6 6v20a6 6 0 0 0 6 6h180a6 6 0 0 0 6-6z",{width:384,height:512}),WQ=R("M204.3 5C104.9 24.4 24.8 104.3 5.2 203.4c-37 187 131.7 326.4 258.8 306.7 41.2-6.4 61.4-54.6 42.5-91.7-23.1-45.4 9.9-98.4 60.9-98.4h79.7c35.8 0 64.8-29.6 64.9-65.3C511.5 97.1 368.1-26.9 204.3 5zM96 320c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm32-128c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128-64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32zm128 64c-17.7 0-32-14.3-32-32s14.3-32 32-32 32 14.3 32 32-14.3 32-32 32z"),dm=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 16l1.465 1.638a2 2 0 1 1 -3.015 .099l1.55 -1.737z"}),b("path",{d:"M13.737 9.737c2.299 -2.3 3.23 -5.095 2.081 -6.245c-1.15 -1.15 -3.945 -.217 -6.244 2.082c-2.3 2.299 -3.231 5.095 -2.082 6.244c1.15 1.15 3.946 .218 6.245 -2.081z"}),b("path",{d:"M7.492 11.818c.362 .362 .768 .676 1.208 .934l6.895 4.047c1.078 .557 2.255 -.075 3.692 -1.512c1.437 -1.437 2.07 -2.614 1.512 -3.692c-.372 -.718 -1.72 -3.017 -4.047 -6.895a6.015 6.015 0 0 0 -.934 -1.208"})]}),K),ky=R(b("g",{strokeWidth:1.5,children:b("path",{d:"M6 18l12 -12"})}),K),mm=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15 8h.01"}),b("path",{d:"M12 20h-5a3 3 0 0 1 -3 -3v-10a3 3 0 0 1 3 -3h10a3 3 0 0 1 3 3v5"}),b("path",{d:"M4 15l4 -4c.928 -.893 2.072 -.893 3 0l4 4"}),b("path",{d:"M14 14l1 -1c.617 -.593 1.328 -.793 2.009 -.598"}),b("path",{d:"M19 16v6"}),b("path",{d:"M22 19l-3 3l-3 -3"})]}),K),Sy=R("M216 0h80c13.3 0 24 10.7 24 24v168h87.7c17.8 0 26.7 21.5 14.1 34.1L269.7 378.3c-7.5 7.5-19.8 7.5-27.3 0L90.1 226.1c-12.6-12.6-3.7-34.1 14.1-34.1H192V24c0-13.3 10.7-24 24-24zm296 376v112c0 13.3-10.7 24-24 24H24c-13.3 0-24-10.7-24-24V376c0-13.3 10.7-24 24-24h146.7l49 49c20.1 20.1 52.5 20.1 72.6 0l49-49H488c13.3 0 24 10.7 24 24zm-124 88c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20zm64 0c0-11-9-20-20-20s-20 9-20 20 9 20 20 20 20-9 20-20z",{width:512,height:512}),YQ=R("M416 208H272V64c0-17.67-14.33-32-32-32h-32c-17.67 0-32 14.33-32 32v144H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h144v144c0 17.67 14.33 32 32 32h32c17.67 0 32-14.33 32-32V304h144c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z",{width:448,height:512}),VQ=R("M416 208H32c-17.67 0-32 14.33-32 32v32c0 17.67 14.33 32 32 32h384c17.67 0 32-14.33 32-32v-32c0-17.67-14.33-32-32-32z",{width:448,height:512}),My=R("M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"),$Q=R("M16 132h416c8.837 0 16-7.163 16-16V76c0-8.837-7.163-16-16-16H16C7.163 60 0 67.163 0 76v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16zm0 160h416c8.837 0 16-7.163 16-16v-40c0-8.837-7.163-16-16-16H16c-8.837 0-16 7.163-16 16v40c0 8.837 7.163 16 16 16z"),sh=R(b("path",{d:"M7.5 10.833 4.167 7.5 7.5 4.167M4.167 7.5h9.166a3.333 3.333 0 0 1 0 6.667H12.5",strokeWidth:"1.25"}),fe),lh=R(b("path",{d:"M12.5 10.833 15.833 7.5 12.5 4.167M15.833 7.5H6.667a3.333 3.333 0 1 0 0 6.667H7.5",strokeWidth:"1.25"}),fe),Py=R("M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zM262.655 90c-54.497 0-89.255 22.957-116.549 63.758-3.536 5.286-2.353 12.415 2.715 16.258l34.699 26.31c5.205 3.947 12.621 3.008 16.665-2.122 17.864-22.658 30.113-35.797 57.303-35.797 20.429 0 45.698 13.148 45.698 32.958 0 14.976-12.363 22.667-32.534 33.976C247.128 238.528 216 254.941 216 296v4c0 6.627 5.373 12 12 12h56c6.627 0 12-5.373 12-12v-1.333c0-28.462 83.186-29.647 83.186-106.667 0-58.002-60.165-102-116.531-102zM256 338c-25.365 0-46 20.635-46 46 0 25.364 20.635 46 46 46s46-20.636 46-46c0-25.365-20.635-46-46-46z",{mirror:!0}),Ay=R(b("path",{d:"M5 12.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM15 7.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM15 17.5a2.5 2.5 0 1 0 0-5 2.5 2.5 0 0 0 0 5ZM7.25 8.917l5.5-2.834M7.25 11.083l5.5 2.834",strokeWidth:"1.5"}),fe),KQ=R("M256 32c14.2 0 27.3 7.5 34.5 19.8l216 368c7.3 12.4 7.3 27.7 .2 40.1S486.3 480 472 480H40c-14.3 0-27.6-7.7-34.7-20.1s-7-27.8 .2-40.1l216-368C228.7 39.5 241.8 32 256 32zm0 128c-13.3 0-24 10.7-24 24V296c0 13.3 10.7 24 24 24s24-10.7 24-24V184c0-13.3-10.7-24-24-24zm32 224a32 32 0 1 0 -64 0 32 32 0 1 0 64 0z"),XQ=R("M16 5l-1.42 1.42-1.59-1.59V16h-1.98V4.83L9.42 6.42 8 5l4-4 4 4zm4 5v11c0 1.1-.9 2-2 2H6c-1.11 0-2-.9-2-2V10c0-1.11.89-2 2-2h3v2H6v11h12V10h-3V8h3c1.1 0 2 .89 2 2z",{width:24,height:24}),ZQ=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 9h-1a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-8a2 2 0 0 0 -2 -2h-1"}),b("path",{d:"M12 14v-11"}),b("path",{d:"M9 6l3 -3l3 3"})]}),K),jQ=R(H(Ue,{children:[b("path",{fill:"currentColor",d:"M40 5.6v6.1l-4.1.7c-8.9 1.4-16.5 6.9-20.6 15C13 32 10.9 43 12.4 43c.4 0 2.4-1.3 4.4-3 5-3.9 12.1-7 18.2-7.7l5-.6v12.8l11.2-11.3L62.5 22 51.2 10.8 40-.5v6.1zm10.2 22.6L44 34.5v-6.8l-6.9.6c-3.9.3-9.8 1.7-13.2 3.1-3.5 1.4-6.5 2.4-6.7 2.2-.9-1 3-7.5 6.4-10.8C28 18.6 34.4 16 40.1 16c3.7 0 3.9-.1 3.9-3.2V9.5l6.2 6.3 6.3 6.2-6.3 6.2z"}),b("path",{stroke:"currentColor",fill:"currentColor",d:"M0 36v20h48v-6.2c0-6 0-6.1-2-4.3-1.1 1-2 2.9-2 4.2V52H4V34c0-17.3-.1-18-2-18s-2 .7-2 20z"})]}),{width:64,height:64}),qQ=R(b("path",{stroke:"currentColor",strokeWidth:"40",fill:"currentColor",d:"M148 560a318 318 0 0 0 522 110 316 316 0 0 0 0-450 316 316 0 0 0-450 0c-11 11-21 22-30 34v4h47c25 0 46 21 46 46s-21 45-46 45H90c-13 0-25-6-33-14-9-9-14-20-14-33V156c0-25 20-45 45-45s45 20 45 45v32l1 1a401 401 0 0 1 623 509l212 212a42 42 0 0 1-59 59L698 757A401 401 0 0 1 65 570a42 42 0 0 1 83-10z"}),{width:1024}),Ly=H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 10l0 10"}),b("path",{d:"M12 10l4 4"}),b("path",{d:"M12 10l-4 4"}),b("path",{d:"M4 4l16 0"})]}),_y=H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 5l0 14"}),b("path",{d:"M16 9l-4 -4"}),b("path",{d:"M8 9l4 -4"})]}),ch=R(_y,K),dh=R(_y,{...K,style:{transform:"rotate(180deg)"}}),mh=R(Ly,K),ph=R(Ly,{...K,style:{transform:"rotate(180deg)"}}),uh=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M3.333 3.333h13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M13.542 6.458h-.417c-.92 0-1.667.747-1.667 1.667v7.083c0 .92.746 1.667 1.667 1.667h.417c.92 0 1.666-.746 1.666-1.667V8.125c0-.92-.746-1.667-1.666-1.667ZM6.875 6.458h-.417c-.92 0-1.666.747-1.666 1.667v3.75c0 .92.746 1.667 1.666 1.667h.417c.92 0 1.667-.746 1.667-1.667v-3.75c0-.92-.747-1.667-1.667-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),gh=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M3.333 16.667h13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M6.875 3.125h-.417c-.92 0-1.666.746-1.666 1.667v7.083c0 .92.746 1.667 1.666 1.667h.417c.92 0 1.667-.746 1.667-1.667V4.792c0-.92-.747-1.667-1.667-1.667ZM13.542 5.817h-.417c-.92 0-1.667.747-1.667 1.667v4.391c0 .92.746 1.667 1.667 1.667h.417c.92 0 1.666-.746 1.666-1.667V7.484c0-.92-.746-1.667-1.666-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),hh=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M3.333 3.333v13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M15.208 4.792H8.125c-.92 0-1.667.746-1.667 1.666v.417c0 .92.747 1.667 1.667 1.667h7.083c.92 0 1.667-.747 1.667-1.667v-.417c0-.92-.746-1.666-1.667-1.666ZM12.516 11.458H8.125c-.92 0-1.667.746-1.667 1.667v.417c0 .92.747 1.666 1.667 1.666h4.391c.92 0 1.667-.746 1.667-1.666v-.417c0-.92-.746-1.667-1.667-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),fh=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M16.667 3.333v13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M11.875 4.792H4.792c-.92 0-1.667.746-1.667 1.666v.417c0 .92.746 1.667 1.667 1.667h7.083c.92 0 1.667-.747 1.667-1.667v-.417c0-.92-.746-1.666-1.667-1.666ZM11.683 11.458H7.292c-.92 0-1.667.746-1.667 1.667v.417c0 .92.746 1.666 1.667 1.666h4.39c.921 0 1.667-.746 1.667-1.666v-.417c0-.92-.746-1.667-1.666-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),Dy=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M16.667 3.333v13.334M3.333 3.333v13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M14.375 10.208v-.416c0-.92-.746-1.667-1.667-1.667H7.292c-.92 0-1.667.746-1.667 1.667v.416c0 .92.746 1.667 1.667 1.667h5.416c.92 0 1.667-.746 1.667-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),Ry=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M3.333 3.333h13.334M3.333 16.667h13.334",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M10.208 5.625h-.416c-.92 0-1.667.746-1.667 1.667v5.416c0 .92.746 1.667 1.667 1.667h.416c.92 0 1.667-.746 1.667-1.667V7.292c0-.92-.746-1.667-1.667-1.667Z"})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),bh=R(H("g",{stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M1.667 10h2.916",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M8.333 10h3.334",strokeLinejoin:"round"}),b("path",{d:"M15.417 10h2.916",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M6.875 4.792h-.417c-.92 0-1.666.746-1.666 1.666v7.084c0 .92.746 1.666 1.666 1.666h.417c.92 0 1.667-.746 1.667-1.666V6.458c0-.92-.747-1.666-1.667-1.666ZM13.542 6.458h-.417c-.92 0-1.667.747-1.667 1.667v3.75c0 .92.746 1.667 1.667 1.667h.417c.92 0 1.666-.746 1.666-1.667v-3.75c0-.92-.746-1.667-1.666-1.667Z"})]}),fe),xh=R(H("g",{stroke:"currentColor",strokeWidth:"1.25",children:[b("path",{d:"M10 18.333v-2.916",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M10 11.667V8.333",strokeLinejoin:"round"}),b("path",{d:"M10 4.583V1.667",strokeLinecap:"round",strokeLinejoin:"round"}),b("path",{d:"M4.792 13.125v.417c0 .92.746 1.666 1.666 1.666h7.084c.92 0 1.666-.746 1.666-1.666v-.417c0-.92-.746-1.667-1.666-1.667H6.458c-.92 0-1.666.746-1.666 1.667ZM6.458 6.458v.417c0 .92.747 1.667 1.667 1.667h3.75c.92 0 1.667-.747 1.667-1.667v-.417c0-.92-.746-1.666-1.667-1.666h-3.75c-.92 0-1.667.746-1.667 1.666Z"})]}),fe),pm=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("circle",{cx:"9",cy:"7",r:"4"}),b("path",{d:"M3 21v-2a4 4 0 0 1 4 -4h4a4 4 0 0 1 4 4v2"}),b("path",{d:"M16 3.13a4 4 0 0 1 0 7.75"}),b("path",{d:"M21 21v-2a4 4 0 0 0 -3 -3.85"})]}),K),JQ=R("M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm115.7 272l-176 101c-15.8 8.8-35.7-2.5-35.7-21V152c0-18.4 19.8-29.8 35.7-21l176 107c16.4 9.2 16.4 32.9 0 42z"),Ny=R("M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm96 328c0 8.8-7.2 16-16 16H176c-8.8 0-16-7.2-16-16V176c0-8.8 7.2-16 16-16h160c8.8 0 16 7.2 16 16v160z"),Fo=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",children:b("path",{d:"M15 5 5 15M5 5l10 10"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),QQ=R("M464 0c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48H176c-26.51 0-48-21.49-48-48V48c0-26.51 21.49-48 48-48h288M176 416c-44.112 0-80-35.888-80-80V128H48c-26.51 0-48 21.49-48 48v288c0 26.51 21.49 48 48 48h288c26.51 0 48-21.49 48-48v-48H176z",{mirror:!0}),eee=R("M11.553 22.894a.998.998 0 00.894 0s3.037-1.516 5.465-4.097C19.616 16.987 21 14.663 21 12V5a1 1 0 00-.649-.936l-8-3a.998.998 0 00-.702 0l-8 3A1 1 0 003 5v7c0 2.663 1.384 4.987 3.088 6.797 2.428 2.581 5.465 4.097 5.465 4.097zm-1.303-8.481l6.644-6.644a.856.856 0 111.212 1.212l-7.25 7.25a.856.856 0 01-1.212 0l-3.75-3.75a.856.856 0 111.212-1.212l3.144 3.144z",{width:24}),tee=R("M369.9 97.9L286 14C277 5 264.8-.1 252.1-.1H48C21.5 0 0 21.5 0 48v416c0 26.5 21.5 48 48 48h288c26.5 0 48-21.5 48-48V131.9c0-12.7-5.1-25-14.1-34zM332.1 128H256V51.9l76.1 76.1zM48 464V48h160v104c0 13.3 10.7 24 24 24h104v288H48zm32-48h224V288l-23.5-23.5c-4.7-4.7-12.3-4.7-17 0L176 352l-39.5-39.5c-4.7-4.7-12.3-4.7-17 0L80 352v64zm48-240c-26.5 0-48 21.5-48 48s21.5 48 48 48 48-21.5 48-48-21.5-48-48-48z",{width:384,height:512}),Eh=Lt.memo(({theme:e})=>R(H(Ue,{children:[b("path",{d:"M25 26H111V111H25",fill:cn(e)}),b("path",{d:"M25 111C25 80.2068 25 49.4135 25 26M25 26C48.6174 26 72.2348 26 111 26H25ZM25 26C53.3671 26 81.7343 26 111 26H25ZM111 26C111 52.303 111 78.606 111 111V26ZM111 26C111 51.2947 111 76.5893 111 111V26ZM111 111C87.0792 111 63.1585 111 25 111H111ZM111 111C87.4646 111 63.9293 111 25 111H111ZM25 111C25 81.1514 25 51.3028 25 26V111Z",stroke:cn(e),strokeWidth:"2"}),b("path",{d:"M100 100H160V160H100",fill:cn(e)}),b("path",{d:"M100 160C100 144.106 100 128.211 100 100M100 100C117.706 100 135.412 100 160 100H100ZM100 100C114.214 100 128.428 100 160 100H100ZM160 100C160 120.184 160 140.369 160 160V100ZM160 100C160 113.219 160 126.437 160 160V100ZM160 160C145.534 160 131.068 160 100 160H160ZM160 160C143.467 160 126.934 160 100 160H160ZM100 160C100 143.661 100 127.321 100 100V160Z",stroke:cn(e),strokeWidth:"2"}),H("g",{fill:ly(e),stroke:cn(e),strokeWidth:"6",children:[b("rect",{x:"2.5",y:"2.5",width:"30",height:"30"}),b("rect",{x:"2.5",y:"149.5",width:"30",height:"30"}),b("rect",{x:"147.5",y:"149.5",width:"30",height:"30"}),b("rect",{x:"147.5",y:"2.5",width:"30",height:"30"})]})]}),{width:182,height:182,mirror:!0})),yh=Lt.memo(({theme:e})=>R(H(Ue,{children:[b("path",{d:"M25 26H111V111H25",fill:cn(e)}),b("path",{d:"M25 111C25 80.2068 25 49.4135 25 26M25 26C48.6174 26 72.2348 26 111 26H25ZM25 26C53.3671 26 81.7343 26 111 26H25ZM111 26C111 52.303 111 78.606 111 111V26ZM111 26C111 51.2947 111 76.5893 111 111V26ZM111 111C87.0792 111 63.1585 111 25 111H111ZM111 111C87.4646 111 63.9293 111 25 111H111ZM25 111C25 81.1514 25 51.3028 25 26V111Z",stroke:cn(e),strokeWidth:"2"}),b("path",{d:"M100 100H160V160H100",fill:cn(e)}),b("path",{d:"M100 160C100 144.106 100 128.211 100 100M100 100C117.706 100 135.412 100 160 100H100ZM100 100C114.214 100 128.428 100 160 100H100ZM160 100C160 120.184 160 140.369 160 160V100ZM160 100C160 113.219 160 126.437 160 160V100ZM160 160C145.534 160 131.068 160 100 160H160ZM160 160C143.467 160 126.934 160 100 160H160ZM100 160C100 143.661 100 127.321 100 100V160Z",stroke:cn(e),strokeWidth:"2"}),H("g",{fill:ly(e),stroke:cn(e),strokeWidth:"6",children:[b("rect",{x:"2.5",y:"2.5",width:"30",height:"30"}),b("rect",{x:"78.5",y:"149.5",width:"30",height:"30"}),b("rect",{x:"147.5",y:"149.5",width:"30",height:"30"}),b("rect",{x:"147.5",y:"78.5",width:"30",height:"30"}),b("rect",{x:"105.5",y:"2.5",width:"30",height:"30"}),b("rect",{x:"2.5",y:"102.5",width:"30",height:"30"})]})]}),{width:182,height:182,mirror:!0})),By=R(b("g",{strokeWidth:1.25,children:b("path",{d:"M5.879 2.625h8.242a3.27 3.27 0 0 1 3.254 3.254v8.242a3.27 3.27 0 0 1-3.254 3.254H5.88a3.27 3.27 0 0 1-3.254-3.254V5.88A3.27 3.27 0 0 1 5.88 2.626l-.001-.001ZM4.518 16.118l7.608-12.83m.198 13.934 5.051-9.897M2.778 9.675l9.348-6.387m-7.608 12.83 12.857-8.793"})}),fe),Fy=R(H(Ue,{children:[b("path",{d:"M5.879 2.625h8.242a3.254 3.254 0 0 1 3.254 3.254v8.242a3.254 3.254 0 0 1-3.254 3.254H5.88a3.254 3.254 0 0 1-3.254-3.254V5.88a3.254 3.254 0 0 1 3.254-3.254Z",stroke:"currentColor",strokeWidth:"1.25"}),b("mask",{id:"FillHachureIcon",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:2,y:2,width:16,height:16,children:b("path",{d:"M5.879 2.625h8.242a3.254 3.254 0 0 1 3.254 3.254v8.242a3.254 3.254 0 0 1-3.254 3.254H5.88a3.254 3.254 0 0 1-3.254-3.254V5.88a3.254 3.254 0 0 1 3.254-3.254Z",fill:"currentColor",stroke:"currentColor",strokeWidth:"1.25"})}),b("g",{mask:"url(#FillHachureIcon)",children:b("path",{d:"M2.258 15.156 15.156 2.258M7.324 20.222 20.222 7.325m-20.444 5.35L12.675-.222m-8.157 18.34L17.416 5.22",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})})]}),fe),Oy=R(H(Ue,{children:[H("g",{clipPath:"url(#a)",children:[b("path",{d:"M5.879 2.625h8.242a3.254 3.254 0 0 1 3.254 3.254v8.242a3.254 3.254 0 0 1-3.254 3.254H5.88a3.254 3.254 0 0 1-3.254-3.254V5.88a3.254 3.254 0 0 1 3.254-3.254Z",stroke:"currentColor",strokeWidth:"1.25"}),b("mask",{id:"FillCrossHatchIcon",style:{maskType:"alpha"},maskUnits:"userSpaceOnUse",x:-1,y:-1,width:22,height:22,children:b("path",{d:"M2.426 15.044 15.044 2.426M7.383 20 20 7.383M0 12.617 12.617 0m-7.98 17.941L17.256 5.324m-2.211 12.25L2.426 4.956M20 12.617 7.383 0m5.234 20L0 7.383m17.941 7.98L5.324 2.745",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),b("g",{mask:"url(#FillCrossHatchIcon)",children:b("path",{d:"M14.121 2H5.88A3.879 3.879 0 0 0 2 5.879v8.242A3.879 3.879 0 0 0 5.879 18h8.242A3.879 3.879 0 0 0 18 14.121V5.88A3.879 3.879 0 0 0 14.121 2Z",fill:"currentColor"})})]}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),zy=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",children:b("path",{d:"M4.91 2.625h10.18a2.284 2.284 0 0 1 2.285 2.284v10.182a2.284 2.284 0 0 1-2.284 2.284H4.909a2.284 2.284 0 0 1-2.284-2.284V4.909a2.284 2.284 0 0 1 2.284-2.284Z",stroke:"currentColor",strokeWidth:"1.25"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),{...fe,fill:"currentColor"}),wh=R(b(Ue,{children:b("path",{d:"M4.167 10h11.666",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),fe),Hy=R(b("path",{d:"M5 10h10",stroke:"currentColor",strokeWidth:"2.5",strokeLinecap:"round",strokeLinejoin:"round"}),fe),Gy=R(b("path",{d:"M5 10h10",stroke:"currentColor",strokeWidth:"3.75",strokeLinecap:"round",strokeLinejoin:"round"}),fe),oee=Lt.memo(({theme:e})=>R(b("path",{d:"M6 10H34",stroke:cn(e),strokeWidth:2,fill:"none",strokeLinecap:"round"}),{width:40,height:20})),Uy=R(H("g",{strokeWidth:"2",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 12h2"}),b("path",{d:"M17 12h2"}),b("path",{d:"M11 12h2"})]}),K),Wy=R(H("g",{strokeWidth:"2",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 12v.01"}),b("path",{d:"M8 12v.01"}),b("path",{d:"M12 12v.01"}),b("path",{d:"M16 12v.01"}),b("path",{d:"M20 12v.01"})]}),K),Yy=R(b("path",{d:"M2.5 12.038c1.655-.885 5.9-3.292 8.568-4.354 2.668-1.063.101 2.821 1.32 3.104 1.218.283 5.112-1.814 5.112-1.814",strokeWidth:"1.25"}),fe),Vy=R(b("path",{d:"M2.5 12.563c1.655-.886 5.9-3.293 8.568-4.355 2.668-1.062.101 2.822 1.32 3.105 1.218.283 5.112-1.814 5.112-1.814m-13.469 2.23c2.963-1.586 6.13-5.62 7.468-4.998 1.338.623-1.153 4.11-.132 5.595 1.02 1.487 6.133-1.43 6.133-1.43",strokeWidth:"1.25"}),fe),$y=R(b("path",{d:"M2.5 11.936c1.737-.879 8.627-5.346 10.42-5.268 1.795.078-.418 5.138.345 5.736.763.598 3.53-1.789 4.235-2.147M2.929 9.788c1.164-.519 5.47-3.28 6.987-3.114 1.519.165 1 3.827 2.121 4.109 1.122.281 3.839-2.016 4.606-2.42",strokeWidth:"1.25"}),fe),Ky=R(H("svg",{strokeWidth:"1.5",children:[b("path",{d:"M3.33334 9.99998V6.66665C3.33334 6.04326 3.33403 4.9332 3.33539 3.33646C4.95233 3.33436 6.06276 3.33331 6.66668 3.33331H10"}),b("path",{d:"M13.3333 3.33331V3.34331"}),b("path",{d:"M16.6667 3.33331V3.34331"}),b("path",{d:"M16.6667 6.66669V6.67669"}),b("path",{d:"M16.6667 10V10.01"}),b("path",{d:"M3.33334 13.3333V13.3433"}),b("path",{d:"M16.6667 13.3333V13.3433"}),b("path",{d:"M3.33334 16.6667V16.6767"}),b("path",{d:"M6.66666 16.6667V16.6767"}),b("path",{d:"M10 16.6667V16.6767"}),b("path",{d:"M13.3333 16.6667V16.6767"}),b("path",{d:"M16.6667 16.6667V16.6767"})]}),fe),Xy=R(H("g",{strokeWidth:"1.5",stroke:"currentColor",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 12v-4a4 4 0 0 1 4 -4h4"}),b("line",{x1:"16",y1:"4",x2:"16",y2:"4.01"}),b("line",{x1:"20",y1:"4",x2:"20",y2:"4.01"}),b("line",{x1:"20",y1:"8",x2:"20",y2:"8.01"}),b("line",{x1:"20",y1:"12",x2:"20",y2:"12.01"}),b("line",{x1:"4",y1:"16",x2:"4",y2:"16.01"}),b("line",{x1:"20",y1:"16",x2:"20",y2:"16.01"}),b("line",{x1:"4",y1:"20",x2:"4",y2:"20.01"}),b("line",{x1:"8",y1:"20",x2:"8",y2:"20.01"}),b("line",{x1:"12",y1:"20",x2:"12",y2:"20.01"}),b("line",{x1:"16",y1:"20",x2:"16",y2:"20.01"}),b("line",{x1:"20",y1:"20",x2:"20",y2:"20.01"})]}),K),Zy=Lt.memo(({flip:e=!1})=>R(H("g",{transform:e?"translate(24, 0) scale(-1, 1)":"",stroke:"currentColor",opacity:.3,strokeWidth:2,children:[b("path",{d:"M12 12l-9 0"}),b("path",{d:"M21 9l-6 6"}),b("path",{d:"M21 15l-6 -6"})]}),K)),jy=Lt.memo(({flip:e=!1})=>R(H("g",{transform:e?"translate(40, 0) scale(-1, 1)":"",stroke:"currentColor",strokeWidth:2,fill:"none",children:[b("path",{d:"M34 10H6M34 10L27 5M34 10L27 15"}),b("path",{d:"M27.5 5L34.5 10L27.5 15"})]}),{width:40,height:20})),qy=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"currentColor",transform:e?"translate(40, 0) scale(-1, 1)":"",children:[b("path",{d:"M32 10L6 10",strokeWidth:2}),b("circle",{r:"4",transform:"matrix(-1 0 0 1 30 10)"})]}),{width:40,height:20})),Jy=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"none",transform:e?"translate(40, 0) scale(-1, 1)":"",strokeWidth:2,children:[b("path",{d:"M26 10L6 10"}),b("circle",{r:"4",transform:"matrix(-1 0 0 1 30 10)"})]}),{width:40,height:20})),Qy=Lt.memo(({flip:e=!1})=>R(b("g",{transform:e?"translate(40, 0) scale(-1, 1)":"",children:b("path",{d:"M34 10H5.99996M34 10L34 5M34 10L34 15",stroke:"currentColor",strokeWidth:2,fill:"none"})}),{width:40,height:20})),ew=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"currentColor",transform:e?"translate(40, 0) scale(-1, 1)":"",children:[b("path",{d:"M32 10L6 10",strokeWidth:2}),b("path",{d:"M27.5 5.5L34.5 10L27.5 14.5L27.5 5.5"})]}),{width:40,height:20})),tw=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"none",transform:e?"translate(40, 0) scale(-1, 1)":"",strokeWidth:2,strokeLinejoin:"round",children:[b("path",{d:"M6,9.5H27"}),b("path",{d:"M27,5L34,10L27,14Z",fill:"none"})]}),{width:40,height:20})),ow=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"currentColor",transform:e?"translate(40, 0) scale(-1, 1)":"",strokeLinejoin:"round",strokeWidth:2,children:[b("path",{d:"M6,9.5H20"}),b("path",{d:"M27,5L34,10L27,14L20,9.5Z"})]}),{width:40,height:20})),nw=Lt.memo(({flip:e=!1})=>R(H("g",{stroke:"currentColor",fill:"none",transform:e?"translate(40, 0) scale(-1, 1)":"",strokeLinejoin:"round",strokeWidth:2,children:[b("path",{d:"M6,9.5H20"}),b("path",{d:"M27,5L34,10L27,14L20,9.5Z"})]}),{width:40,height:20})),rw=Lt.memo(({flip:e=!1})=>R(b("g",{stroke:"currentColor",fill:"none",transform:e?"":"translate(40, 0) scale(-1, 1)",strokeLinejoin:"round",strokeWidth:2,children:b("path",{d:"M34,10 H6 M15,10 L7,5 M15,10 L7,15"})}),{width:40,height:20})),iw=Lt.memo(({flip:e=!1})=>R(b("g",{stroke:"currentColor",fill:"none",transform:e?"":"translate(40, 0) scale(-1, 1)",strokeLinejoin:"round",strokeWidth:2,children:b("path",{d:"M34,10 H6 M15,10 L15,15 L15,5"})}),{width:40,height:20})),aw=Lt.memo(({flip:e=!1})=>R(b("g",{stroke:"currentColor",fill:"none",transform:e?"":"translate(40, 0) scale(-1, 1)",strokeLinejoin:"round",strokeWidth:2,children:b("path",{d:"M34,10 H6 M15,10 L15,16 L15,4 M15,10 L7,5 M15,10 L7,15"})}),{width:40,height:20})),sw=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",children:b("path",{d:"M14.167 6.667a3.333 3.333 0 0 0-3.334-3.334H9.167a3.333 3.333 0 0 0 0 6.667h1.666a3.333 3.333 0 0 1 0 6.667H9.167a3.333 3.333 0 0 1-3.334-3.334",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),lw=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",children:b("path",{d:"M5 16.667V3.333L10 15l5-11.667v13.334",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),cw=R(H(Ue,{children:[b("g",{clipPath:"url(#a)",children:b("path",{d:"M5.833 3.333v13.334h8.334",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),b("defs",{children:b("clipPath",{id:"a",children:b("path",{fill:"#fff",d:"M0 0h20v20H0z"})})})]}),fe),dw=R(b(Ue,{children:b("path",{d:"m1.667 3.333 6.666 13.334M8.333 3.333 1.667 16.667M11.667 3.333v13.334h6.666",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round"})}),fe),Hi=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 7v-2h13v2"}),b("path",{d:"M10 5v14"}),b("path",{d:"M12 19h-4"}),b("path",{d:"M15 13v-1h6v1"}),b("path",{d:"M18 12v7"}),b("path",{d:"M17 19h2"})]}),K),mw=R(b(Ue,{children:H("g",{stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M7 12h10"}),b("path",{d:"M7 5v14"}),b("path",{d:"M17 5v14"}),b("path",{d:"M15 19h4"}),b("path",{d:"M15 5h4"}),b("path",{d:"M5 19h4"}),b("path",{d:"M5 5h4"})]})}),K),Jl=R(b(Ue,{children:b("g",{stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",children:b("path",{d:"M5.833 16.667v-10a3.333 3.333 0 0 1 3.334-3.334h1.666a3.333 3.333 0 0 1 3.334 3.334v10M5.833 10.833h8.334"})})}),fe),vh=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M7 8l-4 4l4 4"}),b("path",{d:"M17 8l4 4l-4 4"}),b("path",{d:"M14 4l-4 16"})]}),K),um=vh,pw=R(H("g",{stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",strokeWidth:2,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"8",x2:"20",y2:"8"}),b("line",{x1:"4",y1:"12",x2:"12",y2:"12"}),b("line",{x1:"4",y1:"16",x2:"16",y2:"16"})]}),K),uw=R(H("g",{stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"8",x2:"20",y2:"8"}),b("line",{x1:"8",y1:"12",x2:"16",y2:"12"}),b("line",{x1:"6",y1:"16",x2:"18",y2:"16"})]}),K),gw=R(H("g",{stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"8",x2:"20",y2:"8"}),b("line",{x1:"10",y1:"12",x2:"20",y2:"12"}),b("line",{x1:"8",y1:"16",x2:"20",y2:"16"})]}),K),hw=Lt.memo(({theme:e})=>R(H("g",{strokeWidth:"1.5",stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"4",x2:"20",y2:"4"}),b("rect",{x:"9",y:"8",width:"6",height:"12",rx:"2"})]}),K)),fw=Lt.memo(({theme:e})=>R(H("g",{strokeWidth:"2",stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"20",x2:"20",y2:"20"}),b("rect",{x:"9",y:"4",width:"6",height:"12",rx:"2"})]}),K)),bw=Lt.memo(({theme:e})=>R(H("g",{strokeWidth:"1.5",stroke:"currentColor",fill:"none",strokeLinecap:"round",strokeLinejoin:"round",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("line",{x1:"4",y1:"12",x2:"9",y2:"12"}),b("line",{x1:"15",y1:"12",x2:"20",y2:"12"}),b("rect",{x:"9",y:"6",width:"6",height:"12",rx:"2"})]}),K)),gm=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M21 19h-18l9 -15"}),b("path",{d:"M20.615 15.171h.015"}),b("path",{d:"M19.515 11.771h.015"}),b("path",{d:"M17.715 8.671h.015"}),b("path",{d:"M15.415 5.971h.015"})]}),K),xw=R(b("path",{d:"M537.6 226.6c4.1-10.7 6.4-22.4 6.4-34.6 0-53-43-96-96-96-19.7 0-38.1 6-53.3 16.2C367 64.2 315.3 32 256 32c-88.4 0-160 71.6-160 160 0 2.7.1 5.4.2 8.1C40.2 219.8 0 273.2 0 336c0 79.5 64.5 144 144 144h368c70.7 0 128-57.3 128-128 0-61.9-44-113.6-102.4-125.4zM393.4 288H328v112c0 8.8-7.2 16-16 16h-48c-8.8 0-16-7.2-16-16V288h-65.4c-14.3 0-21.4-17.2-11.3-27.3l105.4-105.4c6.2-6.2 16.4-6.2 22.6 0l105.4 105.4c10.1 10.1 2.9 27.3-11.3 27.3z",fill:"currentColor"}),{width:640,height:512}),nee=R(b("path",{d:"M480 416C497.7 416 512 430.3 512 448C512 465.7 497.7 480 480 480H150.6C133.7 480 117.4 473.3 105.4 461.3L25.37 381.3C.3786 356.3 .3786 315.7 25.37 290.7L258.7 57.37C283.7 32.38 324.3 32.38 349.3 57.37L486.6 194.7C511.6 219.7 511.6 260.3 486.6 285.3L355.9 416H480zM265.4 416L332.7 348.7L195.3 211.3L70.63 336L150.6 416L265.4 416z"})),Ja=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 13v-7.5a1.5 1.5 0 0 1 3 0v6.5"}),b("path",{d:"M11 5.5v-2a1.5 1.5 0 1 1 3 0v8.5"}),b("path",{d:"M14 5.5a1.5 1.5 0 0 1 3 0v6.5"}),b("path",{d:"M17 7.5a1.5 1.5 0 0 1 3 0v8.5a6 6 0 0 1 -6 6h-2h.208a6 6 0 0 1 -5.012 -2.7a69.74 69.74 0 0 1 -.196 -.3c-.312 -.479 -1.407 -2.388 -3.286 -5.728a1.5 1.5 0 0 1 .536 -2.022a1.867 1.867 0 0 1 2.28 .28l1.47 1.47"})]}),K),Ih=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 17v2a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-2"}),b("path",{d:"M7 11l5 5l5 -5"}),b("path",{d:"M12 4l0 12"})]}),K),Qa=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 8m0 2a2 2 0 0 1 2 -2h8a2 2 0 0 1 2 2v8a2 2 0 0 1 -2 2h-8a2 2 0 0 1 -2 -2z"}),b("path",{d:"M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2"})]}),K),Ew=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M7 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"}),b("path",{d:"M17 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"}),b("path",{d:"M9.15 14.85l8.85 -10.85"}),b("path",{d:"M6 4l8.85 10.85"})]}),K),yw=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 12m-9 0a9 9 0 1 0 18 0a9 9 0 1 0 -18 0"}),b("path",{d:"M12 17l0 .01"}),b("path",{d:"M12 13.5a1.5 1.5 0 0 1 1 -1.5a2.6 2.6 0 1 0 -3 -4"})]}),K),ree=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M7 4v16l13 -8z"})]}),K),iee=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M17 4h-10a3 3 0 0 0 -3 3v10a3 3 0 0 0 3 3h10a3 3 0 0 0 3 -3v-10a3 3 0 0 0 -3 -3z",strokeWidth:"0",fill:"currentColor"})]}),K),ww=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 12l5 5l10 -10"})]}),K),hm=R(H(Ue,{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10.24 3.957l-8.422 14.06a1.989 1.989 0 0 0 1.7 2.983h16.845a1.989 1.989 0 0 0 1.7 -2.983l-8.423 -14.06a1.989 1.989 0 0 0 -3.4 0z"}),b("path",{d:"M12 9v4"}),b("path",{d:"M12 17h.01"})]}),K),vw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M11 7l6 6"}),b("path",{d:"M4 16l11.7 -11.7a1 1 0 0 1 1.4 0l2.6 2.6a1 1 0 0 1 0 1.4l-11.7 11.7h-4v-4z"})]}),K),Ql=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 3l-4 7h8z"}),b("path",{d:"M17 17m-3 0a3 3 0 1 0 6 0a3 3 0 1 0 -6 0"}),b("path",{d:"M4 14m0 1a1 1 0 0 1 1 -1h4a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-4a1 1 0 0 1 -1 -1z"})]}),K),Dn=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 7l16 0"}),b("path",{d:"M4 17l16 0"}),b("path",{d:"M7 4l0 16"}),b("path",{d:"M17 4l0 16"})]}),K),Iw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),b("circle",{cx:"8.5",cy:"8.5",r:"1.5",fill:"currentColor",stroke:"none"}),b("path",{d:"M3 16l5-5c.928-.893 2.072-.893 3 0l5 5"}),b("path",{d:"M14 14l1-1c.928-.893 2.072-.893 3 0l3 3"}),b("path",{d:"M17.5 4.5l0 3m-1.5-1.5l3 0",strokeWidth:"1.5",strokeLinecap:"round"})]}),K),es=R(b("path",{fill:"currentColor",d:"M407.48,111.18C335.587,108.103 269.573,152.338 245.08,220C220.587,152.338 154.573,108.103 82.68,111.18C80.285,168.229 107.577,222.632 154.74,254.82C178.908,271.419 193.35,298.951 193.27,328.27L193.27,379.13L296.9,379.13L296.9,328.27C296.816,298.953 311.255,271.42 335.42,254.82C382.596,222.644 409.892,168.233 407.48,111.18Z"})),Tw=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M20 11a8.1 8.1 0 0 0 -15.5 -2m-.5 -4v4h4"}),b("path",{d:"M4 13a8.1 8.1 0 0 0 15.5 2m.5 4v-4h-4"})]}),K),Cw=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 10l-2 1l8 4l8 -4l-2 -1"}),b("path",{d:"M4 15l8 4l8 -4"}),b("path",{d:"M12 4v7"}),b("path",{d:"M15 8l-3 3l-3 -3"})]}),K),Br=R(H("g",{strokeWidth:"1.25",children:[b("path",{d:"M4.16602 10H15.8327"}),b("path",{d:"M12.5 13.3333L15.8333 10"}),b("path",{d:"M12.5 6.66666L15.8333 9.99999"})]}),fe),Rn=R(H("g",{fill:"none",stroke:"currentColor",strokeWidth:"1.25",strokeLinecap:"round",strokeLinejoin:"round",transform:"rotate(90 10 10)",children:[b("path",{clipRule:"evenodd",d:"m9.644 13.69 7.774-7.773a2.357 2.357 0 0 0-3.334-3.334l-7.773 7.774L8 12l1.643 1.69Z"}),b("path",{d:"m13.25 3.417 3.333 3.333M10 10l2-2M5 15l3-3M2.156 17.894l1-1M5.453 19.029l-.144-1.407M2.377 11.887l.866 1.118M8.354 17.273l-1.194-.758M.953 14.652l1.408.13"})]}),20),Gi=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z"}),b("path",{d:"M6 21l15 -15l-3 -3l-15 15l3 3"}),b("path",{d:"M15 6l3 3"}),b("path",{d:"M9 3a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2"}),b("path",{d:"M19 13a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2"})]}),K),aee=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z"}),b("path",{d:"M6 21l15 -15l-3 -3l-15 15l3 3"}),b("path",{d:"M15 6l3 3"}),b("path",{d:"M9 3a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2"}),b("path",{d:"M19 13a2 2 0 0 0 2 2a2 2 0 0 0 -2 2a2 2 0 0 0 -2 -2a2 2 0 0 0 2 -2"})]}),K),see=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M11.217 19.384a3.501 3.501 0 0 0 6.783 -1.217v-5.167l-6 -3.35"}),b("path",{d:"M5.214 15.014a3.501 3.501 0 0 0 4.446 5.266l4.34 -2.534v-6.946"}),b("path",{d:"M6 7.63c-1.391 -.236 -2.787 .395 -3.534 1.689a3.474 3.474 0 0 0 1.271 4.745l4.263 2.514l6 -3.348"}),b("path",{d:"M12.783 4.616a3.501 3.501 0 0 0 -6.783 1.217v5.067l6 3.45"}),b("path",{d:"M18.786 8.986a3.501 3.501 0 0 0 -4.446 -5.266l-4.34 2.534v6.946"}),b("path",{d:"M18 16.302c1.391 .236 2.787 -.395 3.534 -1.689a3.474 3.474 0 0 0 -1.271 -4.745l-4.308 -2.514l-5.955 3.42"})]}),K),kw=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 8v-2a2 2 0 0 1 2 -2h2"}),b("path",{d:"M4 16v2a2 2 0 0 0 2 2h2"}),b("path",{d:"M16 4h2a2 2 0 0 1 2 2v2"}),b("path",{d:"M16 20h2a2 2 0 0 0 2 -2v-2"})]}),K),ts=R(H("g",{stroke:"currentColor",fill:"none",strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10 12a2 2 0 1 0 4 0a2 2 0 0 0 -4 0"}),b("path",{d:"M21 12c-2.4 4 -5.4 6 -9 6c-3.6 0 -6.6 -2 -9 -6c2.4 -4 5.4 -6 9 -6c3.6 0 6.6 2 9 6"})]}),K),Sw=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10.585 10.587a2 2 0 0 0 2.829 2.828"}),b("path",{d:"M16.681 16.673a8.717 8.717 0 0 1 -4.681 1.327c-3.6 0 -6.6 -2 -9 -6c1.272 -2.12 2.712 -3.678 4.32 -4.674m2.86 -1.146a9.055 9.055 0 0 1 1.82 -.18c3.6 0 6.6 2 9 6c-.666 1.11 -1.379 2.067 -2.138 2.87"}),b("path",{d:"M3 3l18 18"})]}),K),Mw=R(H("g",{stroke:"currentColor",fill:"none",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15.5 13a3.5 3.5 0 0 0 -3.5 3.5v1a3.5 3.5 0 0 0 7 0v-1.8"}),b("path",{d:"M8.5 13a3.5 3.5 0 0 1 3.5 3.5v1a3.5 3.5 0 0 1 -7 0v-1.8"}),b("path",{d:"M17.5 16a3.5 3.5 0 0 0 0 -7h-.5"}),b("path",{d:"M19 9.3v-2.8a3.5 3.5 0 0 0 -7 0"}),b("path",{d:"M6.5 16a3.5 3.5 0 0 1 0 -7h.5"}),b("path",{d:"M5 9.3v-2.8a3.5 3.5 0 0 1 7 0v10"})]}),K),Pw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15.5 13a3.5 3.5 0 0 0 -3.5 3.5v1a3.5 3.5 0 0 0 7 0v-1.8"}),b("path",{d:"M8.5 13a3.5 3.5 0 0 1 3.5 3.5v1a3.5 3.5 0 0 1 -7 0v-1.8"}),b("path",{d:"M17.5 16a3.5 3.5 0 0 0 0 -7h-.5"}),b("path",{d:"M19 9.3v-2.8a3.5 3.5 0 0 0 -7 0"}),b("path",{d:"M6.5 16a3.5 3.5 0 0 1 0 -7h.5"}),b("path",{d:"M5 9.3v-2.8a3.5 3.5 0 0 1 7 0v10"})]}),K),Co=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M10 10m-7 0a7 7 0 1 0 14 0a7 7 0 1 0 -14 0"}),b("path",{d:"M21 21l-6 -6"})]}),K),Aw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M20.984 12.53a9 9 0 1 0 -7.552 8.355"}),b("path",{d:"M12 7v5l3 3"}),b("path",{d:"M19 16l-2 3h4l-2 3"})]}),K),Lw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 8l0 4l2 2"}),b("path",{d:"M3.05 11a9 9 0 1 1 .5 4m-.5 5v-5h5"})]}),K),_w=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M9 2m0 3a3 3 0 0 1 3 -3h0a3 3 0 0 1 3 3v5a3 3 0 0 1 -3 3h0a3 3 0 0 1 -3 -3z"}),b("path",{d:"M5 10a7 7 0 0 0 14 0"}),b("path",{d:"M8 21l8 0"}),b("path",{d:"M12 17l0 4"})]}),K),Dw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 3l18 18"}),b("path",{d:"M9 5a3 3 0 0 1 6 0v5a3 3 0 0 1 -.13 .874m-2 2a3 3 0 0 1 -3.87 -2.872v-1"}),b("path",{d:"M5 10a7 7 0 0 0 10.846 5.85m2 -2a6.967 6.967 0 0 0 1.152 -3.85"}),b("path",{d:"M8 21l8 0"}),b("path",{d:"M12 17l0 4"})]}),K),ec=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M13 3l0 7l6 0l-8 11l0 -7l-6 0l8 -11"})]}),K),Rw=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 8m0 1a1 1 0 0 1 1 -1h6a1 1 0 0 1 1 1v6a1 1 0 0 1 -1 1h-6a1 1 0 0 1 -1 -1z"}),b("path",{d:"M12 20v.01"}),b("path",{d:"M16 20v.01"}),b("path",{d:"M8 20v.01"}),b("path",{d:"M4 20v.01"}),b("path",{d:"M4 16v.01"}),b("path",{d:"M4 12v.01"}),b("path",{d:"M4 8v.01"}),b("path",{d:"M4 4v.01"}),b("path",{d:"M8 4v.01"}),b("path",{d:"M12 4v.01"}),b("path",{d:"M16 4v.01"}),b("path",{d:"M20 4v.01"}),b("path",{d:"M20 8v.01"}),b("path",{d:"M20 12v.01"}),b("path",{d:"M20 16v.01"}),b("path",{d:"M20 20v.01"})]}),K),Nw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 3v18"}),b("path",{d:"M19 21v-18"}),b("path",{d:"M5 7h14"}),b("path",{d:"M5 15h14"}),b("path",{d:"M8 13v4"}),b("path",{d:"M11 13v4"}),b("path",{d:"M16 13v4"}),b("path",{d:"M14 5v4"}),b("path",{d:"M11 5v4"}),b("path",{d:"M8 5v4"}),b("path",{d:"M3 21h18"})]}),K),Bw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 12l18 0"}),b("path",{d:"M7 16l10 0l-10 5l0 -5"}),b("path",{d:"M7 8l10 0l-10 -5l0 5"})]}),K),Fw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M12 3l0 18"}),b("path",{d:"M16 7l0 10l5 0l-5 -10"}),b("path",{d:"M8 7l0 10l-5 0l5 -10"})]}),K),Th=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 3m0 2a2 2 0 0 1 2 -2h10a2 2 0 0 1 2 2v2a2 2 0 0 1 -2 2h-10a2 2 0 0 1 -2 -2z"}),b("path",{d:"M19 6h1a2 2 0 0 1 2 2a5 5 0 0 1 -5 5l-5 0v2"}),b("path",{d:"M10 15m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v4a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"})]}),K),os=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15 15m-5 0a5 5 0 1 0 10 0a5 5 0 1 0 -10 0"}),b("path",{d:"M22 22l-3 -3"}),b("path",{d:"M6 18h-1a2 2 0 0 1 -2 -2v-1"}),b("path",{d:"M3 11v-1"}),b("path",{d:"M3 6v-1a2 2 0 0 1 2 -2h1"}),b("path",{d:"M10 3h1"}),b("path",{d:"M15 3h1a2 2 0 0 1 2 2v1"})]}),K),Ow=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),b("path",{d:"M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4"}),b("path",{d:"M4 20.25c0 .414 .336 .75 .75 .75h1.25a1 1 0 0 0 1 -1v-1a1 1 0 0 0 -1 -1h-1a1 1 0 0 1 -1 -1v-1a1 1 0 0 1 1 -1h1.25a.75 .75 0 0 1 .75 .75"}),b("path",{d:"M10 15l2 6l2 -6"}),b("path",{d:"M20 15h-1a2 2 0 0 0 -2 2v2a2 2 0 0 0 2 2h1v-3"})]}),K),zw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M14 3v4a1 1 0 0 0 1 1h4"}),b("path",{d:"M5 12v-7a2 2 0 0 1 2 -2h7l5 5v4"}),b("path",{d:"M20 15h-1a2 2 0 0 0 -2 2v2a2 2 0 0 0 2 2h1v-3"}),b("path",{d:"M5 18h1.5a1.5 1.5 0 0 0 0 -3h-1.5v6"}),b("path",{d:"M11 21v-6l3 6v-6"})]}),K),Hw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 13v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a2 2 0 0 0 6 0v-8a2 2 0 0 1 2 -2h1a2 2 0 0 1 2 2v8a8 8 0 0 1 -16 0"}),b("path",{d:"M4 8l5 0"}),b("path",{d:"M15 8l4 0"})]}),K),Gw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 14c.83 .642 2.077 1.017 3.5 1c1.423 .017 2.67 -.358 3.5 -1c.83 -.642 2.077 -1.017 3.5 -1c1.423 -.017 2.67 .358 3.5 1"}),b("path",{d:"M8 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"}),b("path",{d:"M12 3a2.4 2.4 0 0 0 -1 2a2.4 2.4 0 0 0 1 2"}),b("path",{d:"M3 10h14v5a6 6 0 0 1 -6 6h-2a6 6 0 0 1 -6 -6v-5z"}),b("path",{d:"M16.746 16.726a3 3 0 1 0 .252 -5.555"})]}),K),Uw=R(H("g",{stroke:"currentColor",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 5a1 1 0 0 1 1-1h16a1 1 0 0 1 1 1v10a1 1 0 0 1-1 1h-16a1 1 0 0 1-1-1v-10zM7 20h10M9 16v4M15 16v4"})]}),{...K,strokeWidth:1.5}),lee=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M15 8v-2a2 2 0 0 0 -2 -2h-7a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h7a2 2 0 0 0 2 -2v-2"}),b("path",{d:"M21 12h-13l3 -3"}),b("path",{d:"M11 15l-3 -3"})]}),K),Ww=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M2 8a4 4 0 0 1 4 -4h12a4 4 0 0 1 4 4v8a4 4 0 0 1 -4 4h-12a4 4 0 0 1 -4 -4v-8z"}),b("path",{d:"M10 9l5 3l-5 3z"})]}),K),Yw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 6h18"}),b("path",{d:"M3 12h18"}),b("path",{d:"M3 18h18"}),b("path",{d:"M6 3v18"}),b("path",{d:"M12 3v18"}),b("path",{d:"M18 3v18"})]}),K),Vw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M17 3m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"}),b("path",{d:"M3 17m0 1a1 1 0 0 1 1 -1h2a1 1 0 0 1 1 1v2a1 1 0 0 1 -1 1h-2a1 1 0 0 1 -1 -1z"}),b("path",{d:"M17 5c-6.627 0 -12 5.373 -12 12"})]}),K),ns=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 18l12 -12"}),b("path",{d:"M18 10v-4h-4"})]}),K),rs=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4,19L10,19C11.097,19 12,18.097 12,17L12,9C12,7.903 12.903,7 14,7L21,7"}),b("path",{d:"M18 4l3 3l-3 3"})]}),K),is=R(H("g",{children:[b("path",{d:"M16,12L20,9L16,6"}),b("path",{d:"M6 20c0 -6.075 4.925 -11 11 -11h3"})]}),K),fm=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 9l6 6l6 -6"})]}),K),$w=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 15l6 -6l6 6"})]}),K),Kw=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 15l6 -6l6 6"})]}),K),Ch=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M8 5v10a1 1 0 0 0 1 1h10"}),b("path",{d:"M5 8h10a1 1 0 0 1 1 1v10"})]}),K),bm=R(H("g",{children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M5 5m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M19 5m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M5 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M19 19m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M5 7l0 10"}),b("path",{d:"M7 5l10 0"}),b("path",{d:"M7 19l10 0"}),b("path",{d:"M19 7l0 10"})]}),K),cee=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 11v8a1 1 0 0 0 1 1h8m-9 -14v-1a1 1 0 0 1 1 -1h1m5 0h2m5 0h1a1 1 0 0 1 1 1v1m0 5v2m0 5v1a1 1 0 0 1 -1 1h-1"}),b("path",{d:"M4 12h7a1 1 0 0 1 1 1v7"})]}),K),Xw=R(H("g",{strokeWidth:1.5,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M14 6m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 6l8 0"}),b("path",{d:"M16 6l4 0"}),b("path",{d:"M8 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 12l2 0"}),b("path",{d:"M10 12l10 0"}),b("path",{d:"M17 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 18l11 0"}),b("path",{d:"M19 18l1 0"})]}),K),Zw=R(H("g",{strokeWidth:1,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M6 10l4 -4 L6 14l8 -8 L6 18l12 -12 L10 18l8 -8 L14 18l4 -4"})]}),K),jw=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 20h4l10.5 -10.5a2.828 2.828 0 1 0 -4 -4l-10.5 10.5v4"}),b("path",{d:"M13.5 6.5l4 4"})]}),K),dee=R(H("g",{strokeWidth:1,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M11 7l-5 5l5 5"}),b("path",{d:"M17 7l-5 5l5 5"})]}),K),qw=R(H("g",{strokeWidth:"1.75",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M4 4m0 2a2 2 0 0 1 2 -2h12a2 2 0 0 1 2 2v12a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2z"}),b("path",{d:"M15 4l0 16"})]}),K),mee=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 20l1.3 -3.9c-2.324 -3.437 -1.426 -7.872 2.1 -10.374c3.526 -2.501 8.59 -2.296 11.845 .48c3.255 2.777 3.695 7.266 1.029 10.501c-2.666 3.235 -7.615 4.215 -11.574 2.293l-4.7 1"})]}),K),pee=R(H("g",{strokeWidth:"1.25",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M3 4l18 0"}),b("path",{d:"M4 4v10a2 2 0 0 0 2 2h12a2 2 0 0 0 2 -2v-10"}),b("path",{d:"M12 16l0 4"}),b("path",{d:"M9 20l6 0"}),b("path",{d:"M8 12l3 -3l2 2l3 -3"})]}),K),Jw=b("div",{style:{width:"1rem",height:"1rem"}}),Qw=R(H("g",{strokeWidth:"1.5",children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("polyline",{points:"9 6 15 12 9 18"})]}),K),ev=R(H("g",{strokeWidth:1.25,children:[b("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"}),b("path",{d:"M14 6m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 6l8 0"}),b("path",{d:"M16 6l4 0"}),b("path",{d:"M8 12m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 12l2 0"}),b("path",{d:"M10 12l10 0"}),b("path",{d:"M17 18m-2 0a2 2 0 1 0 4 0a2 2 0 1 0 -4 0"}),b("path",{d:"M4 18l11 0"}),b("path",{d:"M19 18l1 0"})]}),K);import tv from"clsx";import Sh,{useEffect as GA,useRef as ov,useState as UA}from"react";import{isPromiseLike as WA}from"@orangecatai/common";import zA from"react";import{jsx as kh}from"react/jsx-runtime";var HA=({size:e="1em",circleWidth:t=8,synchronized:o=!1,className:n=""})=>{let i=-(zA.useRef(Date.now()).current%1600);return kh("div",{className:`Spinner ${n}`,children:kh("svg",{viewBox:"0 0 100 100",style:{width:e,height:e,"--spinner-delay":o?`${i}ms`:0},children:kh("circle",{cx:"50",cy:"50",r:50-t/2,strokeWidth:t,fill:"none",strokeMiterlimit:"10"})})})},Gt=HA;import{jsx as tc,jsxs as oc}from"react/jsx-runtime";var ne=Sh.forwardRef(({size:e="medium",visible:t=!0,className:o="",...n},r)=>{let{id:i}=qe(),a=Sh.useRef(null);Sh.useImperativeHandle(r,()=>a.current);let s=`ToolIcon_size_${e}`,[l,c]=UA(!1),m=ov(!0),p=async u=>{let h="onClick"in n&&n.onClick?.(u);if(WA(h))try{c(!0),await h}catch(g){if(g instanceof Ra)console.warn(g);else throw g}finally{m.current&&c(!1)}};GA(()=>(m.current=!0,()=>{m.current=!1}),[]);let d=ov(null);if(n.type==="button"||n.type==="icon"||n.type==="submit"){let u=n.type==="icon"?"button":n.type;return oc("button",{className:tv("ToolIcon_type_button",s,o,t&&!n.hidden?"ToolIcon_type_button--show":"ToolIcon_type_button--hide",{ToolIcon:!n.hidden,"ToolIcon--selected":n.selected,"ToolIcon--plain":n.type==="icon"}),style:n.style,"data-testid":n["data-testid"],hidden:n.hidden,title:n.title,"aria-label":n["aria-label"],type:u,onClick:p,ref:a,disabled:l||n.isLoading||!!n.disabled,children:[(n.icon||n.label)&&oc("div",{className:"ToolIcon__icon","aria-hidden":"true","aria-disabled":!!n.disabled,children:[n.icon||n.label,n.keyBindingLabel&&tc("span",{className:"ToolIcon__keybinding",children:n.keyBindingLabel}),n.isLoading&&tc(Gt,{})]}),n.showAriaLabel&&oc("div",{className:"ToolIcon__label",children:[n["aria-label"]," ",l&&tc(Gt,{})]}),n.children]})}return oc("label",{className:tv("ToolIcon",o),title:n.title,onPointerDown:u=>{d.current=u.pointerType||null,n.onPointerDown?.({pointerType:u.pointerType||null})},onPointerUp:()=>{requestAnimationFrame(()=>{d.current=null})},children:[tc("input",{className:`ToolIcon_type_radio ${s}`,type:"radio",name:n.name,"aria-label":n["aria-label"],"aria-keyshortcuts":n["aria-keyshortcuts"],"data-testid":n["data-testid"],id:`${i}-${n.id}`,onChange:()=>{n.onChange?.({pointerType:d.current})},checked:n.checked,ref:a}),oc("div",{className:"ToolIcon__icon",children:[n.icon,n.keyBindingLabel&&tc("span",{className:"ToolIcon__keybinding",children:n.keyBindingLabel})]})]})});ne.displayName="ToolButton";var xm=[],W=e=>(xm=xm.concat(e),e);import{jsx as JA}from"react/jsx-runtime";var qA=(e,t,o)=>{let n=new Set(le(e.filter(m=>XA(m)),t).map(m=>m.id)),r={},i=o.scene.getNonDeletedElementsMap(),a=new Set;for(let m of n){let p=ZA(e,m);for(let d of p)if(!a.has(d.id)){if(Em(d)){let u=rv(d,i);u&&(r[u.id]=!0)}else r[d.id]=!0;a.add(d.id)}}let s=!0,l=e.map(m=>{if(t.selectedElementIds[m.id]){let p=Em(m)?rv(m,i):null;return m.frameId&&n.has(m.frameId)?(s=!1,r[m.id]=!0,m):p?.frameId&&n.has(p?.frameId)?m:(m.boundElements&&m.boundElements.forEach(d=>{let u=o.scene.getNonDeletedElementsMap().get(d.id);u&&KA(u)&&o.scene.mutateElement(u,{startBinding:m.id===u.startBinding?.elementId?null:u.startBinding,endBinding:m.id===u.endBinding?.elementId?null:u.endBinding})}),wm(m,{isDeleted:!0}))}return m.frameId&&n.has(m.frameId)?(s=!1,Em(m)||(r[m.id]=!0),wm(m,{frameId:null})):Em(m)&&t.selectedElementIds[m.containerId]?wm(m,{isDeleted:!0}):m}),c=t.editingGroupId;if(s&&t.editingGroupId){let m=Ah(l,t.editingGroupId).filter(p=>!p.isDeleted);if(m.length>1)m[0]&&(r[m[0].id]=!0);else{c=null,m[0]&&(r[m[0].id]=!0);let p=m[0];if(p){let d=p.groupIds.findIndex(h=>h===t.editingGroupId),u=p.groupIds[d+1];if(u){let h=Ah(l,u).filter(g=>!g.isDeleted);h.length>1&&(c=u,h.forEach(g=>{r[g.id]=!0}))}}}}return{elements:l,appState:{...t,...jA({selectedElementIds:r,editingGroupId:c},l,t,null)}}},iv=(e,t)=>{if(e.editingGroupId){let o=Ah(Ph(t),e.editingGroupId);if(o.length)return{...e,selectedElementIds:{[o[0].id]:!0}}}return e},nc=W({name:"deleteSelectedElements",label:"labels.delete",icon:Ht,trackEvent:{category:"element",action:"delete"},perform:(e,t,o,n)=>{if(t.selectedLinearElement?.isEditing){let{elementId:a,selectedPointsIndices:s}=t.selectedLinearElement,l=n.scene.getNonDeletedElementsMap(),c=nv.getElement(a,l);if(!c||s==null)return!1;if(s.length>=c.points.length){let m=e.map(d=>d.id===c.id?wm(d,{isDeleted:!0}):d),p=iv(t,m);return{elements:m,appState:{...p,selectedLinearElement:null},captureUpdate:ym.IMMEDIATELY}}return nv.deletePoints(c,n,s),{elements:e,appState:{...t,selectedLinearElement:{...t.selectedLinearElement,selectedPointsIndices:s?.[0]>0?[s[0]-1]:[0]}},captureUpdate:ym.IMMEDIATELY}}let{elements:r,appState:i}=qA(e,t,n);return $A(r,r.filter(a=>a.isDeleted)),i=iv(i,r),{elements:r,appState:{...i,activeTool:VA(t,{type:n.state.preferredSelectionTool.type}),multiElement:null,newElement:null,activeEmbeddable:null,selectedLinearElement:null},captureUpdate:He(Ph(e),t)?ym.IMMEDIATELY:ym.EVENTUALLY}},keyTest:(e,t,o)=>(e.key===Mh.BACKSPACE||e.key===Mh.DELETE)&&!e[Mh.CTRL_OR_CMD],PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>{let r=_t()==="mobile";return JA(ne,{type:"button",icon:Ht,title:f("labels.delete"),"aria-label":f("labels.delete"),onClick:()=>o(null),disabled:!He(Ph(e),t),style:{...r&&t.openPopup!=="compactOtherProperties"?YA:{}}})}});import{KEYS as as,CODES as ss,isDarwin as vm}from"@orangecatai/common";import{moveOneLeft as QA,moveOneRight as eL,moveAllLeft as tL,moveAllRight as oL}from"@orangecatai/element";import{CaptureUpdateAction as Im}from"@orangecatai/element";import{isDarwin as av}from"@orangecatai/common";var G=e=>e.replace(/\b(Opt(?:ion)?|Alt)\b/i,av?f("keys.option"):f("keys.alt")).replace(/\bShift\b/i,f("keys.shift")).replace(/\b(Enter|Return)\b/i,f("keys.enter")).replace(/\b(Ctrl|Cmd|Command|CtrlOrCmd)\b/gi,av?f("keys.cmd"):f("keys.ctrl")).replace(/\b(Esc(?:ape)?)\b/i,f("keys.escape")).replace(/\b(Space(?:bar)?)\b/i,f("keys.spacebar")).replace(/\b(Del(?:ete)?)\b/i,f("keys.delete"));import{jsx as Tm}from"react/jsx-runtime";var Lh=W({name:"sendBackward",label:"labels.sendBackward",keywords:["move down","zindex","layer"],icon:dh,trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:QA(e,t,n.scene),appState:t,captureUpdate:Im.IMMEDIATELY}),keyPriority:40,keyTest:e=>e[as.CTRL_OR_CMD]&&!e.shiftKey&&e.code===ss.BRACKET_LEFT,PanelComponent:({updateData:e,appState:t})=>Tm("button",{type:"button",className:"zIndexButton",onClick:()=>e(null),title:`${f("labels.sendBackward")} \u2014 ${G("CtrlOrCmd+[")}`,children:dh})}),_h=W({name:"bringForward",label:"labels.bringForward",keywords:["move up","zindex","layer"],icon:ch,trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:eL(e,t,n.scene),appState:t,captureUpdate:Im.IMMEDIATELY}),keyPriority:40,keyTest:e=>e[as.CTRL_OR_CMD]&&!e.shiftKey&&e.code===ss.BRACKET_RIGHT,PanelComponent:({updateData:e,appState:t})=>Tm("button",{type:"button",className:"zIndexButton",onClick:()=>e(null),title:`${f("labels.bringForward")} \u2014 ${G("CtrlOrCmd+]")}`,children:ch})}),Dh=W({name:"sendToBack",label:"labels.sendToBack",keywords:["move down","zindex","layer"],icon:ph,trackEvent:{category:"element"},perform:(e,t)=>({elements:tL(e,t),appState:t,captureUpdate:Im.IMMEDIATELY}),keyTest:e=>vm?e[as.CTRL_OR_CMD]&&e.altKey&&e.code===ss.BRACKET_LEFT:e[as.CTRL_OR_CMD]&&e.shiftKey&&e.code===ss.BRACKET_LEFT,PanelComponent:({updateData:e,appState:t})=>Tm("button",{type:"button",className:"zIndexButton",onClick:()=>e(null),title:`${f("labels.sendToBack")} \u2014 ${vm?G("CtrlOrCmd+Alt+["):G("CtrlOrCmd+Shift+[")}`,children:ph})}),Rh=W({name:"bringToFront",label:"labels.bringToFront",keywords:["move up","zindex","layer"],icon:mh,trackEvent:{category:"element"},perform:(e,t)=>({elements:oL(e,t),appState:t,captureUpdate:Im.IMMEDIATELY}),keyTest:e=>vm?e[as.CTRL_OR_CMD]&&e.altKey&&e.code===ss.BRACKET_RIGHT:e[as.CTRL_OR_CMD]&&e.shiftKey&&e.code===ss.BRACKET_RIGHT,PanelComponent:({updateData:e,appState:t})=>Tm("button",{type:"button",className:"zIndexButton",onClick:o=>e(null),title:`${f("labels.bringToFront")} \u2014 ${vm?G("CtrlOrCmd+Alt+]"):G("CtrlOrCmd+Shift+]")}`,children:mh})});import{getNonDeletedElements as nL}from"@orangecatai/element";import{LinearElementEditor as rL}from"@orangecatai/element";import{isLinearElement as iL,isTextElement as aL}from"@orangecatai/element";import{arrayToMap as sL,KEYS as sv}from"@orangecatai/common";import{selectGroupsForSelectedElements as lL}from"@orangecatai/element";import{CaptureUpdateAction as cL}from"@orangecatai/element";var Nh=W({name:"selectAll",label:"labels.selectAll",icon:Rw,trackEvent:{category:"canvas"},viewMode:!1,perform:(e,t,o,n)=>{if(t.selectedLinearElement?.isEditing)return!1;let r=e.filter(i=>!i.isDeleted&&!(aL(i)&&i.containerId)&&!i.locked).reduce((i,a)=>(i[a.id]=!0,i),{});return{appState:{...t,...lL({editingGroupId:null,selectedElementIds:r},nL(e),t,n),selectedLinearElement:Object.keys(r).length===1&&iL(e[0])?new rL(e[0],sL(e)):null},captureUpdate:cL.IMMEDIATELY}},keyTest:e=>e[sv.CTRL_OR_CMD]&&e.key===sv.A});import{DEFAULT_GRID_SIZE as lv,KEYS as cv,MOBILE_ACTION_BUTTON_BG as dL,arrayToMap as dv}from"@orangecatai/common";import{getNonDeletedElements as mv}from"@orangecatai/element";import{LinearElementEditor as mL}from"@orangecatai/element";import{getSelectedElements as pL,getSelectionStateForElements as uL}from"@orangecatai/element";import{syncMovedIndices as gL}from"@orangecatai/element";import{duplicateElements as hL}from"@orangecatai/element";import{CaptureUpdateAction as pv}from"@orangecatai/element";import{jsx as fL}from"react/jsx-runtime";var Bh=W({name:"duplicateSelection",label:"labels.duplicateSelection",icon:Xl,trackEvent:{category:"element"},perform:(e,t,o,n)=>{if(t.selectedElementsAreBeingDragged)return!1;if(t.selectedLinearElement?.isEditing)try{let a=mL.duplicateSelectedPoints(t,n.scene);return{elements:e,appState:a,captureUpdate:pv.IMMEDIATELY}}catch{return!1}let{duplicatedElements:r,elementsWithDuplicates:i}=hL({type:"in-place",elements:e,idsOfElementsToDuplicate:dv(pL(e,t,{includeBoundTextElement:!0,includeElementsInFrames:!0})),appState:t,randomizeSeed:!0,overrides:({origElement:a,origIdToDuplicateId:s})=>{let l=a.frameId&&s.get(a.frameId);return{x:a.x+lv/2,y:a.y+lv/2,frameId:l??a.frameId}}});if(n.props.onDuplicate&&i){let a=n.props.onDuplicate(i,e);a&&(i=a)}return{elements:gL(i,dv(r)),appState:{...t,...uL(r,mv(i),t)},captureUpdate:pv.IMMEDIATELY}},keyTest:e=>e[cv.CTRL_OR_CMD]&&e.key===cv.D,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>{let r=_t()==="mobile";return fL(ne,{type:"button",icon:Xl,title:`${f("labels.duplicateSelection")} \u2014 ${G("CtrlOrCmd+D")}`,"aria-label":f("labels.duplicateSelection"),onClick:()=>o(null),disabled:!He(mv(e),t),style:{...r&&t.openPopup!=="compactOtherProperties"?dL:{}}})}});import{pointFrom as fD}from"@orangecatai/math";import{useEffect as af,useMemo as bD,useRef as sf,useState as xD}from"react";import{DEFAULT_ELEMENT_BACKGROUND_COLOR_PALETTE as ED,DEFAULT_ELEMENT_BACKGROUND_PICKS as yD,DEFAULT_ELEMENT_STROKE_COLOR_PALETTE as wD,DEFAULT_ELEMENT_STROKE_PICKS as vD,ARROW_TYPE as Uo,DEFAULT_FONT_FAMILY as ID,DEFAULT_FONT_SIZE as TD,FONT_FAMILY as CD,ROUNDNESS as Gm,STROKE_WIDTH as lf,VERTICAL_ALIGN as zm,KEYS as hs,randomInteger as kD,arrayToMap as df,getFontFamilyString as SD,getLineHeight as MD,isTransparent as PD,reduceToCommonValue as AD,invariant as mf,FONT_SIZES as Hm}from"@orangecatai/common";import{canBecomePolygon as LD,getNonDeletedElements as o2}from"@orangecatai/element";import{bindBindingElement as Jv,calculateFixedPointForElbowArrowBinding as Qv,updateBoundElements as _D}from"@orangecatai/element";import{LinearElementEditor as Yi}from"@orangecatai/element";import{newElementWith as kt}from"@orangecatai/element";import{getBoundTextElement as $r,redrawTextBoundingBox as hc}from"@orangecatai/element";import{isArrowElement as Um,isBoundToContainer as DD,isElbowArrow as n2,isLinearElement as cf,isLineElement as e2,isTextElement as uo,isUsingAdaptiveRadius as RD}from"@orangecatai/element";import{hasStrokeColor as ND}from"@orangecatai/element";import{updateElbowArrowPoints as BD,CaptureUpdateAction as St,toggleLinePolygonState as FD}from"@orangecatai/element";import{deriveStylesPanelMode as OD}from"@orangecatai/common";import{isDevEnv as bL}from"@orangecatai/common";var xL=new Set(["command_palette","export"]),ge=(e,t,o,n)=>{try{if(typeof window>"u"||C.VITE_WORKER_ID||C.VITE_APP_ENABLE_TRACKING!=="true"||!xL.has(e)||bL())return;C.PROD||console.info("trackEvent",{category:e,action:t,label:o,value:n}),window.sa_event&&window.sa_event(t,{category:e,label:o,value:n})}catch(r){console.error("error during analytics",r)}};import vL from"clsx";import EL from"clsx";import{forwardRef as yL}from"react";import{jsx as wL}from"react/jsx-runtime";var ls=yL((e,t)=>{let{title:o,className:n,testId:r,active:i,standalone:a,icon:s,onClick:l}=e;return wL("button",{type:"button",ref:t,title:o,"data-testid":r,className:EL(n,{standalone:a,active:i}),onClick:l,style:e.style,children:s},o)});import{Fragment as TL,jsx as Fh,jsxs as IL}from"react/jsx-runtime";var Oo=e=>Fh(TL,{children:e.options.map(t=>e.type==="button"?Fh(ls,{icon:t.icon,title:t.text,testId:t.testId,active:t.active??e.value===t.value,onClick:o=>e.onClick(t.value,o)},t.text):IL("label",{className:vL({active:e.value===t.value}),title:t.text,children:[Fh("input",{type:"radio",name:e.group,onChange:()=>e.onChange(t.value),checked:e.value===t.value,"data-testid":t.testId}),t.icon]},t.text))});import{Popover as _v}from"radix-ui";import Dv from"clsx";import{useRef as Rv,useEffect as k_}from"react";import{COLOR_OUTLINE_CONTRAST_THRESHOLD as Av,COLOR_PALETTE as Nv,isColorDark as Lv,isWritableElement as S_}from"@orangecatai/common";import{jsx as CL}from"react/jsx-runtime";var Cm=()=>CL("div",{style:{width:1,height:"1rem",backgroundColor:"var(--default-border-color)",margin:"0 auto"}});import{useEffect as AL,useRef as LL}from"react";import{createPortal as _L}from"react-dom";import{EVENT as Or,KEYS as DL,rgbToHex as RL}from"@orangecatai/common";import uv from"react";var Oh=uv.createContext(null),ye=()=>uv.useContext(Oh);import{useState as kL,useLayoutEffect as gv}from"react";import{THEME as SL}from"@orangecatai/common";var km=e=>{let[t,o]=kL(null),n=we(),{theme:r}=ye(),{container:i}=qe();return gv(()=>{t&&(t.className="",t.classList.add("excalidraw",...e?.className?.split(/\s+/)||[]),t.classList.toggle("excalidraw--mobile",n.formFactor==="phone"),t.classList.toggle("theme--dark",r===SL.DARK))},[t,r,n.formFactor,e?.className]),gv(()=>{let a=e?.parentSelector?i?.querySelector(e.parentSelector):document.body;if(!a)return;let s=document.createElement("div");return a.appendChild(s),o(s),()=>{a.removeChild(s)}},[i,e?.parentSelector]),t};import{useEffect as ML}from"react";import{EVENT as Sm}from"@orangecatai/common";function cs(e,t,o){ML(()=>{function n(r){let i=r;if(!e.current)return;let a=o?.(i,e.current);if(a===!0)return;if(a===!1)return t(i);e.current.contains(i.target)||!document.documentElement.contains(i.target)||i.target.closest("[data-radix-portal]")||i.target===document.documentElement&&document.body.style.pointerEvents==="none"||i.target.closest("[data-prevent-outside-click]")||t(i)}return document.addEventListener(Sm.POINTER_DOWN,n),document.addEventListener(Sm.TOUCH_START,n),()=>{document.removeEventListener(Sm.POINTER_DOWN,n),document.removeEventListener(Sm.TOUCH_START,n)}},[e,t,o])}import{useRef as PL}from"react";var Fr=e=>{let t=PL(e);return Object.assign(t.current,e),t.current};import{jsx as NL}from"react/jsx-runtime";var zr=Ce(null),hv=({onCancel:e,onChange:t,onSelect:o,colorPickerType:n})=>{let r=km({className:"excalidraw-eye-dropper-backdrop",parentSelector:".excalidraw-eye-dropper-container"}),i=ye(),a=Hr(),s=Qe(),l=le(a,i),c=Fr({app:s,onCancel:e,onChange:t,onSelect:o,selectedElements:l}),{container:m}=qe();AL(()=>{let d=p.current;if(!d||!s.canvas||!r)return;let u=!1,h=s.canvas.getContext("2d"),g=({clientX:k,clientY:L})=>{let S=h.getImageData((k-i.offsetLeft)*window.devicePixelRatio,(L-i.offsetTop)*window.devicePixelRatio,1,1).data;return RL(S[0],S[1],S[2])},E=({clientX:k,clientY:L,altKey:S})=>{d.style.top=`${L+20}px`,d.style.left=`${k+20}px`;let _=g({clientX:k,clientY:L});u&&c.onChange(n,_,c.selectedElements,{altKey:S}),d.style.background=_},w=()=>{c.onCancel()},x=(k,L)=>{c.onSelect(k,L)},y=k=>{u=!0,k.stopImmediatePropagation()},v=k=>{u=!1,m?.focus(),k.stopImmediatePropagation(),k.preventDefault(),x(g(k),k)},I=k=>{k.key===DL.ESCAPE&&(k.preventDefault(),k.stopImmediatePropagation(),w())};return r.tabIndex=-1,r.focus(),E({clientX:c.app.lastViewportPosition.x,clientY:c.app.lastViewportPosition.y,altKey:!1}),r.addEventListener(Or.KEYDOWN,I),r.addEventListener(Or.POINTER_DOWN,y),r.addEventListener(Or.POINTER_UP,v),window.addEventListener("pointermove",E,{passive:!0}),window.addEventListener(Or.BLUR,w),()=>{u=!1,r.removeEventListener(Or.KEYDOWN,I),r.removeEventListener(Or.POINTER_DOWN,y),r.removeEventListener(Or.POINTER_UP,v),window.removeEventListener("pointermove",E),window.removeEventListener(Or.BLUR,w)}},[c,s.canvas,r,n,m,i.offsetLeft,i.offsetTop]);let p=LL(null);return cs(p,()=>{e()},d=>!!d.target.closest(".excalidraw-eye-dropper-trigger, .excalidraw-eye-dropper-backdrop")),r?_L(NL("div",{ref:p,className:"excalidraw-eye-dropper-preview"}),r):null};import{Popover as zh}from"radix-ui";import zL from"clsx";import HL from"react";import{isInteractive as GL}from"@orangecatai/common";import BL from"react";import FL from"clsx";import{jsx as OL}from"react/jsx-runtime";var ut=BL.forwardRef(({children:e,padding:t,className:o,style:n},r)=>OL("div",{className:FL("Island",o),style:{"--padding":t,...n},ref:r,children:e}));import{jsx as Hh,jsxs as UL}from"react/jsx-runtime";var cr=HL.forwardRef(({className:e,container:t,children:o,style:n,onClose:r,onKeyDown:i,onFocusOutside:a,onPointerLeave:s,onPointerDownOutside:l,preventAutoFocusOnTouch:c=!1},m)=>{let p=we(),d=p.formFactor==="phone"&&!p.isLandscape;return Hh(zh.Portal,{container:t,children:UL(zh.Content,{ref:m,className:zL("focus-visible-none",e),"data-prevent-outside-click":!0,side:d?"bottom":"right",align:d?"center":"start",alignOffset:-16,sideOffset:20,collisionBoundary:t??void 0,style:{zIndex:"var(--zIndex-ui-styles-popup)",marginLeft:p.formFactor==="phone"?"0.5rem":void 0},onPointerLeave:s,onKeyDown:i,onFocusOutside:a,onPointerDownOutside:l,onOpenAutoFocus:u=>{c&&p.isTouchScreen&&u.preventDefault()},onCloseAutoFocus:u=>{u.stopPropagation(),u.preventDefault(),t&&!GL(document.activeElement)&&t.focus(),r()},children:[Hh(ut,{padding:3,style:n,children:o}),Hh(zh.Arrow,{width:20,height:10,style:{fill:"var(--popup-bg-color)",filter:"drop-shadow(rgba(0, 0, 0, 0.05) 0px 3px 2px)"}})]})})});import{useState as WL,useCallback as Gh}from"react";var Mm=()=>document.querySelector(".excalidraw-wysiwyg"),Pm=()=>{let e=Mm();return e?{start:e.selectionStart,end:e.selectionEnd}:null},rc=e=>{setTimeout(()=>{let t=Mm();t&&(t.focus(),e&&(t.selectionStart=e.start,t.selectionEnd=e.end))},0)},ic=(e,t,o,n)=>{t&&n&&n();let r=t&&o?Pm():null;e(),t&&o&&rc(r)},fv=()=>{let[e,t]=WL(null),o=Gh(()=>{let i=Pm();t(i)},[]),n=Gh(()=>{setTimeout(()=>{let i=Mm();i&&(i.focus(),e&&(i.selectionStart=e.start,i.selectionEnd=e.end,t(null)))},0)},[e]),r=Gh(()=>{t(null)},[]);return{saveCaretPosition:o,restoreCaretPosition:n,clearSavedPosition:r,hasSavedPosition:!!e}},bv=(e=100)=>{let t=Mm();if(t){let o=t.onblur;t.onblur=null,setTimeout(()=>{t.onblur=o},e)}};import VL from"clsx";import{useCallback as $L,useEffect as Wh,useRef as Ev,useState as KL}from"react";import{KEYS as Yh,normalizeInputColor as XL}from"@orangecatai/common";import{MAX_CUSTOM_COLORS_USED_IN_CANVAS as YL}from"@orangecatai/common";var Gr=({palette:e,color:t})=>{if(!t)return null;for(let[o,n]of Object.entries(e))if(Array.isArray(n)){let r=n.indexOf(t);if(r>-1)return{colorName:o,shade:r}}else if(n===t)return{colorName:o,shade:null};return null},ac=[["q","w","e","r","t"],["a","s","d","f","g"],["z","x","c","v","b"]].flat(),Uh=({color:e,palette:t})=>!Object.values(t).flat().includes(e),xv=(e,t,o)=>{let n={elementBackground:"backgroundColor",elementStroke:"strokeColor"},r=e.filter(a=>{if(a.isDeleted)return!1;let s=a[n[t]];return Uh({color:s,palette:o})}),i=new Map;return r.forEach(a=>{let s=a[n[t]];i.has(s)?i.set(s,i.get(s)+1):i.set(s,1)}),[...i.entries()].sort((a,s)=>s[1]-a[1]).map(a=>a[0]).slice(0,YL)},zo=Ce(null);import{Fragment as ZL,jsx as Am,jsxs as yv}from"react/jsx-runtime";var wv=({color:e,onChange:t,label:o,colorPickerType:n,placeholder:r})=>{let i=we(),[a,s]=KL(e),[l,c]=ae(zo);Wh(()=>{s(e)},[e]);let m=$L(g=>{let E=g.toLowerCase(),w=XL(E);w&&t(w),s(E)},[t]),p=Ev(null),d=Ev(null);Wh(()=>{p.current&&p.current.focus()},[l]);let[u,h]=ae(zr);return Wh(()=>()=>{h(null)},[h]),yv("div",{className:"color-picker__input-label",children:[Am("div",{className:"color-picker__input-hash",children:"#"}),Am("input",{ref:l==="hex"?p:void 0,style:{border:0,padding:0},spellCheck:!1,className:"color-picker-input","aria-label":o,onChange:g=>{m(g.target.value)},value:(a||"").replace(/^#/,""),onBlur:()=>{s(e)},tabIndex:-1,onFocus:()=>c("hex"),onKeyDown:g=>{g.key!==Yh.TAB&&(g.key===Yh.ESCAPE&&d.current?.focus(),g.stopPropagation())},placeholder:r}),i.formFactor!=="phone"&&yv(ZL,{children:[Am("div",{style:{width:"1px",height:"1.25rem",backgroundColor:"var(--default-border-color)"}}),Am("div",{ref:d,className:VL("excalidraw-eye-dropper-trigger",{selected:u}),onClick:()=>h(g=>g?null:{keepOpenOnAlt:!1,onSelect:E=>t(E),colorPickerType:n}),title:`${f("labels.eyeDropper")} \u2014 ${Yh.I.toLocaleUpperCase()} or ${G("Alt")} `,children:vw})]})]})};import Xh,{useEffect as Zh,useImperativeHandle as h_,useState as f_}from"react";import{EVENT as Sv}from"@orangecatai/common";import{DEFAULT_ELEMENT_BACKGROUND_COLOR_INDEX as b_,DEFAULT_ELEMENT_STROKE_COLOR_INDEX as x_,KEYS as E_}from"@orangecatai/common";import QL from"clsx";import{useEffect as e_,useRef as t_}from"react";import{isColorDark as jL}from"@orangecatai/common";import{jsxs as JL}from"react/jsx-runtime";var qL=({color:e,keyLabel:t,isShade:o=!1})=>JL("div",{className:"color-picker__button__hotkey-label",style:{color:jL(e)?"#fff":"#000"},children:[o&&"\u21E7",t]}),ds=qL;import{jsx as Vh,jsxs as o_}from"react/jsx-runtime";var vv=({colors:e,color:t,onChange:o,label:n})=>{let[r,i]=ae(zo),a=t_(null);return e_(()=>{a.current&&a.current.focus()},[t,r]),Vh("div",{className:"color-picker-content--default",children:e.map((s,l)=>o_("button",{ref:t===s?a:void 0,tabIndex:-1,type:"button",className:QL("color-picker__button color-picker__button--large has-outline",{active:t===s,"is-transparent":s==="transparent"||!s}),onClick:()=>{o(s),i("custom")},title:s,"aria-label":n,style:{"--swatch-color":s},children:[Vh("div",{className:"color-picker__button-outline"}),Vh(ds,{color:s,keyLabel:l+1})]},l))})};import n_ from"clsx";import{useEffect as r_,useRef as i_}from"react";import{jsx as $h,jsxs as s_}from"react/jsx-runtime";var a_=({palette:e,color:t,onChange:o,activeShade:n,showHotKey:r=!0})=>{let i=Gr({color:t,palette:e}),[a,s]=ae(zo),l=i_(null);return r_(()=>{l.current&&a==="baseColors"&&l.current.focus()},[i?.colorName,a]),$h("div",{className:"color-picker-content--default",children:Object.entries(e).map(([c,m],p)=>{let d=(Array.isArray(m)?m[n]:m)||"transparent",u=ac[p],h=f(`colors.${c.replace(/\d+/,"")}`,null,"");return s_("button",{ref:i?.colorName===c?l:void 0,tabIndex:-1,type:"button",className:n_("color-picker__button color-picker__button--large has-outline",{active:i?.colorName===c,"is-transparent":d==="transparent"||!d}),onClick:()=>{o(d),s("baseColors")},title:`${h}${d.startsWith("#")?` ${d}`:""} \u2014 ${u}`,"aria-label":`${h} \u2014 ${u}`,style:d?{"--swatch-color":d}:void 0,"data-testid":`color-${c}`,children:[$h("div",{className:"color-picker__button-outline"}),r&&$h(ds,{color:d,keyLabel:u})]},c)})})},Iv=a_;import{jsx as c_}from"react/jsx-runtime";var l_=({children:e})=>c_("div",{className:"color-picker__heading",children:e}),ms=l_;import d_ from"clsx";import{useEffect as m_,useRef as p_}from"react";import{jsx as sc,jsxs as Tv}from"react/jsx-runtime";var Cv=({color:e,onChange:t,palette:o,showHotKey:n})=>{let r=Gr({color:e||"transparent",palette:o}),[i,a]=ae(zo),s=p_(null);if(m_(()=>{s.current&&i==="shades"&&s.current.focus()},[r,i]),r){let{colorName:l,shade:c}=r,m=o[l];if(Array.isArray(m))return sc("div",{className:"color-picker-content--default shades",children:m.map((p,d)=>Tv("button",{ref:d===c&&i==="shades"?s:void 0,tabIndex:-1,type:"button",className:d_("color-picker__button color-picker__button--large has-outline",{active:d===c}),"aria-label":"Shade",title:`${l} - ${d+1}`,style:p?{"--swatch-color":p}:void 0,onClick:()=>{t(p),a("shades")},children:[sc("div",{className:"color-picker__button-outline"}),n&&sc(ds,{color:p,keyLabel:d+1,isShade:!0})]},d))})}return Tv("div",{className:"color-picker-content--default",style:{position:"relative"},tabIndex:-1,children:[sc("button",{type:"button",tabIndex:-1,className:"color-picker__button color-picker__button--large color-picker__button--no-focus-visible"}),sc("div",{tabIndex:-1,style:{position:"absolute",top:0,left:0,right:0,bottom:0,display:"flex",alignItems:"center",justifyContent:"center",textAlign:"center",fontSize:"0.75rem"},children:f("colorPicker.noShades")})]})};import{COLORS_PER_ROW as ps,COLOR_PALETTE as u_,KEYS as lc}from"@orangecatai/common";var Kh=(e,t,o)=>{let n=Math.ceil(o/ps);switch(t=t??-1,e){case"ArrowLeft":{let r=t-1;return r<0?o-1:r}case"ArrowRight":return(t+1)%o;case"ArrowDown":{let r=t+ps;return r>=o?t%ps:r}case"ArrowUp":{let r=t-ps,i=r<0?ps*n+r:r;return i>=o?void 0:i}}},g_=({e,colorObj:t,onChange:o,palette:n,customColors:r,setActiveColorPickerSection:i,activeShade:a})=>{if(t?.shade!=null&&["Digit1","Digit2","Digit3","Digit4","Digit5"].includes(e.code)&&e.shiftKey){let s=Number(e.code.slice(-1))-1;return o(n[t.colorName][s]),i("shades"),!0}if(["1","2","3","4","5"].includes(e.key)&&r[Number(e.key)-1])return o(r[Number(e.key)-1]),i("custom"),!0;if(ac.includes(e.key)){let s=ac.indexOf(e.key),l=Object.keys(n)[s],c=n[l],m=Array.isArray(c)?c[a]:c;return o(m),i("baseColors"),!0}return!1},kv=({event:e,activeColorPickerSection:t,palette:o,color:n,onChange:r,customColors:i,setActiveColorPickerSection:a,updateData:s,activeShade:l,onEyeDropperToggle:c,onEscape:m})=>{if(e[lc.CTRL_OR_CMD])return!1;if(e.key===lc.ESCAPE)return m(e),!0;if(e.key===lc.ALT)return c(!0),!0;if(e.key===lc.I)return c(),!0;let p=Gr({color:n,palette:o});if(e.key===lc.TAB){let d={custom:!!i.length,baseColors:!0,shades:p?.shade!=null,hex:!0},u=Object.entries(d).reduce((x,[y,v])=>(v&&x.push(y),x),[]),h=u.indexOf(t),g=e.shiftKey?-1:1,E=h+g>u.length-1?0:h+g<0?u.length-1:h+g,w=u[E];return w&&a(w),w==="custom"?r(i[0]):w==="baseColors"&&(Object.entries(o).find(([y,v])=>Array.isArray(v)?v.includes(n):v===n?y:null)||r(u_.black)),e.preventDefault(),e.stopPropagation(),!0}if(g_({e,colorObj:p,onChange:r,palette:o,customColors:i,setActiveColorPickerSection:a,activeShade:l}))return!0;if(t==="shades"&&p){let{shade:d}=p,u=Kh(e.key,d,ps);if(u!==void 0)return r(o[p.colorName][u]),!0}if(t==="baseColors"&&p){let{colorName:d}=p,u=Object.keys(o),h=u.indexOf(d),g=Kh(e.key,h,u.length);if(g!==void 0){let E=u[g],w=o[E];return r(Array.isArray(w)?w[l]:w),!0}}if(t==="custom"){let d=n!=null?i.indexOf(n):0,u=Kh(e.key,d,i.length);if(u!==void 0){let h=i[u];return r(h),!0}}return!1};import{jsx as Ur,jsxs as Lm}from"react/jsx-runtime";var Mv=Xh.forwardRef(({color:e,onChange:t,type:o,elements:n,palette:r,updateData:i,children:a,showTitle:s,onEyeDropperToggle:l,onEscape:c,showHotKey:m=!0},p)=>{let d=s?o==="elementStroke"?f("labels.stroke"):o==="elementBackground"?f("labels.background"):null:null,[u]=Xh.useState(()=>o==="canvasBackground"?[]:xv(n,o,r)),[h,g]=ae(zo),E=Gr({color:e,palette:r});Zh(()=>{if(!h){let v=!!e&&Uh({color:e,palette:r}),I=v&&!u.includes(e);g(I?null:v?"custom":E?.shade!=null?"shades":"baseColors")}},[h,e,r,g,E,u]);let[w,x]=f_(E?.shade??(o==="elementBackground"?b_:x_));Zh(()=>{E?.shade!=null&&x(E.shade);let v=I=>{I.key===E_.ALT&&l(!1)};return document.addEventListener(Sv.KEYUP,v,{capture:!0}),()=>{document.removeEventListener(Sv.KEYUP,v,{capture:!0})}},[E,l]);let y=Xh.useRef(null);return h_(p,()=>y.current),Zh(()=>{y?.current?.focus()},[]),Ur("div",{role:"dialog","aria-modal":"true","aria-label":f("labels.colorPicker"),children:Lm("div",{ref:y,onKeyDown:v=>{kv({event:v,activeColorPickerSection:h,palette:r,color:e,onChange:t,onEyeDropperToggle:l,customColors:u,setActiveColorPickerSection:g,updateData:i,activeShade:w,onEscape:c})&&(v.preventDefault(),v.stopPropagation())},className:"color-picker-content properties-content",tabIndex:-1,children:[d&&Ur("div",{className:"color-picker__title",children:d}),!!u.length&&Lm("div",{children:[Ur(ms,{children:f("colorPicker.mostUsedCustomColors")}),Ur(vv,{colors:u,color:e,label:f("colorPicker.mostUsedCustomColors"),onChange:t})]}),Lm("div",{children:[Ur(ms,{children:f("colorPicker.colors")}),Ur(Iv,{color:e,palette:r,onChange:t,activeShade:w,showHotKey:m})]}),Lm("div",{children:[Ur(ms,{children:f("colorPicker.shades")}),Ur(Cv,{color:e,onChange:t,palette:r,showHotKey:m})]}),a]})})});import y_ from"clsx";import{COLOR_OUTLINE_CONTRAST_THRESHOLD as w_,DEFAULT_CANVAS_BACKGROUND_PICKS as v_,DEFAULT_ELEMENT_BACKGROUND_PICKS as I_,DEFAULT_ELEMENT_STROKE_PICKS as T_,isColorDark as C_}from"@orangecatai/common";import{jsx as jh}from"react/jsx-runtime";var Pv=({onChange:e,type:t,activeColor:o,topPicks:n})=>{let r;return t==="elementStroke"&&(r=T_),t==="elementBackground"&&(r=I_),t==="canvasBackground"&&(r=v_),n&&(r=n),r?jh("div",{className:"color-picker__top-picks",children:r.map(i=>jh("button",{className:y_("color-picker__button",{active:i===o,"is-transparent":i==="transparent"||!i,"has-outline":!C_(i,w_)}),style:{"--swatch-color":i},type:"button",title:i,onClick:()=>e(i),"data-testid":`color-top-pick-${i}`,children:jh("div",{className:"color-picker__button-outline"})},i))}):(console.error("Invalid type for TopPicks"),null)};import{jsx as Ho,jsxs as _m}from"react/jsx-runtime";var M_=({type:e,color:t,onChange:o,label:n,elements:r,palette:i=Nv,updateData:a,getOpenPopup:s,appState:l})=>{let{container:c}=qe(),m=_t(),p=m!=="full",d=m==="mobile",[,u]=ae(zo),[h,g]=ae(zr),E=_m("div",{children:[Ho(ms,{children:f("colorPicker.hexCode")}),Ho(wv,{color:t||"",label:n,onChange:y=>{o(y)},colorPickerType:e,placeholder:f("colorPicker.color")})]}),w=Rv(null),x=()=>{w.current?.focus()};return Ho(cr,{container:c,style:{maxWidth:"13rem"},preventAutoFocusOnTouch:!!l.editingTextElement,onFocusOutside:y=>{S_(y.target)||x(),y.preventDefault()},onPointerDownOutside:y=>{h&&y.preventDefault()},onClose:()=>{s()===e&&a({openPopup:null}),u(null),l.editingTextElement&&setTimeout(()=>{let y=document.querySelector(".excalidraw-wysiwyg");y&&y.focus()},0)},children:i?Ho(Mv,{ref:w,palette:i,color:t,onChange:y=>{let v=l.editingTextElement?Pm():null;o(y),l.editingTextElement&&v&&rc(v)},onEyeDropperToggle:y=>{g(v=>y?(v=v||{keepOpenOnAlt:!0,onSelect:o,colorPickerType:e},v.keepOpenOnAlt=!0,v):y===!1||v?null:{keepOpenOnAlt:!1,onSelect:o,colorPickerType:e})},onEscape:y=>{h?g(null):a({openPopup:null})},type:e,elements:r,updateData:a,showTitle:p,showHotKey:!d,children:E}):E})},P_=({label:e,color:t,type:o,mode:n="background",onToggle:r,editingTextElement:i})=>{let a=_t(),s=a!=="full",l=a==="mobile",c=m=>{m.preventDefault(),m.stopPropagation(),i&&bv(),r()};return _m(_v.Trigger,{type:"button",className:Dv("color-picker__button active-color properties-trigger",{"is-transparent":!t||t==="transparent","has-outline":!t||!Lv(t,Av),"compact-sizing":s,"mobile-border":l}),"aria-label":e,style:t?{"--swatch-color":t}:void 0,title:o==="elementStroke"?f("labels.showStroke"):f("labels.showBackground"),"data-openpopup":o,onClick:c,children:[Ho("div",{className:"color-picker__button-outline",children:!t&&ky}),s&&t&&n==="stroke"&&Ho("div",{className:"color-picker__button-background",children:Ho("span",{style:{color:t&&Lv(t,Av)?"#fff":"#111"},children:Zw})})]})},cc=({type:e,color:t,onChange:o,label:n,elements:r,palette:i=Nv,topPicks:a,updateData:s,appState:l})=>{let c=Rv(l.openPopup);k_(()=>{c.current=l.openPopup},[l.openPopup]);let p=_t()!=="full";return Ho("div",{children:_m("div",{role:"dialog","aria-modal":"true",className:Dv("color-picker-container",{"color-picker-container--no-top-picks":p}),children:[!p&&Ho(Pv,{activeColor:t,onChange:o,type:e,topPicks:a}),!p&&Ho(Cm,{}),_m(_v.Root,{open:l.openPopup===e,onOpenChange:d=>{d&&s({openPopup:e})},children:[Ho(P_,{color:t,label:n,type:e,mode:e==="elementStroke"?"stroke":"background",editingTextElement:!!l.editingTextElement,onToggle:()=>{l.openPopup===e?s({openPopup:null}):l.openPopup?s({openPopup:e}):s({openPopup:e})}}),l.openPopup===e&&Ho(M_,{type:e,color:t,onChange:o,label:n,elements:r,palette:i,updateData:s,getOpenPopup:()=>c.current,appState:l})]})]})})};import{Popover as oD}from"radix-ui";import nD from"clsx";import rD,{useCallback as iD,useMemo as aD}from"react";import{FONT_FAMILY as ef}from"@orangecatai/common";import K_,{useMemo as Vr,useState as X_,useRef as zv,useEffect as Hv,useCallback as Gv}from"react";import{arrayToList as Z_,debounce as j_,FONT_FAMILY as Ui,getFontFamilyString as q_}from"@orangecatai/common";import A_ from"clsx";import L_ from"react";import{jsx as __,jsxs as D_}from"react/jsx-runtime";var Dm=L_.forwardRef(({className:e,placeholder:t,onChange:o},n)=>D_("div",{className:A_("QuickSearch__wrapper",e),children:[Co,__("input",{ref:n,className:"QuickSearch__input",type:"text",placeholder:t,onChange:r=>o(r.target.value.trim().toLowerCase())})]}));import R_ from"clsx";import{Children as N_}from"react";import{jsx as Bv}from"react/jsx-runtime";var Rm=({className:e,placeholder:t,children:o})=>{let n=!N_.count(o);return Bv("div",{className:R_("ScrollableList__wrapper",e),role:"menu",children:n?Bv("div",{className:"empty",children:t}):o})};import{jsx as B_,jsxs as F_}from"react/jsx-runtime";var Fv=({children:e,className:t="",style:o,title:n})=>F_("div",{className:`dropdown-menu-group ${t}`,style:o,children:[n&&B_("p",{className:"dropdown-menu-group-title",children:n}),e]}),dc=Fv;Fv.displayName="DropdownMenuGroup";import{THEME as V_}from"@orangecatai/common";import{DropdownMenu as $_}from"radix-ui";import O_,{useContext as z_}from"react";import{composeEventHandlers as H_}from"@orangecatai/common";var qh=O_.createContext({}),Wr=(e="",t=!1,o=!1)=>`dropdown-menu-item dropdown-menu-item-base ${e} ${t?"dropdown-menu-item--selected":""} ${o?"dropdown-menu-item--hovered":""}`.trim(),Nm=e=>{let t=z_(qh);return H_(e,o=>{t.onSelect?.(o)})};import{jsx as G_}from"react/jsx-runtime";var mc=({children:e,...t})=>G_("span",{...t,style:{textOverflow:"ellipsis",overflow:"hidden",whiteSpace:"nowrap",...t.style},children:e});import{Fragment as W_,jsx as pc,jsxs as Y_}from"react/jsx-runtime";var U_=({textStyle:e,icon:t,shortcut:o,children:n,badge:r})=>{let i=we();return Y_(W_,{children:[t&&pc("div",{className:"dropdown-menu-item__icon",children:t}),pc("div",{style:e,className:"dropdown-menu-item__text",children:pc(mc,{children:n})}),r&&pc("div",{className:"dropdown-menu-item__badge",children:r}),o&&i.formFactor!=="phone"&&pc("div",{className:"dropdown-menu-item__shortcut",children:o})]})},Yr=U_;import{jsx as Bm}from"react/jsx-runtime";var Jh=({icon:e,badge:t,value:o,children:n,shortcut:r,className:i,selected:a,onSelect:s,...l})=>{let c=Nm(s);return Bm($_.Item,{className:"radix-menu-item",onSelect:c,asChild:!0,children:Bm("button",{...l,value:o,className:Wr(i,a),title:l.title??l["aria-label"],children:Bm(Yr,{icon:e,shortcut:r,badge:t,children:n})})})};Jh.displayName="DropdownMenuItem";var us={GREEN:"green",RED:"red",BLUE:"blue"},Fm=({type:e=us.BLUE,children:t})=>{let{theme:o}=Go(),n={display:"inline-flex",marginLeft:"auto",padding:"2px 4px",borderRadius:6,fontSize:9,fontFamily:"Cascadia, monospace",border:o===V_.LIGHT?"1.5px solid white":"none"};switch(e){case us.GREEN:Object.assign(n,{backgroundColor:"var(--background-color-badge)",color:"var(--color-badge)"});break;case us.RED:Object.assign(n,{backgroundColor:"pink",color:"darkred"});break;case us.BLUE:default:Object.assign(n,{background:"var(--color-promo)",color:"var(--color-surface-lowest)"})}return Bm("div",{className:"DropDownMenuItemBadge",style:n,children:t})};Fm.displayName="DropdownMenuItemBadge";Jh.Badge=Fm;var Qt=Jh;import{KEYS as gs}from"@orangecatai/common";var Ov=({event:e,inputRef:t,hoveredFont:o,filteredFonts:n,onClose:r,onSelect:i,onHover:a})=>{if(!e[gs.CTRL_OR_CMD]&&e.shiftKey&&e.key.toLowerCase()===gs.F)return t.current?.focus(),!0;if(e.key===gs.ESCAPE)return r(),!0;if(e.key===gs.ENTER)return o?.value&&i(o.value),!0;if(e.key===gs.ARROW_DOWN)return o?.next?a(o.next.value):n[0]?.value&&a(n[0].value),!0;if(e.key===gs.ARROW_UP)return o?.prev?a(o.prev.value):n[n.length-1]?.value&&a(n[n.length-1].value),!0};import{jsx as dr,jsxs as Q_}from"react/jsx-runtime";var J_=e=>{switch(e){case Ui.Excalifont:case Ui.Virgil:return Ln;case Ui.Nunito:case Ui.Helvetica:return Jl;case Ui["Lilita One"]:return mw;case Ui["Comic Shanns"]:case Ui.Cascadia:return um;default:return Jl}},Uv=K_.memo(({selectedFontFamily:e,hoveredFontFamily:t,onSelect:o,onHover:n,onLeave:r,onOpen:i,onClose:a})=>{let{container:s}=qe(),l=Qe(),{fonts:c}=l,{showDeprecatedFonts:m}=Nn(),p=_t(),[d,u]=X_(""),h=zv(null),g=Vr(()=>Array.from(Mn.registered.entries()).filter(([T,{metadata:M}])=>!M.private&&!M.fallback).map(([T,{metadata:M,fontFaces:N}])=>{let O={value:T,icon:J_(T),text:N[0]?.fontFace?.family??"Unknown"};return M.deprecated&&Object.assign(O,{deprecated:M.deprecated,badge:{type:us.RED,placeholder:f("fontList.badge.old")}}),O}).sort((T,M)=>T.text.toLowerCase()>M.text.toLowerCase()?1:-1),[]),E=Vr(()=>new Set(c.getSceneFamilies()),[e]),w=Vr(()=>g.filter(T=>E.has(T.value)),[g,E]),x=Vr(()=>g.filter(T=>!E.has(T.value)&&(m||!T.deprecated)),[g,E,m]),y=Vr(()=>Z_([...w,...x].filter(T=>T.text?.toLowerCase().includes(d))),[w,x,d]),v=Vr(()=>{let T;return t?T=y.find(M=>M.value===t):e&&(T=y.find(M=>M.value===e)),!T&&d&&(y[0]?.value?n(y[0].value):r()),T},[t,e,d,y,n,r]),I=Gv(T=>{let M=null;if(l.state.editingTextElement){let N=document.querySelector(".excalidraw-wysiwyg");N&&(M={start:N.selectionStart,end:N.selectionEnd})}o(T),l.state.editingTextElement&&M&&setTimeout(()=>{let N=document.querySelector(".excalidraw-wysiwyg");N&&M&&(N.focus(),N.selectionStart=M.start,N.selectionEnd=M.end)},0)},[o,l.state.editingTextElement]),k=Gv(T=>{Ov({event:T,inputRef:h,hoveredFont:v,filteredFonts:y,onSelect:I,onHover:n,onClose:a})&&(T.preventDefault(),T.stopPropagation())},[v,y,I,n,a]);Hv(()=>(i(),()=>{a()}),[]);let L=Vr(()=>y.filter(T=>E.has(T.value)),[y,E]),S=Vr(()=>y.filter(T=>!E.has(T.value)),[y,E]),_=({font:T,order:M})=>{let N=zv(null),O=T.value===v?.value,B=T.value===e;return Hv(()=>{O&&(M===0?N.current?.scrollIntoView?.({block:"end"}):N.current?.scrollIntoView?.({block:"nearest"}))},[O,M]),dr("button",{ref:N,type:"button",value:T.value,className:Wr("",B,O),title:T.text,tabIndex:B?0:-1,onClick:U=>{I(Number(U.currentTarget.value))},onMouseMove:()=>{v?.value!==T.value&&n(T.value)},children:dr(Yr,{icon:T.icon,badge:T.badge&&dr(Fm,{type:T.badge.type,children:T.badge.placeholder}),textStyle:{fontFamily:q_({fontFamily:T.value})},children:T.text})})},P=[];return L.length&&P.push(dr(dc,{title:f("fontList.sceneFonts"),children:L.map((T,M)=>dr(_,{font:T,order:M},T.value))},"group_1")),S.length&&P.push(dr(dc,{title:f("fontList.availableFonts"),children:S.map((T,M)=>dr(_,{font:T,order:M+L.length},T.value))},"group_2")),Q_(cr,{className:"properties-content",container:s,style:{width:"15rem"},onClose:()=>{a(),l.state.editingTextElement&&setTimeout(()=>{let T=document.querySelector(".excalidraw-wysiwyg");T&&T.focus()},0)},onPointerLeave:r,onKeyDown:k,preventAutoFocusOnTouch:!!l.state.editingTextElement,children:[p==="full"&&dr(Dm,{ref:h,placeholder:f("quickSearch.placeholder"),onChange:j_(u,20)}),dr(Rm,{className:"dropdown-menu fonts manual-hover",placeholder:f("fontList.empty"),children:P.length?P:null})]})},(e,t)=>e.selectedFontFamily===t.selectedFontFamily&&e.hoveredFontFamily===t.hoveredFontFamily);import{Popover as eD}from"radix-ui";import{MOBILE_ACTION_BUTTON_BG as tD}from"@orangecatai/common";import{jsx as Qh}from"react/jsx-runtime";var Wv=({selectedFontFamily:e,isOpened:t=!1,compactMode:o=!1})=>{let n=ve(),r=o?{...tD,width:"2rem",height:"2rem"}:{};return Qh(eD.Trigger,{asChild:!0,children:Qh("div",{"data-openpopup":"fontFamily",className:"properties-trigger",children:Qh(ls,{standalone:!0,icon:_n,title:f("labels.showFonts"),className:"properties-trigger",testId:"font-family-show-fonts",active:t,onClick:()=>{n(i=>({openPopup:i.openPopup==="fontFamily"?null:i.openPopup}))},style:{border:"none",...r}})})})};import{jsx as uc,jsxs as Yv}from"react/jsx-runtime";var Vv=[{value:ef.Excalifont,icon:Ln,text:f("labels.handDrawn"),testId:"font-family-hand-drawn"},{value:ef.Nunito,icon:Jl,text:f("labels.normal"),testId:"font-family-normal"},{value:ef["Comic Shanns"],icon:um,text:f("labels.code"),testId:"font-family-code"}],vae=new Set(Vv.map(e=>e.value));var $v=rD.memo(({isOpened:e,selectedFontFamily:t,hoveredFontFamily:o,onSelect:n,onHover:r,onLeave:i,onPopupChange:a,compactMode:s=!1})=>{let l=aD(()=>Vv,[]),c=iD(m=>{m&&n(m)},[n]);return Yv("div",{role:"dialog","aria-modal":"true",className:nD("FontPicker__container",{"FontPicker__container--compact":s}),children:[!s&&uc("div",{className:"buttonList",children:uc(Oo,{type:"button",options:l,value:t,onClick:c})}),!s&&uc(Cm,{}),Yv(oD.Root,{open:e,onOpenChange:a,children:[uc(Wv,{selectedFontFamily:t,isOpened:e,compactMode:s}),e&&uc(Uv,{selectedFontFamily:t,hoveredFontFamily:o,onSelect:c,onHover:r,onLeave:i,onOpen:()=>a(!0),onClose:()=>a(!1)})]})]})},(e,t)=>e.isOpened===t.isOpened&&e.selectedFontFamily===t.selectedFontFamily&&e.hoveredFontFamily===t.hoveredFontFamily);import{Popover as tf}from"radix-ui";import dD from"clsx";import Om,{useEffect as mD}from"react";import{isArrowKey as pD,KEYS as mr}from"@orangecatai/common";import{jsx as sD}from"react/jsx-runtime";var Bn=({className:e,icon:t,size:o="1em"})=>sD("span",{className:e,style:{width:o,height:"100%",margin:"0 0.5ex 0 0.5ex",display:"inline-flex",lineHeight:0,verticalAlign:"middle",flex:"0 0 auto"},children:t});import{Fragment as cD,jsx as Kv,jsxs as Xv}from"react/jsx-runtime";var lD=({label:e,open:t,openTrigger:o,children:n,className:r,showCollapsedIcon:i=!0})=>Xv(cD,{children:[Xv("div",{style:{cursor:"pointer",display:"flex",justifyContent:"space-between",alignItems:"center"},className:r,onClick:o,children:[e,i&&Kv(Bn,{icon:t?$w:fm})]}),t&&Kv("div",{style:{display:"flex",flexDirection:"column"},children:n})]}),gc=lD;import{jsx as Wi,jsxs as of}from"react/jsx-runtime";var uD=Ce(!1);function gD({options:e,value:t,label:o,onChange:n,onClose:r,numberOfOptionsToAlwaysShow:i=e.length}){let a=we(),{container:s}=qe(),l=g=>{let E=e.find(w=>w.keyBinding===g.key.toLowerCase());if(!(g.metaKey||g.altKey||g.ctrlKey)&&E)n(E.value),g.preventDefault();else if(g.key===mr.TAB){let w=e.findIndex(y=>y.value===t),x=g.shiftKey?(e.length+w-1)%e.length:(w+1)%e.length;n(e[x].value)}else if(pD(g.key)){let w=lr().rtl,x=e.findIndex(y=>y.value===t);if(x!==-1){let y=e.length,v=x;switch(g.key){case(w?mr.ARROW_LEFT:mr.ARROW_RIGHT):v=(x+1)%y;break;case(w?mr.ARROW_RIGHT:mr.ARROW_LEFT):v=(y+x-1)%y;break;case mr.ARROW_DOWN:{v=(x+(i??1))%y;break}case mr.ARROW_UP:{v=(y+x-(i??1))%y;break}}n(e[v].value)}g.preventDefault()}else(g.key===mr.ESCAPE||g.key===mr.ENTER)&&(g.preventDefault(),r());g.nativeEvent.stopImmediatePropagation(),g.stopPropagation()},[c,m]=ae(uD),p=Om.useMemo(()=>e.slice(0,i),[e,i]),d=Om.useMemo(()=>e.slice(i),[e,i]);mD(()=>{p.some(g=>g.value===t)||m(!0)},[t,p,m]);let u=g=>Wi("div",{className:"picker-content",children:g.map((E,w)=>of("button",{type:"button",className:dD("picker-option",{active:t===E.value}),onClick:x=>{n(E.value)},title:`${E.text} ${E.keyBinding&&`\u2014 ${E.keyBinding.toUpperCase()}`}`,"aria-label":E.text||"none","aria-keyshortcuts":E.keyBinding||void 0,ref:x=>{t===E.value&&setTimeout(()=>{x?.focus()},0)},children:[E.icon,E.keyBinding&&Wi("span",{className:"picker-keybinding",children:E.keyBinding})]},E.text))}),h=a.formFactor==="phone";return Wi(tf.Content,{side:h?"right":"bottom",align:"start",sideOffset:h?8:12,style:{zIndex:"var(--zIndex-ui-styles-popup)"},onKeyDown:l,collisionBoundary:s??void 0,children:of("div",{className:"picker",role:"dialog","aria-modal":"true","aria-label":o,children:[u(p),d.length>0&&Wi(gc,{label:f("labels.more_options"),open:c,openTrigger:()=>{m(g=>!g)},className:"picker-collapsible",children:u(d)})]})})}function nf({value:e,label:t,options:o,onChange:n,group:r="",numberOfOptionsToAlwaysShow:i}){let[a,s]=Om.useState(!1),l=Om.useRef(null);return Wi("div",{children:of(tf.Root,{open:a,onOpenChange:c=>s(c),children:[Wi(tf.Trigger,{name:r,type:"button","aria-label":t,onClick:()=>s(!a),ref:l,className:a?"active":"",children:o.find(c=>c.value===e)?.icon}),a&&Wi(gD,{options:o,value:e,label:t,onChange:n,onClose:()=>{s(!1)},numberOfOptionsToAlwaysShow:i})]})})}import Zv,{useEffect as hD}from"react";import{jsx as rf,jsxs as jv}from"react/jsx-runtime";var qv=({updateData:e,app:t,testId:o})=>{let n=Zv.useRef(null),r=Zv.useRef(null),i=t.scene.getSelectedElements(t.state),a=!0,s=i.at(0),c=i.reduce((m,p)=>(m!=null&&m!==p.opacity&&(a=!1),m==null||m>p.opacity?p.opacity:m),s?.opacity??null)??t.state.currentItemOpacity;return hD(()=>{if(n.current&&r.current){let m=n.current,p=r.current,d=m.offsetWidth,u=15,h=c/100*(d-u)+u/2;p.style.left=`${h}px`,m.style.background=`linear-gradient(to right, var(--color-slider-track) 0%, var(--color-slider-track) ${c}%, var(--button-bg) ${c}%, var(--button-bg) 100%)`}},[c]),jv("label",{className:"control-label",children:[f("labels.opacity"),jv("div",{className:"range-wrapper",children:[rf("input",{style:{"--color-slider-track":a?void 0:"var(--button-bg)"},ref:n,type:"range",min:"0",max:"100",step:"10",onChange:m=>{e(+m.target.value)},value:c,className:"range-input","data-testid":o}),rf("div",{className:"value-bubble",ref:r,children:c!==0?c:null}),rf("div",{className:"zero-label",children:"0"})]})]})};import{Fragment as hf,jsx as me,jsxs as to}from"react/jsx-runtime";var r2=.1,fs=e=>{let t=OD(e.editorInterface);return{stylesPanelMode:t,isCompact:t!=="full",isMobile:t==="mobile"}},eo=(e,t,o,n=!1)=>{let r=df(le(e,t,{includeBoundTextElement:n}));return e.map(i=>r.get(i.id)||i.id===t.editingTextElement?.id?o(i):i)},Yt=function(e,t,o,n,r){let i=t.state.editingTextElement,a=o2(e),s=null;if(i&&(s=o(i)),!s)if(He(a,t.state)){let c=t.scene.getSelectedElements(t.state),m=n===!0?c:c.filter(p=>n(p));s=AD(m,o)??(typeof r=="function"?r(!0):r)}else s=typeof r=="function"?r(!1):r;return s},zD=(e,t,o)=>DD(t)||!t.autoResize?t:o.mutateElement(t,{x:e.textAlign==="left"?e.x:e.x+(e.width-t.width)/(e.textAlign==="center"?2:1),y:e.y+(e.height-t.height)/2}),pf=(e,t,o,n,r)=>{let i=new Set,a=eo(e,t,s=>{if(uo(s)){let l=n(s);i.add(l);let c=kt(s,{fontSize:l});return hc(c,o.scene.getContainerElement(s),o.scene),c=zD(s,c,o.scene),c}return s},!0);return le(e,t,{includeBoundTextElement:!0}).forEach(s=>{uo(s)&&_D(s,o.scene)}),{elements:a,appState:{...t,currentItemFontSize:i.size===1?[...i][0]:r??t.currentItemFontSize},captureUpdate:St.IMMEDIATELY}},HD=W({name:"changeStrokeColor",label:"labels.stroke",trackEvent:!1,perform:(e,t,o)=>({...o?.currentItemStrokeColor&&{elements:eo(e,t,n=>ND(n.type)?kt(n,{strokeColor:o.currentItemStrokeColor}):n,!0)},appState:{...t,...o},captureUpdate:o?.currentItemStrokeColor?St.IMMEDIATELY:St.EVENTUALLY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let{stylesPanelMode:i}=fs(n);return to(hf,{children:[i==="full"&&me("h3",{"aria-hidden":"true",children:f("labels.stroke")}),me(cc,{topPicks:vD,palette:wD,type:"elementStroke",label:f("labels.stroke"),color:Yt(e,n,a=>a.strokeColor,!0,a=>a?null:t.currentItemStrokeColor),onChange:a=>o({currentItemStrokeColor:a}),elements:e,appState:t,updateData:o})]})}}),GD=W({name:"changeBackgroundColor",label:"labels.changeBackground",trackEvent:!1,perform:(e,t,o,n)=>{if(!o?.currentItemBackgroundColor)return{appState:{...t,...o},captureUpdate:St.EVENTUALLY};let r,i=n.scene.getSelectedElements(t);if(!PD(o.currentItemBackgroundColor)&&i.every(s=>e2(s)&&LD(s.points))){let s=df(i);r=e.map(l=>s.has(l.id)&&e2(l)?kt(l,{backgroundColor:o.currentItemBackgroundColor,...FD(l,!0)}):l)}else r=eo(e,t,s=>kt(s,{backgroundColor:o.currentItemBackgroundColor}));return{elements:r,appState:{...t,...o},captureUpdate:St.IMMEDIATELY}},PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let{stylesPanelMode:i}=fs(n);return to(hf,{children:[i==="full"&&me("h3",{"aria-hidden":"true",children:f("labels.background")}),me(cc,{topPicks:yD,palette:ED,type:"elementBackground",label:f("labels.background"),color:Yt(e,n,a=>a.backgroundColor,!0,a=>a?null:t.currentItemBackgroundColor),onChange:a=>o({currentItemBackgroundColor:a}),elements:e,appState:t,updateData:o})]})}}),UD=W({name:"changeFillStyle",label:"labels.fill",trackEvent:!1,perform:(e,t,o,n)=>(ge("element","changeFillStyle",`${o} (${n.editorInterface.formFactor==="phone"?"mobile":"desktop"})`),{elements:eo(e,t,r=>kt(r,{fillStyle:o})),appState:{...t,currentItemFillStyle:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>{let r=le(e,t),i=r.length>0&&r.every(a=>a.fillStyle==="zigzag");return to("fieldset",{children:[me("legend",{children:f("labels.fill")}),me("div",{className:"buttonList",children:me(Oo,{type:"button",options:[{value:"hachure",text:`${i?f("labels.zigzag"):f("labels.hachure")} (${G("Alt-Click")})`,icon:i?By:Fy,active:i?!0:void 0,testId:"fill-hachure"},{value:"cross-hatch",text:f("labels.crossHatch"),icon:Oy,testId:"fill-cross-hatch"},{value:"solid",text:f("labels.solid"),icon:zy,testId:"fill-solid"}],value:Yt(e,n,a=>a.fillStyle,a=>a.hasOwnProperty("fillStyle"),a=>a?null:t.currentItemFillStyle),onClick:(a,s)=>{let l=s.altKey&&a==="hachure"&&r.every(c=>c.fillStyle==="hachure")?"zigzag":a;o(l)}})})]})}}),WD=W({name:"changeStrokeWidth",label:"labels.strokeWidth",trackEvent:!1,perform:(e,t,o)=>({elements:eo(e,t,n=>kt(n,{strokeWidth:o})),appState:{...t,currentItemStrokeWidth:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>to("fieldset",{children:[me("legend",{children:f("labels.strokeWidth")}),me("div",{className:"buttonList",children:me(Oo,{group:"stroke-width",options:[{value:lf.thin,text:f("labels.thin"),icon:wh,testId:"strokeWidth-thin"},{value:lf.bold,text:f("labels.bold"),icon:Hy,testId:"strokeWidth-bold"},{value:lf.extraBold,text:f("labels.extraBold"),icon:Gy,testId:"strokeWidth-extraBold"}],value:Yt(e,n,i=>i.strokeWidth,i=>i.hasOwnProperty("strokeWidth"),i=>i?null:t.currentItemStrokeWidth),onChange:i=>o(i)})})]})}),YD=W({name:"changeSloppiness",label:"labels.sloppiness",trackEvent:!1,perform:(e,t,o)=>({elements:eo(e,t,n=>kt(n,{seed:kD(),roughness:o})),appState:{...t,currentItemRoughness:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>to("fieldset",{children:[me("legend",{children:f("labels.sloppiness")}),me("div",{className:"buttonList",children:me(Oo,{group:"sloppiness",options:[{value:0,text:f("labels.architect"),icon:Yy},{value:1,text:f("labels.artist"),icon:Vy},{value:2,text:f("labels.cartoonist"),icon:$y}],value:Yt(e,n,i=>i.roughness,i=>i.hasOwnProperty("roughness"),i=>i?null:t.currentItemRoughness),onChange:i=>o(i)})})]})}),Sse=W({name:"changeStrokeStyle",label:"labels.strokeStyle",trackEvent:!1,perform:(e,t,o)=>({elements:eo(e,t,n=>kt(n,{strokeStyle:o})),appState:{...t,currentItemStrokeStyle:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>to("fieldset",{children:[me("legend",{children:f("labels.strokeStyle")}),me("div",{className:"buttonList",children:me(Oo,{group:"strokeStyle",options:[{value:"solid",text:f("labels.strokeStyle_solid"),icon:wh},{value:"dashed",text:f("labels.strokeStyle_dashed"),icon:Uy},{value:"dotted",text:f("labels.strokeStyle_dotted"),icon:Wy}],value:Yt(e,n,i=>i.strokeStyle,i=>i.hasOwnProperty("strokeStyle"),i=>i?null:t.currentItemStrokeStyle),onChange:i=>o(i)})})]})}),VD=W({name:"changeOpacity",label:"labels.opacity",trackEvent:!1,perform:(e,t,o)=>({elements:eo(e,t,n=>kt(n,{opacity:o}),!0),appState:{...t,currentItemOpacity:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({app:e,updateData:t})=>me(qv,{updateData:t,app:e,testId:"opacity"})}),$D=W({name:"changeFontSize",label:"labels.fontSize",trackEvent:!1,perform:(e,t,o,n)=>pf(e,t,n,()=>(mf(o,"actionChangeFontSize: Expected a font size value"),o),o),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let{isCompact:i}=fs(n);return to("fieldset",{children:[me("legend",{children:f("labels.fontSize")}),me("div",{className:"buttonList",children:me(Oo,{group:"font-size",options:[{value:Hm.sm,text:f("labels.small"),icon:sw,testId:"fontSize-small"},{value:Hm.md,text:f("labels.medium"),icon:lw,testId:"fontSize-medium"},{value:Hm.lg,text:f("labels.large"),icon:cw,testId:"fontSize-large"},{value:Hm.xl,text:f("labels.veryLarge"),icon:dw,testId:"fontSize-veryLarge"}],value:Yt(e,n,a=>{if(uo(a))return a.fontSize;let s=$r(a,n.scene.getNonDeletedElementsMap());return s?s.fontSize:null},a=>uo(a)||$r(a,n.scene.getNonDeletedElementsMap())!==null,a=>a?null:t.currentItemFontSize||TD),onChange:a=>{ic(()=>o(a),i,!!t.editingTextElement,r?.onPreventClose)}})})]})}}),uf=W({name:"decreaseFontSize",label:"labels.decreaseFontSize",icon:Hi,trackEvent:!1,perform:(e,t,o,n)=>pf(e,t,n,r=>Math.round(1/(1+r2)*r.fontSize)),keyTest:e=>e[hs.CTRL_OR_CMD]&&e.shiftKey&&(e.key===hs.CHEVRON_LEFT||e.key===hs.COMMA)}),gf=W({name:"increaseFontSize",label:"labels.increaseFontSize",icon:Hi,trackEvent:!1,perform:(e,t,o,n)=>pf(e,t,n,r=>Math.round(r.fontSize*(1+r2))),keyTest:e=>e[hs.CTRL_OR_CMD]&&e.shiftKey&&(e.key===hs.CHEVRON_RIGHT||e.key===hs.PERIOD)}),KD=W({name:"changeFontFamily",label:"labels.fontFamily",trackEvent:!1,perform:(e,t,o,n)=>{let{cachedElements:r,resetAll:i,resetContainers:a,...s}=o;if(i)return{elements:eo(e,t,g=>{let E=r?.get(g.id);return E?kt(g,{...E}):g},!0),appState:{...t,...s},captureUpdate:St.NEVER};mf(o,"actionChangeFontFamily: value must be defined");let{currentItemFontFamily:l,currentHoveredFontFamily:c}=o,m=St.EVENTUALLY,p,d=!1;if(l)p=l,m=St.IMMEDIATELY;else if(c){p=c,m=St.EVENTUALLY;let h=le(e,t,{includeBoundTextElement:!0}).filter(g=>uo(g));if(h.length>200)d=!0;else{let g=0,E=0;for(;g<h.length&&E<5e3;){let w=h[g];E+=w?.originalText.length||0,g++}E>5e3&&(d=!0)}}let u={appState:{...t,...s},captureUpdate:m};if(p&&!d){let h=new Map,g=new Set,E=!1,w=Array.from(Mn.loadedFontsCache.values()),x=Object.entries(CD).find(([I,k])=>k===p)?.[0];c&&x&&w.some(I=>I.startsWith(x))&&(E=!0),Object.assign(u,{elements:eo(e,t,I=>{if(uo(I)&&(I.fontFamily!==p||l)){let k=kt(I,{fontFamily:p,lineHeight:MD(p)}),L=r?.get(I.containerId||"")||{},S=n.scene.getContainerElement(I);return a&&S&&L&&n.scene.mutateElement(S,{...L}),E||(g=new Set([...g,...Array.from(k.originalText)])),h.set(k,S),k}return I},!0)});let y=`10px ${SD({fontFamily:p})}`,v=Array.from(g.values()).join();if(E||window.document.fonts.check(y,v))for(let[I,k]of h)hc(I,k,n.scene);else window.document.fonts.load(y,v).then(I=>{for(let[k,L]of h){let S=n.scene.getElement(k.id),_=L?n.scene.getElement(L.id):null;S&&hc(S,_,n.scene)}n.fonts.onLoaded(I)})}return u},PanelComponent:({elements:e,appState:t,app:o,updateData:n})=>{let r=sf(new Map),i=sf(null),[a,s]=xD({}),l=sf(!0),{stylesPanelMode:c,isCompact:m}=fs(o),p=bD(()=>{let d=(u,h)=>Yt(u,o,g=>{if(uo(g))return g.fontFamily;let E=$r(g,h);return E?E.fontFamily:null},g=>uo(g)||$r(g,h)!==null,g=>g?null:t.currentItemFontFamily||ID);return a.openPopup==="fontFamily"&&t.openPopup==="fontFamily"?d(Array.from(r.current?.values()??[]),r.current):!a.openPopup&&t.openPopup!=="fontFamily"?d(e,o.scene.getNonDeletedElementsMap()):i.current},[a.openPopup,t,e,o]);return af(()=>{i.current=p},[p]),af(()=>{Object.keys(a).length&&(n(a),s({}))},[a]),af(()=>(l.current=!1,()=>{l.current=!0}),[]),to(hf,{children:[c==="full"&&me("legend",{children:f("labels.fontFamily")}),me($v,{isOpened:t.openPopup==="fontFamily",selectedFontFamily:p,hoveredFontFamily:t.currentHoveredFontFamily,compactMode:c!=="full",onSelect:d=>{ic(()=>{s({openPopup:null,currentHoveredFontFamily:null,currentItemFontFamily:d}),r.current.clear()},m,!!t.editingTextElement)},onHover:d=>{s({currentHoveredFontFamily:d,cachedElements:new Map(r.current),resetContainers:!0})},onLeave:()=>{s({currentHoveredFontFamily:null,cachedElements:new Map(r.current),resetAll:!0})},onPopupChange:d=>{if(d){r.current.clear();let{editingTextElement:u}=t;if(u?.type==="text"){let h=o.scene.getElement(u.id);r.current.set(u.id,kt(h||u,{},!0))}else{let h=le(e,t,{includeBoundTextElement:!0});for(let g of h)r.current.set(g.id,kt(g,{},!0))}s({...a,openPopup:"fontFamily"})}else{let u={currentHoveredFontFamily:null,cachedElements:new Map(r.current),resetAll:!0};s({...u}),r.current.clear(),m&&t.editingTextElement&&rc(null)}}})]})}}),XD=W({name:"changeTextAlign",label:"Change text alignment",trackEvent:!1,perform:(e,t,o,n)=>({elements:eo(e,t,r=>{if(uo(r)){let i=kt(r,{textAlign:o});return hc(i,n.scene.getContainerElement(r),n.scene),i}return r},!0),appState:{...t,currentItemTextAlign:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let i=n.scene.getNonDeletedElementsMap(),{isCompact:a}=fs(n);return to("fieldset",{children:[me("legend",{children:f("labels.textAlign")}),me("div",{className:"buttonList",children:me(Oo,{group:"text-align",options:[{value:"left",text:f("labels.left"),icon:pw,testId:"align-left"},{value:"center",text:f("labels.center"),icon:uw,testId:"align-horizontal-center"},{value:"right",text:f("labels.right"),icon:gw,testId:"align-right"}],value:Yt(e,n,s=>{if(uo(s))return s.textAlign;let l=$r(s,i);return l?l.textAlign:null},s=>uo(s)||$r(s,i)!==null,s=>s?null:t.currentItemTextAlign),onChange:s=>{ic(()=>o(s),a,!!t.editingTextElement,r?.onPreventClose)}})})]})}}),ZD=W({name:"changeVerticalAlign",label:"Change vertical alignment",trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:eo(e,t,r=>{if(uo(r)){let i=kt(r,{verticalAlign:o});return hc(i,n.scene.getContainerElement(r),n.scene),i}return r},!0),appState:{...t},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,data:r})=>{let{isCompact:i}=fs(n);return me("fieldset",{children:me("div",{className:"buttonList",children:me(Oo,{group:"text-align",options:[{value:zm.TOP,text:f("labels.alignTop"),icon:me(hw,{theme:t.theme}),testId:"align-top"},{value:zm.MIDDLE,text:f("labels.centerVertically"),icon:me(bw,{theme:t.theme}),testId:"align-middle"},{value:zm.BOTTOM,text:f("labels.alignBottom"),icon:me(fw,{theme:t.theme}),testId:"align-bottom"}],value:Yt(e,n,a=>{if(uo(a)&&a.containerId)return a.verticalAlign;let s=$r(a,n.scene.getNonDeletedElementsMap());return s?s.verticalAlign:null},a=>uo(a)||$r(a,n.scene.getNonDeletedElementsMap())!==null,a=>a?null:zm.MIDDLE),onChange:a=>{ic(()=>o(a),i,!!t.editingTextElement,r?.onPreventClose)}})})})}}),Mse=W({name:"changeRoundness",label:"Change edge roundness",trackEvent:!1,perform:(e,t,o)=>({elements:eo(e,t,n=>n2(n)?n:kt(n,{roundness:o==="round"?{type:RD(n.type)?Gm.ADAPTIVE_RADIUS:Gm.PROPORTIONAL_RADIUS}:null})),appState:{...t,currentItemRoundness:o},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n,renderAction:r})=>{let a=_a(o2(e),t).some(s=>s.roundness?.type===Gm.LEGACY);return to("fieldset",{children:[me("legend",{children:f("labels.edges")}),to("div",{className:"buttonList",children:[me(Oo,{group:"edges",options:[{value:"sharp",text:f("labels.sharp"),icon:Ky},{value:"round",text:f("labels.round"),icon:Xy}],value:Yt(e,n,s=>a?null:s.roundness?"round":"sharp",s=>!Um(s)&&s.hasOwnProperty("roundness"),s=>s?null:t.currentItemRoundness),onChange:s=>o(s)}),r("togglePolygon")]})]})}}),t2=e=>[{value:null,text:f("labels.arrowhead_none"),keyBinding:"q",icon:me(Zy,{flip:e})},{value:"arrow",text:f("labels.arrowhead_arrow"),keyBinding:"w",icon:me(jy,{flip:e})},{value:"triangle",text:f("labels.arrowhead_triangle"),icon:me(ew,{flip:e}),keyBinding:"e"},{value:"triangle_outline",text:f("labels.arrowhead_triangle_outline"),icon:me(tw,{flip:e}),keyBinding:"r"},{value:"circle",text:f("labels.arrowhead_circle"),keyBinding:"a",icon:me(qy,{flip:e})},{value:"circle_outline",text:f("labels.arrowhead_circle_outline"),keyBinding:"s",icon:me(Jy,{flip:e})},{value:"diamond",text:f("labels.arrowhead_diamond"),icon:me(ow,{flip:e}),keyBinding:"d"},{value:"diamond_outline",text:f("labels.arrowhead_diamond_outline"),icon:me(nw,{flip:e}),keyBinding:"f"},{value:"bar",text:f("labels.arrowhead_bar"),keyBinding:"z",icon:me(Qy,{flip:e})},{value:"crowfoot_one",text:f("labels.arrowhead_crowfoot_one"),icon:me(iw,{flip:e}),keyBinding:"x"},{value:"crowfoot_many",text:f("labels.arrowhead_crowfoot_many"),icon:me(rw,{flip:e}),keyBinding:"c"},{value:"crowfoot_one_or_many",text:f("labels.arrowhead_crowfoot_one_or_many"),icon:me(aw,{flip:e}),keyBinding:"v"}],Pse=W({name:"changeArrowhead",label:"Change arrowheads",trackEvent:!1,perform:(e,t,o)=>(mf(o,"actionChangeArrowhead: value must be defined"),{elements:eo(e,t,n=>{if(cf(n)){let{position:r,type:i}=o;if(r==="start")return kt(n,{startArrowhead:i});if(r==="end")return kt(n,{endArrowhead:i})}return n}),appState:{...t,[o.position==="start"?"currentItemStartArrowhead":"currentItemEndArrowhead"]:o.type},captureUpdate:St.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>{let r=lr().rtl;return to("fieldset",{children:[me("legend",{children:f("labels.arrowheads")}),to("div",{className:"iconSelectList buttonList",children:[me(nf,{label:"arrowhead_start",options:t2(!r),value:Yt(e,n,i=>cf(i)&&Da(i.type)?i.startArrowhead:t.currentItemStartArrowhead,!0,i=>i?null:t.currentItemStartArrowhead),onChange:i=>o({position:"start",type:i}),numberOfOptionsToAlwaysShow:4}),me(nf,{label:"arrowhead_end",group:"arrowheads",options:t2(!!r),value:Yt(e,n,i=>cf(i)&&Da(i.type)?i.endArrowhead:t.currentItemEndArrowhead,!0,i=>i?null:t.currentItemEndArrowhead),onChange:i=>o({position:"end",type:i}),numberOfOptionsToAlwaysShow:4})]})]})}}),jD=W({name:"changeArrowProperties",label:"Change arrow properties",trackEvent:!1,perform:(e,t,o,n)=>!1,PanelComponent:({elements:e,appState:t,updateData:o,app:n,renderAction:r})=>to("div",{className:"selected-shape-actions",children:[r("changeArrowhead"),r("changeArrowType")]})}),Ase=W({name:"changeArrowType",label:"Change arrow types",trackEvent:!1,perform:(e,t,o,n)=>{let r=eo(e,t,s=>{if(!Um(s))return s;let l=n.scene.getNonDeletedElementsMap(),c=Yi.getPointAtIndexGlobalCoordinates(s,0,l),m=Yi.getPointAtIndexGlobalCoordinates(s,-1,l),p=kt(s,{x:o===Uo.elbow?c[0]:s.x,y:o===Uo.elbow?c[1]:s.y,roundness:o===Uo.round?{type:Gm.PROPORTIONAL_RADIUS}:null,elbowed:o===Uo.elbow,angle:o===Uo.elbow?0:s.angle,points:o===Uo.elbow||s.elbowed?[Yi.pointFromAbsoluteCoords({...s,x:c[0],y:c[1],angle:0},c,l),Yi.pointFromAbsoluteCoords({...s,x:c[0],y:c[1],angle:0},m,l)]:s.points});if(n2(p)){p.fixedSegments=null;let d=n.scene.getNonDeletedElementsMap();n.dismissLinearEditor();let u=Yi.getPointAtIndexGlobalCoordinates(p,0,d),h=Yi.getPointAtIndexGlobalCoordinates(p,-1,d),g=p.startBinding&&d.get(p.startBinding.elementId),E=p.endBinding&&d.get(p.endBinding.elementId),w=g&&p.startBinding?{...p.startBinding,...Qv(p,g,"start",d)}:null,x=E&&p.endBinding?{...p.endBinding,...Qv(p,E,"end",d)}:null;p={...p,startBinding:w,endBinding:x,...BD(p,d,{points:[u,h].map(y=>fD(y[0]-p.x,y[1]-p.y)),startBinding:w,endBinding:x,fixedSegments:null})}}else{let d=n.scene.getNonDeletedElementsMap();if(p.startBinding){let u=d.get(p.startBinding.elementId);u&&Jv(p,u,t.bindMode==="inside"?"inside":"orbit","start",n.scene)}if(p.endBinding){let u=d.get(p.endBinding.elementId);u&&Jv(p,u,t.bindMode==="inside"?"inside":"orbit","end",n.scene)}}return p}),i={...t,currentItemArrowType:o},a=t.selectedLinearElement?.elementId;if(a){let s=r.find(l=>l.id===a);s&&(i.selectedLinearElement=new Yi(s,df(e)))}return{elements:r,appState:i,captureUpdate:St.IMMEDIATELY}},PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>to("fieldset",{children:[me("legend",{children:f("labels.arrowtypes")}),me("div",{className:"buttonList",children:me(Oo,{group:"arrowtypes",options:[{value:Uo.sharp,text:f("labels.arrowtype_sharp"),icon:ns,testId:"sharp-arrow"},{value:Uo.round,text:f("labels.arrowtype_round"),icon:is,testId:"round-arrow"},{value:Uo.elbow,text:f("labels.arrowtype_elbowed"),icon:rs,testId:"elbow-arrow"}],value:Yt(e,n,r=>Um(r)?r.elbowed?Uo.elbow:r.roundness?Uo.round:Uo.sharp:null,r=>Um(r),r=>r?null:t.currentItemArrowType),onChange:r=>o(r)})})]})});import{clamp as yf,roundToStep as n8}from"@orangecatai/math";import{DEFAULT_CANVAS_BACKGROUND_PICKS as r8,CURSOR_TYPE as p2,MAX_ZOOM as u2,MIN_ZOOM as g2,THEME as fc,ZOOM_STEP as wf,updateActiveTool as xs,CODES as On,KEYS as ur,viewportCoordsToSceneCoords as i8}from"@orangecatai/common";import{getElementAbsoluteCoords as c2,getNonDeletedElements as h2,getVisibleElements as a8}from"@orangecatai/element";import{newElementWith as s8}from"@orangecatai/element";import{getCommonBounds as f2}from"@orangecatai/element";import{CaptureUpdateAction as dn}from"@orangecatai/element";import{useEffect as qD}from"react";import{jsx as QD}from"react/jsx-runtime";var bs=()=>{let e=document.querySelector(".excalidraw-tooltip");if(e)return e;let t=document.createElement("div");return document.body.appendChild(t),t.classList.add("excalidraw-tooltip"),t},ff=(e,t,o="bottom")=>{let n=e.getBoundingClientRect(),r=window.innerWidth,i=window.innerHeight,a=5,s=t.left+t.width/2-n.width/2;s<0?s=a:s+n.width>=r&&(s=r-n.width-a);let l;o==="bottom"?(l=t.top+t.height+a,l+n.height>=i&&(l=t.top-n.height-a)):(l=t.top-n.height-a,l<0&&(l=t.top+t.height+a)),Object.assign(e.style,{top:`${l}px`,left:`${s}px`})},JD=(e,t,o,n)=>{t.classList.add("excalidraw-tooltip--visible"),t.style.minWidth=n?"50ch":"10ch",t.style.maxWidth=n?"50ch":"15ch",t.textContent=o;let r=e.getBoundingClientRect();ff(t,r)},Vt=({children:e,label:t,long:o=!1,style:n,disabled:r})=>(qD(()=>()=>bs().classList.remove("excalidraw-tooltip--visible"),[]),r?null:QD("div",{className:"excalidraw-tooltip-wrapper",onPointerEnter:i=>JD(i.currentTarget,bs(),t,o),onPointerLeave:()=>bs().classList.remove("excalidraw-tooltip--visible"),style:n,children:e}));import{CURSOR_TYPE as bf,MIME_TYPES as xf,THEME as a2}from"@orangecatai/common";var s2='<svg viewBox="0 0 24 24" stroke-width="1" width="28" height="28" xmlns="http://www.w3.org/2000/svg">',e8='<path d="M6.164 11.755a5.314 5.314 0 0 1-4.932-5.298 5.314 5.314 0 0 1 5.311-5.311 5.314 5.314 0 0 1 5.307 5.113l8.773 8.773a3.322 3.322 0 0 1 0 4.696l-.895.895a3.322 3.322 0 0 1-4.696 0l-8.868-8.868Z" style="fill:#fff"/>',l2='<path stroke="#1b1b1f" fill="#fff" d="m7.868 11.113 7.773 7.774a2.359 2.359 0 0 0 1.667.691 2.368 2.368 0 0 0 2.357-2.358c0-.625-.248-1.225-.69-1.667L11.201 7.78 9.558 9.469l-1.69 1.643v.001Zm10.273 3.606-3.333 3.333m-3.25-6.583 2 2m-7-7 3 3M3.664 3.625l1 1M2.529 6.922l1.407-.144m5.735-2.932-1.118.866M4.285 9.823l.758-1.194m1.863-6.207-.13 1.408"/>',t8=`data:${xf.svg},${encodeURIComponent(`${s2}${l2}</svg>`)}`,o8=`data:${xf.svg},${encodeURIComponent(`${s2}${e8}${l2}</svg>`)}`,ko=e=>{e&&(e.style.cursor="")},Ne=(e,t)=>{e&&(e.style.cursor=t)},Fn,i2,Ef=(e,t)=>{let n=()=>{let r=t===a2.DARK;Fn=document.createElement("canvas"),Fn.theme=t,Fn.height=20,Fn.width=20;let i=Fn.getContext("2d");i.lineWidth=1,i.beginPath(),i.arc(Fn.width/2,Fn.height/2,5,0,2*Math.PI),i.fillStyle=r?"#000":"#fff",i.fill(),i.strokeStyle=r?"#fff":"#000",i.stroke(),i2=Fn.toDataURL(xf.svg)};(!Fn||Fn.theme!==t)&&n(),Ne(e,`url(${i2}) ${20/2} ${20/2}, auto`)},So=(e,t)=>{if(e)if(t.activeTool.type==="selection")ko(e);else if(sr(t))e.style.cursor=bf.GRAB;else if(po(t))Ef(e,t.theme);else if(t.activeTool.type==="laser"){let o=t.theme===a2.LIGHT?t8:o8;e.style.cursor=`url(${o}), auto`}else["image","custom"].includes(t.activeTool.type)?t.activeTool.type!=="image"&&(e.style.cursor=bf.AUTO):e.style.cursor=bf.CROSSHAIR};var pr=({viewportX:e,viewportY:t,nextZoom:o},n)=>{let r=e-n.offsetLeft,i=t-n.offsetTop,a=n.zoom.value,s=n.scrollX+(r-r/a),l=n.scrollY+(i-i/a),c=-(r-r/o),m=-(i-i/o);return{scrollX:s+c,scrollY:l+m,zoom:{value:o}}};import{jsx as Es,jsxs as f8}from"react/jsx-runtime";var l8=W({name:"changeViewBackgroundColor",label:"labels.canvasBackground",trackEvent:!1,predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.changeViewBackgroundColor&&!t.viewModeEnabled,perform:(e,t,o)=>({appState:{...t,...o},captureUpdate:o?.viewBackgroundColor?dn.IMMEDIATELY:dn.EVENTUALLY}),PanelComponent:({elements:e,appState:t,updateData:o,appProps:n,data:r})=>Es(cc,{palette:null,topPicks:r8,label:f("labels.canvasBackground"),type:"canvasBackground",color:t.viewBackgroundColor,onChange:i=>o({viewBackgroundColor:i}),"data-testid":"canvas-background-picker",elements:e,appState:t,updateData:o})}),gr=W({name:"clearCanvas",label:"labels.clearCanvas",icon:Ht,trackEvent:{category:"canvas"},predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.clearCanvas&&!t.viewModeEnabled&&t.openDialog?.name!=="elementLinkSelector",perform:(e,t,o,n)=>(n.imageCache.clear(),{elements:e.map(r=>s8(r,{isDeleted:!0})),appState:{...Rr(),files:{},theme:t.theme,penMode:t.penMode,penDetected:t.penDetected,exportBackground:t.exportBackground,exportEmbedScene:t.exportEmbedScene,gridSize:t.gridSize,gridStep:t.gridStep,gridModeEnabled:t.gridModeEnabled,stats:t.stats,pasteDialog:t.pasteDialog,activeTool:t.activeTool.type==="image"?{...t.activeTool,type:n.state.preferredSelectionTool.type}:t.activeTool},captureUpdate:dn.IMMEDIATELY})}),Wm=W({name:"zoomIn",label:"buttons.zoomIn",viewMode:!0,icon:rh,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>({appState:{...t,...pr({viewportX:t.width/2+t.offsetLeft,viewportY:t.height/2+t.offsetTop,nextZoom:Cn(t.zoom.value+wf)},t),userToFollow:null},captureUpdate:dn.EVENTUALLY}),PanelComponent:({updateData:e,appState:t})=>Es(ne,{type:"button",className:"zoom-in-button zoom-button",icon:rh,title:`${f("buttons.zoomIn")} \u2014 ${G("CtrlOrCmd++")}`,"aria-label":f("buttons.zoomIn"),disabled:t.zoom.value>=u2,onClick:()=>{e(null)}}),keyTest:e=>(e.code===On.EQUAL||e.code===On.NUM_ADD)&&(e[ur.CTRL_OR_CMD]||e.shiftKey)}),Ym=W({name:"zoomOut",label:"buttons.zoomOut",icon:ih,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>({appState:{...t,...pr({viewportX:t.width/2+t.offsetLeft,viewportY:t.height/2+t.offsetTop,nextZoom:Cn(t.zoom.value-wf)},t),userToFollow:null},captureUpdate:dn.EVENTUALLY}),PanelComponent:({updateData:e,appState:t})=>Es(ne,{type:"button",className:"zoom-out-button zoom-button",icon:ih,title:`${f("buttons.zoomOut")} \u2014 ${G("CtrlOrCmd+-")}`,"aria-label":f("buttons.zoomOut"),disabled:t.zoom.value<=g2,onClick:()=>{e(null)}}),keyTest:e=>(e.code===On.MINUS||e.code===On.NUM_SUBTRACT)&&(e[ur.CTRL_OR_CMD]||e.shiftKey)}),Vm=W({name:"resetZoom",label:"buttons.resetZoom",icon:Ey,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>({appState:{...t,...pr({viewportX:t.width/2+t.offsetLeft,viewportY:t.height/2+t.offsetTop,nextZoom:Cn(1)},t),userToFollow:null},captureUpdate:dn.EVENTUALLY}),PanelComponent:({updateData:e,appState:t})=>Es(Vt,{label:f("buttons.resetZoom"),style:{height:"100%"},children:f8(ne,{type:"button",className:"reset-zoom-button zoom-button",title:f("buttons.resetZoom"),"aria-label":f("buttons.resetZoom"),onClick:()=>{e(null)},children:[(t.zoom.value*100).toFixed(0),"%"]})}),keyTest:e=>(e.code===On.ZERO||e.code===On.NUM_ZERO)&&(e[ur.CTRL_OR_CMD]||e.shiftKey)}),c8=(e,t,o=1)=>{let[n,r,i,a]=e,s=i-n,l=t.width/s,c=a-r,m=t.height/c,d=Math.min(l,m)*yf(o,.1,1);return Math.min(d,1)},d8=.8,m8=(e,t)=>e[0]<=t[2]&&e[2]>=t[0]&&e[1]<=t[3]&&e[3]>=t[1],p8=(e,t)=>[e[0]-t,e[1]-t,e[2]+t,e[3]+t],d2=(e,t)=>{let o=(e[0]+e[2])/2,n=(e[1]+e[3])/2;return Math.hypot(o-t.x,n-t.y)},m2=e=>[e[0],e[1],e[2],e[3]],u8=(e,t)=>{let o=h2(e);if(!o.length)return[];let n=a8(o),r=n.length?n:o,i=new Map(o.map(d=>[d.id,d])),a=i8({clientX:t.offsetLeft+t.width/2,clientY:t.offsetTop+t.height/2},t),s=r.reduce((d,u)=>{let h=m2(c2(u,i));return d?d2(h,a)<d2(d.bounds,a)?{element:u,bounds:h}:d:{element:u,bounds:h}},null);if(!s)return[];let l=Math.max(160/t.zoom.value,.12*Math.min(t.width,t.height)/t.zoom.value),c=new Map([[s.element.id,s.element]]),m=s.bounds,p=!0;for(;p;){p=!1;let d=p8(m,l);for(let u of r){if(c.has(u.id))continue;let h=m2(c2(u,i));m8(h,d)&&(c.set(u.id,u),m=f2([...c.values()]),p=!0)}}return[...c.values()]},b2=({bounds:e,appState:t,canvasOffsets:o,fitToViewport:n=!1,viewportZoomFactor:r=1,minZoom:i=-1/0,maxZoom:a=1/0})=>{r=yf(r,g2,u2);let[s,l,c,m]=e,p=(s+c)/2,d=(l+m)/2,u=o?.left??0,h=o?.top??0,g=o?.right??0,E=o?.bottom??0,w=t.width-u-g,x=t.height-h-E,y;if(n){let k=c-s,L=m-l;y=Math.min(w/k,x/L)*r}else y=c8(e,{width:w,height:x},r);let v=Cn(yf(n8(y,wf,"floor"),i,a)),I=FE({scenePoint:{x:p,y:d},viewportDimensions:{width:t.width,height:t.height},offsets:o,zoom:{value:v}});return{appState:{...t,scrollX:I.scrollX,scrollY:I.scrollY,zoom:{value:v}},captureUpdate:dn.EVENTUALLY}},ys=({canvasOffsets:e,targetElements:t,appState:o,fitToViewport:n,viewportZoomFactor:r,minZoom:i,maxZoom:a})=>{let s=f2(h2(t));return b2({canvasOffsets:e,bounds:s,appState:o,fitToViewport:n,viewportZoomFactor:r,minZoom:i,maxZoom:a})},ple=W({name:"zoomToFitSelectionInViewport",label:"labels.zoomToFitViewport",icon:os,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return ys({targetElements:r.length?r:e,appState:{...t,userToFollow:null},fitToViewport:!1,canvasOffsets:n.getEditorUIOffsets()})},keyTest:e=>e.code===On.TWO&&e.shiftKey&&!e.altKey&&!e[ur.CTRL_OR_CMD]}),ule=W({name:"zoomToFitSelection",label:"helpDialog.zoomToSelection",icon:os,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return ys({targetElements:r.length?r:e,appState:{...t,userToFollow:null},fitToViewport:!0,canvasOffsets:n.getEditorUIOffsets()})},keyTest:e=>e.code===On.THREE&&e.shiftKey&&!e.altKey&&!e[ur.CTRL_OR_CMD]}),g8=W({name:"zoomToFit",label:"helpDialog.zoomToFit",icon:os,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>ys({targetElements:e,appState:{...t,userToFollow:null},fitToViewport:!1,canvasOffsets:n.getEditorUIOffsets()}),keyTest:e=>e.code===On.ONE&&e.shiftKey&&!e.altKey&&!e[ur.CTRL_OR_CMD]}),h8=W({name:"scrollBackToContent",label:"buttons.scrollBackToContent",icon:os,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i=r.length?r:u8(e,t);return i.length?ys({targetElements:i,appState:{...t,userToFollow:null},fitToViewport:!0,viewportZoomFactor:d8,canvasOffsets:n.getEditorUIOffsets()}):!1},PanelComponent:({updateData:e})=>Es(Vt,{label:f("buttons.scrollBackToContent"),style:{height:"100%"},children:Es(ne,{type:"button",className:"scroll-back-to-content-button zoom-button",icon:os,title:f("buttons.scrollBackToContent"),"aria-label":f("buttons.scrollBackToContent"),onClick:()=>{e(null)}})})}),Vi=W({name:"toggleTheme",label:(e,t)=>t.theme===fc.DARK?"buttons.lightMode":"buttons.darkMode",keywords:["toggle","dark","light","mode","theme"],icon:(e,t)=>e.theme===fc.LIGHT?Zl:jl,viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t,o)=>({appState:{...t,theme:o||(t.theme===fc.LIGHT?fc.DARK:fc.LIGHT)},captureUpdate:dn.EVENTUALLY}),keyTest:e=>e.altKey&&e.shiftKey&&e.code===On.D,predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.toggleTheme}),gle=W({name:"toggleEraserTool",label:"toolBar.eraser",trackEvent:{category:"toolbar"},perform:(e,t,o,n)=>{let r;return po(t)?r=xs(t,{...t.activeTool.lastActiveTool||{type:n.state.preferredSelectionTool.type},lastActiveToolBeforeEraser:null}):r=xs(t,{type:"eraser",lastActiveToolBeforeEraser:t.activeTool}),{appState:{...t,selectedElementIds:{},selectedGroupIds:{},activeEmbeddable:null,activeTool:r},captureUpdate:dn.IMMEDIATELY}},keyTest:e=>e.key===ur.E}),hle=W({name:"toggleLassoTool",label:"toolBar.lasso",icon:Nr,trackEvent:{category:"toolbar"},predicate:(e,t,o,n)=>n.state.preferredSelectionTool.type!=="lasso",perform:(e,t,o,n)=>{let r;return t.activeTool.type!=="lasso"?(r=xs(t,{type:"lasso",fromSelection:!1}),Ne(n.interactiveCanvas,p2.CROSSHAIR)):r=xs(t,{type:"selection"}),{appState:{...t,selectedElementIds:{},selectedGroupIds:{},activeEmbeddable:null,activeTool:r},captureUpdate:dn.NEVER}}}),x2=W({name:"toggleHandTool",label:"toolBar.hand",trackEvent:{category:"toolbar"},icon:Ja,viewMode:!1,perform:(e,t,o,n)=>{let r;return sr(t)?r=xs(t,{...t.activeTool.lastActiveTool||{type:"selection"},lastActiveToolBeforeEraser:null}):(r=xs(t,{type:"hand",lastActiveToolBeforeEraser:t.activeTool}),Ne(n.interactiveCanvas,p2.GRAB)),{appState:{...t,selectedElementIds:{},selectedGroupIds:{},activeEmbeddable:null,activeTool:r},captureUpdate:dn.IMMEDIATELY}},keyTest:e=>!e.altKey&&!e[ur.CTRL_OR_CMD]&&e.key===ur.H});import{updateActiveTool as E2}from"@orangecatai/common";import{CaptureUpdateAction as b8}from"@orangecatai/element";var x8=W({name:"setEmbeddableAsActiveTool",trackEvent:{category:"toolbar"},target:"Tool",label:"toolBar.embeddable",perform:(e,t,o,n)=>{let r=E2(t,{type:"embeddable"});return So(n.canvas,{...t,activeTool:r}),{elements:e,appState:{...t,activeTool:E2(t,{type:"embeddable"})},captureUpdate:b8.EVENTUALLY}}});import{pointFrom as y2}from"@orangecatai/math";import{bindOrUnbindBindingElement as E8}from"@orangecatai/element/binding";import{isValidPolygon as w2,LinearElementEditor as $m,newElementWith as vf}from"@orangecatai/element";import{isBindingElement as v2,isFreeDrawElement as I2,isLinearElement as T2,isLineElement as Km}from"@orangecatai/element";import{KEYS as If,arrayToMap as y8,invariant as C2,shouldRotateWithDiscreteAngle as w8,updateActiveTool as k2}from"@orangecatai/common";import{isPathALoop as v8}from"@orangecatai/element";import{isInvisiblySmallElement as Tf}from"@orangecatai/element";import{CaptureUpdateAction as S2}from"@orangecatai/element";import{jsx as I8}from"react/jsx-runtime";var oo=W({name:"finalize",label:"",trackEvent:!1,perform:(e,t,o,n)=>{let r=e,{interactiveCanvas:i,focusContainer:a,scene:s}=n,l=s.getNonDeletedElementsMap();if(o&&t.selectedLinearElement){let{event:d,sceneCoords:u}=o,h=$m.getElement(t.selectedLinearElement.elementId,l);C2(h,"Arrow element should exist if selectedLinearElement is set"),C2(u,"sceneCoords should be defined if actionFinalize is called with event");let g=$m.handlePointerUp(d,t.selectedLinearElement,t,n.scene);if(v2(h)&&!t.selectedLinearElement.segmentMidPointHoveredCoords){let E=!!t.newElement,x=(E||!t.selectedLinearElement.selectedPointsIndices?[h.points.length-1]:t.selectedLinearElement.selectedPointsIndices).reduce((y,v)=>(y.set(v,{point:$m.pointFromAbsoluteCoords(h,y2(u.x-g.pointerOffset.x,u.y-g.pointerOffset.y),l)}),y),new Map)??new Map;E8(h,x,u.x-g.pointerOffset.x,u.y-g.pointerOffset.y,s,t,{newArrow:E,altKey:d.altKey,angleLocked:w8(d)})}else Km(h)&&t.selectedLinearElement?.isEditing&&!t.newElement&&!w2(h.points)&&s.mutateElement(h,{polygon:!1});if(g!==t.selectedLinearElement){h&&Tf(h)&&(r=r.map(w=>w.id===h.id?vf(w,{isDeleted:!0}):w));let E=t.activeTool?.locked;return{elements:h.points.length<2||Tf(h)?e.map(w=>w.id===h.id?vf(w,{isDeleted:!0}):w):r,appState:{...t,cursorButton:"up",selectedLinearElement:E?null:{...g,selectedPointsIndices:null,isEditing:!1,initialState:{...g.initialState,lastClickedPoint:-1},pointerOffset:{x:0,y:0}},selectionElement:null,suggestedBinding:null,newElement:null,multiElement:null},captureUpdate:S2.IMMEDIATELY}}}window.document.activeElement instanceof HTMLElement&&a();let c=null;if(t.multiElement)c=t.multiElement;else if(t.newElement?.type==="freedraw"||v2(t.newElement))c=t.newElement;else if(Object.keys(t.selectedElementIds).length===1){let d=l.get(Object.keys(t.selectedElementIds)[0]);d&&(c=d)}if(c){if(t.selectedLinearElement&&t.multiElement&&c.type!=="freedraw"&&t.lastPointerDownWith!=="touch"){let{points:d}=c,{lastCommittedPoint:u}=t.selectedLinearElement;(!u||d[d.length-1]!==u)&&s.mutateElement(c,{points:c.points.slice(0,-1)})}if(c&&Tf(c)&&(r=r.map(d=>d.id===c?.id?vf(d,{isDeleted:!0}):d)),T2(c)||I2(c)){if(v8(c.points,t.zoom.value)&&(Km(c)||I2(c))){let u=c.points,h=u[0],g=u.map((E,w)=>w===u.length-1?y2(h[0],h[1]):E);Km(c)?s.mutateElement(c,{points:g,polygon:!0}):s.mutateElement(c,{points:g})}Km(c)&&!w2(c.points)&&s.mutateElement(c,{polygon:!1})}}(!t.activeTool.locked&&t.activeTool.type!=="freedraw"||!c)&&ko(i);let m;t.activeTool.type==="eraser"?m=k2(t,{...t.activeTool.lastActiveTool||{type:n.state.preferredSelectionTool.type},lastActiveToolBeforeEraser:null}):m=k2(t,{type:n.state.preferredSelectionTool.type});let p=c&&T2(c)?new $m(c,y8(r)):t.selectedLinearElement;return p=p&&{...p,isEditing:t.newElement?!1:p.isEditing,initialState:{...p.initialState,lastClickedPoint:-1,origin:null}},{elements:r,appState:{...t,cursorButton:"up",activeTool:(t.activeTool.locked||t.activeTool.type==="freedraw")&&c?t.activeTool:m,activeEmbeddable:null,newElement:null,selectionElement:null,multiElement:null,editingTextElement:null,startBoundElement:null,suggestedBinding:null,selectedElementIds:c&&!t.activeTool.locked&&t.activeTool.type!=="freedraw"?{...t.selectedElementIds,[c.id]:!0}:t.selectedElementIds,selectedLinearElement:p},captureUpdate:S2.IMMEDIATELY}},keyTest:(e,t)=>e.key===If.ESCAPE&&(t.selectedLinearElement?.isEditing||!t.newElement&&t.multiElement===null)||(e.key===If.ESCAPE||e.key===If.ENTER)&&t.multiElement!==null,PanelComponent:({appState:e,updateData:t,data:o})=>I8(ne,{type:"button",icon:My,title:f("buttons.done"),"aria-label":f("buttons.done"),onClick:t,visible:e.multiElement!=null,size:o?.size||"medium",style:{pointerEvents:"all"}})});import{KEYS as Ts,DEFAULT_EXPORT_PADDING as uR,EXPORT_SCALES as gR,THEME as Sf}from"@orangecatai/common";import{getNonDeletedElements as hR}from"@orangecatai/element";import{CaptureUpdateAction as un}from"@orangecatai/element";import T8 from"clsx";import{jsx as M2,jsxs as C8}from"react/jsx-runtime";var bc=({children:e,checked:t,onChange:o,className:n})=>C8("div",{className:T8("Checkbox",n,{"is-checked":t}),onClick:r=>{o(!t,r),r.currentTarget.querySelector(".Checkbox-box").focus()},children:[M2("button",{type:"button",className:"Checkbox-box",role:"checkbox","aria-checked":t,children:cm}),M2("div",{className:"Checkbox-label",children:e})]});import{THEME as xc}from"@orangecatai/common";import{jsx as Ec}from"react/jsx-runtime";var A2=e=>{let t=e.title||(e.value===xc.DARK?f("buttons.lightMode"):f("buttons.darkMode"));return Ec(ne,{type:"icon",icon:e.value===xc.LIGHT?P2.MOON:P2.SUN,title:t,"aria-label":t,onClick:()=>e.onChange(e.value===xc.DARK?xc.LIGHT:xc.DARK),"data-testid":"toggle-dark-mode"})},P2={SUN:Ec("svg",{width:"512",height:"512",className:"rtl-mirror",viewBox:"0 0 512 512",children:Ec("path",{fill:"currentColor",d:"M256 160c-52.9 0-96 43.1-96 96s43.1 96 96 96 96-43.1 96-96-43.1-96-96-96zm246.4 80.5l-94.7-47.3 33.5-100.4c4.5-13.6-8.4-26.5-21.9-21.9l-100.4 33.5-47.4-94.8c-6.4-12.8-24.6-12.8-31 0l-47.3 94.7L92.7 70.8c-13.6-4.5-26.5 8.4-21.9 21.9l33.5 100.4-94.7 47.4c-12.8 6.4-12.8 24.6 0 31l94.7 47.3-33.5 100.5c-4.5 13.6 8.4 26.5 21.9 21.9l100.4-33.5 47.3 94.7c6.4 12.8 24.6 12.8 31 0l47.3-94.7 100.4 33.5c13.6 4.5 26.5-8.4 21.9-21.9l-33.5-100.4 94.7-47.3c13-6.5 13-24.7.2-31.1zm-155.9 106c-49.9 49.9-131.1 49.9-181 0-49.9-49.9-49.9-131.1 0-181 49.9-49.9 131.1-49.9 181 0 49.9 49.9 49.9 131.1 0 181z"})}),MOON:Ec("svg",{width:"512",height:"512",className:"rtl-mirror",viewBox:"0 0 512 512",children:Ec("path",{fill:"currentColor",d:"M283.211 512c78.962 0 151.079-35.925 198.857-94.792 7.068-8.708-.639-21.43-11.562-19.35-124.203 23.654-238.262-71.576-238.262-196.954 0-72.222 38.662-138.635 101.498-174.394 9.686-5.512 7.25-20.197-3.756-22.23A258.156 258.156 0 0 0 283.211 0c-141.309 0-256 114.511-256 256 0 141.309 114.511 256 256 256z"})})};import{useState as k8}from"react";import{focusNearestParent as S8,KEYS as M8}from"@orangecatai/common";import{jsx as L2,jsxs as P8}from"react/jsx-runtime";var _2=e=>{let{id:t}=qe(),[o,n]=k8(e.value),r=a=>{e.ignoreFocus||S8(a.target);let s=a.target.value;s!==e.value&&e.onChange(s)},i=a=>{if(a.key===M8.ENTER){if(a.preventDefault(),a.nativeEvent.isComposing||a.keyCode===229)return;a.currentTarget.blur()}};return P8("div",{className:"ProjectName",children:[L2("label",{className:"ProjectName-label",htmlFor:"filename",children:`${e.label}:`}),L2("input",{type:"text",className:"TextInput",onBlur:r,onKeyDown:i,id:`${t}-filename`,value:o,onChange:a=>n(a.target.value)})]})};import{DEFAULT_EXPORT_PADDING as rR,DEFAULT_FILENAME as iR,IMAGE_MIME_TYPES as Z2,isFirefox as aR,MIME_TYPES as sR,cloneJSON as lR,SVG_DOCUMENT_PREAMBLE as cR}from"@orangecatai/common";import{getNonDeletedElements as dR}from"@orangecatai/element";import{isFrameLikeElement as mR}from"@orangecatai/element";import{getElementsOverlappingFrame as pR}from"@orangecatai/element";import{ALLOWED_PASTE_MIME_TYPES as G8,EXPORT_DATA_TYPES as vc,MIME_TYPES as Mo,arrayToMap as U8,isMemberOf as W8,isPromiseLike as Y8,EVENT as jm}from"@orangecatai/common";import{mutateElement as V8}from"@orangecatai/element";import{deepCopyElement as $8}from"@orangecatai/element";import{isFrameLikeElement as K8,isInitializedImageElement as X8}from"@orangecatai/element";import{getContainingFrame as W2}from"@orangecatai/element";import{pointFrom as Kr}from"@orangecatai/math";import{COLOR_PALETTE as R2,DEFAULT_CHART_COLOR_INDEX as A8,getAllColorsSpecificShade as L8,DEFAULT_FONT_FAMILY as _8,DEFAULT_FONT_SIZE as N2,VERTICAL_ALIGN as D8,randomId as B2,isDevEnv as F2,FONT_SIZES as R8}from"@orangecatai/common";import{newTextElement as Xm,newLinearElement as wc,newElement as kf}from"@orangecatai/element";var mn=32,$e=12,Xr=256,O2=50,$i="NOT_SPREADSHEET",ws="VALID_SPREADSHEET",yc=e=>{let t=/^([-+]?)[$€£¥₩]?([-+]?)([\d.,]+)[%]?$/.exec(e);return t?parseFloat(`${(t[1]||t[2])+t[3]}`.replace(/,/g,"")):null},Cf=(e,t)=>e.slice(1).every(o=>yc(o[t])!==null),D2=e=>{let t=e[0].length;if(t>2)return{type:$i,reason:"More than 2 columns"};if(t===1){if(!Cf(e,0))return{type:$i,reason:"Value is not numeric"};let l=yc(e[0][0])===null,c=(l?e.slice(1):e).map(m=>yc(m[0]));return c.length<2?{type:$i,reason:"Less than two rows"}:{type:ws,spreadsheet:{title:l?e[0][0]:null,labels:null,values:c}}}let o=Cf(e,0),n=Cf(e,1);if(!o&&!n)return{type:$i,reason:"Value is not numeric"};let[r,i]=n?[0,1]:[1,0],a=yc(e[0][i])===null,s=a?e.slice(1):e;return s.length<2?{type:$i,reason:"Less than 2 rows"}:{type:ws,spreadsheet:{title:a?e[0][i]:null,labels:s.map(l=>l[r]),values:s.map(l=>yc(l[i]))}}},N8=e=>{let t=[];for(let o=0;o<e[0].length;o++){let n=[];for(let r=0;r<e.length;r++)n.push(e[r][o]);t.push(n)}return t},z2=e=>{let t=e.trim().split(`
2
2
  `).map(i=>i.trim().split(" "));if(t.length&&t[0].length!==2&&(t=e.trim().split(`
3
- `).map(i=>i.trim().split(","))),t.length===0)return{type:$i,reason:"No values"};let o=t[0].length;if(!t.every(i=>i.length===o))return{type:$i,reason:"All rows don't have same number of columns"};let r=D2(t);if(r.type!==ws){let i=D2(N8(t));if(i.type===ws)return i}return r},Zm=L8(A8),Wo={fillStyle:"hachure",fontFamily:_8,fontSize:N2,opacity:100,roughness:1,strokeColor:R2.black,roundness:null,strokeStyle:"solid",strokeWidth:1,verticalAlign:D8.MIDDLE,locked:!1},H2=e=>{let t=(mn+$e)*e.values.length+$e,o=Xr+$e*2;return{chartWidth:t,chartHeight:o}},B8=(e,t,o,n,r)=>e.labels?.map((i,a)=>Xm({groupIds:[n],backgroundColor:r,...Wo,text:i.length>8?`${i.slice(0,5)}...`:i,x:t+a*(mn+$e)+$e*2,y:o+$e/2,width:mn,angle:5.87,fontSize:R8.sm,textAlign:"center",verticalAlign:"top"}))||[],F8=(e,t,o,n,r)=>{let i=Xm({groupIds:[n],backgroundColor:r,...Wo,x:t-$e,y:o-$e,text:"0",textAlign:"right"}),a=Xm({groupIds:[n],backgroundColor:r,...Wo,x:t-$e,y:o-Xr-i.height/2,text:Math.max(...e.values).toLocaleString(),textAlign:"right"});return[i,a]},O8=(e,t,o,n,r)=>{let{chartWidth:i,chartHeight:a}=H2(e),s=wc({backgroundColor:r,groupIds:[n],...Wo,type:"line",x:t,y:o,width:i,points:[Kr(0,0),Kr(i,0)]}),l=wc({backgroundColor:r,groupIds:[n],...Wo,type:"line",x:t,y:o,height:a,points:[Kr(0,0),Kr(0,-a)]}),c=wc({backgroundColor:r,groupIds:[n],...Wo,type:"line",x:t,y:o-Xr-$e,strokeStyle:"dotted",width:i,opacity:O2,points:[Kr(0,0),Kr(i,0)]});return[s,l,c]},G2=(e,t,o,n,r,i)=>{let{chartWidth:a,chartHeight:s}=H2(e),l=e.title?Xm({backgroundColor:r,groupIds:[n],...Wo,text:e.title,x:t+a/2,y:o-Xr-$e*2-N2,roundness:null,textAlign:"center"}):null,c=i?kf({backgroundColor:r,groupIds:[n],...Wo,type:"rectangle",x:t,y:o-s,width:a,height:s,strokeColor:R2.black,fillStyle:"solid",opacity:6}):null;return[...c?[c]:[],...l?[l]:[],...B8(e,t,o,n,r),...F8(e,t,o,n,r),...O8(e,t,o,n,r)]},z8=(e,t,o)=>{let n=Math.max(...e.values),r=B2(),i=Zm[Math.floor(Math.random()*Zm.length)];return[...e.values.map((s,l)=>{let c=s/n*Xr;return kf({backgroundColor:i,groupIds:[r],...Wo,type:"rectangle",x:t+l*(mn+$e)+$e,y:o-c-$e,width:mn,height:c})}),...G2(e,t,o,r,i,F2())]},H8=(e,t,o)=>{let n=Math.max(...e.values),r=B2(),i=Zm[Math.floor(Math.random()*Zm.length)],a=0,s=[];for(let g of e.values){let E=a*(mn+$e),w=-(g/n)*Xr;s.push([E,w]),a++}let l=Math.max(...s.map(g=>g[0])),c=Math.max(...s.map(g=>g[1])),m=Math.min(...s.map(g=>g[0])),p=Math.min(...s.map(g=>g[1])),d=wc({backgroundColor:i,groupIds:[r],...Wo,type:"line",x:t+$e+mn/2,y:o-$e,height:c-p,width:l-m,strokeWidth:2,points:s}),u=e.values.map((g,E)=>{let w=E*(mn+$e)+$e/2,x=-(g/n)*Xr+$e/2;return kf({backgroundColor:i,groupIds:[r],...Wo,fillStyle:"solid",strokeWidth:2,type:"ellipse",x:t+w+mn/2,y:o+x-$e*2,width:$e,height:$e})}),h=e.values.map((g,E)=>{let w=E*(mn+$e)+$e/2,x=g/n*Xr+$e/2+$e;return wc({backgroundColor:i,groupIds:[r],...Wo,type:"line",x:t+w+mn/2+$e/2,y:o-x,height:x,strokeStyle:"dotted",opacity:O2,points:[Kr(0,0),Kr(0,x)]})});return[...G2(e,t,o,r,i,F2()),d,...h,...u]},U2=(e,t,o,n)=>e==="line"?H8(t,o,n):z8(t,o,n);var Mce="clipboard"in navigator&&"readText"in navigator.clipboard,qm="clipboard"in navigator&&"writeText"in navigator.clipboard,vs="clipboard"in navigator&&"write"in navigator.clipboard&&"ClipboardItem"in window&&"toBlob"in HTMLCanvasElement.prototype,Z8=e=>!!([vc.excalidraw,vc.excalidrawClipboard,vc.excalidrawClipboardWithAPI].includes(e?.type)&&Array.isArray(e.elements)),Y2=({types:e,files:t})=>{!e&&!t&&console.warn("createPasteEvent: no types or files provided");let o=new ClipboardEvent(jm.PASTE,{clipboardData:new DataTransfer});if(e)for(let[n,r]of Object.entries(e)){if(typeof r!="string"){t=t||[],t.push(r);continue}try{if(o.clipboardData?.items.add(r,n),o.clipboardData?.getData(n)!==r)throw new Error(`Failed to set "${n}" as clipboardData item`)}catch(i){throw new Error(i.message)}}if(t){let n=-1;for(let r of t){n++;try{if(o.clipboardData?.items.add(r),o.clipboardData?.files[n]!==r)throw new Error(`Failed to set file "${r.name}" as clipboardData item`)}catch(i){throw new Error(i.message)}}}return o},j8=({elements:e,files:t})=>{let o=U8(e),n=new Set(e.filter(s=>K8(s))),r=!1,i=e.reduce((s,l)=>(X8(l)&&(r=!0,t&&t[l.fileId]&&(s[l.fileId]=t[l.fileId])),s),{});r&&!t&&console.warn("copyToClipboard: attempting to file element(s) without providing associated `files` object.");let a={type:vc.excalidrawClipboard,elements:e.map(s=>{if(W2(s,o)&&!n.has(W2(s,o))){let l=$8(s);return V8(l,o,{frameId:null}),l}return s}),files:t?i:void 0};return JSON.stringify(a)},Jm=async(e,t,o)=>{let n=j8({elements:e,files:t});await pn({[Po.excalidrawClipboard]:n,[Po.text]:n},o)},q8=e=>{let t=z2(e);return t.type===ws?{spreadsheet:t.spreadsheet}:null};function V2(e){let t=[];for(let o of e.childNodes)if(o.nodeType===3){let n=o.textContent?.trim();n&&t.push({type:"text",value:n})}else if(o instanceof HTMLImageElement){let n=o.getAttribute("src");n&&n.startsWith("http")&&t.push({type:"imageUrl",value:n})}else t=t.concat(V2(o));return t}var J8=e=>{let t=e.value;try{let o=new DOMParser().parseFromString(t,Po.html),n=V2(o.body);if(n.length)return{type:"mixedContent",value:n}}catch(o){console.error(`error in parseHTMLFromPaste: ${o.message}`)}return null},$2=async()=>{let e={},t;try{t=await navigator.clipboard?.read()}catch(o){try{if(navigator.clipboard?.readText){console.warn(`navigator.clipboard.readText() failed (${o.message}). Failling back to navigator.clipboard.read()`);let n=await navigator.clipboard?.readText();if(n)return{[Po.text]:n}}}catch(n){if(navigator.clipboard?.read)console.warn(`navigator.clipboard.readText() failed (${n.message}). Failling back to navigator.clipboard.read()`);else{if(n.name==="DataError")return console.warn(`navigator.clipboard.read() error, clipboard is probably empty: ${n.message}`),e;throw n}}throw o}for(let o of t)for(let n of o.types)if(W8(G8,n))try{if(n===Po.text||n===Po.html)e[n]=await(await o.getType(n)).text();else if(jE(n)){let r=await o.getType(n),i=ny(r,n,void 0);e[n]=i}else throw new Zg(`Unsupported clipboard type: ${n}`)}catch(r){console.warn(r instanceof Zg?r.message:`Cannot retrieve ${n} from clipboardItem: ${r.message}`)}return Object.keys(e).length===0&&console.warn("No clipboard data found from clipboard.read()."),e},Q8=async(e,t=!1)=>{try{let o=e.findByType(Po.html),n=!t&&o&&J8(o);return n?n.value.every(r=>r.type==="text")?{type:"text",value:e.getData(Po.text)??n.value.map(r=>r.value).join(`
4
- `).trim()}:n:{type:"text",value:(e.getData(Po.text)||"").trim()}}catch{return{type:"text",value:""}}},eR=function(e){return this.find(t=>t.type===e)||null},tR=function(e){return this.find(o=>o.type===e)?.value??null},oR=function(){return this.filter(e=>e.kind==="file")},K2=e=>{let t;X2(e)?t=e.clipboardData?.items:t=e.dataTransfer?.items;let o=new Set;for(let n of Array.from(t||[]))o.has(n.type)||o.add(n.type);return o},Is=async e=>{let t;X2(e)?t=e.clipboardData?.items:t=e.dataTransfer?.items;let o=(await Promise.all(Array.from(t||[]).map(async n=>{if(n.kind==="file"){let r=n.getAsFile();if(r){let i=await oy(n);return r=await Kl(r),{type:r.type,kind:"file",file:r,fileHandle:i}}}else if(n.kind==="string"){let{type:r}=n,i;return"clipboardData"in e&&e.clipboardData?i=e.clipboardData?.getData(r):i=await new Promise(a=>{n.getAsString(s=>a(s))}),{type:r,kind:"string",value:i}}return null}))).filter(n=>n!=null);return Object.assign(o,{findByType:eR,getData:tR,getFiles:oR})},Qm=async(e,t=!1)=>{let o=await Q8(e,t);if(o.type==="mixedContent")return{mixedContent:o.value};try{let n=!t&&q8(o.value);if(n)return n}catch(n){console.error(n)}try{let n=JSON.parse(o.value),r=n.type===vc.excalidrawClipboardWithAPI;if(Z8(n))return{elements:n.elements,files:n.files,text:t?JSON.stringify(n.elements,null,2):void 0,programmaticAPI:r}}catch{}return{text:o.value}},ep=async e=>{try{await navigator.clipboard.write([new ClipboardItem({[Po.png]:e})])}catch(t){if(Y8(e))await navigator.clipboard.write([new ClipboardItem({[Po.png]:await e})]);else throw t}},pn=async(e,t)=>{e=e||"";let o=Object.entries(typeof e=="string"?{[Po.text]:e}:e);try{if(t){for(let[r,i]of o)if(t.clipboardData?.setData(r,i),t.clipboardData?.getData(r)!==i)throw new Error("Failed to setData on clipboardEvent");return}}catch(r){console.error(r)}let n=o.find(([r])=>r===Po.text);if(qm&&n)try{await navigator.clipboard.writeText(n[1]);return}catch(r){console.error(r)}if(n&&!nR(n[1]))throw new Error("Error copying to clipboard.")},nR=e=>{e||(e=" ");let t=document.documentElement.getAttribute("dir")==="rtl",o=document.createElement("textarea");o.style.border="0",o.style.padding="0",o.style.margin="0",o.style.position="absolute",o.style[t?"right":"left"]="-9999px";let n=window.pageYOffset||document.documentElement.scrollTop;o.style.top=`${n}px`,o.style.fontSize="12pt",o.setAttribute("readonly",""),o.value=e,document.body.appendChild(o);let r=!1;try{o.select(),o.setSelectionRange(0,o.value.length),r=document.execCommand("copy")}catch(i){console.error(i)}return o.remove(),r},X2=e=>e.type===jm.PASTE||e.type===jm.COPY||e.type===jm.CUT;var Ki=(e,{selectedElementIds:t},o)=>{e=dR(e);let n=o&&He(e,{selectedElementIds:t}),r=null,i=n?le(e,{selectedElementIds:t},{includeBoundTextElement:!0}):e;return n&&(i.length===1&&mR(i[0])?(r=i[0],i=pR(e,r)):i.length>1&&(i=le(e,{selectedElementIds:t},{includeBoundTextElement:!0,includeElementsInFrames:!0}))),{exportingFrame:r,exportedElements:lR(i)}},Xi=async(e,t,o,n,{exportBackground:r,exportPadding:i=rR,viewBackgroundColor:a,name:s=o.name||iR,fileHandle:l=null,exportingFrame:c=null})=>{if(t.length===0)throw new Error(f("alerts.cannotExportEmptyCanvas"));if(e==="svg"||e==="clipboard-svg"){let p=Fa(t,{exportBackground:r,exportWithDarkMode:o.exportWithDarkMode,viewBackgroundColor:a,exportPadding:i,exportScale:o.exportScale,exportEmbedScene:o.exportEmbedScene&&e==="svg"},n,{exportingFrame:c});if(e==="svg")return jg(p.then(d=>new Blob([cR+d.outerHTML],{type:sR.svg})),{description:"Export to SVG",name:s,extension:o.exportEmbedScene?"excalidraw.svg":"svg",mimeTypes:[Z2.svg],fileHandle:l});if(e==="clipboard-svg"){let d=await p.then(u=>u.outerHTML);try{await pn(d)}catch{throw new Error(f("errors.copyToSystemClipboardFailed"))}return}}let m=Ba(t,o,n,{exportBackground:r,viewBackgroundColor:a,exportPadding:i,exportingFrame:c});if(e==="png"){let p=Bi(m);return o.exportEmbedScene&&(p=p.then(d=>import("./data/image-UMAJZASC.js").then(({encodePngMetadata:u})=>u({blob:d,metadata:Wl(t,o,n,"local")})))),jg(p,{description:"Export to PNG",name:s,extension:o.exportEmbedScene?"excalidraw.png":"png",mimeTypes:[Z2.png],fileHandle:l})}else if(e==="clipboard")try{let p=Bi(m);await ep(p)}catch(p){throw console.warn(p),p.name==="CANVAS_POSSIBLY_TOO_BIG"?new Error(f("canvasError.canvasTooBig")):aR&&p.name==="TypeError"?new Error(`${f("alerts.couldNotCopyToClipboard")}
3
+ `).map(i=>i.trim().split(","))),t.length===0)return{type:$i,reason:"No values"};let o=t[0].length;if(!t.every(i=>i.length===o))return{type:$i,reason:"All rows don't have same number of columns"};let r=D2(t);if(r.type!==ws){let i=D2(N8(t));if(i.type===ws)return i}return r},Zm=L8(A8),Wo={fillStyle:"hachure",fontFamily:_8,fontSize:N2,opacity:100,roughness:1,strokeColor:R2.black,roundness:null,strokeStyle:"solid",strokeWidth:1,verticalAlign:D8.MIDDLE,locked:!1},H2=e=>{let t=(mn+$e)*e.values.length+$e,o=Xr+$e*2;return{chartWidth:t,chartHeight:o}},B8=(e,t,o,n,r)=>e.labels?.map((i,a)=>Xm({groupIds:[n],backgroundColor:r,...Wo,text:i.length>8?`${i.slice(0,5)}...`:i,x:t+a*(mn+$e)+$e*2,y:o+$e/2,width:mn,angle:5.87,fontSize:R8.sm,textAlign:"center",verticalAlign:"top"}))||[],F8=(e,t,o,n,r)=>{let i=Xm({groupIds:[n],backgroundColor:r,...Wo,x:t-$e,y:o-$e,text:"0",textAlign:"right"}),a=Xm({groupIds:[n],backgroundColor:r,...Wo,x:t-$e,y:o-Xr-i.height/2,text:Math.max(...e.values).toLocaleString(),textAlign:"right"});return[i,a]},O8=(e,t,o,n,r)=>{let{chartWidth:i,chartHeight:a}=H2(e),s=wc({backgroundColor:r,groupIds:[n],...Wo,type:"line",x:t,y:o,width:i,points:[Kr(0,0),Kr(i,0)]}),l=wc({backgroundColor:r,groupIds:[n],...Wo,type:"line",x:t,y:o,height:a,points:[Kr(0,0),Kr(0,-a)]}),c=wc({backgroundColor:r,groupIds:[n],...Wo,type:"line",x:t,y:o-Xr-$e,strokeStyle:"dotted",width:i,opacity:O2,points:[Kr(0,0),Kr(i,0)]});return[s,l,c]},G2=(e,t,o,n,r,i)=>{let{chartWidth:a,chartHeight:s}=H2(e),l=e.title?Xm({backgroundColor:r,groupIds:[n],...Wo,text:e.title,x:t+a/2,y:o-Xr-$e*2-N2,roundness:null,textAlign:"center"}):null,c=i?kf({backgroundColor:r,groupIds:[n],...Wo,type:"rectangle",x:t,y:o-s,width:a,height:s,strokeColor:R2.black,fillStyle:"solid",opacity:6}):null;return[...c?[c]:[],...l?[l]:[],...B8(e,t,o,n,r),...F8(e,t,o,n,r),...O8(e,t,o,n,r)]},z8=(e,t,o)=>{let n=Math.max(...e.values),r=B2(),i=Zm[Math.floor(Math.random()*Zm.length)];return[...e.values.map((s,l)=>{let c=s/n*Xr;return kf({backgroundColor:i,groupIds:[r],...Wo,type:"rectangle",x:t+l*(mn+$e)+$e,y:o-c-$e,width:mn,height:c})}),...G2(e,t,o,r,i,F2())]},H8=(e,t,o)=>{let n=Math.max(...e.values),r=B2(),i=Zm[Math.floor(Math.random()*Zm.length)],a=0,s=[];for(let g of e.values){let E=a*(mn+$e),w=-(g/n)*Xr;s.push([E,w]),a++}let l=Math.max(...s.map(g=>g[0])),c=Math.max(...s.map(g=>g[1])),m=Math.min(...s.map(g=>g[0])),p=Math.min(...s.map(g=>g[1])),d=wc({backgroundColor:i,groupIds:[r],...Wo,type:"line",x:t+$e+mn/2,y:o-$e,height:c-p,width:l-m,strokeWidth:2,points:s}),u=e.values.map((g,E)=>{let w=E*(mn+$e)+$e/2,x=-(g/n)*Xr+$e/2;return kf({backgroundColor:i,groupIds:[r],...Wo,fillStyle:"solid",strokeWidth:2,type:"ellipse",x:t+w+mn/2,y:o+x-$e*2,width:$e,height:$e})}),h=e.values.map((g,E)=>{let w=E*(mn+$e)+$e/2,x=g/n*Xr+$e/2+$e;return wc({backgroundColor:i,groupIds:[r],...Wo,type:"line",x:t+w+mn/2+$e/2,y:o-x,height:x,strokeStyle:"dotted",opacity:O2,points:[Kr(0,0),Kr(0,x)]})});return[...G2(e,t,o,r,i,F2()),d,...h,...u]},U2=(e,t,o,n)=>e==="line"?H8(t,o,n):z8(t,o,n);var Mce="clipboard"in navigator&&"readText"in navigator.clipboard,qm="clipboard"in navigator&&"writeText"in navigator.clipboard,vs="clipboard"in navigator&&"write"in navigator.clipboard&&"ClipboardItem"in window&&"toBlob"in HTMLCanvasElement.prototype,Z8=e=>!!([vc.excalidraw,vc.excalidrawClipboard,vc.excalidrawClipboardWithAPI].includes(e?.type)&&Array.isArray(e.elements)),Y2=({types:e,files:t})=>{!e&&!t&&console.warn("createPasteEvent: no types or files provided");let o=new ClipboardEvent(jm.PASTE,{clipboardData:new DataTransfer});if(e)for(let[n,r]of Object.entries(e)){if(typeof r!="string"){t=t||[],t.push(r);continue}try{if(o.clipboardData?.items.add(r,n),o.clipboardData?.getData(n)!==r)throw new Error(`Failed to set "${n}" as clipboardData item`)}catch(i){throw new Error(i.message)}}if(t){let n=-1;for(let r of t){n++;try{if(o.clipboardData?.items.add(r),o.clipboardData?.files[n]!==r)throw new Error(`Failed to set file "${r.name}" as clipboardData item`)}catch(i){throw new Error(i.message)}}}return o},j8=({elements:e,files:t})=>{let o=U8(e),n=new Set(e.filter(s=>K8(s))),r=!1,i=e.reduce((s,l)=>(X8(l)&&(r=!0,t&&t[l.fileId]&&(s[l.fileId]=t[l.fileId])),s),{});r&&!t&&console.warn("copyToClipboard: attempting to file element(s) without providing associated `files` object.");let a={type:vc.excalidrawClipboard,elements:e.map(s=>{if(W2(s,o)&&!n.has(W2(s,o))){let l=$8(s);return V8(l,o,{frameId:null}),l}return s}),files:t?i:void 0};return JSON.stringify(a)},Jm=async(e,t,o)=>{let n=j8({elements:e,files:t});await pn({[Mo.excalidrawClipboard]:n,[Mo.text]:n},o)},q8=e=>{let t=z2(e);return t.type===ws?{spreadsheet:t.spreadsheet}:null};function V2(e){let t=[];for(let o of e.childNodes)if(o.nodeType===3){let n=o.textContent?.trim();n&&t.push({type:"text",value:n})}else if(o instanceof HTMLImageElement){let n=o.getAttribute("src");n&&n.startsWith("http")&&t.push({type:"imageUrl",value:n})}else t=t.concat(V2(o));return t}var J8=e=>{let t=e.value;try{let o=new DOMParser().parseFromString(t,Mo.html),n=V2(o.body);if(n.length)return{type:"mixedContent",value:n}}catch(o){console.error(`error in parseHTMLFromPaste: ${o.message}`)}return null},$2=async()=>{let e={},t;try{t=await navigator.clipboard?.read()}catch(o){try{if(navigator.clipboard?.readText){console.warn(`navigator.clipboard.readText() failed (${o.message}). Failling back to navigator.clipboard.read()`);let n=await navigator.clipboard?.readText();if(n)return{[Mo.text]:n}}}catch(n){if(navigator.clipboard?.read)console.warn(`navigator.clipboard.readText() failed (${n.message}). Failling back to navigator.clipboard.read()`);else{if(n.name==="DataError")return console.warn(`navigator.clipboard.read() error, clipboard is probably empty: ${n.message}`),e;throw n}}throw o}for(let o of t)for(let n of o.types)if(W8(G8,n))try{if(n===Mo.text||n===Mo.html)e[n]=await(await o.getType(n)).text();else if(jE(n)){let r=await o.getType(n),i=ny(r,n,void 0);e[n]=i}else throw new Zg(`Unsupported clipboard type: ${n}`)}catch(r){console.warn(r instanceof Zg?r.message:`Cannot retrieve ${n} from clipboardItem: ${r.message}`)}return Object.keys(e).length===0&&console.warn("No clipboard data found from clipboard.read()."),e},Q8=async(e,t=!1)=>{try{let o=e.findByType(Mo.html),n=!t&&o&&J8(o);return n?n.value.every(r=>r.type==="text")?{type:"text",value:e.getData(Mo.text)??n.value.map(r=>r.value).join(`
4
+ `).trim()}:n:{type:"text",value:(e.getData(Mo.text)||"").trim()}}catch{return{type:"text",value:""}}},eR=function(e){return this.find(t=>t.type===e)||null},tR=function(e){return this.find(o=>o.type===e)?.value??null},oR=function(){return this.filter(e=>e.kind==="file")},K2=e=>{let t;X2(e)?t=e.clipboardData?.items:t=e.dataTransfer?.items;let o=new Set;for(let n of Array.from(t||[]))o.has(n.type)||o.add(n.type);return o},Is=async e=>{let t;X2(e)?t=e.clipboardData?.items:t=e.dataTransfer?.items;let o=(await Promise.all(Array.from(t||[]).map(async n=>{if(n.kind==="file"){let r=n.getAsFile();if(r){let i=await oy(n);return r=await Kl(r),{type:r.type,kind:"file",file:r,fileHandle:i}}}else if(n.kind==="string"){let{type:r}=n,i;return"clipboardData"in e&&e.clipboardData?i=e.clipboardData?.getData(r):i=await new Promise(a=>{n.getAsString(s=>a(s))}),{type:r,kind:"string",value:i}}return null}))).filter(n=>n!=null);return Object.assign(o,{findByType:eR,getData:tR,getFiles:oR})},Qm=async(e,t=!1)=>{let o=await Q8(e,t);if(o.type==="mixedContent")return{mixedContent:o.value};try{let n=!t&&q8(o.value);if(n)return n}catch(n){console.error(n)}try{let n=JSON.parse(o.value),r=n.type===vc.excalidrawClipboardWithAPI;if(Z8(n))return{elements:n.elements,files:n.files,text:t?JSON.stringify(n.elements,null,2):void 0,programmaticAPI:r}}catch{}return{text:o.value}},ep=async e=>{try{await navigator.clipboard.write([new ClipboardItem({[Mo.png]:e})])}catch(t){if(Y8(e))await navigator.clipboard.write([new ClipboardItem({[Mo.png]:await e})]);else throw t}},pn=async(e,t)=>{e=e||"";let o=Object.entries(typeof e=="string"?{[Mo.text]:e}:e);try{if(t){for(let[r,i]of o)if(t.clipboardData?.setData(r,i),t.clipboardData?.getData(r)!==i)throw new Error("Failed to setData on clipboardEvent");return}}catch(r){console.error(r)}let n=o.find(([r])=>r===Mo.text);if(qm&&n)try{await navigator.clipboard.writeText(n[1]);return}catch(r){console.error(r)}if(n&&!nR(n[1]))throw new Error("Error copying to clipboard.")},nR=e=>{e||(e=" ");let t=document.documentElement.getAttribute("dir")==="rtl",o=document.createElement("textarea");o.style.border="0",o.style.padding="0",o.style.margin="0",o.style.position="absolute",o.style[t?"right":"left"]="-9999px";let n=window.pageYOffset||document.documentElement.scrollTop;o.style.top=`${n}px`,o.style.fontSize="12pt",o.setAttribute("readonly",""),o.value=e,document.body.appendChild(o);let r=!1;try{o.select(),o.setSelectionRange(0,o.value.length),r=document.execCommand("copy")}catch(i){console.error(i)}return o.remove(),r},X2=e=>e.type===jm.PASTE||e.type===jm.COPY||e.type===jm.CUT;var Ki=(e,{selectedElementIds:t},o)=>{e=dR(e);let n=o&&He(e,{selectedElementIds:t}),r=null,i=n?le(e,{selectedElementIds:t},{includeBoundTextElement:!0}):e;return n&&(i.length===1&&mR(i[0])?(r=i[0],i=pR(e,r)):i.length>1&&(i=le(e,{selectedElementIds:t},{includeBoundTextElement:!0,includeElementsInFrames:!0}))),{exportingFrame:r,exportedElements:lR(i)}},Xi=async(e,t,o,n,{exportBackground:r,exportPadding:i=rR,viewBackgroundColor:a,name:s=o.name||iR,fileHandle:l=null,exportingFrame:c=null})=>{if(t.length===0)throw new Error(f("alerts.cannotExportEmptyCanvas"));if(e==="svg"||e==="clipboard-svg"){let p=Fa(t,{exportBackground:r,exportWithDarkMode:o.exportWithDarkMode,viewBackgroundColor:a,exportPadding:i,exportScale:o.exportScale,exportEmbedScene:o.exportEmbedScene&&e==="svg"},n,{exportingFrame:c});if(e==="svg")return jg(p.then(d=>new Blob([cR+d.outerHTML],{type:sR.svg})),{description:"Export to SVG",name:s,extension:o.exportEmbedScene?"excalidraw.svg":"svg",mimeTypes:[Z2.svg],fileHandle:l});if(e==="clipboard-svg"){let d=await p.then(u=>u.outerHTML);try{await pn(d)}catch{throw new Error(f("errors.copyToSystemClipboardFailed"))}return}}let m=Ba(t,o,n,{exportBackground:r,viewBackgroundColor:a,exportPadding:i,exportingFrame:c});if(e==="png"){let p=Bi(m);return o.exportEmbedScene&&(p=p.then(d=>import("./data/image-UOUIPUYX.js").then(({encodePngMetadata:u})=>u({blob:d,metadata:Wl(t,o,n,"local")})))),jg(p,{description:"Export to PNG",name:s,extension:o.exportEmbedScene?"excalidraw.png":"png",mimeTypes:[Z2.png],fileHandle:l})}else if(e==="clipboard")try{let p=Bi(m);await ep(p)}catch(p){throw console.warn(p),p.name==="CANVAS_POSSIBLY_TOO_BIG"?new Error(f("canvasError.canvasTooBig")):aR&&p.name==="TypeError"?new Error(`${f("alerts.couldNotCopyToClipboard")}
5
5
 
6
- ${f("hints.firefox_clipboard_write")}`):new Error(f("alerts.couldNotCopyToClipboard"))}else throw new Error("Unsupported export type")};var j2=async(e,t,o,n)=>{let{exportBackground:r,viewBackgroundColor:i,fileHandle:a}=t,s=XE(a);if(!a||!ZE(s))throw new Error("fileHandle should exist and should be of type svg or png when resaving");t={...t,exportEmbedScene:!0};let{exportedElements:l,exportingFrame:c}=Ki(e,t,!1);return await Xi(s,l,t,o,{exportBackground:r,viewBackgroundColor:i,name:n,fileHandle:a,exportingFrame:c}),{fileHandle:a}};import{Fragment as fR,jsx as hr,jsxs as bR}from"react/jsx-runtime";var Mf=W({name:"changeProjectName",label:"labels.fileTitle",trackEvent:!1,perform:(e,t,o)=>({appState:{...t,name:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({appState:e,updateData:t,appProps:o,data:n,app:r})=>hr(_2,{label:f("labels.fileTitle"),value:r.getName(),onChange:i=>t(i),ignoreFocus:n?.ignoreFocus??!1})}),q2=W({name:"changeExportScale",label:"imageExportDialog.scale",trackEvent:{category:"export",action:"scale"},perform:(e,t,o)=>({appState:{...t,exportScale:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({elements:e,appState:t,updateData:o})=>{let n=hR(e),i=He(n,t)?le(n,t):n;return hr(fR,{children:gR.map(a=>{let[s,l]=$E(i,uR,a),c=`${f("imageExportDialog.label.scale")} ${a}x (${s}x${l})`;return hr(ne,{size:"small",type:"radio",icon:`${a}x`,name:"export-canvas-scale",title:c,"aria-label":c,id:"export-canvas-scale",checked:a===t.exportScale,onChange:()=>o(a)},a)})})}}),Pf=W({name:"changeExportBackground",label:"imageExportDialog.label.withBackground",trackEvent:{category:"export",action:"toggleBackground"},perform:(e,t,o)=>({appState:{...t,exportBackground:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({appState:e,updateData:t})=>hr(bc,{checked:e.exportBackground,onChange:o=>t(o),children:f("imageExportDialog.label.withBackground")})}),tp=W({name:"changeExportEmbedScene",label:"imageExportDialog.tooltip.embedScene",trackEvent:{category:"export",action:"embedScene"},perform:(e,t,o)=>({appState:{...t,exportEmbedScene:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({appState:e,updateData:t})=>bR(bc,{checked:e.exportEmbedScene,onChange:o=>t(o),children:[f("imageExportDialog.label.embedScene"),hr(Vt,{label:f("imageExportDialog.tooltip.embedScene"),long:!0,children:hr("div",{className:"excalidraw-tooltip-icon",children:Py})})]})}),Zi=W({name:"saveToActiveFile",label:"buttons.save",icon:zi,trackEvent:{category:"export"},predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.saveToActiveFile&&!!t.fileHandle&&!t.viewModeEnabled,perform:async(e,t,o,n)=>{let r=!!t.fileHandle;try{let{fileHandle:i}=Qd(t.fileHandle)?await j2(e,t,n.files,n.getName()):await Zd(e,t,n.files,n.getName());return{captureUpdate:un.EVENTUALLY,appState:{...t,fileHandle:i,toast:r?{message:i?.name?f("toast.fileSavedToFilename").replace("{filename}",`"${i.name}"`):f("toast.fileSaved")}:null}}}catch(i){return i?.name!=="AbortError"?console.error(i):console.warn(i),{captureUpdate:un.EVENTUALLY}}},keyTest:e=>e.key===Ts.S&&e[Ts.CTRL_OR_CMD]&&!e.shiftKey}),Ic=W({name:"saveFileToDisk",label:"exportDialog.disk_title",icon:zi,viewMode:!0,trackEvent:{category:"export"},perform:async(e,t,o,n)=>{try{let{fileHandle:r}=await Zd(e,{...t,fileHandle:null},n.files,n.getName());return{captureUpdate:un.EVENTUALLY,appState:{...t,openDialog:null,fileHandle:r,toast:{message:f("toast.fileSaved")}}}}catch(r){return r?.name!=="AbortError"?console.error(r):console.warn(r),{captureUpdate:un.EVENTUALLY}}},keyTest:e=>e.key===Ts.S&&e.shiftKey&&e[Ts.CTRL_OR_CMD],PanelComponent:({updateData:e})=>hr(ne,{type:"button",icon:Cy,title:f("buttons.saveAs"),"aria-label":f("buttons.saveAs"),showAriaLabel:we().formFactor==="phone",hidden:!Na,onClick:()=>e(null),"data-testid":"save-as-button"})}),Cs=W({name:"loadScene",label:"buttons.load",trackEvent:{category:"export"},predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.loadScene&&!t.viewModeEnabled,perform:async(e,t,o,n)=>{try{let{elements:r,appState:i,files:a}=await qg(t,e);return{elements:r,appState:i,files:a,captureUpdate:un.IMMEDIATELY}}catch(r){return r?.name==="AbortError"?(console.warn(r),!1):{elements:e,appState:{...t,errorMessage:r.message},files:n.files,captureUpdate:un.EVENTUALLY}}},keyTest:e=>e[Ts.CTRL_OR_CMD]&&e.key===Ts.O}),J2=W({name:"exportWithDarkMode",label:"imageExportDialog.label.darkMode",trackEvent:{category:"export",action:"toggleTheme"},perform:(e,t,o)=>({appState:{...t,exportWithDarkMode:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({appState:e,updateData:t})=>hr("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"-45px",marginBottom:"10px"},children:hr(A2,{value:e.exportWithDarkMode?Sf.DARK:Sf.LIGHT,onChange:o=>{t(o===Sf.DARK)},title:f("imageExportDialog.label.darkMode")})})});import{DEFAULT_FONT_SIZE as xR,DEFAULT_FONT_FAMILY as ER,DEFAULT_TEXT_ALIGN as yR,CODES as Q2,KEYS as eI,getLineHeight as wR}from"@orangecatai/common";import{newElementWith as op}from"@orangecatai/element";import{hasBoundTextElement as vR,canApplyRoundnessTypeToElement as IR,getDefaultRoundnessTypeForElement as TR,isFrameLikeElement as CR,isArrowElement as kR,isExcalidrawElement as SR,isTextElement as Af}from"@orangecatai/element";import{getBoundTextElement as MR,redrawTextBoundingBox as PR}from"@orangecatai/element";import{CaptureUpdateAction as Lf}from"@orangecatai/element";var tI="{}",_f=W({name:"copyStyles",label:"labels.copyStyles",icon:Th,trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=[],i=e.find(a=>t.selectedElementIds[a.id]);if(r.push(i),i&&vR(i)){let a=MR(i,n.scene.getNonDeletedElementsMap());r.push(a)}return i&&(tI=JSON.stringify(r)),{appState:{...t,toast:{message:f("toast.copyStyles")}},captureUpdate:Lf.EVENTUALLY}},keyTest:e=>e[eI.CTRL_OR_CMD]&&e.altKey&&e.code===Q2.C}),Df=W({name:"pasteStyles",label:"labels.pasteStyles",icon:Th,trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=JSON.parse(tI),i=r[0],a=r[1];if(!SR(i))return{elements:e,captureUpdate:Lf.EVENTUALLY};let s=le(e,t,{includeBoundTextElement:!0}),l=s.map(c=>c.id);return{elements:e.map(c=>{if(l.includes(c.id)){let m=i;if(Af(c)&&c.containerId&&(m=a),!m)return c;let p=op(c,{backgroundColor:m?.backgroundColor,strokeWidth:m?.strokeWidth,strokeColor:m?.strokeColor,strokeStyle:m?.strokeStyle,fillStyle:m?.fillStyle,opacity:m?.opacity,roughness:m?.roughness,roundness:m.roundness?IR(m.roundness.type,c)?m.roundness:TR(c):null});if(Af(p)){let d=m.fontSize||xR,u=m.fontFamily||ER;p=op(p,{fontSize:d,fontFamily:u,textAlign:m.textAlign||yR,lineHeight:m.lineHeight||wR(u)});let h=null;p.containerId&&(h=s.find(g=>Af(p)&&g.id===p.containerId)||null),PR(p,h,n.scene)}return p.type==="arrow"&&kR(m)&&(p=op(p,{startArrowhead:m.startArrowhead,endArrowhead:m.endArrowhead})),CR(c)&&(p=op(p,{roundness:null,backgroundColor:"transparent"})),p}return c}),captureUpdate:Lf.IMMEDIATELY}},keyTest:e=>e[eI.CTRL_OR_CMD]&&e.altKey&&e.code===Q2.V});import{KEYS as AR}from"@orangecatai/common";import{CaptureUpdateAction as LR}from"@orangecatai/element";var ji=W({name:"toggleShortcuts",label:"welcomeScreen.defaults.helpHint",icon:wy,viewMode:!0,trackEvent:{category:"menu",action:"toggleHelpDialog"},perform:(e,t,o,{focusContainer:n})=>(t.openDialog?.name==="help"&&n(),{appState:{...t,openDialog:t.openDialog?.name==="help"?null:{name:"help"},openMenu:null,openPopup:null},captureUpdate:LR.EVENTUALLY}),keyTest:e=>e.key===AR.QUESTION_MARK});import{getNonDeletedElements as rp}from"@orangecatai/element";import{newElementWith as rI}from"@orangecatai/element";import{isBoundToContainer as _R}from"@orangecatai/element";import{frameAndChildrenSelectedTogether as DR,getElementsInResizingFrame as RR,getFrameLikeElements as NR,getRootElements as BR,groupByFrameLikes as FR,removeElementsFromFrame as OR,replaceAllElementsInFrame as zR}from"@orangecatai/element";import{KEYS as ip,randomId as HR,arrayToMap as Rf}from"@orangecatai/common";import{getSelectedGroupIds as np,selectGroup as GR,selectGroupsForSelectedElements as UR,getElementsInGroup as oI,addToGroup as WR,removeFromSelectedGroups as YR,isElementInGroup as iI}from"@orangecatai/element";import{syncMovedIndices as VR}from"@orangecatai/element";import{CaptureUpdateAction as Tc}from"@orangecatai/element";import{jsx as ks}from"react/jsx-runtime";var $R=e=>{if(e.length>=2){let t=e[0].groupIds;for(let o of t)if(e.reduce((n,r)=>n&&iI(r,o),!0))return!0}return!1},nI=(e,t,o)=>{let n=o.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0});return n.length>=2&&!$R(n)&&!DR(n)},Nf=W({name:"group",label:"labels.group",icon:e=>ks(Eh,{theme:e.theme}),trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=BR(n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0}));if(r.length<2)return{appState:t,elements:e,captureUpdate:Tc.EVENTUALLY};let i=np(t);if(i.length===1){let E=i[0],w=new Set(oI(e,E).map(v=>v.id)),x=new Set(r.map(v=>v.id));if(new Set([...Array.from(w),...Array.from(x)]).size===w.size)return{appState:t,elements:e,captureUpdate:Tc.EVENTUALLY}}let a=[...e];new Set(r.map(E=>E.frameId)).size>1&&FR(r).forEach((w,x)=>{OR(w,n.scene.getNonDeletedElementsMap())});let l=HR(),c=Rf(r);a=a.map(E=>c.get(E.id)?rI(E,{groupIds:WR(E.groupIds,l,t.editingGroupId)}):E);let m=oI(a,l),p=m[m.length-1],d=a.lastIndexOf(p),u=a.slice(d+1),h=a.slice(0,d).filter(E=>!iI(E,l)),g=VR([...h,...m,...u],Rf(m));return{appState:{...t,...GR(l,{...t,selectedGroupIds:{}},rp(a))},elements:g,captureUpdate:Tc.IMMEDIATELY}},predicate:(e,t,o,n)=>nI(e,t,n),keyTest:e=>!e.shiftKey&&e[ip.CTRL_OR_CMD]&&e.key===ip.G,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>ks(ne,{hidden:!nI(e,t,n),type:"button",icon:ks(Eh,{theme:t.theme}),onClick:()=>o(null),title:`${f("labels.group")} \u2014 ${G("CtrlOrCmd+G")}`,"aria-label":f("labels.group"),visible:He(rp(e),t)})}),Bf=W({name:"ungroup",label:"labels.ungroup",icon:e=>ks(yh,{theme:e.theme}),trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=np(t),i=Rf(e);if(r.length===0)return{appState:t,elements:e,captureUpdate:Tc.EVENTUALLY};let a=[...e],s=[];a=a.map(d=>{_R(d)&&s.push(d.id);let u=YR(d.groupIds,t.selectedGroupIds);return u.length===d.groupIds.length?d:rI(d,{groupIds:u})});let l=UR(t,rp(a),t,null),c=n.scene.getSelectedElements(t),m=new Set(c.filter(d=>d.frameId).map(d=>d.frameId));return NR(e).filter(d=>m.has(d.id)).forEach(d=>{d&&(a=zR(a,RR(a,d,t,i),d,n))}),l.selectedElementIds=Object.entries(l.selectedElementIds).reduce((d,[u,h])=>(h&&!s.includes(u)&&(d[u]=!0),d),{}),{appState:{...t,...l},elements:a,captureUpdate:Tc.IMMEDIATELY}},keyTest:e=>e.shiftKey&&e[ip.CTRL_OR_CMD]&&e.key===ip.G.toUpperCase(),predicate:(e,t)=>np(t).length>0,PanelComponent:({elements:e,appState:t,updateData:o})=>ks(ne,{type:"button",hidden:np(t).length===0,icon:ks(yh,{theme:t.theme}),onClick:()=>o(null),title:`${f("labels.ungroup")} \u2014 ${G("CtrlOrCmd+Shift+G")}`,"aria-label":f("labels.ungroup"),visible:He(rp(e),t)})});import QR from"clsx";import{CaptureUpdateAction as dI}from"@orangecatai/element";import{invariant as e7}from"@orangecatai/common";import{COLOR_CHARCOAL_BLACK as KR,COLOR_VOICE_CALL as XR,COLOR_WHITE as sp,THEME as ZR,UserIdleState as aI}from"@orangecatai/common";var ap=(e,t,o,n,r,i,a)=>{e.beginPath(),e.moveTo(t+i,o),e.lineTo(t+n-i,o),e.quadraticCurveTo(t+n,o,t+n,o+i),e.lineTo(t+n,o+r-i),e.quadraticCurveTo(t+n,o+r,t+n-i,o+r),e.lineTo(t+i,o+r),e.quadraticCurveTo(t,o+r,t,o+r-i),e.lineTo(t,o+i),e.quadraticCurveTo(t,o,t+i,o),e.closePath(),e.fill(),a&&(e.strokeStyle=a),e.stroke()};function jR(e){let t=0;if(e.length===0)return t;for(let o=0;o<e.length;o++){let n=e.charCodeAt(o);t=(t<<5)-t+n}return t}var qi=(e,t)=>`hsl(${Math.abs(jR(t?.id||e))%37*10}, 100%, 83%)`,sI=e=>{let t=e?.trim()?.codePointAt(0);return(t?String.fromCodePoint(t):"?").toUpperCase()},lI=({context:e,renderConfig:t,appState:o,normalizedWidth:n,normalizedHeight:r})=>{for(let[i,a]of t.remotePointerViewportCoords){let{x:s,y:l}=a,c=o.collaborators.get(i);s-=o.offsetLeft,l-=o.offsetTop;let m=11,p=14,d=s<0||s>n-m||l<0||l>r-p;s=Math.max(s,0),s=Math.min(s,n-m),l=Math.max(l,0),l=Math.min(l,r-p);let u=qi(i,c);e.save(),e.strokeStyle=u,e.fillStyle=u;let h=t.remotePointerUserStates.get(i),g=d||h===aI.IDLE||h===aI.AWAY;g&&(e.globalAlpha=.3),t.remotePointerButton.get(i)==="down"&&(e.beginPath(),e.arc(s,l,15,0,2*Math.PI,!1),e.lineWidth=3,e.strokeStyle="#ffffff88",e.stroke(),e.closePath(),e.beginPath(),e.arc(s,l,15,0,2*Math.PI,!1),e.lineWidth=1,e.strokeStyle=u,e.stroke(),e.closePath());let E=o.theme===ZR.DARK?"#2f6330":XR,w=c?.isSpeaking;w&&(e.fillStyle=E,e.strokeStyle=E,e.lineWidth=10,e.lineJoin="round",e.beginPath(),e.moveTo(s,l),e.lineTo(s+0,l+14),e.lineTo(s+4,l+9),e.lineTo(s+11,l+8),e.closePath(),e.stroke(),e.fill()),e.fillStyle=sp,e.strokeStyle=sp,e.lineWidth=6,e.lineJoin="round",e.beginPath(),e.moveTo(s,l),e.lineTo(s+0,l+14),e.lineTo(s+4,l+9),e.lineTo(s+11,l+8),e.closePath(),e.stroke(),e.fill(),e.fillStyle=u,e.strokeStyle=u,e.lineWidth=2,e.lineJoin="round",e.beginPath(),g?(e.moveTo(s-1,l-1),e.lineTo(s-1,l+15),e.lineTo(s+5,l+10),e.lineTo(s+12,l+9),e.closePath(),e.fill()):(e.moveTo(s,l),e.lineTo(s+0,l+14),e.lineTo(s+4,l+9),e.lineTo(s+11,l+8),e.closePath(),e.fill(),e.stroke());let x=t.remotePointerUsernames.get(i)||"";if(!d&&x){e.font="600 12px sans-serif";let y=(w?s+0:s)+m/2,v=(w?l+0:l)+p+2,I=5,k=3,L=e.measureText(x),S=L.actualBoundingBoxDescent+L.actualBoundingBoxAscent,_=Math.max(S,12),P=y-1,T=v-1,M=L.width+2+I*2+2,N=_+2+k*2+2;if(e.roundRect?(e.beginPath(),e.roundRect(P,T,M,N,8),e.fillStyle=u,e.fill(),e.strokeStyle=sp,e.stroke(),w&&(e.beginPath(),e.roundRect(P-2,T-2,M+4,N+4,8),e.strokeStyle=E,e.stroke())):ap(e,P,T,M,N,8,sp),e.fillStyle=KR,e.fillText(x,y+I+1,v+k+L.actualBoundingBoxAscent+Math.floor((_-S)/2)+2),w){e.fillStyle=E;let O=8,B=8,U=5;e.fillRect(P+M+B,T+(N/2-O/2),2,O),e.fillRect(P+M+B+U,T+(N/2-O*2/2),2,O*2),e.fillRect(P+M+B+U*2,T+(N/2-O/2),2,O)}}e.restore(),e.closePath()}};import qR from"clsx";import{useState as JR}from"react";import{jsx as cI}from"react/jsx-runtime";var Ff=({color:e,onClick:t,name:o,src:n,className:r})=>{let i=sI(o),[a,s]=JR(!1),l=!a&&n,c=l?void 0:{background:e};return cI("div",{className:qR("Avatar",r),style:c,onClick:t,children:l?cI("img",{className:"Avatar-img",src:n,alt:i,referrerPolicy:"no-referrer",onError:()=>s(!0)}):i})};import{jsx as zn,jsxs as lp}from"react/jsx-runtime";var t7=W({name:"goToCollaborator",label:"Go to a collaborator",viewMode:!0,trackEvent:{category:"collab"},perform:(e,t,o)=>(e7(o,"actionGoToCollaborator: collaborator should be defined when actionGoToCollaborator is called"),!o.socketId||t.userToFollow?.socketId===o.socketId||o.isCurrentUser?{appState:{...t,userToFollow:null},captureUpdate:dI.EVENTUALLY}:{appState:{...t,userToFollow:{socketId:o.socketId,username:o.username||""},openMenu:t.openMenu==="canvas"?null:t.openMenu},captureUpdate:dI.EVENTUALLY}),PanelComponent:({updateData:e,data:t,appState:o})=>{let{socketId:n,collaborator:r,withName:i,isBeingFollowed:a}=t,s=qi(n,r),l=QR({"is-followed":a,"is-current-user":r.isCurrentUser===!0,"is-speaking":r.isSpeaking,"is-in-call":r.isInCall,"is-muted":r.isMuted}),c=r.isInCall?r.isSpeaking?lp("div",{className:"UserList__collaborator-status-icon-speaking-indicator",title:f("userList.hint.isSpeaking"),children:[zn("div",{}),zn("div",{}),zn("div",{})]}):r.isMuted?zn("div",{className:"UserList__collaborator-status-icon-microphone-muted",title:f("userList.hint.micMuted"),children:Dw}):zn("div",{title:f("userList.hint.inCall"),children:_w}):null;return i?lp("div",{className:`dropdown-menu-item dropdown-menu-item-base UserList__collaborator ${l}`,style:{"--avatar-size":"1.5rem"},onClick:()=>e(r),children:[zn(Ff,{color:s,onClick:()=>{},name:r.username||"",src:r.avatarUrl,className:l}),zn("div",{className:"UserList__collaborator-name",children:r.username}),lp("div",{className:"UserList__collaborator-status-icons","aria-hidden":!0,children:[a&&zn("div",{className:"UserList__collaborator-status-icon-is-followed",title:f("userList.hint.followStatus"),children:ts}),c]})]}):lp("div",{className:`UserList__collaborator UserList__collaborator--avatar-only ${l}`,children:[zn(Ff,{color:s,onClick:()=>{e(r)},name:r.username||"",src:r.avatarUrl,className:l}),c&&zn("div",{className:"UserList__collaborator-status-icon",children:c})]})}});import{LIBRARY_DISABLED_TYPES as o7,randomId as n7}from"@orangecatai/common";import{deepCopyElement as r7}from"@orangecatai/element";import{CaptureUpdateAction as Of}from"@orangecatai/element";var zf=W({name:"addToLibrary",trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});for(let i of o7)if(r.some(a=>a.type===i))return{captureUpdate:Of.EVENTUALLY,appState:{...t,errorMessage:f(`errors.libraryElementTypeError.${i}`)}};return n.library.getLatestLibrary().then(i=>n.library.setLibrary([{id:n7(),status:"unpublished",elements:r.map(r7),created:Date.now()},...i])).then(()=>({captureUpdate:Of.EVENTUALLY,appState:{...t,toast:{message:f("toast.addedToLibrary")}}})).catch(i=>({captureUpdate:Of.EVENTUALLY,appState:{...t,errorMessage:i.message}}))},label:"labels.addToLibrary"});import{getNonDeletedElements as Ss}from"@orangecatai/element";import{isFrameLikeElement as i7}from"@orangecatai/element";import{updateFrameMembershipOfSelectedElements as a7}from"@orangecatai/element";import{KEYS as Zr,arrayToMap as s7}from"@orangecatai/common";import{alignElements as l7}from"@orangecatai/element";import{CaptureUpdateAction as Ms}from"@orangecatai/element";import{getSelectedElementsByGroup as c7}from"@orangecatai/element";import{jsx as As}from"react/jsx-runtime";var oo=(e,t)=>{let o=t.scene.getSelectedElements(e);return c7(o,t.scene.getNonDeletedElementsMap(),e).length>1&&!o.some(n=>i7(n))},Ps=(e,t,o,n)=>{let r=o.scene.getSelectedElements(t),i=l7(r,n,o.scene,t),a=s7(i);return a7(e.map(s=>a.get(s.id)||s),t,o)},d7=W({name:"alignTop",label:"labels.alignTop",icon:uh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>oo(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"start",axis:"y"}),captureUpdate:Ms.IMMEDIATELY}),keyTest:e=>e[Zr.CTRL_OR_CMD]&&e.shiftKey&&e.key===Zr.ARROW_UP,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!oo(t,n),type:"button",icon:uh,onClick:()=>o(null),title:`${f("labels.alignTop")} \u2014 ${G("CtrlOrCmd+Shift+Up")}`,"aria-label":f("labels.alignTop"),visible:He(Ss(e),t)})}),m7=W({name:"alignBottom",label:"labels.alignBottom",icon:gh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>oo(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"end",axis:"y"}),captureUpdate:Ms.IMMEDIATELY}),keyTest:e=>e[Zr.CTRL_OR_CMD]&&e.shiftKey&&e.key===Zr.ARROW_DOWN,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!oo(t,n),type:"button",icon:gh,onClick:()=>o(null),title:`${f("labels.alignBottom")} \u2014 ${G("CtrlOrCmd+Shift+Down")}`,"aria-label":f("labels.alignBottom"),visible:He(Ss(e),t)})}),p7=W({name:"alignLeft",label:"labels.alignLeft",icon:hh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>oo(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"start",axis:"x"}),captureUpdate:Ms.IMMEDIATELY}),keyTest:e=>e[Zr.CTRL_OR_CMD]&&e.shiftKey&&e.key===Zr.ARROW_LEFT,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!oo(t,n),type:"button",icon:hh,onClick:()=>o(null),title:`${f("labels.alignLeft")} \u2014 ${G("CtrlOrCmd+Shift+Left")}`,"aria-label":f("labels.alignLeft"),visible:He(Ss(e),t)})}),u7=W({name:"alignRight",label:"labels.alignRight",icon:fh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>oo(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"end",axis:"x"}),captureUpdate:Ms.IMMEDIATELY}),keyTest:e=>e[Zr.CTRL_OR_CMD]&&e.shiftKey&&e.key===Zr.ARROW_RIGHT,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!oo(t,n),type:"button",icon:fh,onClick:()=>o(null),title:`${f("labels.alignRight")} \u2014 ${G("CtrlOrCmd+Shift+Right")}`,"aria-label":f("labels.alignRight"),visible:He(Ss(e),t)})}),g7=W({name:"alignVerticallyCentered",label:"labels.centerVertically",icon:bh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>oo(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"center",axis:"y"}),captureUpdate:Ms.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!oo(t,n),type:"button",icon:bh,onClick:()=>o(null),title:f("labels.centerVertically"),"aria-label":f("labels.centerVertically"),visible:He(Ss(e),t)})}),h7=W({name:"alignHorizontallyCentered",label:"labels.centerHorizontally",icon:xh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>oo(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"center",axis:"x"}),captureUpdate:Ms.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!oo(t,n),type:"button",icon:xh,onClick:()=>o(null),title:f("labels.centerHorizontally"),"aria-label":f("labels.centerHorizontally"),visible:He(Ss(e),t)})});import{getNonDeletedElements as mI}from"@orangecatai/element";import{isFrameLikeElement as f7}from"@orangecatai/element";import{CODES as pI,KEYS as uI,arrayToMap as b7}from"@orangecatai/common";import{updateFrameMembershipOfSelectedElements as x7}from"@orangecatai/element";import{distributeElements as E7}from"@orangecatai/element";import{CaptureUpdateAction as gI}from"@orangecatai/element";import{getSelectedElementsByGroup as y7}from"@orangecatai/element";import{jsx as bI}from"react/jsx-runtime";var hI=(e,t)=>{let o=t.scene.getSelectedElements(e);return y7(o,t.scene.getNonDeletedElementsMap(),e).length>2&&!o.some(n=>f7(n))},fI=(e,t,o,n)=>{let r=o.scene.getSelectedElements(t),i=E7(r,o.scene.getNonDeletedElementsMap(),n,t,o.scene),a=b7(i);return x7(e.map(s=>a.get(s.id)||s),t,o)},w7=W({name:"distributeHorizontally",label:"labels.distributeHorizontally",trackEvent:{category:"element"},perform:(e,t,o,n)=>({appState:t,elements:fI(e,t,n,{space:"between",axis:"x"}),captureUpdate:gI.IMMEDIATELY}),keyTest:e=>!e[uI.CTRL_OR_CMD]&&e.altKey&&e.code===pI.H,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>bI(ne,{hidden:!hI(t,n),type:"button",icon:Dy,onClick:()=>o(null),title:`${f("labels.distributeHorizontally")} \u2014 ${G("Alt+H")}`,"aria-label":f("labels.distributeHorizontally"),visible:He(mI(e),t)})}),v7=W({name:"distributeVertically",label:"labels.distributeVertically",trackEvent:{category:"element"},perform:(e,t,o,n)=>({appState:t,elements:fI(e,t,n,{space:"between",axis:"y"}),captureUpdate:gI.IMMEDIATELY}),keyTest:e=>!e[uI.CTRL_OR_CMD]&&e.altKey&&e.code===pI.V,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>bI(ne,{hidden:!hI(t,n),type:"button",icon:Ry,onClick:()=>o(null),title:`${f("labels.distributeVertically")} \u2014 ${G("Alt+V")}`,"aria-label":f("labels.distributeVertically"),visible:He(mI(e),t)})});import{getNonDeletedElements as I7}from"@orangecatai/element";import{bindOrUnbindBindingElements as T7}from"@orangecatai/element";import{getCommonBoundingBox as xI}from"@orangecatai/element";import{newElementWith as C7}from"@orangecatai/element";import{deepCopyElement as k7}from"@orangecatai/element";import{resizeMultipleElements as S7}from"@orangecatai/element";import{isArrowElement as EI,isElbowArrow as M7}from"@orangecatai/element";import{updateFrameMembershipOfSelectedElements as yI}from"@orangecatai/element";import{CODES as wI,KEYS as P7,arrayToMap as A7}from"@orangecatai/common";import{CaptureUpdateAction as vI}from"@orangecatai/element";var Hf=W({name:"flipHorizontal",label:"labels.flipHorizontal",icon:Fw,trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:yI(II(e,n.scene.getNonDeletedElementsMap(),t,"horizontal",n),t,n),appState:t,captureUpdate:vI.IMMEDIATELY}),keyTest:e=>e.shiftKey&&e.code===wI.H}),Gf=W({name:"flipVertical",label:"labels.flipVertical",icon:Bw,trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:yI(II(e,n.scene.getNonDeletedElementsMap(),t,"vertical",n),t,n),appState:t,captureUpdate:vI.IMMEDIATELY}),keyTest:e=>e.shiftKey&&e.code===wI.V&&!e[P7.CTRL_OR_CMD]}),II=(e,t,o,n,r)=>{let i=le(I7(e),o,{includeBoundTextElement:!0,includeElementsInFrames:!0}),a=L7(i,t,n,r),s=A7(a);return e.map(l=>s.get(l.id)||l)},L7=(e,t,o,n)=>{if(e.every(d=>EI(d)&&(d.startBinding||d.endBinding)))return e.map(d=>{let u=d;return C7(u,{startArrowhead:u.endArrowhead,endArrowhead:u.startArrowhead})});let{midX:r,midY:i}=xI(e);S7(e,t,"nw",n.scene,new Map(Array.from(t.values()).map(d=>[d.id,k7(d)])),{flipByX:o==="horizontal",flipByY:o==="vertical",shouldResizeFromCenter:!0,shouldMaintainAspectRatio:!0}),T7(e.filter(EI),n.scene,n.state);let{elbowArrows:a,otherElements:s}=e.reduce((d,u)=>M7(u)?{...d,elbowArrows:d.elbowArrows.concat(u)}:{...d,otherElements:d.otherElements.concat(u)},{elbowArrows:[],otherElements:[]}),{midX:l,midY:c}=xI(e),[m,p]=[r-l,i-c];return s.forEach(d=>n.scene.mutateElement(d,{x:d.x+m,y:d.y+p})),a.forEach(d=>n.scene.mutateElement(d,{x:d.x+m,y:d.y+p})),e};import{isTextElement as _7}from"@orangecatai/element";import{getTextFromElements as D7}from"@orangecatai/element";import{CODES as R7,KEYS as TI,isFirefox as N7}from"@orangecatai/common";import{CaptureUpdateAction as Ao}from"@orangecatai/element";var Ls=W({name:"copy",label:"labels.copy",icon:Xl,trackEvent:{category:"element"},perform:async(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});try{await Jm(r,n.files,o)}catch(i){return{captureUpdate:Ao.EVENTUALLY,appState:{...t,errorMessage:i.message}}}return{captureUpdate:Ao.EVENTUALLY}},keyTest:void 0}),Uf=W({name:"paste",label:"labels.paste",trackEvent:{category:"element"},perform:async(e,t,o,n)=>{let r;try{r=await $2()}catch(i){return i.name==="AbortError"||i.name==="NotAllowedError"?!1:(console.error(`actionPaste ${i.name}: ${i.message}`),N7?{captureUpdate:Ao.EVENTUALLY,appState:{...t,errorMessage:f("hints.firefox_clipboard_write")}}:{captureUpdate:Ao.EVENTUALLY,appState:{...t,errorMessage:f("errors.asyncPasteFailedOnRead")}})}try{n.pasteFromClipboard(Y2({types:r}))}catch(i){return console.error(i),{captureUpdate:Ao.EVENTUALLY,appState:{...t,errorMessage:f("errors.asyncPasteFailedOnParse")}}}return{captureUpdate:Ao.EVENTUALLY}},keyTest:void 0}),cp=W({name:"cut",label:"labels.cut",icon:Ew,trackEvent:{category:"element"},perform:(e,t,o,n)=>(Ls.perform(e,t,o,n),nc.perform(e,t,null,n)),keyTest:e=>e[TI.CTRL_OR_CMD]&&e.key===TI.X}),dp=W({name:"copyAsSvg",label:"labels.copyAsSvg",icon:Ow,trackEvent:{category:"element"},perform:async(e,t,o,n)=>{if(!n.canvas)return{captureUpdate:Ao.EVENTUALLY};let{exportedElements:r,exportingFrame:i}=Ki(e,t,!0);try{await Xi("clipboard-svg",r,t,n.files,{...t,exportingFrame:i,name:n.getName()});let a=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});return{appState:{toast:{message:f("toast.copyToClipboardAsSvg",{exportSelection:a.length?f("toast.selection"):f("toast.canvas"),exportColorScheme:t.exportWithDarkMode?f("buttons.darkMode"):f("buttons.lightMode")})}},captureUpdate:Ao.EVENTUALLY}}catch(a){return console.error(a),{appState:{errorMessage:a.message},captureUpdate:Ao.EVENTUALLY}}},predicate:e=>qm&&e.length>0,keywords:["svg","clipboard","copy"]}),mp=W({name:"copyAsPng",label:"labels.copyAsPng",icon:zw,trackEvent:{category:"element"},perform:async(e,t,o,n)=>{if(!n.canvas)return{captureUpdate:Ao.EVENTUALLY};let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0}),{exportedElements:i,exportingFrame:a}=Ki(e,t,!0);try{return await Xi("clipboard",i,t,n.files,{...t,exportingFrame:a,name:n.getName()}),{appState:{...t,toast:{message:f("toast.copyToClipboardAsPng",{exportSelection:r.length?f("toast.selection"):f("toast.canvas"),exportColorScheme:t.exportWithDarkMode?f("buttons.darkMode"):f("buttons.lightMode")})}},captureUpdate:Ao.EVENTUALLY}}catch(s){return console.error(s),{appState:{...t,errorMessage:s.message},captureUpdate:Ao.EVENTUALLY}}},predicate:e=>vs&&e.length>0,keyTest:e=>e.code===R7.C&&e.altKey&&e.shiftKey,keywords:["png","clipboard","copy"]}),pp=W({name:"copyText",label:"labels.copyText",trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0});try{pn(D7(r))}catch{throw new Error(f("errors.copyToSystemClipboardFailed"))}return{captureUpdate:Ao.EVENTUALLY}},predicate:(e,t,o,n)=>qm&&n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0}).some(_7),keywords:["text","clipboard","copy"]});import{CODES as B7,KEYS as F7}from"@orangecatai/common";import{CaptureUpdateAction as O7}from"@orangecatai/element";var _s=W({name:"gridMode",icon:Yw,keywords:["snap"],label:"labels.toggleGrid",viewMode:!0,trackEvent:{category:"canvas",predicate:e=>e.gridModeEnabled},perform(e,t){return{appState:{...t,gridModeEnabled:!this.checked(t),objectsSnapModeEnabled:!1},captureUpdate:O7.EVENTUALLY}},checked:e=>e.gridModeEnabled,predicate:(e,t,o)=>o.gridModeEnabled===void 0,keyTest:e=>e[F7.CTRL_OR_CMD]&&e.code===B7.QUOTE});import{CODES as z7,KEYS as H7}from"@orangecatai/common";import{CaptureUpdateAction as G7}from"@orangecatai/element";var jr=W({name:"zenMode",label:"buttons.zenMode",icon:Gw,viewMode:!0,trackEvent:{category:"canvas",predicate:e=>!e.zenModeEnabled},perform(e,t){return{appState:{...t,zenModeEnabled:!this.checked(t)},captureUpdate:G7.EVENTUALLY}},checked:e=>e.zenModeEnabled,predicate:(e,t,o,n)=>n.editorInterface.formFactor!=="phone"&&typeof o.zenModeEnabled>"u",keyTest:e=>!e[H7.CTRL_OR_CMD]&&e.altKey&&e.code===z7.Z});import{CODES as U7,KEYS as W7}from"@orangecatai/common";import{CaptureUpdateAction as Y7}from"@orangecatai/element";var Cc=W({name:"objectsSnapMode",label:"buttons.objectsSnapMode",icon:Hw,viewMode:!1,trackEvent:{category:"canvas",predicate:e=>!e.objectsSnapModeEnabled},perform(e,t){return{appState:{...t,objectsSnapModeEnabled:!this.checked(t),gridModeEnabled:!1},captureUpdate:Y7.EVENTUALLY}},checked:e=>e.objectsSnapModeEnabled,predicate:(e,t,o)=>typeof o.objectsSnapModeEnabled>"u",keyTest:e=>!e[W7.CTRL_OR_CMD]&&e.altKey&&e.code===U7.S});import{CODES as V7,KEYS as $7}from"@orangecatai/common";import{CaptureUpdateAction as K7}from"@orangecatai/element";var qr=W({name:"stats",label:"stats.fullTitle",icon:Nw,viewMode:!0,trackEvent:{category:"menu"},keywords:["edit","attributes","customize"],perform(e,t){return{appState:{...t,stats:{...t.stats,open:!this.checked(t)}},captureUpdate:K7.EVENTUALLY}},checked:e=>e.stats.open,keyTest:e=>!e[$7.CTRL_OR_CMD]&&e.altKey&&e.code===V7.SLASH});import{BOUND_TEXT_PADDING as CI,ROUNDNESS as kI,TEXT_ALIGN as PI,VERTICAL_ALIGN as AI,arrayToMap as LI,getFontString as X7}from"@orangecatai/common";import{getOriginalContainerHeightFromCache as Z7,isBoundToContainer as SI,resetOriginalContainerCache as j7,updateOriginalContainerCache as q7}from"@orangecatai/element";import{computeBoundTextPosition as J7,computeContainerDimensionForBoundText as MI,getBoundTextElement as _I,redrawTextBoundingBox as DI}from"@orangecatai/element";import{hasBoundTextElement as Q7,isArrowElement as eN,isTextBindableContainer as Wf,isTextElement as kc,isUsingAdaptiveRadius as tN}from"@orangecatai/element";import{measureText as oN}from"@orangecatai/element";import{syncMovedIndices as RI}from"@orangecatai/element";import{newElement as nN}from"@orangecatai/element";import{CaptureUpdateAction as Yf}from"@orangecatai/element";var Vf=W({name:"unbindText",label:"labels.unbindText",trackEvent:{category:"element"},predicate:(e,t,o,n)=>n.scene.getSelectedElements(t).some(i=>Q7(i)),perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i=n.scene.getNonDeletedElementsMap();return r.forEach(a=>{let s=_I(a,i);if(s){let{width:l,height:c}=oN(s.originalText,X7(s),s.lineHeight),m=Z7(a.id);j7(a.id);let{x:p,y:d}=J7(a,s,i);n.scene.mutateElement(s,{containerId:null,width:l,height:c,text:s.originalText,x:p,y:d}),n.scene.mutateElement(a,{boundElements:a.boundElements?.filter(u=>u.id!==s.id),height:m||a.height})}}),{elements:e,appState:t,captureUpdate:Yf.IMMEDIATELY}}}),$f=W({name:"bindText",label:"labels.bindText",trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);if(r.length===2){let i=kc(r[0])||kc(r[1]),a;if(Wf(r[0])?a=r[0]:Wf(r[1])&&(a=r[1]),i&&a&&_I(a,n.scene.getNonDeletedElementsMap())===null)return!0}return!1},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i,a;kc(r[0])&&Wf(r[1])?(i=r[0],a=r[1]):(i=r[1],a=r[0]),n.scene.mutateElement(i,{containerId:a.id,verticalAlign:AI.MIDDLE,textAlign:PI.CENTER,autoResize:!0,angle:eN(a)?0:a?.angle??0}),n.scene.mutateElement(a,{boundElements:(a.boundElements||[]).concat({type:"text",id:i.id})});let s=a.height;return DI(i,a,n.scene),q7(a.id,s),{elements:rN(e,a,i),appState:{...t,selectedElementIds:{[a.id]:!0}},captureUpdate:Yf.IMMEDIATELY}}}),rN=(e,t,o)=>{let n=e.slice(),r=n.findIndex(a=>a.id===o.id);n.splice(r,1);let i=n.findIndex(a=>a.id===t.id);return n.splice(i+1,0,o),RI(n,LI([t,o])),n},iN=(e,t,o)=>{let n=e.slice(),r=n.findIndex(a=>a.id===t.id);n.splice(r,1);let i=n.findIndex(a=>a.id===o.id);return n.splice(i,0,t),RI(n,LI([t,o])),n},NI=W({name:"wrapTextInContainer",label:"labels.createContainerFromText",trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i=r.some(a=>kc(a)&&!SI(a));return r.length>0&&i},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i=e.slice(),a={};for(let s of r)if(kc(s)&&!SI(s)){let l=nN({type:"rectangle",backgroundColor:t.currentItemBackgroundColor,boundElements:[...s.boundElements||[],{id:s.id,type:"text"}],angle:s.angle,fillStyle:t.currentItemFillStyle,strokeColor:t.currentItemStrokeColor,roughness:t.currentItemRoughness,strokeWidth:t.currentItemStrokeWidth,strokeStyle:t.currentItemStrokeStyle,roundness:t.currentItemRoundness==="round"?{type:tN("rectangle")?kI.ADAPTIVE_RADIUS:kI.PROPORTIONAL_RADIUS}:null,opacity:100,locked:!1,x:s.x-CI,y:s.y-CI,width:MI(s.width,"rectangle"),height:MI(s.height,"rectangle"),groupIds:s.groupIds,frameId:s.frameId});if(s.boundElements?.length){let c=s.boundElements.filter(p=>p.type==="arrow").map(p=>p.id);i.filter(p=>c.includes(p.id)).forEach(p=>{let d=p.startBinding,u=p.endBinding;d?.elementId===s.id&&(d={...d,elementId:l.id}),u?.elementId===s.id&&(u={...u,elementId:l.id}),(d||u)&&n.scene.mutateElement(p,{startBinding:d,endBinding:u})})}n.scene.mutateElement(s,{containerId:l.id,verticalAlign:AI.MIDDLE,boundElements:null,textAlign:PI.CENTER,autoResize:!0}),DI(s,l,n.scene),i=iN([...i,l],l,s),a[l.id]=!0}return{elements:i,appState:{...t,selectedElementIds:a},captureUpdate:Yf.IMMEDIATELY}}});import{isEmbeddableElement as vN}from"@orangecatai/element";import{KEYS as VI}from"@orangecatai/common";import{CaptureUpdateAction as IN}from"@orangecatai/element";import{pointFrom as zI}from"@orangecatai/math";import aN from"clsx";import{useCallback as BI,useEffect as FI,useLayoutEffect as sN,useRef as lN,useState as cN}from"react";import{EVENT as Kf,HYPERLINK_TOOLTIP_DELAY as dN,KEYS as up}from"@orangecatai/common";import{getElementAbsoluteCoords as Jf}from"@orangecatai/element";import{hitElementBoundingBox as mN}from"@orangecatai/element";import{isElementLink as pN}from"@orangecatai/element";import{getEmbedLink as uN,embeddableURLValidator as gN}from"@orangecatai/element";import{sceneCoordsToViewportCoords as HI,viewportCoordsToSceneCoords as hN,wrapEvent as fN,isLocalLink as bN,normalizeLink as Xf}from"@orangecatai/common";import{isEmbeddableElement as Zf}from"@orangecatai/element";import{jsx as Ds,jsxs as OI}from"react/jsx-runtime";var Qf=380,xN=42,jf=5,GI=85,EN=500,qf=!1,gp=new Map,UI=({element:e,scene:t,setAppState:o,onLinkOpen:n,setToast:r,updateEmbedValidationStatus:i})=>{let a=t.getNonDeletedElementsMap(),s=Go(),l=Nn(),c=we(),m=e.link||"",[p,d]=cN(m),u=lN(null),h=s.showHyperlinkPopup==="editor",g=BI(()=>{if(!u.current)return;let v=Xf(u.current.value)||null;if(!e.link&&v&&ge("hyperlink","create"),Zf(e)){if(s.activeEmbeddable?.element===e&&o({activeEmbeddable:null}),!v){t.mutateElement(e,{link:null}),i(e,!1);return}if(!gN(v,l.validateEmbeddable))v&&r({message:f("toast.unableToEmbed"),closable:!0}),e.link&&gp.set(e.id,e.link),t.mutateElement(e,{link:v}),i(e,!1);else{let{width:I,height:k}=e,L=uN(v);L?.error instanceof URIError&&r({message:f("toast.unrecognizedLinkFormat"),closable:!0});let S=L?L.intrinsicSize.w/L.intrinsicSize.h:1,_=gp.get(e.id)!==e.link;t.mutateElement(e,{..._?{width:L?.type==="video"?I>k?I:k*S:I,height:L?.type==="video"&&I>k?I/S:k}:{},link:v}),i(e,!0),gp.has(e.id)&&gp.delete(e.id)}}else t.mutateElement(e,{link:v})},[e,t,r,l.validateEmbeddable,s.activeEmbeddable,o,i]);sN(()=>()=>{g()},[g]),FI(()=>{h&&u?.current&&!(c.formFactor==="phone"||c.isTouchScreen)&&u.current.select()},[h,c.formFactor,c.isTouchScreen]),FI(()=>{let v=null,I=k=>{if(h)return;v&&clearTimeout(v),wN(e,a,s,zI(k.clientX,k.clientY))&&(v=window.setTimeout(()=>{o({showHyperlinkPopup:!1})},EN))};return window.addEventListener(Kf.POINTER_MOVE,I,!1),()=>{window.removeEventListener(Kf.POINTER_MOVE,I,!1),v&&clearTimeout(v)}},[s,e,h,o,a]);let E=BI(()=>{ge("hyperlink","delete"),t.mutateElement(e,{link:null}),o({showHyperlinkPopup:!1})},[o,e,t]),w=()=>{ge("hyperlink","edit","popup-ui"),o({showHyperlinkPopup:"editor"})},{x,y}=WI(e,s,a);return s.contextMenu||s.selectedElementsAreBeingDragged||s.resizingElement||s.isRotating||s.openMenu||s.viewModeEnabled?null:OI("div",{className:"excalidraw-hyperlinkContainer",style:{top:`${y}px`,left:`${x}px`,width:Qf,padding:jf},children:[h?Ds("input",{className:aN("excalidraw-hyperlinkContainer-input"),placeholder:f("labels.link.hint"),ref:u,value:p,onChange:v=>d(v.target.value),autoFocus:!0,onKeyDown:v=>{v.stopPropagation(),v[up.CTRL_OR_CMD]&&v.key===up.K&&v.preventDefault(),(v.key===up.ENTER||v.key===up.ESCAPE)&&(g(),o({showHyperlinkPopup:"info"}))}}):e.link?Ds("a",{href:Xf(e.link||""),className:"excalidraw-hyperlinkContainer-link",target:bN(e.link)?"_self":"_blank",onClick:v=>{if(e.link&&n){let I=fN(Kf.EXCALIDRAW_LINK,v.nativeEvent);n({...e,link:Xf(e.link)},I),I.defaultPrevented&&v.preventDefault()}},rel:"noopener noreferrer",children:e.link}):Ds("div",{className:"excalidraw-hyperlinkContainer-link",children:f("labels.link.empty")}),OI("div",{className:"excalidraw-hyperlinkContainer__buttons",children:[!h&&Ds(ne,{type:"button",title:f("buttons.edit"),"aria-label":f("buttons.edit"),label:f("buttons.edit"),onClick:w,className:"excalidraw-hyperlinkContainer--edit",icon:Ln}),Ds(ne,{type:"button",title:f("labels.linkToElement"),"aria-label":f("labels.linkToElement"),label:f("labels.linkToElement"),onClick:()=>{o({openDialog:{name:"elementLinkSelector",sourceElementId:e.id}})},icon:bm}),m&&!Zf(e)&&Ds(ne,{type:"button",title:f("buttons.remove"),"aria-label":f("buttons.remove"),label:f("buttons.remove"),onClick:E,className:"excalidraw-hyperlinkContainer--remove",icon:Ht})]})]})},WI=(e,t,o)=>{let[n,r]=Jf(e,o),{x:i,y:a}=HI({sceneX:n+e.width/2,sceneY:r},t),s=i-t.offsetLeft-Qf/2,l=a-t.offsetTop-GI;return{x:s,y:l}},eb=(e,t)=>{let o=le(e,t);return Zf(o[0])?"labels.link.editEmbed":o[0]?.link?"labels.link.edit":"labels.link.create"},Sc=null,YI=(e,t,o)=>{Sc&&clearTimeout(Sc),Sc=window.setTimeout(()=>yN(e,t,o),dN)},yN=(e,t,o)=>{if(!e.link)return;let n=bs();n.classList.add("excalidraw-tooltip--visible"),n.style.maxWidth="20rem",n.textContent=pN(e.link)?f("labels.link.goToElement"):e.link;let[r,i,a,s]=Jf(e,o),[l,c,m,p]=UE([r,i,a,s],e.angle,t),d=HI({sceneX:l,sceneY:c},t);ff(n,{left:d.x,top:d.y,width:m,height:p},"top"),ge("hyperlink","tooltip","link-icon"),qf=!0},tb=()=>{Sc&&clearTimeout(Sc),qf&&(qf=!1,bs().classList.remove("excalidraw-tooltip--visible"))},wN=(e,t,o,[n,r])=>{let{x:i,y:a}=hN({clientX:n,clientY:r},o),s=15/o.zoom.value;if(mN(zI(i,a),e,t))return!1;let[l,c,m]=Jf(e,t);if(i>=l&&i<=m&&a>=c-GI&&a<=c)return!1;let{x:p,y:d}=WI(e,o,t);return!(n>=p-s&&n<=p+Qf+jf*2+s&&r>=d-s&&r<=d+s+jf*2+xN)};import{jsx as TN}from"react/jsx-runtime";var Mc=W({name:"hyperlink",label:(e,t)=>eb(e,t),icon:ql,perform:(e,t)=>t.showHyperlinkPopup==="editor"?!1:{elements:e,appState:{...t,showHyperlinkPopup:"editor",openMenu:null},captureUpdate:IN.IMMEDIATELY},trackEvent:{category:"hyperlink",action:"click"},keyTest:e=>e[VI.CTRL_OR_CMD]&&e.key===VI.K,predicate:(e,t)=>le(e,t).length===1,PanelComponent:({elements:e,appState:t,updateData:o})=>{let n=le(e,t);return TN(ne,{type:"button",icon:ql,"aria-label":f(eb(e,t)),title:`${vN(e[0])?f("labels.link.labelEmbed"):f("labels.link.label")} - ${G("CtrlOrCmd+K")}`,onClick:()=>o(null),selected:n.length===1&&!!n[0].link})}});import{KEYS as $I,arrayToMap as nb,randomId as CN}from"@orangecatai/common";import{elementsAreInSameGroup as kN,newElementWith as KI,selectGroupsFromGivenElements as XI}from"@orangecatai/element";import{CaptureUpdateAction as ZI}from"@orangecatai/element";var ob=e=>e.every(t=>!t.locked),Pc=W({name:"toggleElementLock",label:(e,t,o)=>{let n=o.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!1});return ob(n)?"labels.elementLock.lock":"labels.elementLock.unlock"},icon:(e,t)=>{let o=le(t,e);return ob(o)?Wa:Fi},trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return r.length>0&&!r.some(i=>i.locked&&i.frameId)},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});if(!r.length)return!1;let i=ob(r),a=nb(r),s=r.length>1&&kN(r),c=r.length===1||s?null:CN(),m={...t.lockedMultiSelections};if(i)m={...t.lockedMultiSelections,...c?{[c]:!0}:{}};else if(s){let w=r[0].groupIds.at(-1);delete m[w]}let p=e.map(w=>{if(!a.has(w.id))return w;let x=w.groupIds;return i?c&&(x=[...x,c]):x=x.filter(y=>!t.lockedMultiSelections[y]),KI(w,{locked:i,groupIds:x.length!==w.groupIds.length?x:w.groupIds})}),d=nb(p),u=i?{}:Object.fromEntries(r.map(w=>[w.id,!0])),h=r.map(w=>d.get(w.id)||w),g=i?{}:XI(h,t),E=i?c||(s?r[0].groupIds.at(-1):r[0].id):null;return{elements:p,appState:{...t,selectedElementIds:u,selectedGroupIds:g,selectedLinearElement:i?null:t.selectedLinearElement,lockedMultiSelections:m,activeLockedId:E},captureUpdate:ZI.IMMEDIATELY}},keyTest:(e,t,o,n)=>e.key.toLocaleLowerCase()===$I.L&&e[$I.CTRL_OR_CMD]&&e.shiftKey&&n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!1}).length>0}),jI=W({name:"unlockAllElements",trackEvent:{category:"canvas"},viewMode:!1,icon:Fi,predicate:(e,t)=>le(e,t).length===0&&e.some(n=>n.locked),perform:(e,t)=>{let o=e.filter(a=>a.locked),n=e.map(a=>{if(a.locked){let s=a.groupIds.filter(l=>!t.lockedMultiSelections[l]);return KI(a,{locked:!1,groupIds:a.groupIds.length!==s.length?s:a.groupIds})}return a}),r=nb(n),i=o.map(a=>r.get(a.id)||a);return{elements:n,appState:{...t,selectedElementIds:Object.fromEntries(o.map(a=>[a.id,!0])),selectedGroupIds:XI(i,t),lockedMultiSelections:{},activeLockedId:null},captureUpdate:ZI.IMMEDIATELY}},label:"labels.elementLock.unlockAll"});import{isElbowArrow as pz,isLinearElement as uz,isLineElement as Js}from"@orangecatai/element";import{arrayToMap as gz,invariant as m0}from"@orangecatai/common";import{toggleLinePolygonState as hz,CaptureUpdateAction as E5}from"@orangecatai/element";import KC from"clsx";import oO from"fuzzy";import{useEffect as Wp,useRef as XC,useMemo as nO,useState as Up}from"react";import{DEFAULT_SIDEBAR as YC,EVENT as Vp,KEYS as fn,capitalizeString as rO,isWritableElement as iO}from"@orangecatai/common";import{CaptureUpdateAction as l9}from"@orangecatai/element";import{useEffect as _c,useMemo as qI,useRef as sb,useState as SN}from"react";import{getLinearElementSubType as Bs,updateElbowArrowPoints as MN}from"@orangecatai/element";import{pointFrom as fp,pointRotateRads as PN}from"@orangecatai/math";import{hasBoundTextElement as AN,isArrowBoundToElement as LN,isArrowElement as _N,isElbowArrow as DN,isLinearElement as mb,isUsingAdaptiveRadius as RN}from"@orangecatai/element";import{getCommonBoundingBox as NN,getElementAbsoluteCoords as BN}from"@orangecatai/element";import{getBoundTextElement as oT,getBoundTextMaxHeight as FN,getBoundTextMaxWidth as ON,redrawTextBoundingBox as zN}from"@orangecatai/element";import{wrapText as HN}from"@orangecatai/element";import{assertNever as GN,CLASSES as UN,getFontString as rb,isProdEnv as WN,mapFind as YN,reduceToCommonValue as VN,updateActiveTool as JI}from"@orangecatai/common";import{measureText as QI}from"@orangecatai/element";import{LinearElementEditor as $N}from"@orangecatai/element";import{newArrowElement as ib,newElement as KN,newLinearElement as XN}from"@orangecatai/element";import{ShapeCache as ZN}from"@orangecatai/element";import{updateBindings as jN}from"@orangecatai/element";import{jsx as db}from"react/jsx-runtime";var qN=8,JN=10,Ac=["rectangle","diamond","ellipse"],Lc=["line","sharpArrow","curvedArrow","elbowArrow"],QN=new Set(Ac),e9=new Set(Lc),Fs=e=>QN.has(e),xp=e=>e==="arrow"||e9.has(e),gn=Ce(null),Dc=new Map,Rc=new Map,t9=({app:e})=>{let t=e.scene.getSelectedElements(e.state),o=sb(null);return _c(()=>{if(t.length===0){e.updateEditorAtom(gn,null);return}let n=Os(t);n&&!o.current?o.current=n:(o.current&&!n||o.current&&n!==o.current)&&(e.updateEditorAtom(gn,null),o.current=null)},[t,e]),_c(()=>()=>{Dc.clear(),Rc.clear()},[]),db(o9,{app:e,elements:t})},o9=({app:e,elements:t})=>{let o=Os(t),n=qI(()=>o==="generic"?rT(t):[],[o,t]),r=qI(()=>o==="linear"?cb(t):[],[o,t]),i=o==="generic"?n.every(p=>p.type===n[0].type):o==="linear"?r.every(p=>Bs(p)===Bs(r[0])):!1,[a,s]=SN({x:0,y:0}),l=sb(""),c=sb(null);_c(()=>{let p=[...n,...r].sort((E,w)=>E.id.localeCompare(w.id)),d=`
7
- ${e.state.scrollX}${e.state.scrollY}${e.state.offsetTop}${e.state.offsetLeft}${e.state.zoom.value}${p.map(E=>E.id).join(",")}`;if(d===l.current)return;l.current=d;let u;if(p.length===1){let[E,,,w,x,y]=BN(p[0],e.scene.getNonDeletedElementsMap());u=PN(fp(E,w),fp(x,y),p[0].angle)}else{let{minX:E,maxY:w}=NN(p);u=fp(E,w)}let{x:h,y:g}=aT({sceneX:u[0],sceneY:u[1]},e.state);s({x:h,y:g})},[n,r,e.scene,e.state]),_c(()=>{for(let p of r){let d=lb(p.id,s9(p));Rc.has(d)||Rc.set(d,p)}},[r]),_c(()=>{for(let p of n)if(!Dc.has(p.id)){let d=oT(p,e.scene.getNonDeletedElementsMap());d&&Dc.set(p.id,{fontSize:d.fontSize})}},[n,e.scene]);let m=o==="linear"?[["line",Ka],["sharpArrow",ns],["curvedArrow",is],["elbowArrow",rs]]:o==="generic"?[["rectangle",Ya],["diamond",Va],["ellipse",$a]]:[];return db("div",{ref:c,tabIndex:-1,style:{position:"absolute",top:`${a.y+(JN+8)*e.state.zoom.value-e.state.offsetTop}px`,left:`${a.x-e.state.offsetLeft-qN}px`,zIndex:2},className:UN.CONVERT_ELEMENT_TYPE_POPUP,children:m.map(([p,d])=>{let u=i&&(o==="generic"&&n[0].type===p||o==="linear"&&Bs(r[0])===p);return db(ne,{className:"Shape",type:"radio",icon:d,checked:u,name:"convertElementType-option",title:p,keyBindingLabel:"","aria-label":p,"data-testid":`toolbar-${p}`,onChange:()=>{e.state.activeTool.type!==p&&ge("convertElementType",p,"ui"),pb(e,{conversionType:o,nextType:p}),c.current?.focus()}},`${t[0].id}${t[0].version}_${p}`)})})},n9=(e,t,o)=>{let n=ON(e,t),r=FN(e,t),i=HN(t.text,rb(t),n),a=QI(i,rb(t),t.lineHeight),s=t.fontSize;for(;(a.width>n||a.height>r)&&s>0;){s-=1;let l={...t,fontSize:s};a=QI(t.text,rb(l),t.lineHeight)}Ep(t,o.getNonDeletedElementsMap(),{fontSize:s,width:a.width,height:a.height}),zN(t,e,o)},pb=(e,{conversionType:t,nextType:o,direction:n="right"})=>{if(!t)return!1;let r=e.scene.getSelectedElements(e.state),i=r.reduce((s,l)=>({...s,[l.id]:!0}),{}),a=n==="right"?1:-1;if(t==="generic"){let s=rT(r),c=s.every(m=>m.type===s[0].type)?Ac.indexOf(s[0].type):-1;if(o=o??Ac[(c+Ac.length+a)%Ac.length],o&&Fs(o)){let m={};for(let d of s){let u=tT(d,o,e);m[u.id]=u}let p=[];for(let d of e.scene.getElementsIncludingDeleted())m[d.id]?p.push(m[d.id]):p.push(d);e.scene.replaceAllElements(p);for(let d of Object.values(m)){let u=oT(d,e.scene.getNonDeletedElementsMap());u&&(Dc.get(d.id)&&Ep(u,e.scene.getNonDeletedElementsMap(),{fontSize:Dc.get(d.id)?.fontSize??u.fontSize}),n9(d,u,e.scene))}e.setState(d=>({selectedElementIds:i,activeTool:JI(d,{type:"selection"})}))}}if(t==="linear"){let s=cb(r);if(!o){let c=VN(s,Bs),m=c?Lc.indexOf(c):-1;o=Lc[(m+Lc.length+a)%Lc.length]}if(xp(o)){let c=[],m=e.scene.getElementsMapIncludingDeleted();for(let p of s){let d=Rc.get(lb(p.id,o));if(d&&Bs(d)===o)m.set(d.id,d),c.push(d);else{let u=tT(p,o,e);m.set(u.id,u),c.push(u)}}e.scene.replaceAllElements(m);for(let p of c)if(mb(p))if(DN(p)){let d=r9(p);if(d.length<2)continue;let u=[];for(let g=1;g<d.length-2;g++)u.push({start:d[g],end:d[g+1],index:g+1});let h=MN(p,e.scene.getNonDeletedElementsMap(),{points:d,fixedSegments:u});Ep(p,e.scene.getNonDeletedElementsMap(),{...h,endArrowhead:"arrow"})}else{let d=YN(["line","sharpArrow","curvedArrow"],u=>Rc.get(lb(p.id,u)));if(d){let u=d.points;e.scene.mutateElement(p,{points:u})}}}let l=cb(e.scene.getSelectedElements(e.state));e.setState(c=>({selectedElementIds:i,selectedLinearElement:l.length===1?new $N(l[0],e.scene.getNonDeletedElementsMap()):null,activeTool:JI(c,{type:"selection"})}))}return!0},Os=e=>{if(e.length===0)return null;let t=!1;for(let o of e){if(Fs(o.type))return"generic";nT(o)&&(t=!0)}return t?"linear":null},nT=e=>mb(e)&&(!_N(e)||!LN(e)&&!AN(e)),lb=(e,t)=>`${e}:${t}`,rT=e=>e.filter(t=>Fs(t.type)),cb=e=>e.filter(t=>nT(t)),hp=20,Rs=(e,t)=>e[0]===t[0],ab=(e,t)=>e[1]===t[1],eT=(e,t)=>Rs(e,t)?Math.abs(e[1]-t[1]):Math.abs(e[0]-t[0]),r9=e=>{let t=[e.points[0]],o=i9(e.points);for(let i=1;i<o.length;++i){let a=t[t.length-1],s=[...o[i]];Math.abs(s[0]-a[0])<hp?s[0]=a[0]:Math.abs(s[1]-a[1])<hp&&(s[1]=a[1]),Rs(a,s)||ab(a,s)||t.push(fp(a[0],s[1])),t.push(s)}let n=[t[0]];for(let i=1;i<t.length-1;++i)Rs(t[i-1],t[i])&&Rs(t[i],t[i+1])||ab(t[i-1],t[i])&&ab(t[i],t[i+1])||n.push(t[i]);n.push(t[t.length-1]);let r=[n[0]];for(let i=1;i<n.length-1;++i){let a=r[r.length-1],s=n[i],l=n[i+1],c=Rs(a,s),m=Rs(s,l);if(c!==m){let p=eT(a,s),d=eT(s,l);if(p<hp||d<hp){if(d<p)c?l[0]=a[0]:l[1]=a[1];else if(m)for(let u=r.length-1;u>=0&&r[u][0]===a[0];--u)r[u][0]=s[0];else for(let u=r.length-1;u>=0&&r[u][1]===a[1];--u)r[u][1]=s[1];continue}}r.push(s)}return r.push(n[n.length-1]),r},i9=e=>{if(e.length===0)return[];let t=[e[0]];for(let o=1;o<e.length;o++){let[n,r]=t[t.length-1],[i,a]=e[o];(n!==i||r!==a)&&t.push(e[o])}return t},tT=(e,t,o)=>{if(!a9(e.type,t)){if(!WN())throw Error(`Invalid conversion from ${e.type} to ${t}.`);return e}if(e.type===t)return e;if(ZN.delete(e),Fs(t)){let n=Ns(KN({...e,type:t,roundness:t==="diamond"&&e.roundness?{type:RN(t)?bp.ADAPTIVE_RADIUS:bp.PROPORTIONAL_RADIUS}:e.roundness}));return jN(n,o.scene,o.state),n}if(xp(t))switch(t){case"line":return Ns(XN({...e,type:"line"}));case"sharpArrow":return Ns(ib({...e,type:"arrow",elbowed:!1,roundness:null,startArrowhead:o.state.currentItemStartArrowhead,endArrowhead:o.state.currentItemEndArrowhead}));case"curvedArrow":return Ns(ib({...e,type:"arrow",elbowed:!1,roundness:{type:bp.PROPORTIONAL_RADIUS},startArrowhead:o.state.currentItemStartArrowhead,endArrowhead:o.state.currentItemEndArrowhead}));case"elbowArrow":return Ns(ib({...e,type:"arrow",elbowed:!0,fixedSegments:null,roundness:null}))}return GN(t,`unhandled conversion type: ${t}`),e},a9=(e,t)=>!!(Fs(e)&&Fs(t)||xp(e)&&xp(t)),s9=e=>mb(e)?Bs(e):e.type,iT=t9;var sT=W({name:"toggleShapeSwitch",label:"labels.shapeSwitch",icon:()=>null,viewMode:!0,trackEvent:{category:"shape_switch",action:"toggle"},keywords:["change","switch","swap"],perform(e,t,o,n){return Et.set(gn,{type:"panel"}),{captureUpdate:l9.NEVER}},checked:e=>e.gridModeEnabled,predicate:(e,t,o)=>Os(e)!==null});import{canCreateLinkFromElements as ub,defaultGetElementLinkFromSelection as c9,getLinkIdAndTypeFromSelection as d9}from"@orangecatai/element";import{CaptureUpdateAction as Nc}from"@orangecatai/element";var yp=W({name:"copyElementLink",label:"labels.copyElementLink",icon:Qa,trackEvent:{category:"element"},perform:async(e,t,o,n)=>{let r=le(e,t);try{if(window.location){let i=d9(r,t);return i?(await pn(n.props.generateLinkForSelection?n.props.generateLinkForSelection(i.id,i.type):c9(i.id,i.type)),{appState:{toast:{message:f("toast.elementLinkCopied"),closable:!0}},captureUpdate:Nc.EVENTUALLY}):{appState:t,elements:e,app:n,captureUpdate:Nc.EVENTUALLY}}}catch(i){console.error(i)}return{appState:t,elements:e,app:n,captureUpdate:Nc.EVENTUALLY}},predicate:(e,t)=>ub(le(e,t))}),lT=W({name:"linkToElement",label:"labels.linkToElement",icon:bm,perform:(e,t,o,n)=>{let r=le(e,t);return r.length!==1||!ub(r)?{elements:e,appState:t,app:n,captureUpdate:Nc.EVENTUALLY}:{appState:{...t,openDialog:{name:"elementLinkSelector",sourceElementId:le(e,t)[0].id}},captureUpdate:Nc.IMMEDIATELY}},predicate:(e,t,o,n)=>{let r=le(e,t);return t.openDialog?.name!=="elementLinkSelector"&&r.length===1&&ub(r)},trackEvent:!1});import{isDarwin as cT}from"@orangecatai/common";var m9={toggleTheme:[G("Shift+Alt+D")],saveScene:[G("CtrlOrCmd+S")],loadScene:[G("CtrlOrCmd+O")],clearCanvas:[G("CtrlOrCmd+Delete")],imageExport:[G("CtrlOrCmd+Shift+E")],commandPalette:[G("CtrlOrCmd+/"),G("CtrlOrCmd+Shift+P")],cut:[G("CtrlOrCmd+X")],copy:[G("CtrlOrCmd+C")],paste:[G("CtrlOrCmd+V")],copyStyles:[G("CtrlOrCmd+Alt+C")],pasteStyles:[G("CtrlOrCmd+Alt+V")],selectAll:[G("CtrlOrCmd+A")],deleteSelectedElements:[G("Delete")],duplicateSelection:[G("CtrlOrCmd+D"),G(`Alt+${f("helpDialog.drag")}`)],sendBackward:[G("CtrlOrCmd+[")],bringForward:[G("CtrlOrCmd+]")],sendToBack:[cT?G("CtrlOrCmd+Alt+["):G("CtrlOrCmd+Shift+[")],bringToFront:[cT?G("CtrlOrCmd+Alt+]"):G("CtrlOrCmd+Shift+]")],copyAsPng:[G("Shift+Alt+C")],group:[G("CtrlOrCmd+G")],ungroup:[G("CtrlOrCmd+Shift+G")],gridMode:[G("CtrlOrCmd+'")],zenMode:[G("Alt+Z")],objectsSnapMode:[G("Alt+S")],stats:[G("Alt+/")],addToLibrary:[],flipHorizontal:[G("Shift+H")],flipVertical:[G("Shift+V")],viewMode:[G("Alt+R")],hyperlink:[G("CtrlOrCmd+K")],toggleElementLock:[G("CtrlOrCmd+Shift+L")],resetZoom:[G("CtrlOrCmd+0")],zoomOut:[G("CtrlOrCmd+-")],zoomIn:[G("CtrlOrCmd++")],zoomToFitSelection:[G("Shift+3")],zoomToFit:[G("Shift+1")],zoomToFitSelectionInViewport:[G("Shift+2")],toggleEraserTool:[G("E")],toggleHandTool:[G("H")],setFrameAsActiveTool:[G("F")],saveFileToDisk:[G("CtrlOrCmd+S")],saveToActiveFile:[G("CtrlOrCmd+S")],toggleShortcuts:[G("?")],searchMenu:[G("CtrlOrCmd+F")],wrapSelectionInFrame:[],toolLock:[G("Q")]},Ke=(e,t=0)=>{let o=m9[e];return o&&o.length>0?o[t]||o[0]:""};var p9="\\u0300-\\u036f",u9="\\ufe20-\\ufe2f",g9="\\u20d0-\\u20ff",h9=p9+u9+g9,f9=`[${h9}]`,b9=RegExp(f9,"g"),x9=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,E9={\u00C0:"A",\u00C1:"A",\u00C2:"A",\u00C3:"A",\u00C4:"A",\u00C5:"A",\u00E0:"a",\u00E1:"a",\u00E2:"a",\u00E3:"a",\u00E4:"a",\u00E5:"a",\u00C7:"C",\u00E7:"c",\u00D0:"D",\u00F0:"d",\u00C8:"E",\u00C9:"E",\u00CA:"E",\u00CB:"E",\u00E8:"e",\u00E9:"e",\u00EA:"e",\u00EB:"e",\u00CC:"I",\u00CD:"I",\u00CE:"I",\u00CF:"I",\u00EC:"i",\u00ED:"i",\u00EE:"i",\u00EF:"i",\u00D1:"N",\u00F1:"n",\u00D2:"O",\u00D3:"O",\u00D4:"O",\u00D5:"O",\u00D6:"O",\u00D8:"O",\u00F2:"o",\u00F3:"o",\u00F4:"o",\u00F5:"o",\u00F6:"o",\u00F8:"o",\u00D9:"U",\u00DA:"U",\u00DB:"U",\u00DC:"U",\u00F9:"u",\u00FA:"u",\u00FB:"u",\u00FC:"u",\u00DD:"Y",\u00FD:"y",\u00FF:"y",\u00C6:"E",\u00E6:"e",\u00DE:"T",\u00FE:"t",\u00DF:"s",\u0100:"A",\u0102:"A",\u0104:"A",\u0101:"a",\u0103:"a",\u0105:"a",\u0106:"C",\u0108:"C",\u010A:"C",\u010C:"C",\u0107:"c",\u0109:"c",\u010B:"c",\u010D:"c",\u010E:"D",\u0110:"D",\u010F:"d",\u0111:"d",\u0112:"E",\u0114:"E",\u0116:"E",\u0118:"E",\u011A:"E",\u0113:"e",\u0115:"e",\u0117:"e",\u0119:"e",\u011B:"e",\u011C:"G",\u011E:"G",\u0120:"G",\u0122:"G",\u011D:"g",\u011F:"g",\u0121:"g",\u0123:"g",\u0124:"H",\u0126:"H",\u0125:"h",\u0127:"h",\u0128:"I",\u012A:"I",\u012C:"I",\u012E:"I",\u0130:"I",\u0129:"i",\u012B:"i",\u012D:"i",\u012F:"i",\u0131:"i",\u0134:"J",\u0135:"j",\u0136:"K",\u0137:"k",\u0138:"k",\u0139:"L",\u013B:"L",\u013D:"L",\u013F:"L",\u0141:"L",\u013A:"l",\u013C:"l",\u013E:"l",\u0140:"l",\u0142:"l",\u0143:"N",\u0145:"N",\u0147:"N",\u014A:"N",\u0144:"n",\u0146:"n",\u0148:"n",\u014B:"n",\u014C:"O",\u014E:"O",\u0150:"O",\u014D:"o",\u014F:"o",\u0151:"o",\u0154:"R",\u0156:"R",\u0158:"R",\u0155:"r",\u0157:"r",\u0159:"r",\u015A:"S",\u015C:"S",\u015E:"S",\u0160:"S",\u015B:"s",\u015D:"s",\u015F:"s",\u0161:"s",\u0162:"T",\u0164:"T",\u0166:"T",\u0163:"t",\u0165:"t",\u0167:"t",\u0168:"U",\u016A:"U",\u016C:"U",\u016E:"U",\u0170:"U",\u0172:"U",\u0169:"u",\u016B:"u",\u016D:"u",\u016F:"u",\u0171:"u",\u0173:"u",\u0174:"W",\u0175:"w",\u0176:"Y",\u0177:"y",\u0178:"Y",\u0179:"Z",\u017B:"Z",\u017D:"Z",\u017A:"z",\u017C:"z",\u017E:"z",\u0132:"I",\u0133:"i",\u0152:"E",\u0153:"e",\u0149:"n",\u017F:"s"},Ji=e=>e.replace(x9,t=>E9[t]||t).replace(b9,"");import RF from"clsx";import{useEffect as NF,useState as BF}from"react";import{KEYS as FF,queryFocusableElements as EC}from"@orangecatai/common";import{useCallback as y9,useState as w9}from"react";var dT=()=>{let[e,t]=w9(null),o=y9(n=>t(n),[]);return[e,o]};import{useState as uC,useCallback as Nb,useMemo as gC,useEffect as Bb,memo as hC,useRef as EF}from"react";import{LIBRARY_DISABLED_TYPES as yF,randomId as wF,isShallowEqual as vF,KEYS as IF,isWritableElement as TF,addEventListener as CF,EVENT as kF,CLASSES as dC}from"@orangecatai/common";import{useEffect as gT,useRef as hT}from"react";import{URL_HASH_KEYS as fb,URL_QUERY_KEYS as bb,APP_NAME as fT,EVENT as vp,DEFAULT_SIDEBAR as C9,LIBRARY_SIDEBAR_TAB as k9,arrayToMap as xb,cloneJSON as S9,preventUnload as M9,promiseTry as bT,resolvablePromise as P9,toValidURL as A9,Queue as L9,Emitter as _9}from"@orangecatai/common";import{hashElementsVersion as D9,hashString as R9}from"@orangecatai/element";import{getCommonBoundingBox as hb}from"@orangecatai/element";import{MIME_TYPES as Qi}from"@orangecatai/common";var Jr=({elements:e,appState:t,files:o,maxWidthOrHeight:n,getDimensions:r,exportPadding:i,exportingFrame:a})=>{let s=Ni(e,null,{deleteInvisibleElements:!0}),l=Oa(t,null),{exportBackground:c,viewBackgroundColor:m}=l;return Ba(s,{...l,offsetTop:0,offsetLeft:0,width:0,height:0},o||{},{exportBackground:c,exportPadding:i,viewBackgroundColor:m,exportingFrame:a},(p,d)=>{let u=document.createElement("canvas");if(n){typeof r=="function"&&console.warn("`getDimensions()` is ignored when `maxWidthOrHeight` is supplied.");let g=Math.max(p,d),E=n<g?n/g:t?.exportScale??1;return u.width=p*E,u.height=d*E,{canvas:u,scale:E}}let h=r?.(p,d)||{width:p,height:d};return u.width=h.width,u.height=h.height,{canvas:u,scale:h.scale??1}})},mT=async e=>{let{mimeType:t=Qi.png,quality:o}=e;t===Qi.png&&typeof o=="number"&&console.warn(`"quality" will be ignored for "${Qi.png}" mimeType`),t==="image/jpg"&&(t=Qi.jpg),t===Qi.jpg&&!e.appState?.exportBackground&&(console.warn(`Defaulting "exportBackground" to "true" for "${Qi.jpg}" mimeType`),e={...e,appState:{...e.appState,exportBackground:!0}});let n=await Jr(e);return o=o||(/image\/jpe?g/.test(t)?.92:.8),new Promise((r,i)=>{n.toBlob(async a=>{if(!a)return i(new Error("couldn't export to blob"));a&&t===Qi.png&&e.appState?.exportEmbedScene&&(a=await KE({blob:a,metadata:Wl(e.elements,e.appState,e.files||{},"local")})),r(a)},t,o)})},zs=async({elements:e,appState:t=Rr(),files:o={},exportPadding:n,renderEmbeddables:r,exportingFrame:i,skipInliningFonts:a,reuseImages:s})=>{let l=Ni(e,null,{deleteInvisibleElements:!0}),m={...Oa(t,null),exportPadding:n};return Fa(l,m,o,{exportingFrame:i,renderEmbeddables:r,skipInliningFonts:a,reuseImages:s})},v9=async e=>{if(e.type==="svg"){let t=await zs(e);await pn(t.outerHTML)}else if(e.type==="png")await ep(mT(e));else if(e.type==="json")await Jm(e.elements,e.files);else throw new Error("Invalid export type")};import{useEffect as pT,useState as I9}from"react";import{COLOR_PALETTE as T9}from"@orangecatai/common";var gb=Ce(new Map),uT=async e=>await zs({elements:e,appState:{exportBackground:!1,viewBackgroundColor:T9.white},files:null,renderEmbeddables:!1,skipInliningFonts:!0}),wp=(e,t,o,n)=>{let[r,i]=I9();return pT(()=>{if(t)if(e){let a=o.get(e);a?i(a):(async()=>{let s=await uT(t);s.querySelector(".style-fonts")?.remove(),s&&(o.set(e,s),i(s))})()}else(async()=>{let a=await uT(t);i(a)})()},[e,t,o,i]),pT(()=>{let a=n.current;if(a)return r&&(a.innerHTML=r.outerHTML),()=>{a.innerHTML=""}},[r,n]),r},Hs=()=>{let[e]=ae(gb);return{clearLibraryCache:()=>e.clear(),deleteItemsFromLibraryCache:n=>{n.forEach(r=>e.delete(r))},svgCache:e}};var N9=["excalidraw.com","raw.githubusercontent.com/excalidraw/excalidraw-libraries"],ET=new _9,fr=Ce({status:"loaded",isInitialized:!1,libraryItems:[]}),Bc=e=>S9(e),B9=(e,t)=>!e.find(o=>o.elements.length!==t.elements.length?!1:o.elements.every((n,r)=>n.id===t.elements[r].id&&n.versionNonce===t.elements[r].versionNonce)),yT=(e,t)=>{let o=[];for(let n of t)B9(e,n)&&o.push(n);return[...o,...e]},wT=(e,t)=>{let o=xb(t),n={deletedItems:new Map,addedItems:new Map,updatedItems:new Map};for(let i of e)o.has(i.id)||n.deletedItems.set(i.id,i);let r=xb(e);for(let i of t){let a=r.get(i.id);a?wb(a)!==wb(i)&&n.updatedItems.set(i.id,i):n.addedItems.set(i.id,i)}return n},Eb=class{constructor(t){A(this,"currLibraryItems",[]);A(this,"prevLibraryItems",Bc(this.currLibraryItems));A(this,"app");A(this,"updateQueue",[]);A(this,"getLastUpdateTask",()=>this.updateQueue[this.updateQueue.length-1]);A(this,"notifyListeners",()=>{if(this.updateQueue.length>0)Et.set(fr,t=>({status:"loading",libraryItems:this.currLibraryItems,isInitialized:t.isInitialized}));else{Et.set(fr,{status:"loaded",libraryItems:this.currLibraryItems,isInitialized:!0});try{let t=this.prevLibraryItems;this.prevLibraryItems=Bc(this.currLibraryItems);let o=Bc(this.currLibraryItems);this.app.props.onLibraryChange?.(o),ET.trigger(wT(t,o),o)}catch(t){console.error(t)}}});A(this,"destroy",()=>{this.updateQueue=[],this.currLibraryItems=[],Et.set(gb,new Map)});A(this,"resetLibrary",()=>this.setLibrary([]));A(this,"getLatestLibrary",()=>new Promise(async t=>{try{let o=await(this.getLastUpdateTask()||this.currLibraryItems);this.updateQueue.length>0?t(this.getLatestLibrary()):t(Bc(o))}catch{return t(this.currLibraryItems)}}));A(this,"updateLibrary",async({libraryItems:t,prompt:o=!1,merge:n=!1,openLibraryMenu:r=!1,defaultStatus:i="unpublished"})=>(r&&this.app.setState({openSidebar:{name:C9.name,tab:k9}}),this.setLibrary(()=>new Promise(async(a,s)=>{try{let l=await(typeof t=="function"&&!(t instanceof Blob)?t(this.currLibraryItems):t),c;l instanceof Blob?c=await eh(l,i):c=$l(l,i),!o||window.confirm(f("alerts.confirmAddLibrary",{numShapes:c.length}))?(o&&this.app.focusContainer(),a(n?yT(this.currLibraryItems,c):c)):s(new Ra)}catch(l){s(l)}}))));A(this,"setLibrary",t=>{let o=new Promise(async(n,r)=>{try{await this.getLastUpdateTask(),typeof t=="function"&&(t=t(this.currLibraryItems)),this.currLibraryItems=Bc(await t),n(this.currLibraryItems)}catch(i){r(i)}}).catch(n=>{if(n.name==="AbortError")return console.warn("Library update aborted by user"),this.currLibraryItems;throw n}).finally(()=>{this.updateQueue=this.updateQueue.filter(n=>n!==o),this.notifyListeners()});return this.updateQueue.push(o),this.notifyListeners(),o});this.app=t}},vT=Eb,Us=e=>{let o=Math.ceil(Math.sqrt(e.length)),n=[],r=u=>e.slice(u*o,u*o+o).reduce((g,E)=>{let{height:w}=hb(E.elements);return Math.max(g,w)},0),i=u=>{let h=0,g=0,E=0;for(let w of e){if(h%o===0&&(g=0),g===u){let{width:x}=hb(w.elements);E=Math.max(E,x)}h++,g++}return E},a=0,s=0,l=0,c=0,m=0,p=0,d=0;for(let u of e){m&&m%o===0&&(s+=l+50,a=0,p=0,d++),p===0&&(l=r(d)),c=i(p);let{minX:h,minY:g,width:E,height:w}=hb(u.elements),x=(c-E)/2,y=(l-w)/2;n.push(...u.elements.map(v=>({...v,x:v.x+a+x-h,y:v.y+s+y-g}))),a+=c+50,m++,p++}return n},F9=(e,t=N9)=>{if(typeof t=="function"?t(e):t.some(o=>{let n=new URL(`https://${o.replace(/^https?:\/\//,"")}`),{hostname:r,pathname:i}=new URL(e);return new RegExp(`(^|\\.)${n.hostname}$`).test(r)&&new RegExp(`^${n.pathname.replace(/\/+$/,"")}(/+|$)`).test(i)}))return!0;throw new Error(`Invalid or disallowed library URL: "${e}"`)},yb=()=>{let e=new URLSearchParams(window.location.hash.slice(1)).get(fb.addLibrary)||new URLSearchParams(window.location.search).get(bb.addLibrary),t=e?new URLSearchParams(window.location.hash.slice(1)).get("token"):null;return e?{libraryUrl:e,idToken:t}:null},Qr=class Qr{constructor(t){A(this,"adapter");this.adapter=t}static async getLibraryItems(t,o,n=!0){let r=()=>new Promise(async(i,a)=>{try{let s=await t.load({source:o});i($l(s?.libraryItems||[],"published"))}catch(s){a(s)}});return n?Qr.queue.push(r):r()}getLibraryItems(t){return Qr.getLibraryItems(this.adapter,t,!1)}};A(Qr,"queue",new L9),A(Qr,"run",async(t,o)=>{let n=new Qr(t);return Qr.queue.push(()=>o(n))});var Gs=Qr,Fc=0,Ip=0,wb=e=>`${e.id}:${e.name||""}:${D9(e.elements)}`,Tp=e=>R9(e.map(t=>wb(t)).sort().join()),xT=async(e,t)=>{try{return Ip++,await Gs.run(e,async o=>{let n=xb(await o.getLibraryItems("save"));for(let[s]of t.deletedItems)n.delete(s);let r=[];for(let[s,l]of t.addedItems)n.has(s)?n.set(s,l):r.push(l);if(t.updatedItems)for(let[s,l]of t.updatedItems)n.set(s,l);let i=r.concat(Array.from(n.values())),a=Tp(i);return a!==Fc&&await e.save({libraryItems:i}),Fc=a,i})}finally{Ip--}},O9=e=>{let{excalidrawAPI:t}=e,o=hT(e);o.current=e;let n=hT(!1);gT(()=>{if(!t)return;n.current=!1;let r=async({libraryUrl:s,idToken:l})=>{let c=new Promise(async(p,d)=>{try{s=decodeURIComponent(s),s=A9(s),F9(s,o.current.validateLibraryUrl);let h=await(await fetch(s)).blob();p(h)}catch(u){d(u)}}),m=l!==t.id;await(m&&document.hidden?new Promise(p=>{window.addEventListener("focus",()=>p(),{once:!0})}):null);try{await t.updateLibrary({libraryItems:c,prompt:m,merge:!0,defaultStatus:"published",openLibraryMenu:!0})}catch(p){throw t.updateScene({appState:{errorMessage:p.message}}),p}finally{if(window.location.hash.includes(fb.addLibrary)){let p=new URLSearchParams(window.location.hash.slice(1));p.delete(fb.addLibrary),window.history.replaceState({},fT,`#${p.toString()}`)}else if(window.location.search.includes(bb.addLibrary)){let p=new URLSearchParams(window.location.search);p.delete(bb.addLibrary),window.history.replaceState({},fT,`?${p.toString()}`)}}},i=s=>{s.preventDefault();let l=yb();l&&(s.stopImmediatePropagation(),window.history.replaceState({},"",s.oldURL),r(l))},a=yb();if(a&&r(a),"getInitialLibraryItems"in o.current&&o.current.getInitialLibraryItems&&(console.warn("useHandleLibrar `opts.getInitialLibraryItems` is deprecated. Use `opts.adapter` instead."),Promise.resolve(o.current.getInitialLibraryItems()).then(s=>{t.updateLibrary({libraryItems:s,merge:!0})}).catch(s=>{console.error(`UseHandeLibrary getInitialLibraryItems failed: ${s?.message}`)})),"adapter"in o.current&&o.current.adapter){let s=o.current.adapter,l=o.current.migrationAdapter,c=P9();l?c.resolve(bT(l.load).then(async m=>{let p=null;try{if(!m)return Gs.getLibraryItems(s,"load");p=$l(m.libraryItems||[],"published");let d=await xT(s,wT([],p));try{await l.clear()}catch(u){console.error(`couldn't delete legacy library data: ${u.message}`)}return d}catch(d){return console.error(`couldn't migrate legacy library data: ${d.message}`),p}}).catch(m=>(console.error(`error during library migration: ${m.message}`),Gs.getLibraryItems(s,"load")))):c.resolve(bT(Gs.getLibraryItems,s,"load")),t.updateLibrary({libraryItems:c.then(m=>{let p=m||[];return Fc=Tp(p),p}),merge:!0}).finally(()=>{n.current=!0})}return window.addEventListener(vp.HASHCHANGE,i),()=>{window.removeEventListener(vp.HASHCHANGE,i)}},[t]),gT(()=>{let r=ET.on(async(a,s)=>{let l=n.current,c="adapter"in o.current&&o.current.adapter||null;try{c&&Fc!==Tp(s)&&await xT(c,a)}catch(m){console.error(`couldn't persist library update: ${m.message}`,a),l&&o.current.excalidrawAPI&&o.current.excalidrawAPI.updateScene({appState:{errorMessage:f("errors.saveLibraryError")}})}}),i=a=>{Ip&&M9(a)};return window.addEventListener(vp.BEFORE_UNLOAD,i),()=>{window.removeEventListener(vp.BEFORE_UNLOAD,i),r(),Fc=0,Ip=0}},[])};import U9 from"clsx";import{VERSIONS as z9}from"@orangecatai/common";import{jsx as G9}from"react/jsx-runtime";var H9=({theme:e,id:t,libraryReturnUrl:o})=>{let n=o||window.location.origin+window.location.pathname;return G9("a",{className:"library-menu-browse-button",href:`${C.VITE_APP_LIBRARY_URL}?target=${window.name||"_blank"}&referrer=${n}&useHash=true&token=${t}&theme=${e}&version=${z9.excalidrawLibrary}`,target:"_excalidraw_libraries",children:f("labels.libraries")})},IT=H9;import{jsx as W9,jsxs as Y9}from"react/jsx-runtime";var Cp=({libraryReturnUrl:e,theme:t,id:o,style:n,children:r,className:i})=>Y9("div",{className:U9("library-menu-control-buttons",i),style:n,children:[W9(IT,{id:o,libraryReturnUrl:e,theme:t}),r]});import{useCallback as Vs,useEffect as Lb,useMemo as _b,useRef as sC,useState as lC}from"react";import{MIME_TYPES as pF,arrayToMap as uF,nextAnimationFrame as gF}from"@orangecatai/common";import{duplicateElements as hF}from"@orangecatai/element";import fF from"clsx";import V9 from"lodash.throttle";import{useEffect as $9}from"react";var K9=Ce(0),TT=e=>{let[t,o]=ae(K9);return $9(()=>{let{current:n}=e;if(!n)return;let r=V9(()=>{let{scrollTop:i}=n;o(i)},200);return n.addEventListener("scroll",r),()=>{r.cancel(),n.removeEventListener("scroll",r)}},[e,o]),t};import UB from"clsx";import{useCallback as WB,useState as Mb}from"react";import{muteFSAbortError as YB}from"@orangecatai/common";import{flushSync as CT}from"react-dom";import X9 from"clsx";import{jsx as kp,jsxs as j9}from"react/jsx-runtime";var Z9=({label:e,onClick:t,className:o,children:n,actionType:r,type:i="button",isLoading:a,...s})=>{let l=r?`Dialog__action-button--${r}`:"";return j9("button",{className:X9("Dialog__action-button",l,o),type:i,"aria-label":e,onClick:t,...s,children:[n&&kp("div",{style:a?{visibility:"hidden"}:{},children:n}),kp("div",{style:a?{visibility:"hidden"}:{},children:e}),a&&kp("div",{style:{position:"absolute",inset:0},children:kp(Gt,{})})]})},br=Z9;import{jsx as kT,jsxs as ST}from"react/jsx-runtime";var q9=e=>{let{onConfirm:t,onCancel:o,children:n,confirmText:r=f("buttons.confirm"),cancelText:i=f("buttons.cancel"),className:a="",...s}=e,l=ve(),c=Pn(Ws),{container:m}=qe();return ST(ht,{onCloseRequest:o,size:"small",...s,className:`confirm-dialog ${a}`,children:[n,ST("div",{className:"confirm-dialog-buttons",children:[kT(br,{label:i,onClick:()=>{l({openMenu:null}),c(!1),CT(()=>{o()}),m?.focus()}}),kT(br,{label:r,onClick:()=>{l({openMenu:null}),c(!1),CT(()=>{t()}),m?.focus()},actionType:"danger"})]})]})},Sp=q9;import{useCallback as rB,useEffect as Tb,useRef as MT,useState as vb}from"react";import{EDITOR_LS_KEYS as Ib,EXPORT_DATA_TYPES as iB,MIME_TYPES as PT,VERSIONS as aB,chunk as sB,getExportSource as lB}from"@orangecatai/common";var Yo=class{static has(t){try{return!!window.localStorage.getItem(t)}catch(o){return console.warn(`localStorage.getItem error: ${o.message}`),!1}}static get(t){try{let o=window.localStorage.getItem(t);return o?JSON.parse(o):null}catch(o){return console.warn(`localStorage.getItem error: ${o.message}`),null}}};A(Yo,"set",(t,o)=>{try{return window.localStorage.setItem(t,JSON.stringify(o)),!0}catch(n){return console.warn(`localStorage.setItem error: ${n.message}`),!1}}),A(Yo,"delete",t=>{try{window.localStorage.removeItem(t)}catch(o){console.warn(`localStorage.removeItem error: ${o.message}`)}});import Mp from"react";var J9=/({{[\w-]+}})|(<[\w-]+>)|(<\/[\w-]+>)/g,Q9=/{{([\w-]+)}}/,eB=/<([\w-]+)>/,tB=/<\/([\w-]+)>/,oB=(e,t)=>{let o=[{name:"",children:[]}];return e.split(J9).filter(Boolean).forEach(n=>{let r=n.match(eB),i=n.match(tB),a=n.match(Q9);if(r!==null){let s=r[1];t.hasOwnProperty(s)?o.push({name:s,children:[]}):console.warn(`Trans: missed to pass in prop ${s} for interpolating ${e}`)}else if(i!==null)if(i[1]===o[o.length-1].name){let l=o.pop(),c=Mp.createElement(Mp.Fragment,{},...l.children),m=t[l.name];typeof m=="function"&&o[o.length-1].children.push(m(c))}else console.warn(`Trans: unexpected end tag ${n} for interpolating ${e}`);else if(a!==null){let s=a[1];t.hasOwnProperty(s)?o[o.length-1].children.push(t[s]):console.warn(`Trans: key ${s} not in props for interpolating ${e}`)}else o[o.length-1].children.push(n)}),o.length!==1&&console.warn(`Trans: stack not empty for interpolating ${e}`),o[0].children},nB=({i18nKey:e,children:t,...o})=>{let{t:n}=Ge();return Mp.createElement(Mp.Fragment,{},...oB(n(e),o))},no=nB;import{jsx as ke,jsxs as $t}from"react/jsx-runtime";var cB=async e=>{let n=Math.round(8),r=Math.max(Math.round(128/64),2),i=sB(e,6),a=document.createElement("canvas");a.width=i[0].length*128+(i[0].length+1)*(n*2)-n*2,a.height=i.length*128+(i.length+1)*(n*2)-n*2;let s=a.getContext("2d");s.fillStyle="#fff",s.fillRect(0,0,a.width,a.height);for(let[l,c]of e.entries()){let m=await Jr({elements:c.elements,files:null,maxWidthOrHeight:128}),{width:p,height:d}=m,u=Math.floor(l/6)*(128+n*2),h=l%6*(128+n*2);s.drawImage(m,h+(128-p)/2+n,u+(128-d)/2+n),s.lineWidth=r,s.strokeStyle="#ced4da",s.strokeRect(h+n/2,u+n/2,128+n,128+n)}return await tm(new File([await Bi(a)],"preview",{type:PT.png}),{outputType:PT.jpg,maxWidthOrHeight:5e3})},dB=({libItem:e,appState:t,index:o,onChange:n,onRemove:r})=>{let i=MT(null),a=MT(null);return Tb(()=>{let s=i.current;s&&(async()=>{let l=await zs({elements:e.elements,appState:{...t,viewBackgroundColor:"#fff",exportBackground:!0},files:null,skipInliningFonts:!0});s.innerHTML=l.outerHTML})()},[e.elements,t]),$t("div",{className:"single-library-item",children:[e.status==="published"&&ke("span",{className:"single-library-item-status",children:f("labels.statusPublished")}),ke("div",{ref:i,className:"single-library-item__svg"}),ke(ne,{"aria-label":f("buttons.remove"),type:"button",icon:Fo,className:"single-library-item--remove",onClick:r.bind(null,e.id),title:f("buttons.remove")}),$t("div",{style:{display:"flex",margin:"0.8rem 0",width:"100%",fontSize:"14px",fontWeight:500,flexDirection:"column"},children:[$t("label",{style:{display:"flex",justifyContent:"space-between",flexDirection:"column"},children:[$t("div",{style:{padding:"0.5em 0"},children:[ke("span",{style:{fontWeight:500,color:"#868e96"},children:f("publishDialog.itemName")}),ke("span",{"aria-hidden":"true",className:"required",children:"*"})]}),ke("input",{type:"text",ref:a,style:{width:"80%",padding:"0.2rem"},defaultValue:e.name,placeholder:"Item name",onChange:s=>{n(s.target.value,o)}})]}),ke("span",{className:"error",children:e.error})]})]})},mB=({onClose:e,libraryItems:t,appState:o,onSuccess:n,onError:r,updateItemsInStorage:i,onRemove:a})=>{let[s,l]=vb({authorName:"",githubHandle:"",name:"",description:"",twitterHandle:"",website:""}),[c,m]=vb(!1);Tb(()=>{let y=Yo.get(Ib.PUBLISH_LIBRARY);y&&l(y)},[]);let[p,d]=vb(t.slice());Tb(()=>{d(t.slice())},[t]);let u=y=>{l({...s,[y.target.name]:y.target.value})},h=async y=>{y.preventDefault(),m(!0);let v=[],I=!1;if(p.forEach(T=>{let M="";T.name||(M=f("publishDialog.errors.required"),I=!0),v.push({...T,error:M})}),I){d(v),m(!1);return}let k=await cB(p),L={type:iB.excalidrawLibrary,version:aB.excalidrawLibrary,source:lB(),libraryItems:p},S=JSON.stringify(L,null,2),_=new Blob([S],{type:"application/json"}),P=new FormData;P.append("excalidrawLib",_),P.append("previewImage",k),P.append("previewImageType",k.type),P.append("title",s.name),P.append("authorName",s.authorName),P.append("githubHandle",s.githubHandle),P.append("name",s.name),P.append("description",s.description),P.append("twitterHandle",s.twitterHandle),P.append("website",s.website),fetch(`${C.VITE_APP_LIBRARY_BACKEND}/submit`,{method:"post",body:P}).then(T=>T.ok?T.json().then(({url:M})=>{Yo.delete(Ib.PUBLISH_LIBRARY),n({url:M,authorName:s.authorName,items:p})}):T.json().catch(()=>{throw new Error(T.statusText||"something went wrong")}).then(M=>{throw new Error(M.message||T.statusText||"something went wrong")}),T=>{console.error(T),r(T),m(!1)}).catch(T=>{console.error(T),r(T),m(!1)})},g=()=>{let y=[];return p.forEach((v,I)=>{y.push(ke("div",{className:"single-library-item-wrapper",children:ke(dB,{libItem:v,appState:o,index:I,onChange:(k,L)=>{let S=p.slice();S[L].name=k,d(S)},onRemove:a})},I))}),ke("div",{className:"selected-library-items",children:y})},E=rB(()=>{i(p),Yo.set(Ib.PUBLISH_LIBRARY,s),e()},[p,e,i,s]),w=!!t.length,x=t.some(y=>y.status==="published");return ke(ht,{onCloseRequest:E,title:f("publishDialog.title"),className:"publish-library",children:w?$t("form",{onSubmit:h,children:[ke("div",{className:"publish-library-note",children:ke(no,{i18nKey:"publishDialog.noteDescription",link:y=>ke("a",{href:"https://libraries.excalidraw.com",target:"_blank",rel:"noopener",children:y})})}),ke("span",{className:"publish-library-note",children:ke(no,{i18nKey:"publishDialog.noteGuidelines",link:y=>ke("a",{href:"https://github.com/excalidraw/excalidraw-libraries#guidelines",target:"_blank",rel:"noopener noreferrer",children:y})})}),ke("div",{className:"publish-library-note",children:f("publishDialog.noteItems")}),x&&ke("span",{className:"publish-library-note publish-library-warning",children:f("publishDialog.republishWarning")}),g(),$t("div",{className:"publish-library__fields",children:[$t("label",{children:[$t("div",{children:[ke("span",{children:f("publishDialog.libraryName")}),ke("span",{"aria-hidden":"true",className:"required",children:"*"})]}),ke("input",{type:"text",name:"name",required:!0,value:s.name,onChange:u,placeholder:f("publishDialog.placeholder.libraryName")})]}),$t("label",{style:{alignItems:"flex-start"},children:[$t("div",{children:[ke("span",{children:f("publishDialog.libraryDesc")}),ke("span",{"aria-hidden":"true",className:"required",children:"*"})]}),ke("textarea",{name:"description",rows:4,required:!0,value:s.description,onChange:u,placeholder:f("publishDialog.placeholder.libraryDesc")})]}),$t("label",{children:[$t("div",{children:[ke("span",{children:f("publishDialog.authorName")}),ke("span",{"aria-hidden":"true",className:"required",children:"*"})]}),ke("input",{type:"text",name:"authorName",required:!0,value:s.authorName,onChange:u,placeholder:f("publishDialog.placeholder.authorName")})]}),$t("label",{children:[ke("span",{children:f("publishDialog.githubUsername")}),ke("input",{type:"text",name:"githubHandle",value:s.githubHandle,onChange:u,placeholder:f("publishDialog.placeholder.githubHandle")})]}),$t("label",{children:[ke("span",{children:f("publishDialog.twitterUsername")}),ke("input",{type:"text",name:"twitterHandle",value:s.twitterHandle,onChange:u,placeholder:f("publishDialog.placeholder.twitterHandle")})]}),$t("label",{children:[ke("span",{children:f("publishDialog.website")}),ke("input",{type:"text",name:"website",pattern:"https?://.+",title:f("publishDialog.errors.website"),value:s.website,onChange:u,placeholder:f("publishDialog.placeholder.website")})]}),ke("span",{className:"publish-library-note",children:ke(no,{i18nKey:"publishDialog.noteLicense",link:y=>ke("a",{href:"https://github.com/excalidraw/excalidraw-libraries/blob/main/LICENSE",target:"_blank",rel:"noopener noreferrer",children:y})})})]}),$t("div",{className:"publish-library__buttons",children:[ke(br,{label:f("buttons.saveLibNames"),onClick:E,"data-testid":"cancel-clear-canvas-button"}),ke(br,{type:"submit",label:f("buttons.submit"),actionType:"primary",isLoading:c})]})]}):ke("p",{style:{padding:"1em",textAlign:"center",fontWeight:500},children:f("publishDialog.atleastOneLibItem")})})},AT=mB;import eC from"react";import{DropdownMenu as OB}from"radix-ui";import{CLASSES as zB}from"@orangecatai/common";import gB from"clsx";import{useCallback as hB,useEffect as fB,useRef as bB}from"react";import{CLASSES as xB,EVENT as RT,KEYS as EB}from"@orangecatai/common";import{DropdownMenu as yB}from"radix-ui";import{forwardRef as LT}from"react";import _T from"clsx";import{jsx as DT}from"react/jsx-runtime";var pB=LT(({children:e,gap:t,align:o,justifyContent:n,className:r,style:i},a)=>DT("div",{className:_T("Stack Stack_horizontal",r),style:{"--gap":t,alignItems:o,justifyContent:n,...i},ref:a,children:e})),uB=LT(({children:e,gap:t,align:o,justifyContent:n,className:r,style:i},a)=>DT("div",{className:_T("Stack Stack_vertical",r),style:{"--gap":t,justifyItems:o,justifyContent:n,...i},ref:a,children:e})),Dt={Row:pB,Col:uB};import{jsx as Pp}from"react/jsx-runtime";var NT=({children:e,onClickOutside:t,className:o="",onSelect:n,open:r=!0,align:i="end",style:a})=>{let s=we(),l=bB(null),c=Fr({onClickOutside:t});cs(l,hB(p=>{l.current?.closest(`.${xB.DROPDOWN_MENU_EVENT_WRAPPER}`)?.contains(p.target)||c.onClickOutside?.()},[c])),fB(()=>{if(!r)return;let p=u=>{u.key===EB.ESCAPE&&(u.stopImmediatePropagation(),c.onClickOutside?.())},d={capture:!0};return document.addEventListener(RT.KEYDOWN,p,d),()=>{document.removeEventListener(RT.KEYDOWN,p,d)}},[c,r]);let m=gB(`dropdown-menu ${o}`,{"dropdown-menu--mobile":s.formFactor==="phone"}).trim();return Pp(qh.Provider,{value:{onSelect:n},children:Pp(yB.Content,{ref:l,className:m,style:a,"data-testid":"dropdown-menu",align:i,sideOffset:8,onCloseAutoFocus:p=>p.preventDefault(),children:s.formFactor==="phone"?Pp(Dt.Col,{className:"dropdown-menu-container",children:e}):Pp(ut,{className:"dropdown-menu-container",padding:2,children:e})})})};NT.displayName="DropdownMenuContent";var BT=NT;import{jsx as vB}from"react/jsx-runtime";var wB=({children:e,className:t="",selected:o,...n})=>vB("div",{...n,className:`dropdown-menu-item-base dropdown-menu-item-custom ${t} ${o?"dropdown-menu-item--selected":""}`.trim(),children:e}),FT=wB;import{DropdownMenu as IB}from"radix-ui";import{jsx as Cb}from"react/jsx-runtime";var OT=({icon:e,shortcut:t,href:o,children:n,onSelect:r,className:i="",selected:a,rel:s="noopener",...l})=>{let c=Nm(r);return Cb(IB.Item,{className:"radix-menu-item",onSelect:c,asChild:!0,children:Cb("a",{...l,href:o,target:"_blank",rel:`noopener ${s}`,className:Wr(i,a),title:l.title??l["aria-label"],children:Cb(Yr,{icon:e,shortcut:t,children:n})})})},Ys=OT;OT.displayName="DropdownMenuItemLink";import{jsx as TB}from"react/jsx-runtime";var zT=()=>TB("div",{style:{height:"1px",backgroundColor:"var(--default-border-color)",margin:"6px 0",flex:"0 0 auto"}}),HT=zT;zT.displayName="DropdownMenuSeparator";import{DropdownMenu as LB}from"radix-ui";import CB from"clsx";import{DropdownMenu as kB}from"radix-ui";import{useCallback as SB,useState as GT}from"react";import{jsx as Sb}from"react/jsx-runtime";var kb=-4,MB=4,UT=({children:e,className:t})=>{let o=we(),n=CB(`dropdown-menu dropdown-submenu ${t}`,{"dropdown-menu--mobile":o.formFactor==="phone"}).trim(),r=SB(c=>{if(c){let p=c.closest(".dropdown-menu-container")?.getBoundingClientRect();if(p){let d=c.getBoundingClientRect().width,h=window.innerWidth-p.right;h<d+20&&(a(h-d+kb),l(kb+8))}}},[]),[i,a]=GT(MB),[s,l]=GT(kb);return Sb(kB.SubContent,{className:n,sideOffset:i,alignOffset:s,collisionPadding:8,ref:r,children:o.formFactor==="phone"?Sb(Dt.Col,{className:"dropdown-menu-container",children:e}):Sb(ut,{className:"dropdown-menu-container",padding:2,style:{zIndex:1},children:e})})},WT=UT;UT.displayName="DropdownMenuSubContent";import{DropdownMenu as PB}from"radix-ui";import{jsx as YT,jsxs as AB}from"react/jsx-runtime";var VT=({children:e,icon:t,shortcut:o,className:n})=>AB(PB.SubTrigger,{className:`${Wr(n)} dropdown-menu__submenu-trigger`,children:[YT(Yr,{icon:t,shortcut:o,children:e}),YT("div",{className:"dropdown-menu__submenu-trigger-icon",children:Qw})]}),$T=VT;VT.displayName="DropdownMenuSubTrigger";import KT from"react";var Ap=e=>t=>{let o=KT.Children.toArray(t).find(n=>KT.isValidElement(n)&&typeof n.type!="string"&&n?.type.displayName&&n.type.displayName===e);return o||null},XT=Ap("DropdownMenuTrigger"),ZT=Ap("DropdownMenuContent"),jT=Ap("DropdownMenuSubTrigger"),qT=Ap("DropdownMenuSubContent");import{jsxs as _B}from"react/jsx-runtime";var Lp=({children:e})=>{let t=jT(e),o=qT(e);return _B(LB.Sub,{children:[t,o]})};Lp.Trigger=$T;Lp.Content=WT;Lp.displayName="DropdownMenuSub";var ei=Lp;import DB from"clsx";import{DropdownMenu as RB}from"radix-ui";import{jsx as NB}from"react/jsx-runtime";var JT=({className:e="",children:t,onToggle:o,title:n,...r})=>{let i=we(),a=DB(`dropdown-menu-button ${e}`,"zen-mode-transition",{"dropdown-menu-button--mobile":i.formFactor==="phone"}).trim();return NB(RB.Trigger,{className:a,onClick:o,type:"button","data-testid":"dropdown-menu-button",title:n,...r,children:t})},QT=JT;JT.displayName="DropdownMenuTrigger";import{jsx as FB}from"react/jsx-runtime";var BB=e=>FB(Jt,{...e,icon:e.checked?cm:Jw}),xr=BB;import{jsx as GB,jsxs as HB}from"react/jsx-runtime";var hn=({children:e,open:t})=>{let o=XT(e),n=ZT(e),r=n&&eC.isValidElement(n)?eC.cloneElement(n,{open:t}):n;return GB(OB.Root,{open:t,modal:!1,children:HB("div",{className:zB.DROPDOWN_MENU_EVENT_WRAPPER,style:{display:"contents"},children:[o,r]})})};hn.Trigger=QT;hn.Content=BT;hn.Item=Jt;hn.ItemCheckbox=xr;hn.ItemLink=Ys;hn.ItemCustom=FT;hn.Group=dc;hn.Separator=HT;hn.Sub=ei;var he=hn;hn.displayName="DropdownMenu";import{jsx as go,jsxs as _p}from"react/jsx-runtime";var VB=(e,t)=>e.filter(o=>t.includes(o.id)),$B=({setAppState:e,selectedItems:t,library:o,onRemoveFromLibrary:n,resetLibrary:r,onSelectItems:i,appState:a,className:s})=>{let[l]=ae(fr),[c,m]=ae(Ws),p=()=>{let P=t.length?f("alerts.removeItemsFromsLibrary",{count:t.length}):f("alerts.resetLibrary"),T=t.length?f("confirmDialog.removeItemsFromLib"):f("confirmDialog.resetLibrary");return go(Sp,{onConfirm:()=>{t.length?n():r(),u(!1)},onCancel:()=>{u(!1)},title:T,children:go("p",{children:P})})},[d,u]=Mb(!1),h=!!t.length,g=h?l.libraryItems.filter(P=>t.includes(P.id)):l.libraryItems,E=h?f("buttons.remove"):f("buttons.resetLibrary"),[w,x]=Mb(!1),[y,v]=Mb(null),I=WB(()=>_p(ht,{onCloseRequest:()=>v(null),title:f("publishSuccessDialog.title"),className:"publish-library-success",size:"small",children:[go("p",{children:go(no,{i18nKey:"publishSuccessDialog.content",authorName:y.authorName,link:P=>go("a",{href:y?.url,target:"_blank",rel:"noopener noreferrer",children:P})})}),go(ne,{type:"button",title:f("buttons.close"),"aria-label":f("buttons.close"),label:f("buttons.close"),onClick:()=>v(null),"data-testid":"publish-library-success-close",className:"publish-library-success-close"})]}),[v,y]),k=(P,T)=>{x(!1),v({url:P.url,authorName:P.authorName});let M=T.slice();M.forEach(N=>{t.includes(N.id)&&(N.status="published")}),o.setLibrary(M)},L=async()=>{try{await o.updateLibrary({libraryItems:Xd({description:"Excalidraw library files"}),merge:!0,openLibraryMenu:!0})}catch(P){if(P?.name==="AbortError"){console.warn(P);return}e({errorMessage:f("errors.importLibraryError")})}},S=async()=>{let P=h?g:await o.getLatestLibrary();GE(P).catch(YB).catch(T=>{e({errorMessage:T.message})})},_=()=>_p(he,{open:c,children:[go(he.Trigger,{onToggle:()=>m(!c),children:dy}),_p(he.Content,{onClickOutside:()=>m(!1),onSelect:()=>m(!1),className:"library-menu",children:[!h&&go(he.Item,{onSelect:L,icon:qa,"data-testid":"lib-dropdown--load",children:f("buttons.load")}),!!g.length&&go(he.Item,{onSelect:S,icon:zi,"data-testid":"lib-dropdown--export",children:f("buttons.export")}),h&&go(he.Item,{icon:xw,onSelect:()=>x(!0),"data-testid":"lib-dropdown--remove",children:f("buttons.publishLibrary")}),!!g.length&&go(he.Item,{onSelect:()=>u(!0),icon:Ht,children:E})]})]});return _p("div",{className:UB("library-menu-dropdown-container",s),children:[_(),t.length>0&&go("div",{className:"library-actions-counter",children:t.length}),d&&p(),w&&go(AT,{onClose:()=>x(!1),libraryItems:VB(l.libraryItems,t),appState:a,onSuccess:P=>k(P,l.libraryItems),onError:P=>window.alert(P),updateItemsInStorage:()=>o.setLibrary(l.libraryItems),onRemove:P=>i(t.filter(T=>T!==P))}),y&&I()]})},tC=({selectedItems:e,onSelectItems:t,className:o})=>{let{library:n}=Qe(),{clearLibraryCache:r,deleteItemsFromLibraryCache:i}=Hs(),a=ye(),s=ve(),[l]=ae(fr),c=async p=>{let d=p.filter(u=>!e.includes(u.id));n.setLibrary(d).catch(()=>{s({errorMessage:f("alerts.errorRemovingFromLibrary")})}),i(e),t([])};return go($B,{appState:a,setAppState:s,selectedItems:e,onSelectItems:t,library:n,onRemoveFromLibrary:()=>c(l.libraryItems),resetLibrary:()=>{n.resetLibrary(),r()},className:o})};import{memo as eF,useEffect as tF,useState as oF}from"react";import KB,{useCallback as XB}from"react";function ZB(){return[!1,XB(t=>t(),[])]}var oC=KB.useTransition||ZB;import nC from"clsx";import{memo as jB,useRef as qB,useState as JB}from"react";import{jsx as Dp,jsxs as QB}from"react/jsx-runtime";var rC=jB(({id:e,elements:t,isPending:o,onClick:n,selected:r,onToggle:i,onDrag:a,svgCache:s})=>{let l=qB(null),c=wp(e,t,s,l),[m,p]=JB(!1),d=we().formFactor==="phone",u=o&&Dp("div",{className:"library-unit__adder",children:cy});return QB("div",{className:nC("library-unit",{"library-unit__active":t,"library-unit--hover":t&&m,"library-unit--selected":r,"library-unit--skeleton":!c}),onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:[Dp("div",{className:nC("library-unit__dragger",{"library-unit__pulse":!!o}),ref:l,draggable:!!t,onClick:t||o?h=>{e&&h.shiftKey?i(e,h):n(e)}:void 0,onDragStart:h=>{if(!e){h.preventDefault();return}p(!1),a(e,h)}}),u,e&&t&&(m||d||r)&&Dp(bc,{checked:r,onChange:(h,g)=>i(e,g),className:"library-unit__checkbox"})]})}),iC=()=>Dp("div",{className:"library-unit library-unit--skeleton"});import{Fragment as nF,jsx as Rp}from"react/jsx-runtime";var Np=({children:e})=>Rp("div",{className:"library-menu-items-container__grid",children:e}),Oc=eF(({items:e,onItemSelectToggle:t,onItemDrag:o,isItemSelected:n,onClick:r,svgCache:i,itemsRenderedPerBatch:a})=>{let[,s]=oC(),[l,c]=oF(0);return tF(()=>{l<e.length&&s(()=>{c(l+a)})},[l,e.length,s,a]),Rp(nF,{children:e.map((m,p)=>p<l?Rp(rC,{elements:m?.elements,isPending:!m?.id&&!!m?.elements,onClick:r,svgCache:i,id:m?.id,selected:n(m.id),onToggle:t,onDrag:o},m?.id??p):Rp(iC,{},p))})});import Pb from"clsx";import{forwardRef as sF,useRef as lF,useImperativeHandle as cF,useLayoutEffect as dF,useState as mF}from"react";import rF from"clsx";import{composeEventHandlers as iF}from"@orangecatai/common";import{jsx as aF}from"react/jsx-runtime";var ro=({type:e="button",onSelect:t,selected:o,children:n,className:r="",...i})=>aF("button",{onClick:iF(i.onClick,a=>{t()}),type:e,className:rF("excalidraw-button",r,{selected:o}),...i,children:n});import{jsx as Ab,jsxs as aC}from"react/jsx-runtime";var ti=sF(({onChange:e,label:t,fullWidth:o,placeholder:n,readonly:r,selectOnRender:i,onKeyDown:a,isRedacted:s=!1,icon:l,className:c,type:m,...p},d)=>{let u=lF(null);cF(d,()=>u.current),dF(()=>{i&&(u.current?.focus(),u.current?.select())},[i]);let[h,g]=mF(!1);return aC("div",{className:Pb("ExcTextField",c,{"ExcTextField--fullWidth":o,"ExcTextField--hasIcon":!!l}),onClick:()=>{u.current?.focus()},children:[l,t&&Ab("div",{className:"ExcTextField__label",children:t}),aC("div",{className:Pb("ExcTextField__input",{"ExcTextField__input--readonly":r}),children:[Ab("input",{className:Pb({"is-redacted":"value"in p&&p.value&&s&&!h}),readOnly:r,value:"value"in p?p.value:void 0,defaultValue:"defaultValue"in p?p.defaultValue:void 0,placeholder:n,ref:u,onChange:E=>e?.(E.target.value),onKeyDown:a,type:m}),s&&Ab(ro,{onSelect:()=>g(!h),style:{border:0,userSelect:"none"},children:h?Sw:ts})]})]})});import{Fragment as cC,jsx as Rt,jsxs as Hn}from"react/jsx-runtime";var bF=17,xF=64;function Db({isLoading:e,libraryItems:t,onAddToLibrary:o,onInsertLibraryItems:n,pendingElements:r,theme:i,id:a,libraryReturnUrl:s,onSelectItems:l,selectedItems:c}){let m=we(),p=sC(null),d=TT(p);Lb(()=>{d>0&&p.current?.scrollTo(0,d)},[]);let{svgCache:u}=Hs(),[h,g]=lC(null),[E,w]=lC(""),x=!t.length&&!r.length,y=!x&&!!E.trim(),v=_b(()=>{let D=Ji(E.trim().toLowerCase());return D?t.filter(F=>{let z=F.name||"";return z.trim()&&Ji(z.toLowerCase()).includes(D)}):[]},[t,E]),I=_b(()=>t.filter(D=>D.status!=="published"),[t]),k=_b(()=>t.filter(D=>D.status==="published"),[t]),L=Vs((D,F)=>{let z=!c.includes(D),$=[...I,...k];if(z){if(F.shiftKey&&h){let V=$.findIndex(De=>De.id===h),Q=$.findIndex(De=>De.id===D);if(V===-1||Q===-1){l([...c,D]);return}let ee=uF(c),ie=Math.min(V,Q),Ee=Math.max(V,Q),Le=$.reduce((De,We,lt)=>((lt>=ie&&lt<=Ee||ee.has(We.id))&&De.push(We.id),De),[]);l(Le)}else l([...c,D]);g(D)}else g(null),l(c.filter(V=>V!==D))},[h,l,k,c,I]);Lb(()=>{c.length||g(null)},[c]);let S=Vs(D=>{let F;return c.includes(D)?F=t.filter(z=>c.includes(z.id)):F=t.filter(z=>z.id===D),F.map(z=>({...z,elements:hF({type:"everything",elements:z.elements,randomizeSeed:!0}).duplicatedElements}))},[t,c]),_=Vs((D,F)=>{let z={itemIds:c.includes(D)?c:[D]};F.dataTransfer.setData(pF.excalidrawlibIds,JSON.stringify(z))},[c]),P=Vs(D=>D?c.includes(D):!1,[c]),T=Vs(()=>{o(r)},[r,o]),M=Vs(D=>{D&&n(S(D))},[S,n]),N=u.size>=(v.length?v:t).length?xF:bF,O=sC(null);Lb(()=>{gF(()=>{O.current?.focus()})},[]);let B=!y&&Hn(cC,{children:[!x&&Rt("div",{className:"library-menu-items-container__header",children:f("labels.personalLib")}),!r.length&&!I.length?Hn("div",{className:"library-menu-items__no-items",children:[!k.length&&Rt("div",{className:"library-menu-items__no-items__label",children:f("library.noItems")}),Rt("div",{className:"library-menu-items__no-items__hint",children:k.length>0?f("library.hint_emptyPrivateLibrary"):f("library.hint_emptyLibrary")})]}):Hn(Np,{children:[r.length>0&&Rt(Oc,{itemsRenderedPerBatch:N,items:[{id:null,elements:r}],onItemSelectToggle:L,onItemDrag:_,onClick:T,isItemSelected:P,svgCache:u}),Rt(Oc,{itemsRenderedPerBatch:N,items:I,onItemSelectToggle:L,onItemDrag:_,onClick:M,isItemSelected:P,svgCache:u})]}),k.length>0&&Rt("div",{className:"library-menu-items-container__header",style:{marginTop:"0.75rem"},children:f("labels.excalidrawLib")}),k.length>0&&Rt(Np,{children:Rt(Oc,{itemsRenderedPerBatch:N,items:k,onItemSelectToggle:L,onItemDrag:_,onClick:M,isItemSelected:P,svgCache:u})})]}),U=y&&Hn(cC,{children:[Hn("div",{className:"library-menu-items-container__header",children:[f("library.search.heading"),!e&&Hn("div",{className:"library-menu-items-container__header__hint",style:{cursor:"pointer"},onPointerDown:D=>D.preventDefault(),onClick:D=>{w("")},children:[Rt("kbd",{children:"esc"})," to clear"]})]}),v.length>0?Rt(Np,{children:Rt(Oc,{itemsRenderedPerBatch:N,items:v,onItemSelectToggle:L,onItemDrag:_,onClick:M,isItemSelected:P,svgCache:u})}):Hn("div",{className:"library-menu-items__no-items",children:[Rt("div",{className:"library-menu-items__no-items__hint",children:f("library.search.noResults")}),Rt(ro,{onPointerDown:D=>D.preventDefault(),onSelect:()=>{w("")},style:{width:"auto",marginTop:"1rem"},children:f("library.search.clearSearch")})]})]});return Hn("div",{className:"library-menu-items-container",style:r.length||I.length||k.length?{justifyContent:"flex-start"}:{borderBottom:0},children:[Hn("div",{className:"library-menu-items-header",children:[!x&&Rt(ti,{ref:O,type:"search",className:fF("library-menu-items-container__search",{hideCancelButton:m.formFactor!=="phone"}),placeholder:f("library.search.inputPlaceholder"),value:E,onChange:D=>w(D)}),Rt(tC,{selectedItems:c,onSelectItems:l,className:"library-menu-dropdown-container--in-heading"})]}),Hn(Dt.Col,{className:"library-menu-items-container__items",align:"start",gap:1,style:{flex:k.length>0?1:"0 1 auto",margin:x?"auto":0},ref:p,children:[e&&Rt("div",{style:{position:"absolute",top:"var(--container-padding-y)",right:"var(--container-padding-x)",transform:"translateY(50%)"},children:Rt(Gt,{})}),B,U,x&&Rt(Cp,{style:{padding:"16px 0",width:"100%"},id:a,libraryReturnUrl:s,theme:i})]})]})}import{jsx as oi,jsxs as pC}from"react/jsx-runtime";var Ws=Ce(!1),mC=({children:e})=>oi("div",{className:"layer-ui__library",children:e}),SF=hC(({onInsertLibraryItems:e,pendingElements:t,onAddToLibrary:o,setAppState:n,libraryReturnUrl:r,library:i,id:a,theme:s,selectedItems:l,onSelectItems:c})=>{let[m]=ae(fr),p=Nb(h=>{(async(E,w)=>{ge("element","addToLibrary","ui");for(let y of yF)if(E.some(v=>v.type===y))return n({errorMessage:f(`errors.libraryElementTypeError.${y}`)});let x=[{status:"unpublished",elements:E,id:wF(),created:Date.now()},...w];o(),i.setLibrary(x).catch(()=>{n({errorMessage:f("alerts.errorAddingToLibrary")})})})(h,m.libraryItems)},[o,i,n,m.libraryItems]),d=gC(()=>m.libraryItems,[m]);if(m.status==="loading"&&!m.isInitialized)return oi(mC,{children:oi("div",{className:"layer-ui__library-message",children:pC("div",{children:[oi(Gt,{size:"2em"}),oi("span",{children:f("labels.libraryLoadingMessage")})]})})});let u=m.libraryItems.length>0||t.length>0;return pC(mC,{children:[oi(Db,{isLoading:m.status==="loading",libraryItems:d,onAddToLibrary:p,onInsertLibraryItems:e,pendingElements:t,id:a,libraryReturnUrl:r,theme:s,onSelectItems:c,selectedItems:l}),u&&oi(Cp,{className:"library-menu-control-buttons--at-bottom",style:{padding:"16px 12px 0 12px"},id:a,libraryReturnUrl:r,theme:s})]})}),Rb=(e,t)=>({elements:e,pending:le(e,{selectedElementIds:t},{includeBoundTextElement:!0,includeElementsInFrames:!0}),selectedElementIds:t}),MF=(e,t)=>{let o=Hr(),[n,r]=uC(()=>Rb(o,e.selectedElementIds)),i=EF(new Map);return Bb(()=>{for(let a of n.pending)i.current.set(a.id,a.version)},[n.pending]),Bb(()=>{t.state.cursorButton==="up"&&t.state.activeTool.type==="selection"&&r(a=>{if(!vF(a.selectedElementIds,e.selectedElementIds))return i.current.clear(),Rb(o,e.selectedElementIds);let s=t.scene.getNonDeletedElementsMap();for(let l of Object.keys(e.selectedElementIds)){let c=s.get(l)?.version;if(c&&c!==i.current.get(l))return Rb(o,e.selectedElementIds)}return a})},[t,t.state.cursorButton,t.state.activeTool.type,e.selectedElementIds,o]),n.pending},fC=hC(()=>{let e=Qe(),{onInsertElements:t}=e,o=Nn(),n=ye(),r=ve(),[i,a]=uC([]),s=gC(()=>e.library,[e.library]),l=MF(n,e);Bb(()=>CF(document,kF.KEYDOWN,p=>{if(p.key===IF.ESCAPE&&p.target instanceof HTMLElement){let d=p.target;if(d.closest(`.${dC.SIDEBAR}`))i.length>0?(p.stopPropagation(),a([])):TF(d)&&d instanceof HTMLInputElement&&!d.value&&(p.stopPropagation(),r({openSidebar:null}),e.focusContainer());else if(i.length>0){let{x:u,y:h}=e.lastViewportPosition;document.elementFromPoint(u,h)?.closest(`.${dC.SIDEBAR}`)&&(p.stopPropagation(),a([]))}}},{capture:!0}),[i,r,e]);let c=Nb(p=>{t(Us(p)),e.focusContainer()},[t,e]),m=Nb(()=>{r({selectedElementIds:{},selectedGroupIds:{},activeEmbeddable:null})},[r]);return oi(SF,{pendingElements:l,onInsertLibraryItems:c,onAddToLibrary:m,setAppState:r,libraryReturnUrl:o.libraryReturnUrl,library:s,id:e.id,theme:n.theme,selectedItems:i,onSelectItems:a})});import PF from"clsx";import{useRef as AF}from"react";import{createPortal as LF}from"react-dom";import{KEYS as _F}from"@orangecatai/common";import{jsx as bC,jsxs as DF}from"react/jsx-runtime";var xC=e=>{let{closeOnClickOutside:t=!0}=e,o=km({className:"excalidraw-modal-container"}),n=AF(document.body.classList.contains("excalidraw-animations-disabled"));if(!o)return null;let r=i=>{i.key===_F.ESCAPE&&(i.nativeEvent.stopImmediatePropagation(),i.stopPropagation(),e.onCloseRequest())};return LF(DF("div",{className:PF("Modal",e.className,{"animations-disabled":n.current}),role:"dialog","aria-modal":"true",onKeyDown:r,"aria-labelledby":e.labelledBy,children:[bC("div",{className:"Modal__background",onClick:t?e.onCloseRequest:void 0}),bC("div",{className:"Modal__content",style:{"--max-width":`${e.maxWidth}px`},tabIndex:0,children:e.children})]}),o)};import{jsx as zc,jsxs as zF}from"react/jsx-runtime";function OF(e){if(e&&typeof e=="number")return e;switch(e){case"small":return 550;case"wide":return 1024;case"regular":default:return 800}}var ht=e=>{let[t,o]=dT(),[n]=BF(document.activeElement),{id:r}=qe(),i=we().formFactor==="phone";NF(()=>{if(!t)return;let c=EC(t);setTimeout(()=>{c.length>0&&e.autofocus!==!1&&(c[1]||c[0]).focus()});let m=p=>{if(p.key===FF.TAB){let d=EC(t),{activeElement:u}=document,h=d.findIndex(g=>g===u);h===0&&p.shiftKey?(d[d.length-1].focus(),p.preventDefault()):h===d.length-1&&!p.shiftKey&&(d[0].focus(),p.preventDefault())}};return t.addEventListener("keydown",m),()=>t.removeEventListener("keydown",m)},[t,e.autofocus]);let a=ve(),s=Pn(Ws),l=()=>{a({openMenu:null}),s(!1),n.focus(),e.onCloseRequest()};return zc(xC,{className:RF("Dialog",e.className,{"Dialog--fullscreen":i}),labelledBy:"dialog-title",maxWidth:OF(e.size),onCloseRequest:l,closeOnClickOutside:e.closeOnClickOutside,children:zF(ut,{ref:o,children:[e.title&&zc("h2",{id:`${r}-dialog-title`,className:"Dialog__title",children:zc("span",{className:"Dialog__titleContent",children:e.title})}),i&&zc("button",{className:"Dialog__close",onClick:l,title:f("buttons.close"),"aria-label":f("buttons.close"),type:"button",children:Fo}),zc("div",{className:"Dialog__content",children:e.children})]})})};import{KEYS as ct}from"@orangecatai/common";var Bp=[{icon:Ja,value:"hand",key:ct.H,numericKey:null,fillable:!1,toolbar:!0},{icon:Oi,value:"selection",key:ct.V,numericKey:ct[1],fillable:!0,toolbar:!0},{icon:Ya,value:"rectangle",key:ct.R,numericKey:ct[2],fillable:!0,toolbar:!0},{icon:Va,value:"diamond",key:ct.D,numericKey:ct[3],fillable:!0,toolbar:!0},{icon:$a,value:"ellipse",key:ct.O,numericKey:ct[4],fillable:!0,toolbar:!0},{icon:am,value:"arrow",key:ct.A,numericKey:ct[5],fillable:!0,toolbar:!0},{icon:Ka,value:"line",key:ct.L,numericKey:ct[6],fillable:!0,toolbar:!0},{icon:Ln,value:"freedraw",key:[ct.P,ct.X],numericKey:ct[7],fillable:!1,toolbar:!0},{icon:_n,value:"text",key:ct.T,numericKey:ct[8],fillable:!1,toolbar:!0},{icon:Xa,value:"image",key:null,numericKey:ct[9],fillable:!1,toolbar:!0},{icon:sm,value:"eraser",key:ct.E,numericKey:ct[0],fillable:!1,toolbar:!0},{icon:Rn,value:"laser",key:ct.K,numericKey:null,fillable:!1,toolbar:!1}],Fb=e=>e.state.preferredSelectionTool.type==="lasso"?[{value:"lasso",icon:Oi,key:ct.V,numericKey:ct[1],fillable:!0,toolbar:!0},...Bp.slice(1)]:Bp,yC=(e,t)=>Fb(t).find((n,r)=>n.numericKey!=null&&e===n.numericKey.toString()||n.key&&(typeof n.key=="string"?n.key===e:n.key.includes(e)))?.value||null;import Un from"clsx";import{useRef as XF,useState as ZF}from"react";import{Popover as ri}from"radix-ui";import{CLASSES as kC,KEYS as jF,capitalizeString as ni,isTransparent as Op}from"@orangecatai/common";import{shouldAllowVerticalAlign as SC,suppportsHorizontalAlign as MC,hasBoundTextElement as zp,isElbowArrow as Gb,isImageElement as PC,isLinearElement as Ub,isTextElement as Gp,isArrowElement as TC,hasStrokeColor as CC,toolIsArrow as Hp}from"@orangecatai/element";import{createIsolation as HF}from"jotai-scope";import Ob from"react";import Gn from"tunnel-rat";var zb=Ob.createContext(null),Xe=()=>Ob.useContext(zb),GF=HF(),wC=()=>Ob.useMemo(()=>({MainMenuTunnel:Gn(),WelcomeScreenMenuHintTunnel:Gn(),WelcomeScreenToolbarHintTunnel:Gn(),WelcomeScreenHelpHintTunnel:Gn(),WelcomeScreenCenterTunnel:Gn(),FooterCenterTunnel:Gn(),DefaultSidebarTriggerTunnel:Gn(),DefaultSidebarTabTriggersTunnel:Gn(),OverwriteConfirmDialogTunnel:Gn(),TTDDialogTriggerTunnel:Gn(),tunnelsJotai:GF}),[]);import{CODES as UF,KEYS as WF}from"@orangecatai/common";import{CaptureUpdateAction as YF}from"@orangecatai/element";var ea=W({name:"viewMode",label:"labels.viewMode",icon:ts,viewMode:!0,trackEvent:{category:"canvas",predicate:e=>!e.viewModeEnabled},perform(e,t){return{appState:{...t,viewModeEnabled:!this.checked(t)},captureUpdate:YF.EVENTUALLY}},checked:e=>e.viewModeEnabled,predicate:(e,t,o)=>typeof o.viewModeEnabled>"u",keyTest:e=>!e[WF.CTRL_OR_CMD]&&e.altKey&&e.code===UF.R});import{useEffect as VF,useState as $F}from"react";import vC from"clsx";import{capitalizeString as IC}from"@orangecatai/common";import{Popover as Hb}from"radix-ui";import{jsx as Fp,jsxs as KF}from"react/jsx-runtime";var $s=({app:e,options:t,activeTool:o,defaultOption:n,className:r="Shape",namePrefix:i,title:a,"data-testid":s,onToolChange:l,displayedOption:c,fillable:m=!1})=>{let[p,d]=$F(!1),u=o.type,h=c.type===u,g=32/2+10,{container:E}=qe();return!t.some(w=>w.type===u)&&p&&d(!1),VF(()=>{let w=e.onPointerDownEmitter.on(()=>{d(!1)});return()=>w?.()},[e]),KF(Hb.Root,{open:p,children:[Fp(Hb.Trigger,{asChild:!0,children:Fp(ne,{className:vC(r,{fillable:m,active:t.some(w=>w.type===o.type)}),type:"radio",icon:c.icon,checked:h,name:"editor-current-shape",title:a,"aria-label":a,"data-testid":s,onPointerDown:()=>{d(w=>!w),l(n)}})}),Fp(Hb.Content,{className:"tool-popover-content",sideOffset:g,collisionBoundary:E??void 0,children:t.map(({type:w,icon:x,title:y})=>Fp(ne,{className:vC(r,{active:u===w}),type:"radio",icon:x,checked:u===w,name:`${i}-option`,title:y||IC(w),keyBindingLabel:"","aria-label":y||IC(w),"data-testid":`toolbar-${w}`,onChange:()=>{e.state.activeTool.type!==w&&ge("toolbar",w,"ui"),e.setActiveTool({type:w}),l?.(w)}},w))})]})};import{Fragment as Lo,jsx as re,jsxs as Ie}from"react/jsx-runtime";var Wb=Un([kC.SHAPE_ACTIONS_THEME_SCOPE,"properties-content"]),Hc=(e,t)=>{let o=t[0]?.type||null;for(let n of t)if(n.type!==o){o=null;break}return CC(e.activeTool.type)&&o!=="image"&&o!=="frame"&&o!=="magicframe"||t.some(n=>CC(n.type))},Gc=(e,t)=>kn(e.activeTool.type)||t.some(o=>kn(o.type)),AC=({appState:e,elementsMap:t,renderAction:o,app:n})=>{let r=_a(t,e),i=!1;r.length===2&&(zp(r[0])||zp(r[1]))&&(i=!0);let a=!!(e.editingTextElement||e.newElement),s=we(),l=document.documentElement.getAttribute("dir")==="rtl",c=kn(e.activeTool.type)&&!Op(e.currentItemBackgroundColor)||r.some(h=>kn(h.type)&&!Op(h.backgroundColor)),m=r.length===1||i,p=!e.selectedLinearElement?.isEditing&&r.length===1&&Ub(r[0])&&!Gb(r[0]),d=!e.croppingElementId&&r.length===1&&PC(r[0]),u=!i&&oo(e,n);return Ie("div",{className:"selected-shape-actions",children:[re("div",{children:Hc(e,r)&&o("changeStrokeColor")}),Gc(e,r)&&re("div",{children:o("changeBackgroundColor")}),c&&o("changeFillStyle"),(Hl(e.activeTool.type)||r.some(h=>Hl(h.type)))&&o("changeStrokeWidth"),(e.activeTool.type==="freedraw"||r.some(h=>h.type==="freedraw"))&&o("changeStrokeShape"),(Gl(e.activeTool.type)||r.some(h=>Gl(h.type)))&&Ie(Lo,{children:[o("changeStrokeStyle"),o("changeSloppiness")]}),(Ul(e.activeTool.type)||r.some(h=>Ul(h.type)))&&re(Lo,{children:o("changeRoundness")}),(Hp(e.activeTool.type)||r.some(h=>Hp(h.type)))&&re(Lo,{children:o("changeArrowType")}),(e.activeTool.type==="text"||r.some(Gp))&&Ie(Lo,{children:[o("changeFontFamily"),o("changeFontSize"),(e.activeTool.type==="text"||MC(r,t))&&o("changeTextAlign")]}),SC(r,t)&&o("changeVerticalAlign"),(Da(e.activeTool.type)||r.some(h=>Da(h.type)))&&re(Lo,{children:o("changeArrowhead")}),o("changeOpacity"),Ie("fieldset",{children:[re("legend",{children:f("labels.layers")}),Ie("div",{className:"buttonList",children:[o("sendToBack"),o("sendBackward"),o("bringForward"),o("bringToFront")]})]}),u&&!i&&Ie("fieldset",{children:[re("legend",{children:f("labels.align")}),Ie("div",{className:"buttonList",children:[l?Ie(Lo,{children:[o("alignRight"),o("alignHorizontallyCentered"),o("alignLeft")]}):Ie(Lo,{children:[o("alignLeft"),o("alignHorizontallyCentered"),o("alignRight")]}),r.length>2&&o("distributeHorizontally"),re("div",{style:{flexBasis:"100%",height:0}}),Ie("div",{style:{display:"flex",flexWrap:"wrap",gap:".5rem",marginTop:"-0.5rem"},children:[o("alignTop"),o("alignVerticallyCentered"),o("alignBottom"),r.length>2&&o("distributeVertically")]})]})]}),!a&&r.length>0&&Ie("fieldset",{children:[re("legend",{children:f("labels.actions")}),Ie("div",{className:"buttonList",children:[s.formFactor!=="phone"&&o("duplicateSelection"),s.formFactor!=="phone"&&o("deleteSelectedElements"),o("group"),o("ungroup"),m&&o("hyperlink"),d&&o("cropEditor"),p&&o("toggleLinearEditor")]})]})]})},LC=({appState:e,renderAction:t,setAppState:o,targetElements:n,container:r})=>{let i=kn(e.activeTool.type)&&!Op(e.currentItemBackgroundColor)||n.some(l=>kn(l.type)&&!Op(l.backgroundColor)),a=n.length>0||e.activeTool.type!=="selection"&&e.activeTool.type!=="eraser"&&e.activeTool.type!=="hand"&&e.activeTool.type!=="laser"&&e.activeTool.type!=="lasso",s=e.openPopup==="compactStrokeStyles";return a?re("div",{className:"compact-action-item",children:Ie(ri.Root,{open:s,onOpenChange:l=>{o(l?{openPopup:"compactStrokeStyles"}:{openPopup:null})},children:[re(ri.Trigger,{asChild:!0,children:re("button",{type:"button",className:Un("compact-action-button properties-trigger",{active:s}),title:f("labels.stroke"),onClick:l=>{l.preventDefault(),l.stopPropagation(),o({openPopup:s?null:"compactStrokeStyles"})},children:Xw})}),s&&re(cr,{className:Wb,container:r,style:{maxWidth:"13rem"},onClose:()=>{},children:Ie("div",{className:"selected-shape-actions",children:[i&&t("changeFillStyle"),(Hl(e.activeTool.type)||n.some(l=>Hl(l.type)))&&t("changeStrokeWidth"),(Gl(e.activeTool.type)||n.some(l=>Gl(l.type)))&&Ie(Lo,{children:[t("changeStrokeStyle"),t("changeSloppiness")]}),(Ul(e.activeTool.type)||n.some(l=>Ul(l.type)))&&t("changeRoundness"),t("changeOpacity")]})})]})}):null},_C=({appState:e,renderAction:t,setAppState:o,targetElements:n,container:r,app:i})=>{let a=Hp(e.activeTool.type)||n.some(l=>Hp(l.type)),s=e.openPopup==="compactArrowProperties";return a?re("div",{className:"compact-action-item",children:Ie(ri.Root,{open:s,onOpenChange:l=>{o(l?{openPopup:"compactArrowProperties"}:{openPopup:null})},children:[re(ri.Trigger,{asChild:!0,children:re("button",{type:"button",className:Un("compact-action-button properties-trigger",{active:s}),title:f("labels.arrowtypes"),onClick:l=>{l.preventDefault(),l.stopPropagation(),o({openPopup:s?null:"compactArrowProperties"})},children:(()=>{let l=Yt(n,i,c=>TC(c)?c.elbowed?"elbow":c.roundness?"round":"sharp":null,c=>TC(c),c=>c?null:e.currentItemArrowType);return l==="elbow"?rs:l==="round"?is:ns})()})}),s&&re(cr,{container:r,className:"properties-content",style:{maxWidth:"13rem"},onClose:()=>{},children:t("changeArrowProperties")})]})}):null},DC=({appState:e,renderAction:t,setAppState:o,targetElements:n,container:r,elementsMap:i})=>{let{saveCaretPosition:a,restoreCaretPosition:s}=fv(),l=e.openPopup==="compactTextProperties";return re("div",{className:"compact-action-item",children:Ie(ri.Root,{open:l,onOpenChange:c=>{c?(e.editingTextElement&&a(),o({openPopup:"compactTextProperties"})):(o({openPopup:null}),e.editingTextElement&&s())},children:[re(ri.Trigger,{asChild:!0,children:re("button",{type:"button",className:Un("compact-action-button properties-trigger",{active:l}),title:f("labels.textAlign"),onClick:c=>{c.preventDefault(),c.stopPropagation(),l?o({openPopup:null}):(e.editingTextElement&&a(),o({openPopup:"compactTextProperties"}))},children:xy})}),e.openPopup==="compactTextProperties"&&re(cr,{className:Wb,container:r,style:{maxWidth:"13rem"},preventAutoFocusOnTouch:!!e.editingTextElement,onClose:()=>{e.editingTextElement&&s()},children:Ie("div",{className:"selected-shape-actions",children:[(e.activeTool.type==="text"||n.some(Gp))&&t("changeFontSize"),(e.activeTool.type==="text"||MC(n,i))&&t("changeTextAlign"),SC(n,i)&&t("changeVerticalAlign")]})})]})})},RC=({appState:e,renderAction:t,targetElements:o,setAppState:n,container:r,app:i,showDuplicate:a,showDelete:s})=>{let l=!!(e.editingTextElement||e.newElement),c=!e.croppingElementId&&o.length===1&&PC(o[0]),m=o.length===1,p=oo(e,i),d=!1;o.length===2&&(zp(o[0])||zp(o[1]))&&(d=!0);let u=document.documentElement.getAttribute("dir")==="rtl",h=e.openPopup==="compactOtherProperties";return l||o.length===0?null:re("div",{className:"compact-action-item",children:Ie(ri.Root,{open:h,onOpenChange:g=>{n(g?{openPopup:"compactOtherProperties"}:{openPopup:null})},children:[re(ri.Trigger,{asChild:!0,children:re("button",{type:"button",className:Un("compact-action-button properties-trigger",{active:h}),title:f("labels.actions"),onClick:g=>{g.preventDefault(),g.stopPropagation(),n({openPopup:h?null:"compactOtherProperties"})},children:my})}),h&&re(cr,{className:Wb,container:r,style:{maxWidth:"12rem",justifyContent:"center",alignItems:"center"},onClose:()=>{},children:Ie("div",{className:"selected-shape-actions",children:[Ie("fieldset",{children:[re("legend",{children:f("labels.layers")}),Ie("div",{className:"buttonList",children:[t("sendToBack"),t("sendBackward"),t("bringForward"),t("bringToFront")]})]}),p&&!d&&Ie("fieldset",{children:[re("legend",{children:f("labels.align")}),Ie("div",{className:"buttonList",children:[u?Ie(Lo,{children:[t("alignRight"),t("alignHorizontallyCentered"),t("alignLeft")]}):Ie(Lo,{children:[t("alignLeft"),t("alignHorizontallyCentered"),t("alignRight")]}),o.length>2&&t("distributeHorizontally"),re("div",{style:{flexBasis:"100%",height:0}}),Ie("div",{style:{display:"flex",flexWrap:"wrap",gap:".5rem",marginTop:"-0.5rem"},children:[t("alignTop"),t("alignVerticallyCentered"),t("alignBottom"),o.length>2&&t("distributeVertically")]})]})]}),Ie("fieldset",{children:[re("legend",{children:f("labels.actions")}),Ie("div",{className:"buttonList",children:[t("group"),t("ungroup"),m&&t("hyperlink"),c&&t("cropEditor"),a&&t("duplicateSelection"),s&&t("deleteSelectedElements")]})]})]})})]})})},qF=({appState:e,renderAction:t,targetElements:o})=>!e.selectedLinearElement?.isEditing&&o.length===1&&Ub(o[0])&&!Gb(o[0])?re("div",{className:"compact-action-item",children:t("toggleLinearEditor")}):null,NC=({appState:e,elementsMap:t,renderAction:o,app:n,setAppState:r})=>{let i=_a(t,e),{container:a}=qe(),s=!!(e.editingTextElement||e.newElement),l=!e.selectedLinearElement?.isEditing&&i.length===1&&Ub(i[0])&&!Gb(i[0]);return Ie("div",{className:"compact-shape-actions",children:[Hc(e,i)&&re("div",{className:Un("compact-action-item"),children:o("changeStrokeColor")}),Gc(e,i)&&re("div",{className:"compact-action-item",children:o("changeBackgroundColor")}),re(LC,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a}),re(_C,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a,app:n}),l&&re("div",{className:"compact-action-item",children:o("toggleLinearEditor")}),(e.activeTool.type==="text"||i.some(Gp))&&Ie(Lo,{children:[re("div",{className:"compact-action-item",children:o("changeFontFamily")}),re(DC,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a,elementsMap:t})]}),!s&&i.length>0&&re("div",{className:"compact-action-item",children:o("duplicateSelection")}),!s&&i.length>0&&re("div",{className:"compact-action-item",children:o("deleteSelectedElements")}),re(RC,{appState:e,renderAction:o,targetElements:i,setAppState:r,container:a,app:n})]})},BC=({appState:e,elementsMap:t,renderAction:o,app:n,setAppState:r})=>{let i=_a(t,e),{container:a}=qe(),s=XF(null),l=s.current?.getBoundingClientRect()?.width??0,c=9,m=6,p=32,d=c*p+(c-1)*m,u=p+m,h=l>=d+u,g=l>=d+2*u;return Ie(ut,{className:"compact-shape-actions mobile-shape-actions",style:{flexDirection:"row",boxShadow:"none",padding:0,zIndex:2,backgroundColor:"transparent",height:p*1.35,marginBottom:4,alignItems:"center",gap:m,pointerEvents:"none"},ref:s,children:[Ie("div",{style:{display:"flex",flexDirection:"row",gap:m,flex:1},children:[Hc(e,i)&&re("div",{className:Un("compact-action-item"),children:o("changeStrokeColor")}),Gc(e,i)&&re("div",{className:"compact-action-item",children:o("changeBackgroundColor")}),re(LC,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a}),re(_C,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a,app:n}),re(qF,{appState:e,renderAction:o,targetElements:i}),(e.activeTool.type==="text"||i.some(Gp))&&Ie(Lo,{children:[re("div",{className:"compact-action-item",children:o("changeFontFamily")}),re(DC,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a,elementsMap:t})]}),re(RC,{appState:e,renderAction:o,targetElements:i,setAppState:r,container:a,app:n,showDuplicate:!g,showDelete:!h})]}),Ie("div",{style:{display:"flex",flexDirection:"row",gap:m},children:[re("div",{className:"compact-action-item",children:o("undo")}),re("div",{className:"compact-action-item",children:o("redo")}),g&&re("div",{className:"compact-action-item",children:o("duplicateSelection")}),h&&re("div",{className:"compact-action-item",children:o("deleteSelectedElements")})]})]})},FC=({activeTool:e,setAppState:t,app:o,UIOptions:n})=>{let[r,i]=ZF(!1),a=_t(),s=a==="full",l=a==="compact",c=[{type:"selection",icon:Oi,title:ni(f("toolBar.selection"))},{type:"lasso",icon:Nr,title:ni(f("toolBar.lasso"))}],m=e.type==="frame",p=e.type==="laser",d=s&&e.type==="lasso"&&o.state.preferredSelectionTool.type!=="lasso",u=e.type==="embeddable",{TTDDialogTriggerTunnel:h}=Xe();return Ie(Lo,{children:[Fb(o).map(({value:g,icon:E,key:w,numericKey:x,fillable:y,toolbar:v})=>{if(v===!1||n.tools?.[g]===!1)return null;let I=f(`toolBar.${g}`),k=w&&ni(typeof w=="string"?w:w[0]),L=k?`${k} ${f("helpDialog.or")} ${x}`:`${x}`,S=g==="hand"?void 0:x||k;return(g==="selection"||g==="lasso")&&l?re($s,{app:o,options:c,activeTool:e,defaultOption:o.state.preferredSelectionTool.type,namePrefix:"selectionType",title:ni(f("toolBar.selection")),"data-testid":"toolbar-selection",onToolChange:_=>{(_==="selection"||_==="lasso")&&(o.setActiveTool({type:_}),t({preferredSelectionTool:{type:_,initialized:!0}}))},displayedOption:c.find(_=>_.type===o.state.preferredSelectionTool.type)||c[0],fillable:e.type==="selection"},"selection-popover"):re(ne,{className:Un("Shape",{fillable:y}),type:"radio",icon:E,checked:e.type===g,name:"editor-current-shape",title:`${ni(I)} \u2014 ${L}`,keyBindingLabel:S,"aria-label":ni(I),"aria-keyshortcuts":L,"data-testid":`toolbar-${g}`,onPointerDown:({pointerType:_})=>{!o.state.penDetected&&_==="pen"&&o.togglePenMode(!0),g==="selection"&&(o.state.activeTool.type==="selection"?o.setActiveTool({type:"lasso"}):o.setActiveTool({type:"selection"}))},onChange:({pointerType:_})=>{o.state.activeTool.type!==g&&ge("toolbar",g,"ui"),g==="image"?o.setActiveTool({type:g}):o.setActiveTool({type:g})}},g)}),re("div",{className:"App-toolbar__divider"}),re(ne,{className:"Shape",type:"radio",icon:Iw,checked:!1,name:"editor-current-shape",title:"Image Generator \u2014 A",keyBindingLabel:"A","aria-label":"Image Generator","data-testid":"toolbar-image-generator",onChange:()=>{ge("toolbar","imageGenerator","ui"),o.onImageGeneratorSelect()}}),re(ne,{className:"Shape",type:"radio",icon:Dn,checked:m,name:"editor-current-shape",title:`${ni(f("toolBar.frame"))} \u2014 F`,keyBindingLabel:"F","aria-label":ni(f("toolBar.frame")),"data-testid":"toolbar-frame",onChange:()=>{ge("toolbar","frame","ui"),o.setActiveTool({type:"frame"})}}),Ie(he,{open:r,children:[re(he.Trigger,{className:Un("App-toolbar__extra-tools-trigger",{"App-toolbar__extra-tools-trigger--selected":u||d||p&&!o.props.isCollaborating}),onToggle:()=>{i(!r),t({openMenu:null,openPopup:null})},title:f("toolBar.extraTools"),children:u?Za:p&&!o.props.isCollaborating?Rn:d?Nr:Ql}),Ie(he.Content,{onClickOutside:()=>i(!1),onSelect:()=>i(!1),className:"App-toolbar__extra-tools-dropdown",children:[re(he.Item,{onSelect:()=>o.setActiveTool({type:"embeddable"}),icon:Za,"data-testid":"toolbar-embeddable",selected:u,children:f("toolBar.embeddable")}),re(he.Item,{onSelect:()=>o.setActiveTool({type:"laser"}),icon:Rn,"data-testid":"toolbar-laser",selected:p,shortcut:jF.K.toLocaleUpperCase(),children:f("toolBar.laser")}),s&&re(he.Item,{onSelect:()=>o.setActiveTool({type:"lasso"}),icon:Nr,"data-testid":"toolbar-lasso",selected:d,children:f("toolBar.lasso")}),re("div",{style:{margin:"6px 0",fontSize:14,fontWeight:600},children:"Generate"}),o.props.aiEnabled!==!1&&re(h.Out,{}),re(he.Item,{onSelect:()=>o.setOpenDialog({name:"ttd",tab:"mermaid"}),icon:es,"data-testid":"toolbar-mermaid",children:f("toolBar.mermaidToExcalidraw")}),o.props.aiEnabled!==!1&&o.plugins.diagramToCode&&re(he.Item,{onSelect:()=>o.onMagicframeToolSelect(),icon:Gi,"data-testid":"toolbar-magicframe",badge:re(he.Item.Badge,{children:"AI"}),children:f("toolBar.magicframe")})]})]})]})},OC=({renderAction:e})=>e("scrollBackToContent"),zC=({renderAction:e,zoom:t})=>Ie(Dt.Row,{align:"center",className:kC.ZOOM_ACTIONS,children:[e("zoomOut"),e("resetZoom"),e("zoomIn")]}),HC=({renderAction:e,className:t})=>Ie("div",{className:`undo-redo-buttons ${t}`,children:[re("div",{className:"undo-button-container",children:re(Vt,{label:f("buttons.undo"),children:e("undo")})}),re("div",{className:"redo-button-container",children:Ie(Vt,{label:f("buttons.redo"),children:[" ",e("redo")]})})]}),GC=({actionManager:e,showExitZenModeBtn:t})=>re("button",{type:"button",className:Un("disable-zen-mode",{"disable-zen-mode--visible":t}),onClick:()=>e.executeAction(jr),children:f("buttons.exitZenMode")}),UC=({actionManager:e})=>re("button",{type:"button",className:"disable-view-mode",onClick:()=>e.executeAction(ea),children:jw});import{useRef as JF}from"react";var Yb=e=>{let t=JF({userFn:e});return t.current.userFn=e,t.current.stableFn||(t.current.stableFn=(...o)=>t.current.userFn(...o)),t.current.stableFn};import{jsx as eO,jsxs as QF}from"react/jsx-runtime";var ta=Ce(null),WC=()=>{let[e,t]=ae(ta),o=nt();return e&&e==="clearCanvas"?eO(Sp,{onConfirm:()=>{o.executeAction(gr),t(null)},onCancel:()=>t(null),title:f("clearCanvasDialog.title"),children:QF("p",{className:"clear-canvas__content",children:[" ",f("alerts.clearReset")]})}):null};var Vb={};NE(Vb,{toggleTheme:()=>tO});var tO={...Vi,category:"App",label:"Toggle theme",perform:({actionManager:e})=>{e.executeAction(Vi,"commandPalette")}};import{jsx as Nt,jsxs as Wn}from"react/jsx-runtime";var aO=Ce(null),rt={app:"App",export:"Export",tools:"Tools",editor:"Editor",elements:"Elements",links:"Links",library:"Library"},VC=e=>{switch(e){case rt.app:return 1;case rt.export:return 2;case rt.editor:return 3;case rt.tools:return 4;case rt.elements:return 5;case rt.links:return 6;default:return 10}},Yp=({shortcut:e,className:t,children:o})=>{let n=e.replace("++","+$").split("+");return Wn("div",{className:KC("shortcut",t),children:[n.map((r,i)=>Nt("div",{className:"shortcut-wrapper",children:Nt("div",{className:"shortcut-key",children:r==="$"?"+":r})},r)),Nt("div",{className:"shortcut-desc",children:o})]})},ZC=e=>!e.altKey&&e[fn.CTRL_OR_CMD]&&(e.shiftKey&&e.key.toLowerCase()===fn.P||e.key===fn.SLASH),sO=Object.assign(e=>{let t=ye(),o=ve();return Wp(()=>{let n=r=>{ZC(r)&&(r.preventDefault(),r.stopPropagation(),o(i=>{let a=i.openDialog?.name==="commandPalette"?null:{name:"commandPalette"};return a&&ge("command_palette","open","shortcut"),{openDialog:a}}))};return window.addEventListener(Vp.KEYDOWN,n,{capture:!0}),()=>window.removeEventListener(Vp.KEYDOWN,n,{capture:!0})},[o]),t.openDialog?.name!=="commandPalette"?null:Nt(lO,{...e})},{defaultItems:Vb});function lO({customCommandPaletteItems:e}){let t=Qe(),o=ye(),n=ve(),r=Nn(),i=nt(),[a,s]=ae(aO),[l,c]=Up(null),m=XC(null),p=Fr({uiAppState:o,customCommandPaletteItems:e,appProps:r}),[d]=ae(fr),u=nO(()=>d.libraryItems?.filter(S=>!!S.name).map(S=>({label:S.name,icon:Nt(cO,{id:S.id,elements:S.elements}),category:"Library",order:VC("Library"),haystack:Ji(S.name),perform:()=>{t.onInsertElements(Us([S]))}}))||[],[t,d.libraryItems]);Wp(()=>{let{uiAppState:S,customCommandPaletteItems:_,appProps:P}=p,T=B=>{let U="";return B.label&&(typeof B.label=="function"?U=f(B.label(t.scene.getNonDeletedElements(),S,t)):U=f(B.label)),U},M=B=>typeof B.icon=="function"?B.icon(S,t.scene.getNonDeletedElements()):B.icon,N=[],O=(B,U,D)=>{let F={label:T(B),icon:M(B),category:U,shortcut:Ke(B.name),keywords:B.keywords,predicate:B.predicate,viewMode:B.viewMode,perform:()=>{i.executeAction(B,"commandPalette")}};return D?D(F,B):F};if(S&&t.scene&&i){let B=[i.actions.group,i.actions.ungroup,i.actions.cut,i.actions.copy,i.actions.deleteSelectedElements,i.actions.wrapSelectionInFrame,i.actions.copyStyles,i.actions.pasteStyles,i.actions.bringToFront,i.actions.bringForward,i.actions.sendBackward,i.actions.sendToBack,i.actions.alignTop,i.actions.alignBottom,i.actions.alignLeft,i.actions.alignRight,i.actions.alignVerticallyCentered,i.actions.alignHorizontallyCentered,i.actions.duplicateSelection,i.actions.flipHorizontal,i.actions.flipVertical,i.actions.zoomToFitSelection,i.actions.zoomToFitSelectionInViewport,i.actions.increaseFontSize,i.actions.decreaseFontSize,i.actions.toggleLinearEditor,i.actions.cropEditor,i.actions.togglePolygon,Mc,yp,lT].map(V=>O(V,rt.elements,(Q,ee)=>({...Q,predicate:ee.predicate?ee.predicate:(ie,Ee,Le,De)=>le(ie,Ee).length>0}))),U=[i.actions.toggleHandTool,i.actions.setFrameAsActiveTool,i.actions.toggleLassoTool].map(V=>O(V,rt.tools)),D=[i.actions.undo,i.actions.redo,i.actions.zoomIn,i.actions.zoomOut,i.actions.resetZoom,i.actions.zoomToFit,i.actions.zenMode,i.actions.viewMode,i.actions.gridMode,i.actions.objectsSnapMode,i.actions.toggleShortcuts,i.actions.selectAll,i.actions.toggleElementLock,i.actions.unlockAllElements,i.actions.stats].map(V=>O(V,rt.editor)),F=[i.actions.saveToActiveFile,i.actions.saveFileToDisk,i.actions.copyAsPng,i.actions.copyAsSvg].map(V=>O(V,rt.export));N=[...B,...D,{label:T(gr),icon:M(gr),shortcut:Ke(gr.name),category:rt.editor,keywords:["delete","destroy"],viewMode:!1,perform:()=>{Et.set(ta,"clearCanvas")}},{label:f("buttons.exportImage"),category:rt.export,icon:mm,shortcut:Ke("imageExport"),keywords:["export","image","png","jpeg","svg","clipboard","picture"],perform:()=>{n({openDialog:{name:"imageExport"}})}},...F];let z=[{label:f("toolBar.library"),category:rt.app,icon:im,viewMode:!1,perform:()=>{S.openSidebar?n({openSidebar:null}):n({openSidebar:{name:YC.name,tab:YC.defaultTab}})}},{label:f("search.title"),category:rt.app,icon:ko,viewMode:!0,perform:()=>{i.executeAction(Uc)}},{label:f("labels.shapeSwitch"),category:rt.elements,icon:ec,perform:()=>{i.executeAction(sT)}},{label:f("labels.changeStroke"),keywords:["color","outline"],category:rt.elements,icon:dm,viewMode:!1,predicate:(V,Q)=>{let ee=le(V,Q);return ee.length>0&&Hc(Q,ee)},perform:()=>{n(V=>({openPopup:"elementStroke"}))}},{label:f("labels.changeBackground"),keywords:["color","fill"],icon:dm,category:rt.elements,viewMode:!1,predicate:(V,Q)=>{let ee=le(V,Q);return ee.length>0&&Gc(Q,ee)},perform:()=>{n(V=>({openPopup:"elementBackground"}))}},{label:f("labels.canvasBackground"),keywords:["color"],icon:dm,category:rt.editor,viewMode:!1,perform:()=>{n(V=>({openMenu:V.openMenu==="canvas"?null:"canvas",openPopup:"canvasBackground"}))}},...Bp.reduce((V,Q)=>{let{value:ee,icon:ie,key:Ee,numericKey:Le}=Q;if(P.UIOptions.tools?.[ee]===!1)return V;let We=Ee&&rO(typeof Ee=="string"?Ee:Ee[0])||Le,lt={label:f(`toolBar.${ee}`),category:rt.tools,shortcut:We,icon:ie,keywords:["toolbar"],viewMode:!1,perform:({event:qt})=>{ee==="image"?t.setActiveTool({type:ee}):t.setActiveTool({type:ee})}};return V.push(lt),V},[]),...U,{label:f("toolBar.lock"),category:rt.tools,icon:S.activeTool.locked?Wa:Fi,shortcut:fn.Q.toLocaleUpperCase(),viewMode:!1,perform:()=>{t.toggleLock()}},{label:`${f("labels.textToDiagram")}...`,category:rt.tools,icon:Pw,viewMode:!1,predicate:P.aiEnabled,perform:()=>{n(V=>({...V,openDialog:{name:"ttd",tab:"text-to-diagram"}}))}},{label:`${f("toolBar.mermaidToExcalidraw")}...`,category:rt.tools,icon:es,viewMode:!1,predicate:P.aiEnabled,perform:()=>{n(V=>({...V,openDialog:{name:"ttd",tab:"mermaid"}}))}}],$=[...N,...z,..._||[]].map(V=>({...V,icon:V.icon||ec,order:V.order??VC(V.category),haystack:`${Ji(V.label.toLocaleLowerCase())} ${V.keywords?.join(" ")||""}`}));c($),s([...$,...u].find(V=>V.label===a?.label)??null)}},[p,t,i,c,a?.label,s,n,u]);let[h,g]=Up(""),[E,w]=Up(null),[x,y]=Up({}),v=S=>{n({openDialog:null},S),g("")},I=(S,_)=>{o.openDialog?.name==="commandPalette"&&(_.stopPropagation(),_.preventDefault(),document.body.classList.add("excalidraw-animations-disabled"),v(()=>{S.perform({actionManager:i,event:_}),s(S),requestAnimationFrame(()=>{document.body.classList.remove("excalidraw-animations-disabled")})}))},k=Yb(S=>S.viewMode===!1&&o.viewModeEnabled?!1:typeof S.predicate=="function"?S.predicate(t.scene.getNonDeletedElements(),o,r,t):S.predicate===void 0||S.predicate),L=Yb(S=>{let _=iO(S.target)||ZC(S)||S.key===fn.ESCAPE;if(_&&S.key!==fn.ARROW_UP&&S.key!==fn.ARROW_DOWN&&S.key!==fn.ENTER)return;let P=Object.values(x).flat(),T=a&&!h&&k(a);if(S.key===fn.ARROW_UP){S.preventDefault();let M=P.findIndex(B=>B.label===E?.label);if(T){if(M===0){w(a);return}if(E===a){let B=P[P.length-1];B&&w(B);return}}let N;M===-1?N=P.length-1:N=M===0?P.length-1:(M-1)%P.length;let O=P[N];O&&w(O);return}if(S.key===fn.ARROW_DOWN){S.preventDefault();let M=P.findIndex(B=>B.label===E?.label);if(T){if(!E||M===P.length-1){w(a);return}if(E===a){let B=P[0];B&&w(B);return}}let N=(M+1)%P.length,O=P[N];O&&w(O);return}if(S.key===fn.ENTER&&E&&setTimeout(()=>{I(E,S)}),!_){if(S.stopPropagation(),/^[a-zA-Z0-9]$/.test(S.key)){m?.current?.focus();return}S.preventDefault()}});return Wp(()=>(window.addEventListener(Vp.KEYDOWN,L,{capture:!0}),()=>window.removeEventListener(Vp.KEYDOWN,L,{capture:!0})),[L]),Wp(()=>{if(!l)return;let S=M=>{let N={};for(let O of M)N[O.category]?N[O.category].push(O):N[O.category]=[O];return N},_=h?.length>1?[...l.filter(k).sort((M,N)=>M.order-N.order),...u]:l.filter(k).sort((M,N)=>M.order-N.order),P=!h&&a&&k(a);if(!h){y(S(P?_.filter(M=>M.label!==a?.label):_)),w(P?a:_[0]||null);return}let T=Ji(h.toLocaleLowerCase().replace(/[<>_| -]/g,""));_=oO.filter(T,_,{extract:M=>M.haystack??""}).sort((M,N)=>N.score-M.score).map(M=>M.original),y(S(_)),w(_[0]??null)},[h,l,k,a,u]),Wn(ht,{onCloseRequest:()=>v(),closeOnClickOutside:!0,title:!1,size:720,autofocus:!0,className:"command-palette-dialog",children:[Nt(ti,{value:h,placeholder:f("commandPalette.search.placeholder"),onChange:S=>{g(S)},selectOnRender:!0,ref:m}),t.editorInterface.formFactor!=="phone"&&Wn("div",{className:"shortcuts-wrapper",children:[Nt(Yp,{shortcut:"\u2191\u2193",children:f("commandPalette.shortcuts.select")}),Nt(Yp,{shortcut:"\u21B5",children:f("commandPalette.shortcuts.confirm")}),Nt(Yp,{shortcut:G("Esc"),children:f("commandPalette.shortcuts.close")})]}),Wn("div",{className:"commands",children:[a&&!h&&Wn("div",{className:"command-category",children:[Wn("div",{className:"command-category-title",children:[f("commandPalette.recents"),Nt("div",{className:"icon",style:{marginLeft:"6px"},children:Aw})]}),Nt($C,{command:a,isSelected:a.label===E?.label,onClick:S=>I(a,S),disabled:!k(a),onMouseMove:()=>w(a),showShortcut:t.editorInterface.formFactor!=="phone",appState:o})]}),Object.keys(x).length>0?Object.keys(x).map((S,_)=>Wn("div",{className:"command-category",children:[Nt("div",{className:"command-category-title",children:S}),x[S].map(P=>Nt($C,{command:P,isSelected:P.label===E?.label,onClick:T=>I(P,T),onMouseMove:()=>w(P),showShortcut:t.editorInterface.formFactor!=="phone",appState:o,size:S==="Library"?"large":"small"},P.label))]},S)):l?Wn("div",{className:"no-match",children:[Nt("div",{className:"icon",children:ko})," ",f("commandPalette.search.noMatch")]}):null]})]})}var cO=({id:e,elements:t})=>{let o=XC(null),{svgCache:n}=Hs();return wp(e,t,n,o),Nt("div",{className:"library-item-icon",ref:o})},$C=({command:e,isSelected:t,disabled:o,onMouseMove:n,onClick:r,showShortcut:i,appState:a,size:s="small"})=>{let l=()=>{};return Wn("div",{className:KC("command-item",{"item-selected":t,"item-disabled":o,"command-item-large":s==="large"}),ref:c=>{t&&!o&&c?.scrollIntoView?.({block:"nearest"})},onClick:o?l:r,onMouseMove:o?l:n,title:o?f("commandPalette.itemNotAvailable"):"",children:[Wn("div",{className:"name",children:[e.icon&&Nt(Bn,{className:"icon",size:"var(--icon-size, 1rem)",icon:typeof e.icon=="function"?e.icon(a,[]):e.icon}),Nt(mc,{children:e.label})]}),i&&e.shortcut&&Nt(Yp,{shortcut:e.shortcut})]})};import{getSizeFromPoints as ike,randomInteger as dz,getUpdatedTimestamp as mz}from"@orangecatai/common";import{simplify as ZO}from"points-on-curve";import{getStroke as jO}from"perfect-freehand";import{pointsOnBezierCurves as Vye}from"points-on-curve";import{invariant as Kye}from"@orangecatai/common";import{curve as Zye,lineSegment as jye,pointFrom as qye,pointDistance as Jye,pointFromArray as Qye,pointFromVector as ewe,pointRotateRads as twe,polygon as owe,polygonFromPoints as nwe,PRECISION as rwe,segmentsIntersectAt as iwe,vector as awe,vectorAdd as swe,vectorFromPoint as lwe,vectorScale as cwe}from"@orangecatai/math";import{getElementAbsoluteCoords as mwe}from"@orangecatai/element";var $b=e=>{if(!e)return[];for(let t of e.sets)if(t.type==="path")return t.ops;return e.sets[0].ops};import{pointFrom as qO,pointDistance as u5,pointRotateRads as Y3e}from"@orangecatai/math";import{ROUGHNESS as JO,THEME as d0,isTransparent as $c,assertNever as QO,COLOR_PALETTE as ez,LINE_POLYGON_POINT_MERGE_DISTANCE as $3e,applyDarkModeFilter as tu}from"@orangecatai/common";import{RoughGenerator as tz}from"roughjs/bin/generator";import e3e from"roughjs/bin/rough";import{isRightAngleRads as o3e,lineSegment as n3e,pointFrom as r3e,pointRotateRads as i3e}from"@orangecatai/math";import{BOUND_TEXT_PADDING as s3e,DEFAULT_REDUCED_GLOBAL_ALPHA as l3e,ELEMENT_READY_TO_ERASE_OPACITY as c3e,FRAME_STYLE as d3e,DARK_THEME_FILTER as m3e,MIME_TYPES as m5,THEME as p3e,distance as u3e,getFontString as g3e,isRTL as h3e,getVerticalOffset as f3e,invariant as b3e,applyDarkModeFilter as x3e,isSafari as E3e}from"@orangecatai/common";import pCe from"roughjs/bin/rough";import{arrayToMap as gCe,invariant as r5,rescalePoints as hCe,sizeOf as fCe}from"@orangecatai/common";import{degreesToRadians as r0,lineSegment as xCe,pointDistance as ECe,pointFrom as Ut,pointFromArray as LO,pointRotateRads as qs}from"@orangecatai/math";import{pointsOnBezierCurves as vCe}from"points-on-curve";import{pointCenter as STe,pointFrom as MTe,pointRotateRads as PTe,pointsEqual as ATe,pointDistance as LTe,vectorFromPoint as _Te,curveLength as DTe,curvePointAtLength as RTe}from"@orangecatai/math";import{DRAGGING_THRESHOLD as FTe,KEYS as OTe,shouldRotateWithDiscreteAngle as zTe,getGridPoint as HTe,invariant as GTe,isShallowEqual as UTe,getFeatureFlag as WTe}from"@orangecatai/common";import{deconstructLinearOrFreeDrawElement as VTe,getSnapOutlineMidPoint as $Te,isPathALoop as KTe,moveArrowAboveBindable as XTe,projectFixedPointOntoDiagonal as ZTe}from"@orangecatai/element";import{KEYS as SIe,arrayToMap as MIe,getFeatureFlag as PIe,invariant as AIe,isTransparent as LIe}from"@orangecatai/common";import{PRECISION as DIe,clamp as RIe,lineSegment as NIe,pointDistance as BIe,pointDistanceSq as FIe,pointFrom as OIe,pointFromVector as zIe,pointRotateRads as HIe,pointsEqual as GIe,vectorFromPoint as UIe,vectorNormalize as WIe,vectorScale as YIe}from"@orangecatai/math";import{invariant as Qve,isTransparent as e2e}from"@orangecatai/common";import{curveIntersectLineSegment as o2e,isPointWithinBounds as n2e,lineSegment as r2e,lineSegmentIntersectionPoints as i2e,pointFrom as a2e,pointFromVector as s2e,pointRotateRads as l2e,pointsEqual as c2e,vectorFromPoint as d2e,vectorNormalize as m2e,vectorScale as p2e}from"@orangecatai/math";import{ellipse as g2e,ellipseSegmentInterceptPoints as h2e}from"@orangecatai/math/ellipse";import{DEFAULT_ADAPTIVE_RADIUS as pO,DEFAULT_PROPORTIONAL_RADIUS as Xb,invariant as vwe,LINE_CONFIRM_THRESHOLD as uO,ROUNDNESS as Zb}from"@orangecatai/common";import{bezierEquation as Twe,curve as Cwe,curveCatmullRomCubicApproxPoints as kwe,curveOffsetPoints as Swe,lineSegment as Mwe,lineSegmentIntersectionPoints as Pwe,pointDistance as gO,pointFrom as Awe,pointFromArray as Lwe,pointFromVector as _we,pointRotateRads as Dwe,pointTranslate as Rwe,rectangle as Nwe,vectorFromPoint as Bwe,vectorNormalize as Fwe,vectorScale as Owe}from"@orangecatai/math";import{ROUNDNESS as hwe,assertNever as fwe}from"@orangecatai/common";import{pointsEqual as xwe}from"@orangecatai/math";var jC=e=>!!e&&e.type==="embeddable",qC=e=>!!e&&e.type==="iframe",Kb=e=>!!e&&(e.type==="iframe"||e.type==="embeddable"),oa=e=>e!=null&&e.type==="text";var $p=e=>e!=null&&(e.type==="frame"||e.type==="magicframe");var na=e=>e!=null&&dO(e.type);var ra=e=>e!=null&&e.type==="arrow",Wc=e=>ra(e)&&e.elbowed;var dO=e=>e==="arrow"||e==="line";var Ks=e=>e!==null&&"containerId"in e&&e.containerId!==null&&oa(e);var Kp=(e,t=1)=>{if(e.length>=3){let[o,n]=[e[0],e[e.length-1]];return gO(o,n)<=uO/t}return!1},Yc=(e,t)=>{if(t.roundness?.type===Zb.PROPORTIONAL_RADIUS||t.roundness?.type===Zb.LEGACY)return e*Xb;if(t.roundness?.type===Zb.ADAPTIVE_RADIUS){let o=t.roundness?.value??pO,n=o/Xb;return e<=n?e*Xb:o}return 0};import{ARROW_LABEL_FONT_SIZE_TO_MIN_WIDTH_RATIO as vve,ARROW_LABEL_WIDTH_FRACTION as Ive,BOUND_TEXT_PADDING as Tve,DEFAULT_FONT_SIZE as Cve,TEXT_ALIGN as kve,VERTICAL_ALIGN as Sve,getFontString as Mve,isProdEnv as Pve,invariant as Ave}from"@orangecatai/common";import{pointFrom as _ve,pointRotateRads as Dve}from"@orangecatai/math";import{BOUND_TEXT_PADDING as Qwe,DEFAULT_FONT_SIZE as eve,DEFAULT_FONT_FAMILY as tve,getFontString as ove,isTestEnv as nve,normalizeEOL as rve}from"@orangecatai/common";var ive="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toLocaleUpperCase();import{isDevEnv as pve,isTestEnv as uve}from"@orangecatai/common";import{curvePointDistance as Uve,distanceToLineSegment as Wve,pointRotateRads as Yve}from"@orangecatai/math";import{ellipse as $ve,ellipseDistanceFromPoint as Kve}from"@orangecatai/math/ellipse";import{invariant as P2e,isDevEnv as A2e,isTestEnv as L2e}from"@orangecatai/common";import{pointFrom as D2e,pointFromVector as R2e,pointRotateRads as N2e,pointScaleFromOrigin as B2e,pointsEqual as F2e,triangleIncludesPoint as O2e,vectorCross as z2e,vectorFromPoint as TO,vectorScale as H2e}from"@orangecatai/math";var o0=[1,0],e5=[0,1],n0=[-1,0],t5=[0,-1],jp=e=>{let[t,o]=e,n=Math.abs(t),r=Math.abs(o);return t>r?o0:t<=-r?n0:o>n?e5:t5},o5=(e,t)=>jp(TO(e,t)),qp=(e,t)=>Jp(o5(e,t)),t0=(e,t)=>e[0]===t[0]&&e[1]===t[1],Jp=e=>t0(e,o0)||t0(e,n0);import{clamp as $2e,pointDistance as K2e,pointFrom as X2e,pointScaleFromOrigin as Z2e,pointsEqual as j2e,pointTranslate as q2e,vector as J2e,vectorCross as Q2e,vectorFromPoint as eIe,vectorScale as tIe}from"@orangecatai/math";import{BinaryHeap as nIe,invariant as rIe,isAnyTrue as iIe,getSizeFromPoints as aIe,isDevEnv as sIe,arrayToMap as lIe}from"@orangecatai/common";var oTe=10/1.5;import{SHIFT_LOCKING_ANGLE as sTe,viewportCoordsToSceneCoords as lTe}from"@orangecatai/common";import{normalizeRadians as dTe,radiansBetweenAngles as mTe,radiansDifference as pTe}from"@orangecatai/math";import{pointsEqual as gTe}from"@orangecatai/math";var Xp=e=>{let t=Math.floor(e.width/2)+1,o=0,n=e.width,r=Math.floor(e.height/2)+1,i=t,a=e.height;return[t,o,n,r,i,a,0,r]};var _O=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}},DO=e=>{switch(e){case"bar":return 90;case"arrow":return 20;default:return 25}},i0=(e,t,o,n)=>{if(t.length<1)return null;let r=$b(t[0]);if(r.length<1)return null;let i=o==="start"?1:r.length-1,a=r[i].data;r5(a.length===6,"Op data length is not 6");let s=Ut(a[4],a[5]),l=Ut(a[2],a[3]),c=Ut(a[0],a[1]),m=r[i-1],p=Ut(0,0);if(m.op==="move"){let B=LO(m.data);r5(B!=null,"Op data is not a point"),p=B}else m.op==="bcurveTo"&&(p=Ut(m.data[4],m.data[5]));let d=(B,U)=>Math.pow(1-B,3)*s[U]+3*B*Math.pow(1-B,2)*l[U]+3*Math.pow(B,2)*(1-B)*c[U]+p[U]*Math.pow(B,3),[u,h]=o==="start"?p:s,[g,E]=[d(.3,0),d(.3,1)],w=Math.hypot(u-g,h-E),x=(u-g)/w,y=(h-E)/w,v=_O(n),I=0;{let[B,U]=o==="end"?e.points[e.points.length-1]:e.points[0],[D,F]=e.points.length>1?o==="end"?e.points[e.points.length-2]:e.points[1]:[0,0];I=Math.hypot(B-D,U-F)}let L=Math.min(v,I*(n==="diamond"||n==="diamond_outline"?.25:.5)),S=u-x*L,_=h-y*L;if(n==="dot"||n==="circle"||n==="circle_outline"){let B=Math.hypot(_-h,S-u)+e.strokeWidth-2;return[u,h,B]}let P=DO(n);if(n==="crowfoot_many"||n==="crowfoot_one_or_many"){let[B,U]=qs(Ut(u,h),Ut(S,_),r0(-P)),[D,F]=qs(Ut(u,h),Ut(S,_),r0(P));return[S,_,B,U,D,F]}let[T,M]=qs(Ut(S,_),Ut(u,h),-P*Math.PI/180),[N,O]=qs(Ut(S,_),Ut(u,h),r0(P));if(n==="diamond"||n==="diamond_outline"){let B,U;if(o==="start"){let[D,F]=e.points.length>1?e.points[1]:[0,0];[B,U]=qs(Ut(u+L*2,h),Ut(u,h),Math.atan2(F-h,D-u))}else{let[D,F]=e.points.length>1?e.points[e.points.length-2]:[0,0];[B,U]=qs(Ut(u-L*2,h),Ut(u,h),Math.atan2(h-F,u-D))}return[u,h,T,M,B,U,N,O]}return[u,h,T,M,N,O]};import{pointFrom as BCe,pointCenter as FCe,pointRotateRads as OCe,vectorFromPoint as zCe,vectorNormalize as HCe,vectorSubtract as GCe,vectorAdd as UCe,vectorScale as WCe,pointFromVector as YCe,clamp as VCe,isCloseTo as $Ce}from"@orangecatai/math";import{arrayToMap as _5e}from"@orangecatai/common";import{isPointWithinBounds as R5e,pointFrom as N5e}from"@orangecatai/math";import{vectorCross as qCe,vectorFromPoint as JCe}from"@orangecatai/math";import{arrayToMap as RO}from"@orangecatai/common";import{getElementBounds as NO}from"@orangecatai/element";import{isArrowElement as BO,isExcalidrawElement as FO,isFreeDrawElement as OO,isLinearElement as zO,isTextElement as HO}from"@orangecatai/element";import{rangeIncludesValue as Qp,pointFrom as yr,pointRotateRads as GO,rangeInclusive as eu}from"@orangecatai/math";var UO=e=>e.type==="diamond"?[yr(e.width/2,0),yr(e.width,e.height/2),yr(e.width/2,e.height),yr(0,e.height/2)]:[yr(0,0),yr(0+e.width,0),yr(0+e.width,e.height),yr(0,e.height)],WO=e=>zO(e)||OO(e)?e.points:UO(e),a5=e=>{let t=e.reduce((o,[n,r])=>(o.minY=Math.min(o.minY,r),o.minX=Math.min(o.minX,n),o.maxX=Math.max(o.maxX,n),o.maxY=Math.max(o.maxY,r),o),{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,cx:0,cy:0});return t.cx=(t.maxX+t.minX)/2,t.cy=(t.maxY+t.minY)/2,t},s5=e=>{let t=WO(e),{cx:o,cy:n}=a5(t),r=yr(o,n),i=t.map(m=>GO(m,r,e.angle)),{minX:a,minY:s,maxX:l,maxY:c}=a5(i);return[a+e.x,s+e.y,l+e.x,c+e.y]},a0=(e,t,o=!1)=>{let n=s5(e),r=t[0]<=n[0]&&t[2]>=n[2]&&t[1]<=n[1]&&t[3]>=n[3];return o?r?!0:n[0]<=t[0]&&n[2]>=t[2]&&n[1]<=t[1]&&n[3]>=t[3]:r},l5=(e,t)=>{let o=s5(e);return(Qp(o[0],eu(t[0],t[2]))||Qp(t[0],eu(o[0],o[2])))&&(Qp(o[1],eu(t[1],t[3]))||Qp(t[1],eu(o[1],o[3])))},c5=({elements:e,bounds:t,type:o,errorMargin:n=0})=>{FO(t)&&(t=NO(t,RO(e)));let r=[t[0]-n,t[1]-n,t[2]+n,t[3]+n],i=new Set;for(let a of e){if(i.has(a.id))continue;if(o==="overlap"?l5(a,r):o==="inside"?a0(a,r):a0(a,r,!0)){if(i.add(a.id),a.boundElements)for(let l of a.boundElements)i.add(l.id);HO(a)&&a.containerId&&i.add(a.containerId),BO(a)&&(a.startBinding&&i.add(a.startBinding.elementId),a.endBinding&&i.add(a.endBinding?.elementId))}}return e.filter(a=>i.has(a.id))};import{arrayToMap as g5e,isShallowEqual as VO}from"@orangecatai/common";var YO=function(){let e=null,t=null,o=null,n=(i,a,s,l)=>{if(o!==void 0&&a===t&&i===e&&s.editingGroupId===o?.editingGroupId)return o;let c={};for(let d of i){let u=d.groupIds;if(s.editingGroupId){let h=u.indexOf(s.editingGroupId);h>-1&&(u=u.slice(0,h))}if(u.length>0){let h=u[u.length-1];c[h]=!0}}let m={},p=a.reduce((d,u)=>{if(u.isDeleted)return d;let h=u.groupIds.find(g=>c[g]);return h&&(d[u.id]=!0,Array.isArray(m[h])?m[h].push(u.id):m[h]=[u.id]),d},{});for(let d of Object.keys(m))m[d].length<2&&c[d]&&(c[d]=!1);return t=a,e=i,o={editingGroupId:s.editingGroupId,selectedGroupIds:c,selectedElementIds:s0({...s.selectedElementIds,...p},l)},o},r=(i,a,s,l)=>{let c=l?l.scene.getSelectedElements({selectedElementIds:i.selectedElementIds,elements:a}):l0(a,i);return c.length?n(c,a,i,s):{selectedGroupIds:{},editingGroupId:null,selectedElementIds:s0(i.selectedElementIds,s)}};return r.clearCache=()=>{t=null,e=null,o=null},r}();var w5e=function(){let e=null,t=null,o=null,n=(r,i)=>(o!=null&&r===e&&i.selectedElementIds===t||(o=r.some(a=>i.selectedElementIds[a.id]),e=r,t=i.selectedElementIds),o);return n.clearCache=()=>{e=null,t=null,o=null},n}(),l0=(e,t,o)=>{let n=new Set,r=[];for(let i of e.values()){if(t.selectedElementIds[i.id]){r.push(i),n.add(i.id);continue}if(o?.includeBoundTextElement&&Ks(i)&&t.selectedElementIds[i?.containerId]){r.push(i),n.add(i.id);continue}}if(o?.includeElementsInFrames){let i=[];return r.forEach(a=>{$p(a)&&d5(e,a.id).forEach(s=>!n.has(s.id)&&i.push(s)),i.push(a)}),i}return r};var s0=(e,t)=>VO(t.selectedElementIds,e)?t.selectedElementIds:e;var d5=(e,t)=>{let o=[];for(let n of e.values())n.frameId===t&&o.push(n);return o};var KO=typeof document<"u"?document.createElement("img"):{src:""};KO.src=`data:${m5.svg},${encodeURIComponent('<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="image" class="svg-inline--fa fa-image fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="#888" d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48zM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56zM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48z"></path></svg>')}`;var XO=typeof document<"u"?document.createElement("img"):{src:""};XO.src=`data:${m5.svg},${encodeURIComponent('<svg viewBox="0 0 668 668" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48ZM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56ZM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.81709 0 0 .81709 124.825 145.825)"/><path d="M256 8C119.034 8 8 119.033 8 256c0 136.967 111.034 248 248 248s248-111.034 248-248S392.967 8 256 8Zm130.108 117.892c65.448 65.448 70 165.481 20.677 235.637L150.47 105.216c70.204-49.356 170.226-44.735 235.638 20.676ZM125.892 386.108c-65.448-65.448-70-165.481-20.677-235.637L361.53 406.784c-70.203 49.356-170.226 44.736-235.638-20.676Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.30366 0 0 .30366 506.822 60.065)"/></svg>')}`;var c0=new WeakMap;var p5=e=>e==="rectangle"||e==="iframe"||e==="embeddable"||e==="line"||e==="diamond"||e==="image";var ho=class ho{};A(ho,"rg",new tz),A(ho,"cache",new WeakMap),A(ho,"get",(t,o)=>{let n=ho.cache.get(t);if(n&&(o===null||n.theme===o))return n.shape}),A(ho,"delete",t=>{ho.cache.delete(t),c0.delete(t)}),A(ho,"destroy",()=>{ho.cache=new WeakMap}),A(ho,"generateElementShape",(t,o)=>{let n=o?.isExporting?void 0:ho.get(t,o?o.theme:null);if(n!==void 0)return n;c0.delete(t);let r=rz(t,ho.rg,o||{isExporting:!1,canvasBackgroundColor:ez.white,embedsValidationStatus:null,theme:d0.LIGHT});return o?.isExporting||ho.cache.set(t,{shape:r,theme:o?.theme||d0.LIGHT}),r});var js=ho,oz=e=>[8,8+e],b5=e=>[1.5,6+e];function nz(e){let t=e.roughness,o=Math.max(e.width,e.height),n=Math.min(e.width,e.height);return n>=20&&o>=50||n>=15&&e.roundness&&p5(e.type)||na(e)&&o>=50?t:Math.min(t/(o<10?3:2),2.5)}var Er=(e,t=!1,o=!1)=>{let n={seed:e.seed,strokeLineDash:e.strokeStyle==="dashed"?oz(e.strokeWidth):e.strokeStyle==="dotted"?b5(e.strokeWidth):void 0,disableMultiStroke:e.strokeStyle!=="solid",strokeWidth:e.strokeStyle!=="solid"?e.strokeWidth+.5:e.strokeWidth,fillWeight:e.strokeWidth/2,hachureGap:e.strokeWidth*4,roughness:nz(e),stroke:o?tu(e.strokeColor):e.strokeColor,preserveVertices:t||e.roughness<JO.cartoonist};switch(e.type){case"rectangle":case"iframe":case"embeddable":case"diamond":case"ellipse":return n.fillStyle=e.fillStyle,n.fill=$c(e.backgroundColor)?void 0:o?tu(e.backgroundColor):e.backgroundColor,e.type==="ellipse"&&(n.curveFitting=1),n;case"line":case"freedraw":return Kp(e.points)&&(n.fillStyle=e.fillStyle,n.fill=e.backgroundColor==="transparent"?void 0:o?tu(e.backgroundColor):e.backgroundColor),n;case"arrow":return n;default:throw new Error(`Unimplemented type ${e.type}`)}},g5=(e,t,o)=>Kb(e)&&(t||jC(e)&&o?.get(e.id)!==!0)&&$c(e.backgroundColor)&&$c(e.strokeColor)?{...e,roughness:0,backgroundColor:"#d3d3d3",fillStyle:"solid"}:qC(e)?{...e,strokeColor:$c(e.strokeColor)?"#000000":e.strokeColor,backgroundColor:$c(e.backgroundColor)?"#f4f4f6":e.backgroundColor}:e,h5=(e,t,o,n,r,i,a,s)=>{let l=i0(e,t,o,n);if(l===null)return[];let c=(p,d)=>{if(p===null)return[];let[,,u,h,g,E]=p;return[r.line(u,h,g,E,d)]},m=s?tu(e.strokeColor):e.strokeColor;switch(n){case"dot":case"circle":case"circle_outline":{let[p,d,u]=l;return delete i.strokeLineDash,[r.circle(p,d,u,{...i,fill:n==="circle_outline"?a:m,fillStyle:"solid",stroke:m,roughness:Math.min(.5,i.roughness||0)})]}case"triangle":case"triangle_outline":{let[p,d,u,h,g,E]=l;return delete i.strokeLineDash,[r.polygon([[p,d],[u,h],[g,E],[p,d]],{...i,fill:n==="triangle_outline"?a:m,fillStyle:"solid",roughness:Math.min(1,i.roughness||0)})]}case"diamond":case"diamond_outline":{let[p,d,u,h,g,E,w,x]=l;return delete i.strokeLineDash,[r.polygon([[p,d],[u,h],[g,E],[w,x],[p,d]],{...i,fill:n==="diamond_outline"?a:m,fillStyle:"solid",roughness:Math.min(1,i.roughness||0)})]}case"crowfoot_one":return c(l,i);case"bar":case"arrow":case"crowfoot_many":case"crowfoot_one_or_many":default:{let[p,d,u,h,g,E]=l;if(e.strokeStyle==="dotted"){let w=b5(e.strokeWidth-1);i.strokeLineDash=[w[0],w[1]-1]}else delete i.strokeLineDash;return i.roughness=Math.min(1,i.roughness||0),[r.line(u,h,p,d,i),r.line(g,E,p,d,i),...n==="crowfoot_one_or_many"?c(i0(e,t,o,"crowfoot_one"),i):[]]}}};var rz=(e,t,{isExporting:o,canvasBackgroundColor:n,embedsValidationStatus:r,theme:i})=>{let a=i===d0.DARK;switch(e.type){case"rectangle":case"iframe":case"embeddable":{let s;if(e.roundness){let l=e.width,c=e.height,m=Yc(Math.min(l,c),e);s=t.path(`M ${m} 0 L ${l-m} 0 Q ${l} 0, ${l} ${m} L ${l} ${c-m} Q ${l} ${c}, ${l-m} ${c} L ${m} ${c} Q 0 ${c}, 0 ${c-m} L 0 ${m} Q 0 0, ${m} 0`,Er(g5(e,o,r),!0,a))}else s=t.rectangle(0,0,e.width,e.height,Er(g5(e,o,r),!1,a));return s}case"diamond":{let s,[l,c,m,p,d,u,h,g]=Xp(e);if(e.roundness){let E=Yc(Math.abs(l-h),e),w=Yc(Math.abs(p-c),e);s=t.path(`M ${l+E} ${c+w} L ${m-E} ${p-w}
6
+ ${f("hints.firefox_clipboard_write")}`):new Error(f("alerts.couldNotCopyToClipboard"))}else throw new Error("Unsupported export type")};var j2=async(e,t,o,n)=>{let{exportBackground:r,viewBackgroundColor:i,fileHandle:a}=t,s=XE(a);if(!a||!ZE(s))throw new Error("fileHandle should exist and should be of type svg or png when resaving");t={...t,exportEmbedScene:!0};let{exportedElements:l,exportingFrame:c}=Ki(e,t,!1);return await Xi(s,l,t,o,{exportBackground:r,viewBackgroundColor:i,name:n,fileHandle:a,exportingFrame:c}),{fileHandle:a}};import{Fragment as fR,jsx as hr,jsxs as bR}from"react/jsx-runtime";var Mf=W({name:"changeProjectName",label:"labels.fileTitle",trackEvent:!1,perform:(e,t,o)=>({appState:{...t,name:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({appState:e,updateData:t,appProps:o,data:n,app:r})=>hr(_2,{label:f("labels.fileTitle"),value:r.getName(),onChange:i=>t(i),ignoreFocus:n?.ignoreFocus??!1})}),q2=W({name:"changeExportScale",label:"imageExportDialog.scale",trackEvent:{category:"export",action:"scale"},perform:(e,t,o)=>({appState:{...t,exportScale:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({elements:e,appState:t,updateData:o})=>{let n=hR(e),i=He(n,t)?le(n,t):n;return hr(fR,{children:gR.map(a=>{let[s,l]=$E(i,uR,a),c=`${f("imageExportDialog.label.scale")} ${a}x (${s}x${l})`;return hr(ne,{size:"small",type:"radio",icon:`${a}x`,name:"export-canvas-scale",title:c,"aria-label":c,id:"export-canvas-scale",checked:a===t.exportScale,onChange:()=>o(a)},a)})})}}),Pf=W({name:"changeExportBackground",label:"imageExportDialog.label.withBackground",trackEvent:{category:"export",action:"toggleBackground"},perform:(e,t,o)=>({appState:{...t,exportBackground:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({appState:e,updateData:t})=>hr(bc,{checked:e.exportBackground,onChange:o=>t(o),children:f("imageExportDialog.label.withBackground")})}),tp=W({name:"changeExportEmbedScene",label:"imageExportDialog.tooltip.embedScene",trackEvent:{category:"export",action:"embedScene"},perform:(e,t,o)=>({appState:{...t,exportEmbedScene:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({appState:e,updateData:t})=>bR(bc,{checked:e.exportEmbedScene,onChange:o=>t(o),children:[f("imageExportDialog.label.embedScene"),hr(Vt,{label:f("imageExportDialog.tooltip.embedScene"),long:!0,children:hr("div",{className:"excalidraw-tooltip-icon",children:Py})})]})}),Zi=W({name:"saveToActiveFile",label:"buttons.save",icon:zi,trackEvent:{category:"export"},predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.saveToActiveFile&&!!t.fileHandle&&!t.viewModeEnabled,perform:async(e,t,o,n)=>{let r=!!t.fileHandle;try{let{fileHandle:i}=Qd(t.fileHandle)?await j2(e,t,n.files,n.getName()):await Zd(e,t,n.files,n.getName());return{captureUpdate:un.EVENTUALLY,appState:{...t,fileHandle:i,toast:r?{message:i?.name?f("toast.fileSavedToFilename").replace("{filename}",`"${i.name}"`):f("toast.fileSaved")}:null}}}catch(i){return i?.name!=="AbortError"?console.error(i):console.warn(i),{captureUpdate:un.EVENTUALLY}}},keyTest:e=>e.key===Ts.S&&e[Ts.CTRL_OR_CMD]&&!e.shiftKey}),Ic=W({name:"saveFileToDisk",label:"exportDialog.disk_title",icon:zi,viewMode:!0,trackEvent:{category:"export"},perform:async(e,t,o,n)=>{try{let{fileHandle:r}=await Zd(e,{...t,fileHandle:null},n.files,n.getName());return{captureUpdate:un.EVENTUALLY,appState:{...t,openDialog:null,fileHandle:r,toast:{message:f("toast.fileSaved")}}}}catch(r){return r?.name!=="AbortError"?console.error(r):console.warn(r),{captureUpdate:un.EVENTUALLY}}},keyTest:e=>e.key===Ts.S&&e.shiftKey&&e[Ts.CTRL_OR_CMD],PanelComponent:({updateData:e})=>hr(ne,{type:"button",icon:Cy,title:f("buttons.saveAs"),"aria-label":f("buttons.saveAs"),showAriaLabel:we().formFactor==="phone",hidden:!Na,onClick:()=>e(null),"data-testid":"save-as-button"})}),Cs=W({name:"loadScene",label:"buttons.load",trackEvent:{category:"export"},predicate:(e,t,o,n)=>!!n.props.UIOptions.canvasActions.loadScene&&!t.viewModeEnabled,perform:async(e,t,o,n)=>{try{let{elements:r,appState:i,files:a}=await qg(t,e);return{elements:r,appState:i,files:a,captureUpdate:un.IMMEDIATELY}}catch(r){return r?.name==="AbortError"?(console.warn(r),!1):{elements:e,appState:{...t,errorMessage:r.message},files:n.files,captureUpdate:un.EVENTUALLY}}},keyTest:e=>e[Ts.CTRL_OR_CMD]&&e.key===Ts.O}),J2=W({name:"exportWithDarkMode",label:"imageExportDialog.label.darkMode",trackEvent:{category:"export",action:"toggleTheme"},perform:(e,t,o)=>({appState:{...t,exportWithDarkMode:o},captureUpdate:un.EVENTUALLY}),PanelComponent:({appState:e,updateData:t})=>hr("div",{style:{display:"flex",justifyContent:"flex-end",marginTop:"-45px",marginBottom:"10px"},children:hr(A2,{value:e.exportWithDarkMode?Sf.DARK:Sf.LIGHT,onChange:o=>{t(o===Sf.DARK)},title:f("imageExportDialog.label.darkMode")})})});import{DEFAULT_FONT_SIZE as xR,DEFAULT_FONT_FAMILY as ER,DEFAULT_TEXT_ALIGN as yR,CODES as Q2,KEYS as eI,getLineHeight as wR}from"@orangecatai/common";import{newElementWith as op}from"@orangecatai/element";import{hasBoundTextElement as vR,canApplyRoundnessTypeToElement as IR,getDefaultRoundnessTypeForElement as TR,isFrameLikeElement as CR,isArrowElement as kR,isExcalidrawElement as SR,isTextElement as Af}from"@orangecatai/element";import{getBoundTextElement as MR,redrawTextBoundingBox as PR}from"@orangecatai/element";import{CaptureUpdateAction as Lf}from"@orangecatai/element";var tI="{}",_f=W({name:"copyStyles",label:"labels.copyStyles",icon:Th,trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=[],i=e.find(a=>t.selectedElementIds[a.id]);if(r.push(i),i&&vR(i)){let a=MR(i,n.scene.getNonDeletedElementsMap());r.push(a)}return i&&(tI=JSON.stringify(r)),{appState:{...t,toast:{message:f("toast.copyStyles")}},captureUpdate:Lf.EVENTUALLY}},keyTest:e=>e[eI.CTRL_OR_CMD]&&e.altKey&&e.code===Q2.C}),Df=W({name:"pasteStyles",label:"labels.pasteStyles",icon:Th,trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=JSON.parse(tI),i=r[0],a=r[1];if(!SR(i))return{elements:e,captureUpdate:Lf.EVENTUALLY};let s=le(e,t,{includeBoundTextElement:!0}),l=s.map(c=>c.id);return{elements:e.map(c=>{if(l.includes(c.id)){let m=i;if(Af(c)&&c.containerId&&(m=a),!m)return c;let p=op(c,{backgroundColor:m?.backgroundColor,strokeWidth:m?.strokeWidth,strokeColor:m?.strokeColor,strokeStyle:m?.strokeStyle,fillStyle:m?.fillStyle,opacity:m?.opacity,roughness:m?.roughness,roundness:m.roundness?IR(m.roundness.type,c)?m.roundness:TR(c):null});if(Af(p)){let d=m.fontSize||xR,u=m.fontFamily||ER;p=op(p,{fontSize:d,fontFamily:u,textAlign:m.textAlign||yR,lineHeight:m.lineHeight||wR(u)});let h=null;p.containerId&&(h=s.find(g=>Af(p)&&g.id===p.containerId)||null),PR(p,h,n.scene)}return p.type==="arrow"&&kR(m)&&(p=op(p,{startArrowhead:m.startArrowhead,endArrowhead:m.endArrowhead})),CR(c)&&(p=op(p,{roundness:null,backgroundColor:"transparent"})),p}return c}),captureUpdate:Lf.IMMEDIATELY}},keyTest:e=>e[eI.CTRL_OR_CMD]&&e.altKey&&e.code===Q2.V});import{KEYS as AR}from"@orangecatai/common";import{CaptureUpdateAction as LR}from"@orangecatai/element";var ji=W({name:"toggleShortcuts",label:"welcomeScreen.defaults.helpHint",icon:wy,viewMode:!0,trackEvent:{category:"menu",action:"toggleHelpDialog"},perform:(e,t,o,{focusContainer:n})=>(t.openDialog?.name==="help"&&n(),{appState:{...t,openDialog:t.openDialog?.name==="help"?null:{name:"help"},openMenu:null,openPopup:null},captureUpdate:LR.EVENTUALLY}),keyTest:e=>e.key===AR.QUESTION_MARK});import{getNonDeletedElements as rp}from"@orangecatai/element";import{newElementWith as rI}from"@orangecatai/element";import{isBoundToContainer as _R}from"@orangecatai/element";import{frameAndChildrenSelectedTogether as DR,getElementsInResizingFrame as RR,getFrameLikeElements as NR,getRootElements as BR,groupByFrameLikes as FR,removeElementsFromFrame as OR,replaceAllElementsInFrame as zR}from"@orangecatai/element";import{KEYS as ip,randomId as HR,arrayToMap as Rf}from"@orangecatai/common";import{getSelectedGroupIds as np,selectGroup as GR,selectGroupsForSelectedElements as UR,getElementsInGroup as oI,addToGroup as WR,removeFromSelectedGroups as YR,isElementInGroup as iI}from"@orangecatai/element";import{syncMovedIndices as VR}from"@orangecatai/element";import{CaptureUpdateAction as Tc}from"@orangecatai/element";import{jsx as ks}from"react/jsx-runtime";var $R=e=>{if(e.length>=2){let t=e[0].groupIds;for(let o of t)if(e.reduce((n,r)=>n&&iI(r,o),!0))return!0}return!1},nI=(e,t,o)=>{let n=o.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0});return n.length>=2&&!$R(n)&&!DR(n)},Nf=W({name:"group",label:"labels.group",icon:e=>ks(Eh,{theme:e.theme}),trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=BR(n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0}));if(r.length<2)return{appState:t,elements:e,captureUpdate:Tc.EVENTUALLY};let i=np(t);if(i.length===1){let E=i[0],w=new Set(oI(e,E).map(v=>v.id)),x=new Set(r.map(v=>v.id));if(new Set([...Array.from(w),...Array.from(x)]).size===w.size)return{appState:t,elements:e,captureUpdate:Tc.EVENTUALLY}}let a=[...e];new Set(r.map(E=>E.frameId)).size>1&&FR(r).forEach((w,x)=>{OR(w,n.scene.getNonDeletedElementsMap())});let l=HR(),c=Rf(r);a=a.map(E=>c.get(E.id)?rI(E,{groupIds:WR(E.groupIds,l,t.editingGroupId)}):E);let m=oI(a,l),p=m[m.length-1],d=a.lastIndexOf(p),u=a.slice(d+1),h=a.slice(0,d).filter(E=>!iI(E,l)),g=VR([...h,...m,...u],Rf(m));return{appState:{...t,...GR(l,{...t,selectedGroupIds:{}},rp(a))},elements:g,captureUpdate:Tc.IMMEDIATELY}},predicate:(e,t,o,n)=>nI(e,t,n),keyTest:e=>!e.shiftKey&&e[ip.CTRL_OR_CMD]&&e.key===ip.G,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>ks(ne,{hidden:!nI(e,t,n),type:"button",icon:ks(Eh,{theme:t.theme}),onClick:()=>o(null),title:`${f("labels.group")} \u2014 ${G("CtrlOrCmd+G")}`,"aria-label":f("labels.group"),visible:He(rp(e),t)})}),Bf=W({name:"ungroup",label:"labels.ungroup",icon:e=>ks(yh,{theme:e.theme}),trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=np(t),i=Rf(e);if(r.length===0)return{appState:t,elements:e,captureUpdate:Tc.EVENTUALLY};let a=[...e],s=[];a=a.map(d=>{_R(d)&&s.push(d.id);let u=YR(d.groupIds,t.selectedGroupIds);return u.length===d.groupIds.length?d:rI(d,{groupIds:u})});let l=UR(t,rp(a),t,null),c=n.scene.getSelectedElements(t),m=new Set(c.filter(d=>d.frameId).map(d=>d.frameId));return NR(e).filter(d=>m.has(d.id)).forEach(d=>{d&&(a=zR(a,RR(a,d,t,i),d,n))}),l.selectedElementIds=Object.entries(l.selectedElementIds).reduce((d,[u,h])=>(h&&!s.includes(u)&&(d[u]=!0),d),{}),{appState:{...t,...l},elements:a,captureUpdate:Tc.IMMEDIATELY}},keyTest:e=>e.shiftKey&&e[ip.CTRL_OR_CMD]&&e.key===ip.G.toUpperCase(),predicate:(e,t)=>np(t).length>0,PanelComponent:({elements:e,appState:t,updateData:o})=>ks(ne,{type:"button",hidden:np(t).length===0,icon:ks(yh,{theme:t.theme}),onClick:()=>o(null),title:`${f("labels.ungroup")} \u2014 ${G("CtrlOrCmd+Shift+G")}`,"aria-label":f("labels.ungroup"),visible:He(rp(e),t)})});import QR from"clsx";import{CaptureUpdateAction as dI}from"@orangecatai/element";import{invariant as e7}from"@orangecatai/common";import{COLOR_CHARCOAL_BLACK as KR,COLOR_VOICE_CALL as XR,COLOR_WHITE as sp,THEME as ZR,UserIdleState as aI}from"@orangecatai/common";var ap=(e,t,o,n,r,i,a)=>{e.beginPath(),e.moveTo(t+i,o),e.lineTo(t+n-i,o),e.quadraticCurveTo(t+n,o,t+n,o+i),e.lineTo(t+n,o+r-i),e.quadraticCurveTo(t+n,o+r,t+n-i,o+r),e.lineTo(t+i,o+r),e.quadraticCurveTo(t,o+r,t,o+r-i),e.lineTo(t,o+i),e.quadraticCurveTo(t,o,t+i,o),e.closePath(),e.fill(),a&&(e.strokeStyle=a),e.stroke()};function jR(e){let t=0;if(e.length===0)return t;for(let o=0;o<e.length;o++){let n=e.charCodeAt(o);t=(t<<5)-t+n}return t}var qi=(e,t)=>`hsl(${Math.abs(jR(t?.id||e))%37*10}, 100%, 83%)`,sI=e=>{let t=e?.trim()?.codePointAt(0);return(t?String.fromCodePoint(t):"?").toUpperCase()},lI=({context:e,renderConfig:t,appState:o,normalizedWidth:n,normalizedHeight:r})=>{for(let[i,a]of t.remotePointerViewportCoords){let{x:s,y:l}=a,c=o.collaborators.get(i);s-=o.offsetLeft,l-=o.offsetTop;let m=11,p=14,d=s<0||s>n-m||l<0||l>r-p;s=Math.max(s,0),s=Math.min(s,n-m),l=Math.max(l,0),l=Math.min(l,r-p);let u=qi(i,c);e.save(),e.strokeStyle=u,e.fillStyle=u;let h=t.remotePointerUserStates.get(i),g=d||h===aI.IDLE||h===aI.AWAY;g&&(e.globalAlpha=.3),t.remotePointerButton.get(i)==="down"&&(e.beginPath(),e.arc(s,l,15,0,2*Math.PI,!1),e.lineWidth=3,e.strokeStyle="#ffffff88",e.stroke(),e.closePath(),e.beginPath(),e.arc(s,l,15,0,2*Math.PI,!1),e.lineWidth=1,e.strokeStyle=u,e.stroke(),e.closePath());let E=o.theme===ZR.DARK?"#2f6330":XR,w=c?.isSpeaking;w&&(e.fillStyle=E,e.strokeStyle=E,e.lineWidth=10,e.lineJoin="round",e.beginPath(),e.moveTo(s,l),e.lineTo(s+0,l+14),e.lineTo(s+4,l+9),e.lineTo(s+11,l+8),e.closePath(),e.stroke(),e.fill()),e.fillStyle=sp,e.strokeStyle=sp,e.lineWidth=6,e.lineJoin="round",e.beginPath(),e.moveTo(s,l),e.lineTo(s+0,l+14),e.lineTo(s+4,l+9),e.lineTo(s+11,l+8),e.closePath(),e.stroke(),e.fill(),e.fillStyle=u,e.strokeStyle=u,e.lineWidth=2,e.lineJoin="round",e.beginPath(),g?(e.moveTo(s-1,l-1),e.lineTo(s-1,l+15),e.lineTo(s+5,l+10),e.lineTo(s+12,l+9),e.closePath(),e.fill()):(e.moveTo(s,l),e.lineTo(s+0,l+14),e.lineTo(s+4,l+9),e.lineTo(s+11,l+8),e.closePath(),e.fill(),e.stroke());let x=t.remotePointerUsernames.get(i)||"";if(!d&&x){e.font="600 12px sans-serif";let y=(w?s+0:s)+m/2,v=(w?l+0:l)+p+2,I=5,k=3,L=e.measureText(x),S=L.actualBoundingBoxDescent+L.actualBoundingBoxAscent,_=Math.max(S,12),P=y-1,T=v-1,M=L.width+2+I*2+2,N=_+2+k*2+2;if(e.roundRect?(e.beginPath(),e.roundRect(P,T,M,N,8),e.fillStyle=u,e.fill(),e.strokeStyle=sp,e.stroke(),w&&(e.beginPath(),e.roundRect(P-2,T-2,M+4,N+4,8),e.strokeStyle=E,e.stroke())):ap(e,P,T,M,N,8,sp),e.fillStyle=KR,e.fillText(x,y+I+1,v+k+L.actualBoundingBoxAscent+Math.floor((_-S)/2)+2),w){e.fillStyle=E;let O=8,B=8,U=5;e.fillRect(P+M+B,T+(N/2-O/2),2,O),e.fillRect(P+M+B+U,T+(N/2-O*2/2),2,O*2),e.fillRect(P+M+B+U*2,T+(N/2-O/2),2,O)}}e.restore(),e.closePath()}};import qR from"clsx";import{useState as JR}from"react";import{jsx as cI}from"react/jsx-runtime";var Ff=({color:e,onClick:t,name:o,src:n,className:r})=>{let i=sI(o),[a,s]=JR(!1),l=!a&&n,c=l?void 0:{background:e};return cI("div",{className:qR("Avatar",r),style:c,onClick:t,children:l?cI("img",{className:"Avatar-img",src:n,alt:i,referrerPolicy:"no-referrer",onError:()=>s(!0)}):i})};import{jsx as zn,jsxs as lp}from"react/jsx-runtime";var t7=W({name:"goToCollaborator",label:"Go to a collaborator",viewMode:!0,trackEvent:{category:"collab"},perform:(e,t,o)=>(e7(o,"actionGoToCollaborator: collaborator should be defined when actionGoToCollaborator is called"),!o.socketId||t.userToFollow?.socketId===o.socketId||o.isCurrentUser?{appState:{...t,userToFollow:null},captureUpdate:dI.EVENTUALLY}:{appState:{...t,userToFollow:{socketId:o.socketId,username:o.username||""},openMenu:t.openMenu==="canvas"?null:t.openMenu},captureUpdate:dI.EVENTUALLY}),PanelComponent:({updateData:e,data:t,appState:o})=>{let{socketId:n,collaborator:r,withName:i,isBeingFollowed:a}=t,s=qi(n,r),l=QR({"is-followed":a,"is-current-user":r.isCurrentUser===!0,"is-speaking":r.isSpeaking,"is-in-call":r.isInCall,"is-muted":r.isMuted}),c=r.isInCall?r.isSpeaking?lp("div",{className:"UserList__collaborator-status-icon-speaking-indicator",title:f("userList.hint.isSpeaking"),children:[zn("div",{}),zn("div",{}),zn("div",{})]}):r.isMuted?zn("div",{className:"UserList__collaborator-status-icon-microphone-muted",title:f("userList.hint.micMuted"),children:Dw}):zn("div",{title:f("userList.hint.inCall"),children:_w}):null;return i?lp("div",{className:`dropdown-menu-item dropdown-menu-item-base UserList__collaborator ${l}`,style:{"--avatar-size":"1.5rem"},onClick:()=>e(r),children:[zn(Ff,{color:s,onClick:()=>{},name:r.username||"",src:r.avatarUrl,className:l}),zn("div",{className:"UserList__collaborator-name",children:r.username}),lp("div",{className:"UserList__collaborator-status-icons","aria-hidden":!0,children:[a&&zn("div",{className:"UserList__collaborator-status-icon-is-followed",title:f("userList.hint.followStatus"),children:ts}),c]})]}):lp("div",{className:`UserList__collaborator UserList__collaborator--avatar-only ${l}`,children:[zn(Ff,{color:s,onClick:()=>{e(r)},name:r.username||"",src:r.avatarUrl,className:l}),c&&zn("div",{className:"UserList__collaborator-status-icon",children:c})]})}});import{LIBRARY_DISABLED_TYPES as o7,randomId as n7}from"@orangecatai/common";import{deepCopyElement as r7}from"@orangecatai/element";import{CaptureUpdateAction as Of}from"@orangecatai/element";var zf=W({name:"addToLibrary",trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});for(let i of o7)if(r.some(a=>a.type===i))return{captureUpdate:Of.EVENTUALLY,appState:{...t,errorMessage:f(`errors.libraryElementTypeError.${i}`)}};return n.library.getLatestLibrary().then(i=>n.library.setLibrary([{id:n7(),status:"unpublished",elements:r.map(r7),created:Date.now()},...i])).then(()=>({captureUpdate:Of.EVENTUALLY,appState:{...t,toast:{message:f("toast.addedToLibrary")}}})).catch(i=>({captureUpdate:Of.EVENTUALLY,appState:{...t,errorMessage:i.message}}))},label:"labels.addToLibrary"});import{getNonDeletedElements as Ss}from"@orangecatai/element";import{isFrameLikeElement as i7}from"@orangecatai/element";import{updateFrameMembershipOfSelectedElements as a7}from"@orangecatai/element";import{KEYS as Zr,arrayToMap as s7}from"@orangecatai/common";import{alignElements as l7}from"@orangecatai/element";import{CaptureUpdateAction as Ms}from"@orangecatai/element";import{getSelectedElementsByGroup as c7}from"@orangecatai/element";import{jsx as As}from"react/jsx-runtime";var no=(e,t)=>{let o=t.scene.getSelectedElements(e);return c7(o,t.scene.getNonDeletedElementsMap(),e).length>1&&!o.some(n=>i7(n))},Ps=(e,t,o,n)=>{let r=o.scene.getSelectedElements(t),i=l7(r,n,o.scene,t),a=s7(i);return a7(e.map(s=>a.get(s.id)||s),t,o)},d7=W({name:"alignTop",label:"labels.alignTop",icon:uh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>no(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"start",axis:"y"}),captureUpdate:Ms.IMMEDIATELY}),keyTest:e=>e[Zr.CTRL_OR_CMD]&&e.shiftKey&&e.key===Zr.ARROW_UP,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!no(t,n),type:"button",icon:uh,onClick:()=>o(null),title:`${f("labels.alignTop")} \u2014 ${G("CtrlOrCmd+Shift+Up")}`,"aria-label":f("labels.alignTop"),visible:He(Ss(e),t)})}),m7=W({name:"alignBottom",label:"labels.alignBottom",icon:gh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>no(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"end",axis:"y"}),captureUpdate:Ms.IMMEDIATELY}),keyTest:e=>e[Zr.CTRL_OR_CMD]&&e.shiftKey&&e.key===Zr.ARROW_DOWN,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!no(t,n),type:"button",icon:gh,onClick:()=>o(null),title:`${f("labels.alignBottom")} \u2014 ${G("CtrlOrCmd+Shift+Down")}`,"aria-label":f("labels.alignBottom"),visible:He(Ss(e),t)})}),p7=W({name:"alignLeft",label:"labels.alignLeft",icon:hh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>no(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"start",axis:"x"}),captureUpdate:Ms.IMMEDIATELY}),keyTest:e=>e[Zr.CTRL_OR_CMD]&&e.shiftKey&&e.key===Zr.ARROW_LEFT,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!no(t,n),type:"button",icon:hh,onClick:()=>o(null),title:`${f("labels.alignLeft")} \u2014 ${G("CtrlOrCmd+Shift+Left")}`,"aria-label":f("labels.alignLeft"),visible:He(Ss(e),t)})}),u7=W({name:"alignRight",label:"labels.alignRight",icon:fh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>no(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"end",axis:"x"}),captureUpdate:Ms.IMMEDIATELY}),keyTest:e=>e[Zr.CTRL_OR_CMD]&&e.shiftKey&&e.key===Zr.ARROW_RIGHT,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!no(t,n),type:"button",icon:fh,onClick:()=>o(null),title:`${f("labels.alignRight")} \u2014 ${G("CtrlOrCmd+Shift+Right")}`,"aria-label":f("labels.alignRight"),visible:He(Ss(e),t)})}),g7=W({name:"alignVerticallyCentered",label:"labels.centerVertically",icon:bh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>no(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"center",axis:"y"}),captureUpdate:Ms.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!no(t,n),type:"button",icon:bh,onClick:()=>o(null),title:f("labels.centerVertically"),"aria-label":f("labels.centerVertically"),visible:He(Ss(e),t)})}),h7=W({name:"alignHorizontallyCentered",label:"labels.centerHorizontally",icon:xh,trackEvent:{category:"element"},predicate:(e,t,o,n)=>no(t,n),perform:(e,t,o,n)=>({appState:t,elements:Ps(e,t,n,{position:"center",axis:"x"}),captureUpdate:Ms.IMMEDIATELY}),PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>As(ne,{hidden:!no(t,n),type:"button",icon:xh,onClick:()=>o(null),title:f("labels.centerHorizontally"),"aria-label":f("labels.centerHorizontally"),visible:He(Ss(e),t)})});import{getNonDeletedElements as mI}from"@orangecatai/element";import{isFrameLikeElement as f7}from"@orangecatai/element";import{CODES as pI,KEYS as uI,arrayToMap as b7}from"@orangecatai/common";import{updateFrameMembershipOfSelectedElements as x7}from"@orangecatai/element";import{distributeElements as E7}from"@orangecatai/element";import{CaptureUpdateAction as gI}from"@orangecatai/element";import{getSelectedElementsByGroup as y7}from"@orangecatai/element";import{jsx as bI}from"react/jsx-runtime";var hI=(e,t)=>{let o=t.scene.getSelectedElements(e);return y7(o,t.scene.getNonDeletedElementsMap(),e).length>2&&!o.some(n=>f7(n))},fI=(e,t,o,n)=>{let r=o.scene.getSelectedElements(t),i=E7(r,o.scene.getNonDeletedElementsMap(),n,t,o.scene),a=b7(i);return x7(e.map(s=>a.get(s.id)||s),t,o)},w7=W({name:"distributeHorizontally",label:"labels.distributeHorizontally",trackEvent:{category:"element"},perform:(e,t,o,n)=>({appState:t,elements:fI(e,t,n,{space:"between",axis:"x"}),captureUpdate:gI.IMMEDIATELY}),keyTest:e=>!e[uI.CTRL_OR_CMD]&&e.altKey&&e.code===pI.H,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>bI(ne,{hidden:!hI(t,n),type:"button",icon:Dy,onClick:()=>o(null),title:`${f("labels.distributeHorizontally")} \u2014 ${G("Alt+H")}`,"aria-label":f("labels.distributeHorizontally"),visible:He(mI(e),t)})}),v7=W({name:"distributeVertically",label:"labels.distributeVertically",trackEvent:{category:"element"},perform:(e,t,o,n)=>({appState:t,elements:fI(e,t,n,{space:"between",axis:"y"}),captureUpdate:gI.IMMEDIATELY}),keyTest:e=>!e[uI.CTRL_OR_CMD]&&e.altKey&&e.code===pI.V,PanelComponent:({elements:e,appState:t,updateData:o,app:n})=>bI(ne,{hidden:!hI(t,n),type:"button",icon:Ry,onClick:()=>o(null),title:`${f("labels.distributeVertically")} \u2014 ${G("Alt+V")}`,"aria-label":f("labels.distributeVertically"),visible:He(mI(e),t)})});import{getNonDeletedElements as I7}from"@orangecatai/element";import{bindOrUnbindBindingElements as T7}from"@orangecatai/element";import{getCommonBoundingBox as xI}from"@orangecatai/element";import{newElementWith as C7}from"@orangecatai/element";import{deepCopyElement as k7}from"@orangecatai/element";import{resizeMultipleElements as S7}from"@orangecatai/element";import{isArrowElement as EI,isElbowArrow as M7}from"@orangecatai/element";import{updateFrameMembershipOfSelectedElements as yI}from"@orangecatai/element";import{CODES as wI,KEYS as P7,arrayToMap as A7}from"@orangecatai/common";import{CaptureUpdateAction as vI}from"@orangecatai/element";var Hf=W({name:"flipHorizontal",label:"labels.flipHorizontal",icon:Fw,trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:yI(II(e,n.scene.getNonDeletedElementsMap(),t,"horizontal",n),t,n),appState:t,captureUpdate:vI.IMMEDIATELY}),keyTest:e=>e.shiftKey&&e.code===wI.H}),Gf=W({name:"flipVertical",label:"labels.flipVertical",icon:Bw,trackEvent:{category:"element"},perform:(e,t,o,n)=>({elements:yI(II(e,n.scene.getNonDeletedElementsMap(),t,"vertical",n),t,n),appState:t,captureUpdate:vI.IMMEDIATELY}),keyTest:e=>e.shiftKey&&e.code===wI.V&&!e[P7.CTRL_OR_CMD]}),II=(e,t,o,n,r)=>{let i=le(I7(e),o,{includeBoundTextElement:!0,includeElementsInFrames:!0}),a=L7(i,t,n,r),s=A7(a);return e.map(l=>s.get(l.id)||l)},L7=(e,t,o,n)=>{if(e.every(d=>EI(d)&&(d.startBinding||d.endBinding)))return e.map(d=>{let u=d;return C7(u,{startArrowhead:u.endArrowhead,endArrowhead:u.startArrowhead})});let{midX:r,midY:i}=xI(e);S7(e,t,"nw",n.scene,new Map(Array.from(t.values()).map(d=>[d.id,k7(d)])),{flipByX:o==="horizontal",flipByY:o==="vertical",shouldResizeFromCenter:!0,shouldMaintainAspectRatio:!0}),T7(e.filter(EI),n.scene,n.state);let{elbowArrows:a,otherElements:s}=e.reduce((d,u)=>M7(u)?{...d,elbowArrows:d.elbowArrows.concat(u)}:{...d,otherElements:d.otherElements.concat(u)},{elbowArrows:[],otherElements:[]}),{midX:l,midY:c}=xI(e),[m,p]=[r-l,i-c];return s.forEach(d=>n.scene.mutateElement(d,{x:d.x+m,y:d.y+p})),a.forEach(d=>n.scene.mutateElement(d,{x:d.x+m,y:d.y+p})),e};import{isTextElement as _7}from"@orangecatai/element";import{getTextFromElements as D7}from"@orangecatai/element";import{CODES as R7,KEYS as TI,isFirefox as N7}from"@orangecatai/common";import{CaptureUpdateAction as Po}from"@orangecatai/element";var Ls=W({name:"copy",label:"labels.copy",icon:Xl,trackEvent:{category:"element"},perform:async(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});try{await Jm(r,n.files,o)}catch(i){return{captureUpdate:Po.EVENTUALLY,appState:{...t,errorMessage:i.message}}}return{captureUpdate:Po.EVENTUALLY}},keyTest:void 0}),Uf=W({name:"paste",label:"labels.paste",trackEvent:{category:"element"},perform:async(e,t,o,n)=>{let r;try{r=await $2()}catch(i){return i.name==="AbortError"||i.name==="NotAllowedError"?!1:(console.error(`actionPaste ${i.name}: ${i.message}`),N7?{captureUpdate:Po.EVENTUALLY,appState:{...t,errorMessage:f("hints.firefox_clipboard_write")}}:{captureUpdate:Po.EVENTUALLY,appState:{...t,errorMessage:f("errors.asyncPasteFailedOnRead")}})}try{n.pasteFromClipboard(Y2({types:r}))}catch(i){return console.error(i),{captureUpdate:Po.EVENTUALLY,appState:{...t,errorMessage:f("errors.asyncPasteFailedOnParse")}}}return{captureUpdate:Po.EVENTUALLY}},keyTest:void 0}),cp=W({name:"cut",label:"labels.cut",icon:Ew,trackEvent:{category:"element"},perform:(e,t,o,n)=>(Ls.perform(e,t,o,n),nc.perform(e,t,null,n)),keyTest:e=>e[TI.CTRL_OR_CMD]&&e.key===TI.X}),dp=W({name:"copyAsSvg",label:"labels.copyAsSvg",icon:Ow,trackEvent:{category:"element"},perform:async(e,t,o,n)=>{if(!n.canvas)return{captureUpdate:Po.EVENTUALLY};let{exportedElements:r,exportingFrame:i}=Ki(e,t,!0);try{await Xi("clipboard-svg",r,t,n.files,{...t,exportingFrame:i,name:n.getName()});let a=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});return{appState:{toast:{message:f("toast.copyToClipboardAsSvg",{exportSelection:a.length?f("toast.selection"):f("toast.canvas"),exportColorScheme:t.exportWithDarkMode?f("buttons.darkMode"):f("buttons.lightMode")})}},captureUpdate:Po.EVENTUALLY}}catch(a){return console.error(a),{appState:{errorMessage:a.message},captureUpdate:Po.EVENTUALLY}}},predicate:e=>qm&&e.length>0,keywords:["svg","clipboard","copy"]}),mp=W({name:"copyAsPng",label:"labels.copyAsPng",icon:zw,trackEvent:{category:"element"},perform:async(e,t,o,n)=>{if(!n.canvas)return{captureUpdate:Po.EVENTUALLY};let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0}),{exportedElements:i,exportingFrame:a}=Ki(e,t,!0);try{return await Xi("clipboard",i,t,n.files,{...t,exportingFrame:a,name:n.getName()}),{appState:{...t,toast:{message:f("toast.copyToClipboardAsPng",{exportSelection:r.length?f("toast.selection"):f("toast.canvas"),exportColorScheme:t.exportWithDarkMode?f("buttons.darkMode"):f("buttons.lightMode")})}},captureUpdate:Po.EVENTUALLY}}catch(s){return console.error(s),{appState:{...t,errorMessage:s.message},captureUpdate:Po.EVENTUALLY}}},predicate:e=>vs&&e.length>0,keyTest:e=>e.code===R7.C&&e.altKey&&e.shiftKey,keywords:["png","clipboard","copy"]}),pp=W({name:"copyText",label:"labels.copyText",trackEvent:{category:"element"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0});try{pn(D7(r))}catch{throw new Error(f("errors.copyToSystemClipboardFailed"))}return{captureUpdate:Po.EVENTUALLY}},predicate:(e,t,o,n)=>qm&&n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0}).some(_7),keywords:["text","clipboard","copy"]});import{CODES as B7,KEYS as F7}from"@orangecatai/common";import{CaptureUpdateAction as O7}from"@orangecatai/element";var _s=W({name:"gridMode",icon:Yw,keywords:["snap"],label:"labels.toggleGrid",viewMode:!0,trackEvent:{category:"canvas",predicate:e=>e.gridModeEnabled},perform(e,t){return{appState:{...t,gridModeEnabled:!this.checked(t),objectsSnapModeEnabled:!1},captureUpdate:O7.EVENTUALLY}},checked:e=>e.gridModeEnabled,predicate:(e,t,o)=>o.gridModeEnabled===void 0,keyTest:e=>e[F7.CTRL_OR_CMD]&&e.code===B7.QUOTE});import{CODES as z7,KEYS as H7}from"@orangecatai/common";import{CaptureUpdateAction as G7}from"@orangecatai/element";var jr=W({name:"zenMode",label:"buttons.zenMode",icon:Gw,viewMode:!0,trackEvent:{category:"canvas",predicate:e=>!e.zenModeEnabled},perform(e,t){return{appState:{...t,zenModeEnabled:!this.checked(t)},captureUpdate:G7.EVENTUALLY}},checked:e=>e.zenModeEnabled,predicate:(e,t,o,n)=>n.editorInterface.formFactor!=="phone"&&typeof o.zenModeEnabled>"u",keyTest:e=>!e[H7.CTRL_OR_CMD]&&e.altKey&&e.code===z7.Z});import{CODES as U7,KEYS as W7}from"@orangecatai/common";import{CaptureUpdateAction as Y7}from"@orangecatai/element";var Cc=W({name:"objectsSnapMode",label:"buttons.objectsSnapMode",icon:Hw,viewMode:!1,trackEvent:{category:"canvas",predicate:e=>!e.objectsSnapModeEnabled},perform(e,t){return{appState:{...t,objectsSnapModeEnabled:!this.checked(t),gridModeEnabled:!1},captureUpdate:Y7.EVENTUALLY}},checked:e=>e.objectsSnapModeEnabled,predicate:(e,t,o)=>typeof o.objectsSnapModeEnabled>"u",keyTest:e=>!e[W7.CTRL_OR_CMD]&&e.altKey&&e.code===U7.S});import{CODES as V7,KEYS as $7}from"@orangecatai/common";import{CaptureUpdateAction as K7}from"@orangecatai/element";var qr=W({name:"stats",label:"stats.fullTitle",icon:Nw,viewMode:!0,trackEvent:{category:"menu"},keywords:["edit","attributes","customize"],perform(e,t){return{appState:{...t,stats:{...t.stats,open:!this.checked(t)}},captureUpdate:K7.EVENTUALLY}},checked:e=>e.stats.open,keyTest:e=>!e[$7.CTRL_OR_CMD]&&e.altKey&&e.code===V7.SLASH});import{BOUND_TEXT_PADDING as CI,ROUNDNESS as kI,TEXT_ALIGN as PI,VERTICAL_ALIGN as AI,arrayToMap as LI,getFontString as X7}from"@orangecatai/common";import{getOriginalContainerHeightFromCache as Z7,isBoundToContainer as SI,resetOriginalContainerCache as j7,updateOriginalContainerCache as q7}from"@orangecatai/element";import{computeBoundTextPosition as J7,computeContainerDimensionForBoundText as MI,getBoundTextElement as _I,redrawTextBoundingBox as DI}from"@orangecatai/element";import{hasBoundTextElement as Q7,isArrowElement as eN,isTextBindableContainer as Wf,isTextElement as kc,isUsingAdaptiveRadius as tN}from"@orangecatai/element";import{measureText as oN}from"@orangecatai/element";import{syncMovedIndices as RI}from"@orangecatai/element";import{newElement as nN}from"@orangecatai/element";import{CaptureUpdateAction as Yf}from"@orangecatai/element";var Vf=W({name:"unbindText",label:"labels.unbindText",trackEvent:{category:"element"},predicate:(e,t,o,n)=>n.scene.getSelectedElements(t).some(i=>Q7(i)),perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i=n.scene.getNonDeletedElementsMap();return r.forEach(a=>{let s=_I(a,i);if(s){let{width:l,height:c}=oN(s.originalText,X7(s),s.lineHeight),m=Z7(a.id);j7(a.id);let{x:p,y:d}=J7(a,s,i);n.scene.mutateElement(s,{containerId:null,width:l,height:c,text:s.originalText,x:p,y:d}),n.scene.mutateElement(a,{boundElements:a.boundElements?.filter(u=>u.id!==s.id),height:m||a.height})}}),{elements:e,appState:t,captureUpdate:Yf.IMMEDIATELY}}}),$f=W({name:"bindText",label:"labels.bindText",trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);if(r.length===2){let i=kc(r[0])||kc(r[1]),a;if(Wf(r[0])?a=r[0]:Wf(r[1])&&(a=r[1]),i&&a&&_I(a,n.scene.getNonDeletedElementsMap())===null)return!0}return!1},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i,a;kc(r[0])&&Wf(r[1])?(i=r[0],a=r[1]):(i=r[1],a=r[0]),n.scene.mutateElement(i,{containerId:a.id,verticalAlign:AI.MIDDLE,textAlign:PI.CENTER,autoResize:!0,angle:eN(a)?0:a?.angle??0}),n.scene.mutateElement(a,{boundElements:(a.boundElements||[]).concat({type:"text",id:i.id})});let s=a.height;return DI(i,a,n.scene),q7(a.id,s),{elements:rN(e,a,i),appState:{...t,selectedElementIds:{[a.id]:!0}},captureUpdate:Yf.IMMEDIATELY}}}),rN=(e,t,o)=>{let n=e.slice(),r=n.findIndex(a=>a.id===o.id);n.splice(r,1);let i=n.findIndex(a=>a.id===t.id);return n.splice(i+1,0,o),RI(n,LI([t,o])),n},iN=(e,t,o)=>{let n=e.slice(),r=n.findIndex(a=>a.id===t.id);n.splice(r,1);let i=n.findIndex(a=>a.id===o.id);return n.splice(i,0,t),RI(n,LI([t,o])),n},NI=W({name:"wrapTextInContainer",label:"labels.createContainerFromText",trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i=r.some(a=>kc(a)&&!SI(a));return r.length>0&&i},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t),i=e.slice(),a={};for(let s of r)if(kc(s)&&!SI(s)){let l=nN({type:"rectangle",backgroundColor:t.currentItemBackgroundColor,boundElements:[...s.boundElements||[],{id:s.id,type:"text"}],angle:s.angle,fillStyle:t.currentItemFillStyle,strokeColor:t.currentItemStrokeColor,roughness:t.currentItemRoughness,strokeWidth:t.currentItemStrokeWidth,strokeStyle:t.currentItemStrokeStyle,roundness:t.currentItemRoundness==="round"?{type:tN("rectangle")?kI.ADAPTIVE_RADIUS:kI.PROPORTIONAL_RADIUS}:null,opacity:100,locked:!1,x:s.x-CI,y:s.y-CI,width:MI(s.width,"rectangle"),height:MI(s.height,"rectangle"),groupIds:s.groupIds,frameId:s.frameId});if(s.boundElements?.length){let c=s.boundElements.filter(p=>p.type==="arrow").map(p=>p.id);i.filter(p=>c.includes(p.id)).forEach(p=>{let d=p.startBinding,u=p.endBinding;d?.elementId===s.id&&(d={...d,elementId:l.id}),u?.elementId===s.id&&(u={...u,elementId:l.id}),(d||u)&&n.scene.mutateElement(p,{startBinding:d,endBinding:u})})}n.scene.mutateElement(s,{containerId:l.id,verticalAlign:AI.MIDDLE,boundElements:null,textAlign:PI.CENTER,autoResize:!0}),DI(s,l,n.scene),i=iN([...i,l],l,s),a[l.id]=!0}return{elements:i,appState:{...t,selectedElementIds:a},captureUpdate:Yf.IMMEDIATELY}}});import{isEmbeddableElement as vN}from"@orangecatai/element";import{KEYS as VI}from"@orangecatai/common";import{CaptureUpdateAction as IN}from"@orangecatai/element";import{pointFrom as zI}from"@orangecatai/math";import aN from"clsx";import{useCallback as BI,useEffect as FI,useLayoutEffect as sN,useRef as lN,useState as cN}from"react";import{EVENT as Kf,HYPERLINK_TOOLTIP_DELAY as dN,KEYS as up}from"@orangecatai/common";import{getElementAbsoluteCoords as Jf}from"@orangecatai/element";import{hitElementBoundingBox as mN}from"@orangecatai/element";import{isElementLink as pN}from"@orangecatai/element";import{getEmbedLink as uN,embeddableURLValidator as gN}from"@orangecatai/element";import{sceneCoordsToViewportCoords as HI,viewportCoordsToSceneCoords as hN,wrapEvent as fN,isLocalLink as bN,normalizeLink as Xf}from"@orangecatai/common";import{isEmbeddableElement as Zf}from"@orangecatai/element";import{jsx as Ds,jsxs as OI}from"react/jsx-runtime";var Qf=380,xN=42,jf=5,GI=85,EN=500,qf=!1,gp=new Map,UI=({element:e,scene:t,setAppState:o,onLinkOpen:n,setToast:r,updateEmbedValidationStatus:i})=>{let a=t.getNonDeletedElementsMap(),s=Go(),l=Nn(),c=we(),m=e.link||"",[p,d]=cN(m),u=lN(null),h=s.showHyperlinkPopup==="editor",g=BI(()=>{if(!u.current)return;let v=Xf(u.current.value)||null;if(!e.link&&v&&ge("hyperlink","create"),Zf(e)){if(s.activeEmbeddable?.element===e&&o({activeEmbeddable:null}),!v){t.mutateElement(e,{link:null}),i(e,!1);return}if(!gN(v,l.validateEmbeddable))v&&r({message:f("toast.unableToEmbed"),closable:!0}),e.link&&gp.set(e.id,e.link),t.mutateElement(e,{link:v}),i(e,!1);else{let{width:I,height:k}=e,L=uN(v);L?.error instanceof URIError&&r({message:f("toast.unrecognizedLinkFormat"),closable:!0});let S=L?L.intrinsicSize.w/L.intrinsicSize.h:1,_=gp.get(e.id)!==e.link;t.mutateElement(e,{..._?{width:L?.type==="video"?I>k?I:k*S:I,height:L?.type==="video"&&I>k?I/S:k}:{},link:v}),i(e,!0),gp.has(e.id)&&gp.delete(e.id)}}else t.mutateElement(e,{link:v})},[e,t,r,l.validateEmbeddable,s.activeEmbeddable,o,i]);sN(()=>()=>{g()},[g]),FI(()=>{h&&u?.current&&!(c.formFactor==="phone"||c.isTouchScreen)&&u.current.select()},[h,c.formFactor,c.isTouchScreen]),FI(()=>{let v=null,I=k=>{if(h)return;v&&clearTimeout(v),wN(e,a,s,zI(k.clientX,k.clientY))&&(v=window.setTimeout(()=>{o({showHyperlinkPopup:!1})},EN))};return window.addEventListener(Kf.POINTER_MOVE,I,!1),()=>{window.removeEventListener(Kf.POINTER_MOVE,I,!1),v&&clearTimeout(v)}},[s,e,h,o,a]);let E=BI(()=>{ge("hyperlink","delete"),t.mutateElement(e,{link:null}),o({showHyperlinkPopup:!1})},[o,e,t]),w=()=>{ge("hyperlink","edit","popup-ui"),o({showHyperlinkPopup:"editor"})},{x,y}=WI(e,s,a);return s.contextMenu||s.selectedElementsAreBeingDragged||s.resizingElement||s.isRotating||s.openMenu||s.viewModeEnabled?null:OI("div",{className:"excalidraw-hyperlinkContainer",style:{top:`${y}px`,left:`${x}px`,width:Qf,padding:jf},children:[h?Ds("input",{className:aN("excalidraw-hyperlinkContainer-input"),placeholder:f("labels.link.hint"),ref:u,value:p,onChange:v=>d(v.target.value),autoFocus:!0,onKeyDown:v=>{v.stopPropagation(),v[up.CTRL_OR_CMD]&&v.key===up.K&&v.preventDefault(),(v.key===up.ENTER||v.key===up.ESCAPE)&&(g(),o({showHyperlinkPopup:"info"}))}}):e.link?Ds("a",{href:Xf(e.link||""),className:"excalidraw-hyperlinkContainer-link",target:bN(e.link)?"_self":"_blank",onClick:v=>{if(e.link&&n){let I=fN(Kf.EXCALIDRAW_LINK,v.nativeEvent);n({...e,link:Xf(e.link)},I),I.defaultPrevented&&v.preventDefault()}},rel:"noopener noreferrer",children:e.link}):Ds("div",{className:"excalidraw-hyperlinkContainer-link",children:f("labels.link.empty")}),OI("div",{className:"excalidraw-hyperlinkContainer__buttons",children:[!h&&Ds(ne,{type:"button",title:f("buttons.edit"),"aria-label":f("buttons.edit"),label:f("buttons.edit"),onClick:w,className:"excalidraw-hyperlinkContainer--edit",icon:Ln}),Ds(ne,{type:"button",title:f("labels.linkToElement"),"aria-label":f("labels.linkToElement"),label:f("labels.linkToElement"),onClick:()=>{o({openDialog:{name:"elementLinkSelector",sourceElementId:e.id}})},icon:bm}),m&&!Zf(e)&&Ds(ne,{type:"button",title:f("buttons.remove"),"aria-label":f("buttons.remove"),label:f("buttons.remove"),onClick:E,className:"excalidraw-hyperlinkContainer--remove",icon:Ht})]})]})},WI=(e,t,o)=>{let[n,r]=Jf(e,o),{x:i,y:a}=HI({sceneX:n+e.width/2,sceneY:r},t),s=i-t.offsetLeft-Qf/2,l=a-t.offsetTop-GI;return{x:s,y:l}},eb=(e,t)=>{let o=le(e,t);return Zf(o[0])?"labels.link.editEmbed":o[0]?.link?"labels.link.edit":"labels.link.create"},Sc=null,YI=(e,t,o)=>{Sc&&clearTimeout(Sc),Sc=window.setTimeout(()=>yN(e,t,o),dN)},yN=(e,t,o)=>{if(!e.link)return;let n=bs();n.classList.add("excalidraw-tooltip--visible"),n.style.maxWidth="20rem",n.textContent=pN(e.link)?f("labels.link.goToElement"):e.link;let[r,i,a,s]=Jf(e,o),[l,c,m,p]=UE([r,i,a,s],e.angle,t),d=HI({sceneX:l,sceneY:c},t);ff(n,{left:d.x,top:d.y,width:m,height:p},"top"),ge("hyperlink","tooltip","link-icon"),qf=!0},tb=()=>{Sc&&clearTimeout(Sc),qf&&(qf=!1,bs().classList.remove("excalidraw-tooltip--visible"))},wN=(e,t,o,[n,r])=>{let{x:i,y:a}=hN({clientX:n,clientY:r},o),s=15/o.zoom.value;if(mN(zI(i,a),e,t))return!1;let[l,c,m]=Jf(e,t);if(i>=l&&i<=m&&a>=c-GI&&a<=c)return!1;let{x:p,y:d}=WI(e,o,t);return!(n>=p-s&&n<=p+Qf+jf*2+s&&r>=d-s&&r<=d+s+jf*2+xN)};import{jsx as TN}from"react/jsx-runtime";var Mc=W({name:"hyperlink",label:(e,t)=>eb(e,t),icon:ql,perform:(e,t)=>t.showHyperlinkPopup==="editor"?!1:{elements:e,appState:{...t,showHyperlinkPopup:"editor",openMenu:null},captureUpdate:IN.IMMEDIATELY},trackEvent:{category:"hyperlink",action:"click"},keyTest:e=>e[VI.CTRL_OR_CMD]&&e.key===VI.K,predicate:(e,t)=>le(e,t).length===1,PanelComponent:({elements:e,appState:t,updateData:o})=>{let n=le(e,t);return TN(ne,{type:"button",icon:ql,"aria-label":f(eb(e,t)),title:`${vN(e[0])?f("labels.link.labelEmbed"):f("labels.link.label")} - ${G("CtrlOrCmd+K")}`,onClick:()=>o(null),selected:n.length===1&&!!n[0].link})}});import{KEYS as $I,arrayToMap as nb,randomId as CN}from"@orangecatai/common";import{elementsAreInSameGroup as kN,newElementWith as KI,selectGroupsFromGivenElements as XI}from"@orangecatai/element";import{CaptureUpdateAction as ZI}from"@orangecatai/element";var ob=e=>e.every(t=>!t.locked),Pc=W({name:"toggleElementLock",label:(e,t,o)=>{let n=o.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!1});return ob(n)?"labels.elementLock.lock":"labels.elementLock.unlock"},icon:(e,t)=>{let o=le(t,e);return ob(o)?Wa:Fi},trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return r.length>0&&!r.some(i=>i.locked&&i.frameId)},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});if(!r.length)return!1;let i=ob(r),a=nb(r),s=r.length>1&&kN(r),c=r.length===1||s?null:CN(),m={...t.lockedMultiSelections};if(i)m={...t.lockedMultiSelections,...c?{[c]:!0}:{}};else if(s){let w=r[0].groupIds.at(-1);delete m[w]}let p=e.map(w=>{if(!a.has(w.id))return w;let x=w.groupIds;return i?c&&(x=[...x,c]):x=x.filter(y=>!t.lockedMultiSelections[y]),KI(w,{locked:i,groupIds:x.length!==w.groupIds.length?x:w.groupIds})}),d=nb(p),u=i?{}:Object.fromEntries(r.map(w=>[w.id,!0])),h=r.map(w=>d.get(w.id)||w),g=i?{}:XI(h,t),E=i?c||(s?r[0].groupIds.at(-1):r[0].id):null;return{elements:p,appState:{...t,selectedElementIds:u,selectedGroupIds:g,selectedLinearElement:i?null:t.selectedLinearElement,lockedMultiSelections:m,activeLockedId:E},captureUpdate:ZI.IMMEDIATELY}},keyTest:(e,t,o,n)=>e.key.toLocaleLowerCase()===$I.L&&e[$I.CTRL_OR_CMD]&&e.shiftKey&&n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!1}).length>0}),jI=W({name:"unlockAllElements",trackEvent:{category:"canvas"},viewMode:!1,icon:Fi,predicate:(e,t)=>le(e,t).length===0&&e.some(n=>n.locked),perform:(e,t)=>{let o=e.filter(a=>a.locked),n=e.map(a=>{if(a.locked){let s=a.groupIds.filter(l=>!t.lockedMultiSelections[l]);return KI(a,{locked:!1,groupIds:a.groupIds.length!==s.length?s:a.groupIds})}return a}),r=nb(n),i=o.map(a=>r.get(a.id)||a);return{elements:n,appState:{...t,selectedElementIds:Object.fromEntries(o.map(a=>[a.id,!0])),selectedGroupIds:XI(i,t),lockedMultiSelections:{},activeLockedId:null},captureUpdate:ZI.IMMEDIATELY}},label:"labels.elementLock.unlockAll"});import{isElbowArrow as pz,isLinearElement as uz,isLineElement as Js}from"@orangecatai/element";import{arrayToMap as gz,invariant as m0}from"@orangecatai/common";import{toggleLinePolygonState as hz,CaptureUpdateAction as E5}from"@orangecatai/element";import KC from"clsx";import oO from"fuzzy";import{useEffect as Wp,useRef as XC,useMemo as nO,useState as Up}from"react";import{DEFAULT_SIDEBAR as YC,EVENT as Vp,KEYS as fn,capitalizeString as rO,isWritableElement as iO}from"@orangecatai/common";import{CaptureUpdateAction as l9}from"@orangecatai/element";import{useEffect as _c,useMemo as qI,useRef as sb,useState as SN}from"react";import{getLinearElementSubType as Bs,updateElbowArrowPoints as MN}from"@orangecatai/element";import{pointFrom as fp,pointRotateRads as PN}from"@orangecatai/math";import{hasBoundTextElement as AN,isArrowBoundToElement as LN,isArrowElement as _N,isElbowArrow as DN,isLinearElement as mb,isUsingAdaptiveRadius as RN}from"@orangecatai/element";import{getCommonBoundingBox as NN,getElementAbsoluteCoords as BN}from"@orangecatai/element";import{getBoundTextElement as oT,getBoundTextMaxHeight as FN,getBoundTextMaxWidth as ON,redrawTextBoundingBox as zN}from"@orangecatai/element";import{wrapText as HN}from"@orangecatai/element";import{assertNever as GN,CLASSES as UN,getFontString as rb,isProdEnv as WN,mapFind as YN,reduceToCommonValue as VN,updateActiveTool as JI}from"@orangecatai/common";import{measureText as QI}from"@orangecatai/element";import{LinearElementEditor as $N}from"@orangecatai/element";import{newArrowElement as ib,newElement as KN,newLinearElement as XN}from"@orangecatai/element";import{ShapeCache as ZN}from"@orangecatai/element";import{updateBindings as jN}from"@orangecatai/element";import{jsx as db}from"react/jsx-runtime";var qN=8,JN=10,Ac=["rectangle","diamond","ellipse"],Lc=["line","sharpArrow","curvedArrow","elbowArrow"],QN=new Set(Ac),e9=new Set(Lc),Fs=e=>QN.has(e),xp=e=>e==="arrow"||e9.has(e),gn=Ce(null),Dc=new Map,Rc=new Map,t9=({app:e})=>{let t=e.scene.getSelectedElements(e.state),o=sb(null);return _c(()=>{if(t.length===0){e.updateEditorAtom(gn,null);return}let n=Os(t);n&&!o.current?o.current=n:(o.current&&!n||o.current&&n!==o.current)&&(e.updateEditorAtom(gn,null),o.current=null)},[t,e]),_c(()=>()=>{Dc.clear(),Rc.clear()},[]),db(o9,{app:e,elements:t})},o9=({app:e,elements:t})=>{let o=Os(t),n=qI(()=>o==="generic"?rT(t):[],[o,t]),r=qI(()=>o==="linear"?cb(t):[],[o,t]),i=o==="generic"?n.every(p=>p.type===n[0].type):o==="linear"?r.every(p=>Bs(p)===Bs(r[0])):!1,[a,s]=SN({x:0,y:0}),l=sb(""),c=sb(null);_c(()=>{let p=[...n,...r].sort((E,w)=>E.id.localeCompare(w.id)),d=`
7
+ ${e.state.scrollX}${e.state.scrollY}${e.state.offsetTop}${e.state.offsetLeft}${e.state.zoom.value}${p.map(E=>E.id).join(",")}`;if(d===l.current)return;l.current=d;let u;if(p.length===1){let[E,,,w,x,y]=BN(p[0],e.scene.getNonDeletedElementsMap());u=PN(fp(E,w),fp(x,y),p[0].angle)}else{let{minX:E,maxY:w}=NN(p);u=fp(E,w)}let{x:h,y:g}=aT({sceneX:u[0],sceneY:u[1]},e.state);s({x:h,y:g})},[n,r,e.scene,e.state]),_c(()=>{for(let p of r){let d=lb(p.id,s9(p));Rc.has(d)||Rc.set(d,p)}},[r]),_c(()=>{for(let p of n)if(!Dc.has(p.id)){let d=oT(p,e.scene.getNonDeletedElementsMap());d&&Dc.set(p.id,{fontSize:d.fontSize})}},[n,e.scene]);let m=o==="linear"?[["line",Ka],["sharpArrow",ns],["curvedArrow",is],["elbowArrow",rs]]:o==="generic"?[["rectangle",Ya],["diamond",Va],["ellipse",$a]]:[];return db("div",{ref:c,tabIndex:-1,style:{position:"absolute",top:`${a.y+(JN+8)*e.state.zoom.value-e.state.offsetTop}px`,left:`${a.x-e.state.offsetLeft-qN}px`,zIndex:2},className:UN.CONVERT_ELEMENT_TYPE_POPUP,children:m.map(([p,d])=>{let u=i&&(o==="generic"&&n[0].type===p||o==="linear"&&Bs(r[0])===p);return db(ne,{className:"Shape",type:"radio",icon:d,checked:u,name:"convertElementType-option",title:p,keyBindingLabel:"","aria-label":p,"data-testid":`toolbar-${p}`,onChange:()=>{e.state.activeTool.type!==p&&ge("convertElementType",p,"ui"),pb(e,{conversionType:o,nextType:p}),c.current?.focus()}},`${t[0].id}${t[0].version}_${p}`)})})},n9=(e,t,o)=>{let n=ON(e,t),r=FN(e,t),i=HN(t.text,rb(t),n),a=QI(i,rb(t),t.lineHeight),s=t.fontSize;for(;(a.width>n||a.height>r)&&s>0;){s-=1;let l={...t,fontSize:s};a=QI(t.text,rb(l),t.lineHeight)}Ep(t,o.getNonDeletedElementsMap(),{fontSize:s,width:a.width,height:a.height}),zN(t,e,o)},pb=(e,{conversionType:t,nextType:o,direction:n="right"})=>{if(!t)return!1;let r=e.scene.getSelectedElements(e.state),i=r.reduce((s,l)=>({...s,[l.id]:!0}),{}),a=n==="right"?1:-1;if(t==="generic"){let s=rT(r),c=s.every(m=>m.type===s[0].type)?Ac.indexOf(s[0].type):-1;if(o=o??Ac[(c+Ac.length+a)%Ac.length],o&&Fs(o)){let m={};for(let d of s){let u=tT(d,o,e);m[u.id]=u}let p=[];for(let d of e.scene.getElementsIncludingDeleted())m[d.id]?p.push(m[d.id]):p.push(d);e.scene.replaceAllElements(p);for(let d of Object.values(m)){let u=oT(d,e.scene.getNonDeletedElementsMap());u&&(Dc.get(d.id)&&Ep(u,e.scene.getNonDeletedElementsMap(),{fontSize:Dc.get(d.id)?.fontSize??u.fontSize}),n9(d,u,e.scene))}e.setState(d=>({selectedElementIds:i,activeTool:JI(d,{type:"selection"})}))}}if(t==="linear"){let s=cb(r);if(!o){let c=VN(s,Bs),m=c?Lc.indexOf(c):-1;o=Lc[(m+Lc.length+a)%Lc.length]}if(xp(o)){let c=[],m=e.scene.getElementsMapIncludingDeleted();for(let p of s){let d=Rc.get(lb(p.id,o));if(d&&Bs(d)===o)m.set(d.id,d),c.push(d);else{let u=tT(p,o,e);m.set(u.id,u),c.push(u)}}e.scene.replaceAllElements(m);for(let p of c)if(mb(p))if(DN(p)){let d=r9(p);if(d.length<2)continue;let u=[];for(let g=1;g<d.length-2;g++)u.push({start:d[g],end:d[g+1],index:g+1});let h=MN(p,e.scene.getNonDeletedElementsMap(),{points:d,fixedSegments:u});Ep(p,e.scene.getNonDeletedElementsMap(),{...h,endArrowhead:"arrow"})}else{let d=YN(["line","sharpArrow","curvedArrow"],u=>Rc.get(lb(p.id,u)));if(d){let u=d.points;e.scene.mutateElement(p,{points:u})}}}let l=cb(e.scene.getSelectedElements(e.state));e.setState(c=>({selectedElementIds:i,selectedLinearElement:l.length===1?new $N(l[0],e.scene.getNonDeletedElementsMap()):null,activeTool:JI(c,{type:"selection"})}))}return!0},Os=e=>{if(e.length===0)return null;let t=!1;for(let o of e){if(Fs(o.type))return"generic";nT(o)&&(t=!0)}return t?"linear":null},nT=e=>mb(e)&&(!_N(e)||!LN(e)&&!AN(e)),lb=(e,t)=>`${e}:${t}`,rT=e=>e.filter(t=>Fs(t.type)),cb=e=>e.filter(t=>nT(t)),hp=20,Rs=(e,t)=>e[0]===t[0],ab=(e,t)=>e[1]===t[1],eT=(e,t)=>Rs(e,t)?Math.abs(e[1]-t[1]):Math.abs(e[0]-t[0]),r9=e=>{let t=[e.points[0]],o=i9(e.points);for(let i=1;i<o.length;++i){let a=t[t.length-1],s=[...o[i]];Math.abs(s[0]-a[0])<hp?s[0]=a[0]:Math.abs(s[1]-a[1])<hp&&(s[1]=a[1]),Rs(a,s)||ab(a,s)||t.push(fp(a[0],s[1])),t.push(s)}let n=[t[0]];for(let i=1;i<t.length-1;++i)Rs(t[i-1],t[i])&&Rs(t[i],t[i+1])||ab(t[i-1],t[i])&&ab(t[i],t[i+1])||n.push(t[i]);n.push(t[t.length-1]);let r=[n[0]];for(let i=1;i<n.length-1;++i){let a=r[r.length-1],s=n[i],l=n[i+1],c=Rs(a,s),m=Rs(s,l);if(c!==m){let p=eT(a,s),d=eT(s,l);if(p<hp||d<hp){if(d<p)c?l[0]=a[0]:l[1]=a[1];else if(m)for(let u=r.length-1;u>=0&&r[u][0]===a[0];--u)r[u][0]=s[0];else for(let u=r.length-1;u>=0&&r[u][1]===a[1];--u)r[u][1]=s[1];continue}}r.push(s)}return r.push(n[n.length-1]),r},i9=e=>{if(e.length===0)return[];let t=[e[0]];for(let o=1;o<e.length;o++){let[n,r]=t[t.length-1],[i,a]=e[o];(n!==i||r!==a)&&t.push(e[o])}return t},tT=(e,t,o)=>{if(!a9(e.type,t)){if(!WN())throw Error(`Invalid conversion from ${e.type} to ${t}.`);return e}if(e.type===t)return e;if(ZN.delete(e),Fs(t)){let n=Ns(KN({...e,type:t,roundness:t==="diamond"&&e.roundness?{type:RN(t)?bp.ADAPTIVE_RADIUS:bp.PROPORTIONAL_RADIUS}:e.roundness}));return jN(n,o.scene,o.state),n}if(xp(t))switch(t){case"line":return Ns(XN({...e,type:"line"}));case"sharpArrow":return Ns(ib({...e,type:"arrow",elbowed:!1,roundness:null,startArrowhead:o.state.currentItemStartArrowhead,endArrowhead:o.state.currentItemEndArrowhead}));case"curvedArrow":return Ns(ib({...e,type:"arrow",elbowed:!1,roundness:{type:bp.PROPORTIONAL_RADIUS},startArrowhead:o.state.currentItemStartArrowhead,endArrowhead:o.state.currentItemEndArrowhead}));case"elbowArrow":return Ns(ib({...e,type:"arrow",elbowed:!0,fixedSegments:null,roundness:null}))}return GN(t,`unhandled conversion type: ${t}`),e},a9=(e,t)=>!!(Fs(e)&&Fs(t)||xp(e)&&xp(t)),s9=e=>mb(e)?Bs(e):e.type,iT=t9;var sT=W({name:"toggleShapeSwitch",label:"labels.shapeSwitch",icon:()=>null,viewMode:!0,trackEvent:{category:"shape_switch",action:"toggle"},keywords:["change","switch","swap"],perform(e,t,o,n){return xt.set(gn,{type:"panel"}),{captureUpdate:l9.NEVER}},checked:e=>e.gridModeEnabled,predicate:(e,t,o)=>Os(e)!==null});import{canCreateLinkFromElements as ub,defaultGetElementLinkFromSelection as c9,getLinkIdAndTypeFromSelection as d9}from"@orangecatai/element";import{CaptureUpdateAction as Nc}from"@orangecatai/element";var yp=W({name:"copyElementLink",label:"labels.copyElementLink",icon:Qa,trackEvent:{category:"element"},perform:async(e,t,o,n)=>{let r=le(e,t);try{if(window.location){let i=d9(r,t);return i?(await pn(n.props.generateLinkForSelection?n.props.generateLinkForSelection(i.id,i.type):c9(i.id,i.type)),{appState:{toast:{message:f("toast.elementLinkCopied"),closable:!0}},captureUpdate:Nc.EVENTUALLY}):{appState:t,elements:e,app:n,captureUpdate:Nc.EVENTUALLY}}}catch(i){console.error(i)}return{appState:t,elements:e,app:n,captureUpdate:Nc.EVENTUALLY}},predicate:(e,t)=>ub(le(e,t))}),lT=W({name:"linkToElement",label:"labels.linkToElement",icon:bm,perform:(e,t,o,n)=>{let r=le(e,t);return r.length!==1||!ub(r)?{elements:e,appState:t,app:n,captureUpdate:Nc.EVENTUALLY}:{appState:{...t,openDialog:{name:"elementLinkSelector",sourceElementId:le(e,t)[0].id}},captureUpdate:Nc.IMMEDIATELY}},predicate:(e,t,o,n)=>{let r=le(e,t);return t.openDialog?.name!=="elementLinkSelector"&&r.length===1&&ub(r)},trackEvent:!1});import{isDarwin as cT}from"@orangecatai/common";var m9={toggleTheme:[G("Shift+Alt+D")],saveScene:[G("CtrlOrCmd+S")],loadScene:[G("CtrlOrCmd+O")],clearCanvas:[G("CtrlOrCmd+Delete")],imageExport:[G("CtrlOrCmd+Shift+E")],commandPalette:[G("CtrlOrCmd+/"),G("CtrlOrCmd+Shift+P")],cut:[G("CtrlOrCmd+X")],copy:[G("CtrlOrCmd+C")],paste:[G("CtrlOrCmd+V")],copyStyles:[G("CtrlOrCmd+Alt+C")],pasteStyles:[G("CtrlOrCmd+Alt+V")],selectAll:[G("CtrlOrCmd+A")],deleteSelectedElements:[G("Delete")],duplicateSelection:[G("CtrlOrCmd+D"),G(`Alt+${f("helpDialog.drag")}`)],sendBackward:[G("CtrlOrCmd+[")],bringForward:[G("CtrlOrCmd+]")],sendToBack:[cT?G("CtrlOrCmd+Alt+["):G("CtrlOrCmd+Shift+[")],bringToFront:[cT?G("CtrlOrCmd+Alt+]"):G("CtrlOrCmd+Shift+]")],copyAsPng:[G("Shift+Alt+C")],group:[G("CtrlOrCmd+G")],ungroup:[G("CtrlOrCmd+Shift+G")],gridMode:[G("CtrlOrCmd+'")],zenMode:[G("Alt+Z")],objectsSnapMode:[G("Alt+S")],stats:[G("Alt+/")],addToLibrary:[],flipHorizontal:[G("Shift+H")],flipVertical:[G("Shift+V")],viewMode:[G("Alt+R")],hyperlink:[G("CtrlOrCmd+K")],toggleElementLock:[G("CtrlOrCmd+Shift+L")],resetZoom:[G("CtrlOrCmd+0")],zoomOut:[G("CtrlOrCmd+-")],zoomIn:[G("CtrlOrCmd++")],zoomToFitSelection:[G("Shift+3")],zoomToFit:[G("Shift+1")],zoomToFitSelectionInViewport:[G("Shift+2")],toggleEraserTool:[G("E")],toggleHandTool:[G("H")],setFrameAsActiveTool:[G("F")],saveFileToDisk:[G("CtrlOrCmd+S")],saveToActiveFile:[G("CtrlOrCmd+S")],toggleShortcuts:[G("?")],searchMenu:[G("CtrlOrCmd+F")],wrapSelectionInFrame:[],toolLock:[G("Q")]},Ke=(e,t=0)=>{let o=m9[e];return o&&o.length>0?o[t]||o[0]:""};var p9="\\u0300-\\u036f",u9="\\ufe20-\\ufe2f",g9="\\u20d0-\\u20ff",h9=p9+u9+g9,f9=`[${h9}]`,b9=RegExp(f9,"g"),x9=/[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g,E9={\u00C0:"A",\u00C1:"A",\u00C2:"A",\u00C3:"A",\u00C4:"A",\u00C5:"A",\u00E0:"a",\u00E1:"a",\u00E2:"a",\u00E3:"a",\u00E4:"a",\u00E5:"a",\u00C7:"C",\u00E7:"c",\u00D0:"D",\u00F0:"d",\u00C8:"E",\u00C9:"E",\u00CA:"E",\u00CB:"E",\u00E8:"e",\u00E9:"e",\u00EA:"e",\u00EB:"e",\u00CC:"I",\u00CD:"I",\u00CE:"I",\u00CF:"I",\u00EC:"i",\u00ED:"i",\u00EE:"i",\u00EF:"i",\u00D1:"N",\u00F1:"n",\u00D2:"O",\u00D3:"O",\u00D4:"O",\u00D5:"O",\u00D6:"O",\u00D8:"O",\u00F2:"o",\u00F3:"o",\u00F4:"o",\u00F5:"o",\u00F6:"o",\u00F8:"o",\u00D9:"U",\u00DA:"U",\u00DB:"U",\u00DC:"U",\u00F9:"u",\u00FA:"u",\u00FB:"u",\u00FC:"u",\u00DD:"Y",\u00FD:"y",\u00FF:"y",\u00C6:"E",\u00E6:"e",\u00DE:"T",\u00FE:"t",\u00DF:"s",\u0100:"A",\u0102:"A",\u0104:"A",\u0101:"a",\u0103:"a",\u0105:"a",\u0106:"C",\u0108:"C",\u010A:"C",\u010C:"C",\u0107:"c",\u0109:"c",\u010B:"c",\u010D:"c",\u010E:"D",\u0110:"D",\u010F:"d",\u0111:"d",\u0112:"E",\u0114:"E",\u0116:"E",\u0118:"E",\u011A:"E",\u0113:"e",\u0115:"e",\u0117:"e",\u0119:"e",\u011B:"e",\u011C:"G",\u011E:"G",\u0120:"G",\u0122:"G",\u011D:"g",\u011F:"g",\u0121:"g",\u0123:"g",\u0124:"H",\u0126:"H",\u0125:"h",\u0127:"h",\u0128:"I",\u012A:"I",\u012C:"I",\u012E:"I",\u0130:"I",\u0129:"i",\u012B:"i",\u012D:"i",\u012F:"i",\u0131:"i",\u0134:"J",\u0135:"j",\u0136:"K",\u0137:"k",\u0138:"k",\u0139:"L",\u013B:"L",\u013D:"L",\u013F:"L",\u0141:"L",\u013A:"l",\u013C:"l",\u013E:"l",\u0140:"l",\u0142:"l",\u0143:"N",\u0145:"N",\u0147:"N",\u014A:"N",\u0144:"n",\u0146:"n",\u0148:"n",\u014B:"n",\u014C:"O",\u014E:"O",\u0150:"O",\u014D:"o",\u014F:"o",\u0151:"o",\u0154:"R",\u0156:"R",\u0158:"R",\u0155:"r",\u0157:"r",\u0159:"r",\u015A:"S",\u015C:"S",\u015E:"S",\u0160:"S",\u015B:"s",\u015D:"s",\u015F:"s",\u0161:"s",\u0162:"T",\u0164:"T",\u0166:"T",\u0163:"t",\u0165:"t",\u0167:"t",\u0168:"U",\u016A:"U",\u016C:"U",\u016E:"U",\u0170:"U",\u0172:"U",\u0169:"u",\u016B:"u",\u016D:"u",\u016F:"u",\u0171:"u",\u0173:"u",\u0174:"W",\u0175:"w",\u0176:"Y",\u0177:"y",\u0178:"Y",\u0179:"Z",\u017B:"Z",\u017D:"Z",\u017A:"z",\u017C:"z",\u017E:"z",\u0132:"I",\u0133:"i",\u0152:"E",\u0153:"e",\u0149:"n",\u017F:"s"},Ji=e=>e.replace(x9,t=>E9[t]||t).replace(b9,"");import RF from"clsx";import{useEffect as NF,useState as BF}from"react";import{KEYS as FF,queryFocusableElements as EC}from"@orangecatai/common";import{useCallback as y9,useState as w9}from"react";var dT=()=>{let[e,t]=w9(null),o=y9(n=>t(n),[]);return[e,o]};import{useState as uC,useCallback as Nb,useMemo as gC,useEffect as Bb,memo as hC,useRef as EF}from"react";import{LIBRARY_DISABLED_TYPES as yF,randomId as wF,isShallowEqual as vF,KEYS as IF,isWritableElement as TF,addEventListener as CF,EVENT as kF,CLASSES as dC}from"@orangecatai/common";import{useEffect as gT,useRef as hT}from"react";import{URL_HASH_KEYS as fb,URL_QUERY_KEYS as bb,APP_NAME as fT,EVENT as vp,DEFAULT_SIDEBAR as C9,LIBRARY_SIDEBAR_TAB as k9,arrayToMap as xb,cloneJSON as S9,preventUnload as M9,promiseTry as bT,resolvablePromise as P9,toValidURL as A9,Queue as L9,Emitter as _9}from"@orangecatai/common";import{hashElementsVersion as D9,hashString as R9}from"@orangecatai/element";import{getCommonBoundingBox as hb}from"@orangecatai/element";import{MIME_TYPES as Qi}from"@orangecatai/common";var Jr=({elements:e,appState:t,files:o,maxWidthOrHeight:n,getDimensions:r,exportPadding:i,exportingFrame:a})=>{let s=Ni(e,null,{deleteInvisibleElements:!0}),l=Oa(t,null),{exportBackground:c,viewBackgroundColor:m}=l;return Ba(s,{...l,offsetTop:0,offsetLeft:0,width:0,height:0},o||{},{exportBackground:c,exportPadding:i,viewBackgroundColor:m,exportingFrame:a},(p,d)=>{let u=document.createElement("canvas");if(n){typeof r=="function"&&console.warn("`getDimensions()` is ignored when `maxWidthOrHeight` is supplied.");let g=Math.max(p,d),E=n<g?n/g:t?.exportScale??1;return u.width=p*E,u.height=d*E,{canvas:u,scale:E}}let h=r?.(p,d)||{width:p,height:d};return u.width=h.width,u.height=h.height,{canvas:u,scale:h.scale??1}})},mT=async e=>{let{mimeType:t=Qi.png,quality:o}=e;t===Qi.png&&typeof o=="number"&&console.warn(`"quality" will be ignored for "${Qi.png}" mimeType`),t==="image/jpg"&&(t=Qi.jpg),t===Qi.jpg&&!e.appState?.exportBackground&&(console.warn(`Defaulting "exportBackground" to "true" for "${Qi.jpg}" mimeType`),e={...e,appState:{...e.appState,exportBackground:!0}});let n=await Jr(e);return o=o||(/image\/jpe?g/.test(t)?.92:.8),new Promise((r,i)=>{n.toBlob(async a=>{if(!a)return i(new Error("couldn't export to blob"));a&&t===Qi.png&&e.appState?.exportEmbedScene&&(a=await KE({blob:a,metadata:Wl(e.elements,e.appState,e.files||{},"local")})),r(a)},t,o)})},zs=async({elements:e,appState:t=Rr(),files:o={},exportPadding:n,renderEmbeddables:r,exportingFrame:i,skipInliningFonts:a,reuseImages:s})=>{let l=Ni(e,null,{deleteInvisibleElements:!0}),m={...Oa(t,null),exportPadding:n};return Fa(l,m,o,{exportingFrame:i,renderEmbeddables:r,skipInliningFonts:a,reuseImages:s})},v9=async e=>{if(e.type==="svg"){let t=await zs(e);await pn(t.outerHTML)}else if(e.type==="png")await ep(mT(e));else if(e.type==="json")await Jm(e.elements,e.files);else throw new Error("Invalid export type")};import{useEffect as pT,useState as I9}from"react";import{COLOR_PALETTE as T9}from"@orangecatai/common";var gb=Ce(new Map),uT=async e=>await zs({elements:e,appState:{exportBackground:!1,viewBackgroundColor:T9.white},files:null,renderEmbeddables:!1,skipInliningFonts:!0}),wp=(e,t,o,n)=>{let[r,i]=I9();return pT(()=>{if(t)if(e){let a=o.get(e);a?i(a):(async()=>{let s=await uT(t);s.querySelector(".style-fonts")?.remove(),s&&(o.set(e,s),i(s))})()}else(async()=>{let a=await uT(t);i(a)})()},[e,t,o,i]),pT(()=>{let a=n.current;if(a)return r&&(a.innerHTML=r.outerHTML),()=>{a.innerHTML=""}},[r,n]),r},Hs=()=>{let[e]=ae(gb);return{clearLibraryCache:()=>e.clear(),deleteItemsFromLibraryCache:n=>{n.forEach(r=>e.delete(r))},svgCache:e}};var N9=["excalidraw.com","raw.githubusercontent.com/excalidraw/excalidraw-libraries"],ET=new _9,fr=Ce({status:"loaded",isInitialized:!1,libraryItems:[]}),Bc=e=>S9(e),B9=(e,t)=>!e.find(o=>o.elements.length!==t.elements.length?!1:o.elements.every((n,r)=>n.id===t.elements[r].id&&n.versionNonce===t.elements[r].versionNonce)),yT=(e,t)=>{let o=[];for(let n of t)B9(e,n)&&o.push(n);return[...o,...e]},wT=(e,t)=>{let o=xb(t),n={deletedItems:new Map,addedItems:new Map,updatedItems:new Map};for(let i of e)o.has(i.id)||n.deletedItems.set(i.id,i);let r=xb(e);for(let i of t){let a=r.get(i.id);a?wb(a)!==wb(i)&&n.updatedItems.set(i.id,i):n.addedItems.set(i.id,i)}return n},Eb=class{constructor(t){A(this,"currLibraryItems",[]);A(this,"prevLibraryItems",Bc(this.currLibraryItems));A(this,"app");A(this,"updateQueue",[]);A(this,"getLastUpdateTask",()=>this.updateQueue[this.updateQueue.length-1]);A(this,"notifyListeners",()=>{if(this.updateQueue.length>0)xt.set(fr,t=>({status:"loading",libraryItems:this.currLibraryItems,isInitialized:t.isInitialized}));else{xt.set(fr,{status:"loaded",libraryItems:this.currLibraryItems,isInitialized:!0});try{let t=this.prevLibraryItems;this.prevLibraryItems=Bc(this.currLibraryItems);let o=Bc(this.currLibraryItems);this.app.props.onLibraryChange?.(o),ET.trigger(wT(t,o),o)}catch(t){console.error(t)}}});A(this,"destroy",()=>{this.updateQueue=[],this.currLibraryItems=[],xt.set(gb,new Map)});A(this,"resetLibrary",()=>this.setLibrary([]));A(this,"getLatestLibrary",()=>new Promise(async t=>{try{let o=await(this.getLastUpdateTask()||this.currLibraryItems);this.updateQueue.length>0?t(this.getLatestLibrary()):t(Bc(o))}catch{return t(this.currLibraryItems)}}));A(this,"updateLibrary",async({libraryItems:t,prompt:o=!1,merge:n=!1,openLibraryMenu:r=!1,defaultStatus:i="unpublished"})=>(r&&this.app.setState({openSidebar:{name:C9.name,tab:k9}}),this.setLibrary(()=>new Promise(async(a,s)=>{try{let l=await(typeof t=="function"&&!(t instanceof Blob)?t(this.currLibraryItems):t),c;l instanceof Blob?c=await eh(l,i):c=$l(l,i),!o||window.confirm(f("alerts.confirmAddLibrary",{numShapes:c.length}))?(o&&this.app.focusContainer(),a(n?yT(this.currLibraryItems,c):c)):s(new Ra)}catch(l){s(l)}}))));A(this,"setLibrary",t=>{let o=new Promise(async(n,r)=>{try{await this.getLastUpdateTask(),typeof t=="function"&&(t=t(this.currLibraryItems)),this.currLibraryItems=Bc(await t),n(this.currLibraryItems)}catch(i){r(i)}}).catch(n=>{if(n.name==="AbortError")return console.warn("Library update aborted by user"),this.currLibraryItems;throw n}).finally(()=>{this.updateQueue=this.updateQueue.filter(n=>n!==o),this.notifyListeners()});return this.updateQueue.push(o),this.notifyListeners(),o});this.app=t}},vT=Eb,Us=e=>{let o=Math.ceil(Math.sqrt(e.length)),n=[],r=u=>e.slice(u*o,u*o+o).reduce((g,E)=>{let{height:w}=hb(E.elements);return Math.max(g,w)},0),i=u=>{let h=0,g=0,E=0;for(let w of e){if(h%o===0&&(g=0),g===u){let{width:x}=hb(w.elements);E=Math.max(E,x)}h++,g++}return E},a=0,s=0,l=0,c=0,m=0,p=0,d=0;for(let u of e){m&&m%o===0&&(s+=l+50,a=0,p=0,d++),p===0&&(l=r(d)),c=i(p);let{minX:h,minY:g,width:E,height:w}=hb(u.elements),x=(c-E)/2,y=(l-w)/2;n.push(...u.elements.map(v=>({...v,x:v.x+a+x-h,y:v.y+s+y-g}))),a+=c+50,m++,p++}return n},F9=(e,t=N9)=>{if(typeof t=="function"?t(e):t.some(o=>{let n=new URL(`https://${o.replace(/^https?:\/\//,"")}`),{hostname:r,pathname:i}=new URL(e);return new RegExp(`(^|\\.)${n.hostname}$`).test(r)&&new RegExp(`^${n.pathname.replace(/\/+$/,"")}(/+|$)`).test(i)}))return!0;throw new Error(`Invalid or disallowed library URL: "${e}"`)},yb=()=>{let e=new URLSearchParams(window.location.hash.slice(1)).get(fb.addLibrary)||new URLSearchParams(window.location.search).get(bb.addLibrary),t=e?new URLSearchParams(window.location.hash.slice(1)).get("token"):null;return e?{libraryUrl:e,idToken:t}:null},Qr=class Qr{constructor(t){A(this,"adapter");this.adapter=t}static async getLibraryItems(t,o,n=!0){let r=()=>new Promise(async(i,a)=>{try{let s=await t.load({source:o});i($l(s?.libraryItems||[],"published"))}catch(s){a(s)}});return n?Qr.queue.push(r):r()}getLibraryItems(t){return Qr.getLibraryItems(this.adapter,t,!1)}};A(Qr,"queue",new L9),A(Qr,"run",async(t,o)=>{let n=new Qr(t);return Qr.queue.push(()=>o(n))});var Gs=Qr,Fc=0,Ip=0,wb=e=>`${e.id}:${e.name||""}:${D9(e.elements)}`,Tp=e=>R9(e.map(t=>wb(t)).sort().join()),xT=async(e,t)=>{try{return Ip++,await Gs.run(e,async o=>{let n=xb(await o.getLibraryItems("save"));for(let[s]of t.deletedItems)n.delete(s);let r=[];for(let[s,l]of t.addedItems)n.has(s)?n.set(s,l):r.push(l);if(t.updatedItems)for(let[s,l]of t.updatedItems)n.set(s,l);let i=r.concat(Array.from(n.values())),a=Tp(i);return a!==Fc&&await e.save({libraryItems:i}),Fc=a,i})}finally{Ip--}},O9=e=>{let{excalidrawAPI:t}=e,o=hT(e);o.current=e;let n=hT(!1);gT(()=>{if(!t)return;n.current=!1;let r=async({libraryUrl:s,idToken:l})=>{let c=new Promise(async(p,d)=>{try{s=decodeURIComponent(s),s=A9(s),F9(s,o.current.validateLibraryUrl);let h=await(await fetch(s)).blob();p(h)}catch(u){d(u)}}),m=l!==t.id;await(m&&document.hidden?new Promise(p=>{window.addEventListener("focus",()=>p(),{once:!0})}):null);try{await t.updateLibrary({libraryItems:c,prompt:m,merge:!0,defaultStatus:"published",openLibraryMenu:!0})}catch(p){throw t.updateScene({appState:{errorMessage:p.message}}),p}finally{if(window.location.hash.includes(fb.addLibrary)){let p=new URLSearchParams(window.location.hash.slice(1));p.delete(fb.addLibrary),window.history.replaceState({},fT,`#${p.toString()}`)}else if(window.location.search.includes(bb.addLibrary)){let p=new URLSearchParams(window.location.search);p.delete(bb.addLibrary),window.history.replaceState({},fT,`?${p.toString()}`)}}},i=s=>{s.preventDefault();let l=yb();l&&(s.stopImmediatePropagation(),window.history.replaceState({},"",s.oldURL),r(l))},a=yb();if(a&&r(a),"getInitialLibraryItems"in o.current&&o.current.getInitialLibraryItems&&(console.warn("useHandleLibrar `opts.getInitialLibraryItems` is deprecated. Use `opts.adapter` instead."),Promise.resolve(o.current.getInitialLibraryItems()).then(s=>{t.updateLibrary({libraryItems:s,merge:!0})}).catch(s=>{console.error(`UseHandeLibrary getInitialLibraryItems failed: ${s?.message}`)})),"adapter"in o.current&&o.current.adapter){let s=o.current.adapter,l=o.current.migrationAdapter,c=P9();l?c.resolve(bT(l.load).then(async m=>{let p=null;try{if(!m)return Gs.getLibraryItems(s,"load");p=$l(m.libraryItems||[],"published");let d=await xT(s,wT([],p));try{await l.clear()}catch(u){console.error(`couldn't delete legacy library data: ${u.message}`)}return d}catch(d){return console.error(`couldn't migrate legacy library data: ${d.message}`),p}}).catch(m=>(console.error(`error during library migration: ${m.message}`),Gs.getLibraryItems(s,"load")))):c.resolve(bT(Gs.getLibraryItems,s,"load")),t.updateLibrary({libraryItems:c.then(m=>{let p=m||[];return Fc=Tp(p),p}),merge:!0}).finally(()=>{n.current=!0})}return window.addEventListener(vp.HASHCHANGE,i),()=>{window.removeEventListener(vp.HASHCHANGE,i)}},[t]),gT(()=>{let r=ET.on(async(a,s)=>{let l=n.current,c="adapter"in o.current&&o.current.adapter||null;try{c&&Fc!==Tp(s)&&await xT(c,a)}catch(m){console.error(`couldn't persist library update: ${m.message}`,a),l&&o.current.excalidrawAPI&&o.current.excalidrawAPI.updateScene({appState:{errorMessage:f("errors.saveLibraryError")}})}}),i=a=>{Ip&&M9(a)};return window.addEventListener(vp.BEFORE_UNLOAD,i),()=>{window.removeEventListener(vp.BEFORE_UNLOAD,i),r(),Fc=0,Ip=0}},[])};import U9 from"clsx";import{VERSIONS as z9}from"@orangecatai/common";import{jsx as G9}from"react/jsx-runtime";var H9=({theme:e,id:t,libraryReturnUrl:o})=>{let n=o||window.location.origin+window.location.pathname;return G9("a",{className:"library-menu-browse-button",href:`${C.VITE_APP_LIBRARY_URL}?target=${window.name||"_blank"}&referrer=${n}&useHash=true&token=${t}&theme=${e}&version=${z9.excalidrawLibrary}`,target:"_excalidraw_libraries",children:f("labels.libraries")})},IT=H9;import{jsx as W9,jsxs as Y9}from"react/jsx-runtime";var Cp=({libraryReturnUrl:e,theme:t,id:o,style:n,children:r,className:i})=>Y9("div",{className:U9("library-menu-control-buttons",i),style:n,children:[W9(IT,{id:o,libraryReturnUrl:e,theme:t}),r]});import{useCallback as Vs,useEffect as Lb,useMemo as _b,useRef as sC,useState as lC}from"react";import{MIME_TYPES as pF,arrayToMap as uF,nextAnimationFrame as gF}from"@orangecatai/common";import{duplicateElements as hF}from"@orangecatai/element";import fF from"clsx";import V9 from"lodash.throttle";import{useEffect as $9}from"react";var K9=Ce(0),TT=e=>{let[t,o]=ae(K9);return $9(()=>{let{current:n}=e;if(!n)return;let r=V9(()=>{let{scrollTop:i}=n;o(i)},200);return n.addEventListener("scroll",r),()=>{r.cancel(),n.removeEventListener("scroll",r)}},[e,o]),t};import UB from"clsx";import{useCallback as WB,useState as Mb}from"react";import{muteFSAbortError as YB}from"@orangecatai/common";import{flushSync as CT}from"react-dom";import X9 from"clsx";import{jsx as kp,jsxs as j9}from"react/jsx-runtime";var Z9=({label:e,onClick:t,className:o,children:n,actionType:r,type:i="button",isLoading:a,...s})=>{let l=r?`Dialog__action-button--${r}`:"";return j9("button",{className:X9("Dialog__action-button",l,o),type:i,"aria-label":e,onClick:t,...s,children:[n&&kp("div",{style:a?{visibility:"hidden"}:{},children:n}),kp("div",{style:a?{visibility:"hidden"}:{},children:e}),a&&kp("div",{style:{position:"absolute",inset:0},children:kp(Gt,{})})]})},br=Z9;import{jsx as kT,jsxs as ST}from"react/jsx-runtime";var q9=e=>{let{onConfirm:t,onCancel:o,children:n,confirmText:r=f("buttons.confirm"),cancelText:i=f("buttons.cancel"),className:a="",...s}=e,l=ve(),c=Pn(Ws),{container:m}=qe();return ST(ht,{onCloseRequest:o,size:"small",...s,className:`confirm-dialog ${a}`,children:[n,ST("div",{className:"confirm-dialog-buttons",children:[kT(br,{label:i,onClick:()=>{l({openMenu:null}),c(!1),CT(()=>{o()}),m?.focus()}}),kT(br,{label:r,onClick:()=>{l({openMenu:null}),c(!1),CT(()=>{t()}),m?.focus()},actionType:"danger"})]})]})},Sp=q9;import{useCallback as rB,useEffect as Tb,useRef as MT,useState as vb}from"react";import{EDITOR_LS_KEYS as Ib,EXPORT_DATA_TYPES as iB,MIME_TYPES as PT,VERSIONS as aB,chunk as sB,getExportSource as lB}from"@orangecatai/common";var Yo=class{static has(t){try{return!!window.localStorage.getItem(t)}catch(o){return console.warn(`localStorage.getItem error: ${o.message}`),!1}}static get(t){try{let o=window.localStorage.getItem(t);return o?JSON.parse(o):null}catch(o){return console.warn(`localStorage.getItem error: ${o.message}`),null}}};A(Yo,"set",(t,o)=>{try{return window.localStorage.setItem(t,JSON.stringify(o)),!0}catch(n){return console.warn(`localStorage.setItem error: ${n.message}`),!1}}),A(Yo,"delete",t=>{try{window.localStorage.removeItem(t)}catch(o){console.warn(`localStorage.removeItem error: ${o.message}`)}});import Mp from"react";var J9=/({{[\w-]+}})|(<[\w-]+>)|(<\/[\w-]+>)/g,Q9=/{{([\w-]+)}}/,eB=/<([\w-]+)>/,tB=/<\/([\w-]+)>/,oB=(e,t)=>{let o=[{name:"",children:[]}];return e.split(J9).filter(Boolean).forEach(n=>{let r=n.match(eB),i=n.match(tB),a=n.match(Q9);if(r!==null){let s=r[1];t.hasOwnProperty(s)?o.push({name:s,children:[]}):console.warn(`Trans: missed to pass in prop ${s} for interpolating ${e}`)}else if(i!==null)if(i[1]===o[o.length-1].name){let l=o.pop(),c=Mp.createElement(Mp.Fragment,{},...l.children),m=t[l.name];typeof m=="function"&&o[o.length-1].children.push(m(c))}else console.warn(`Trans: unexpected end tag ${n} for interpolating ${e}`);else if(a!==null){let s=a[1];t.hasOwnProperty(s)?o[o.length-1].children.push(t[s]):console.warn(`Trans: key ${s} not in props for interpolating ${e}`)}else o[o.length-1].children.push(n)}),o.length!==1&&console.warn(`Trans: stack not empty for interpolating ${e}`),o[0].children},nB=({i18nKey:e,children:t,...o})=>{let{t:n}=Ge();return Mp.createElement(Mp.Fragment,{},...oB(n(e),o))},ro=nB;import{jsx as ke,jsxs as $t}from"react/jsx-runtime";var cB=async e=>{let n=Math.round(8),r=Math.max(Math.round(128/64),2),i=sB(e,6),a=document.createElement("canvas");a.width=i[0].length*128+(i[0].length+1)*(n*2)-n*2,a.height=i.length*128+(i.length+1)*(n*2)-n*2;let s=a.getContext("2d");s.fillStyle="#fff",s.fillRect(0,0,a.width,a.height);for(let[l,c]of e.entries()){let m=await Jr({elements:c.elements,files:null,maxWidthOrHeight:128}),{width:p,height:d}=m,u=Math.floor(l/6)*(128+n*2),h=l%6*(128+n*2);s.drawImage(m,h+(128-p)/2+n,u+(128-d)/2+n),s.lineWidth=r,s.strokeStyle="#ced4da",s.strokeRect(h+n/2,u+n/2,128+n,128+n)}return await tm(new File([await Bi(a)],"preview",{type:PT.png}),{outputType:PT.jpg,maxWidthOrHeight:5e3})},dB=({libItem:e,appState:t,index:o,onChange:n,onRemove:r})=>{let i=MT(null),a=MT(null);return Tb(()=>{let s=i.current;s&&(async()=>{let l=await zs({elements:e.elements,appState:{...t,viewBackgroundColor:"#fff",exportBackground:!0},files:null,skipInliningFonts:!0});s.innerHTML=l.outerHTML})()},[e.elements,t]),$t("div",{className:"single-library-item",children:[e.status==="published"&&ke("span",{className:"single-library-item-status",children:f("labels.statusPublished")}),ke("div",{ref:i,className:"single-library-item__svg"}),ke(ne,{"aria-label":f("buttons.remove"),type:"button",icon:Fo,className:"single-library-item--remove",onClick:r.bind(null,e.id),title:f("buttons.remove")}),$t("div",{style:{display:"flex",margin:"0.8rem 0",width:"100%",fontSize:"14px",fontWeight:500,flexDirection:"column"},children:[$t("label",{style:{display:"flex",justifyContent:"space-between",flexDirection:"column"},children:[$t("div",{style:{padding:"0.5em 0"},children:[ke("span",{style:{fontWeight:500,color:"#868e96"},children:f("publishDialog.itemName")}),ke("span",{"aria-hidden":"true",className:"required",children:"*"})]}),ke("input",{type:"text",ref:a,style:{width:"80%",padding:"0.2rem"},defaultValue:e.name,placeholder:"Item name",onChange:s=>{n(s.target.value,o)}})]}),ke("span",{className:"error",children:e.error})]})]})},mB=({onClose:e,libraryItems:t,appState:o,onSuccess:n,onError:r,updateItemsInStorage:i,onRemove:a})=>{let[s,l]=vb({authorName:"",githubHandle:"",name:"",description:"",twitterHandle:"",website:""}),[c,m]=vb(!1);Tb(()=>{let y=Yo.get(Ib.PUBLISH_LIBRARY);y&&l(y)},[]);let[p,d]=vb(t.slice());Tb(()=>{d(t.slice())},[t]);let u=y=>{l({...s,[y.target.name]:y.target.value})},h=async y=>{y.preventDefault(),m(!0);let v=[],I=!1;if(p.forEach(T=>{let M="";T.name||(M=f("publishDialog.errors.required"),I=!0),v.push({...T,error:M})}),I){d(v),m(!1);return}let k=await cB(p),L={type:iB.excalidrawLibrary,version:aB.excalidrawLibrary,source:lB(),libraryItems:p},S=JSON.stringify(L,null,2),_=new Blob([S],{type:"application/json"}),P=new FormData;P.append("excalidrawLib",_),P.append("previewImage",k),P.append("previewImageType",k.type),P.append("title",s.name),P.append("authorName",s.authorName),P.append("githubHandle",s.githubHandle),P.append("name",s.name),P.append("description",s.description),P.append("twitterHandle",s.twitterHandle),P.append("website",s.website),fetch(`${C.VITE_APP_LIBRARY_BACKEND}/submit`,{method:"post",body:P}).then(T=>T.ok?T.json().then(({url:M})=>{Yo.delete(Ib.PUBLISH_LIBRARY),n({url:M,authorName:s.authorName,items:p})}):T.json().catch(()=>{throw new Error(T.statusText||"something went wrong")}).then(M=>{throw new Error(M.message||T.statusText||"something went wrong")}),T=>{console.error(T),r(T),m(!1)}).catch(T=>{console.error(T),r(T),m(!1)})},g=()=>{let y=[];return p.forEach((v,I)=>{y.push(ke("div",{className:"single-library-item-wrapper",children:ke(dB,{libItem:v,appState:o,index:I,onChange:(k,L)=>{let S=p.slice();S[L].name=k,d(S)},onRemove:a})},I))}),ke("div",{className:"selected-library-items",children:y})},E=rB(()=>{i(p),Yo.set(Ib.PUBLISH_LIBRARY,s),e()},[p,e,i,s]),w=!!t.length,x=t.some(y=>y.status==="published");return ke(ht,{onCloseRequest:E,title:f("publishDialog.title"),className:"publish-library",children:w?$t("form",{onSubmit:h,children:[ke("div",{className:"publish-library-note",children:ke(ro,{i18nKey:"publishDialog.noteDescription",link:y=>ke("a",{href:"https://libraries.excalidraw.com",target:"_blank",rel:"noopener",children:y})})}),ke("span",{className:"publish-library-note",children:ke(ro,{i18nKey:"publishDialog.noteGuidelines",link:y=>ke("a",{href:"https://github.com/excalidraw/excalidraw-libraries#guidelines",target:"_blank",rel:"noopener noreferrer",children:y})})}),ke("div",{className:"publish-library-note",children:f("publishDialog.noteItems")}),x&&ke("span",{className:"publish-library-note publish-library-warning",children:f("publishDialog.republishWarning")}),g(),$t("div",{className:"publish-library__fields",children:[$t("label",{children:[$t("div",{children:[ke("span",{children:f("publishDialog.libraryName")}),ke("span",{"aria-hidden":"true",className:"required",children:"*"})]}),ke("input",{type:"text",name:"name",required:!0,value:s.name,onChange:u,placeholder:f("publishDialog.placeholder.libraryName")})]}),$t("label",{style:{alignItems:"flex-start"},children:[$t("div",{children:[ke("span",{children:f("publishDialog.libraryDesc")}),ke("span",{"aria-hidden":"true",className:"required",children:"*"})]}),ke("textarea",{name:"description",rows:4,required:!0,value:s.description,onChange:u,placeholder:f("publishDialog.placeholder.libraryDesc")})]}),$t("label",{children:[$t("div",{children:[ke("span",{children:f("publishDialog.authorName")}),ke("span",{"aria-hidden":"true",className:"required",children:"*"})]}),ke("input",{type:"text",name:"authorName",required:!0,value:s.authorName,onChange:u,placeholder:f("publishDialog.placeholder.authorName")})]}),$t("label",{children:[ke("span",{children:f("publishDialog.githubUsername")}),ke("input",{type:"text",name:"githubHandle",value:s.githubHandle,onChange:u,placeholder:f("publishDialog.placeholder.githubHandle")})]}),$t("label",{children:[ke("span",{children:f("publishDialog.twitterUsername")}),ke("input",{type:"text",name:"twitterHandle",value:s.twitterHandle,onChange:u,placeholder:f("publishDialog.placeholder.twitterHandle")})]}),$t("label",{children:[ke("span",{children:f("publishDialog.website")}),ke("input",{type:"text",name:"website",pattern:"https?://.+",title:f("publishDialog.errors.website"),value:s.website,onChange:u,placeholder:f("publishDialog.placeholder.website")})]}),ke("span",{className:"publish-library-note",children:ke(ro,{i18nKey:"publishDialog.noteLicense",link:y=>ke("a",{href:"https://github.com/excalidraw/excalidraw-libraries/blob/main/LICENSE",target:"_blank",rel:"noopener noreferrer",children:y})})})]}),$t("div",{className:"publish-library__buttons",children:[ke(br,{label:f("buttons.saveLibNames"),onClick:E,"data-testid":"cancel-clear-canvas-button"}),ke(br,{type:"submit",label:f("buttons.submit"),actionType:"primary",isLoading:c})]})]}):ke("p",{style:{padding:"1em",textAlign:"center",fontWeight:500},children:f("publishDialog.atleastOneLibItem")})})},AT=mB;import eC from"react";import{DropdownMenu as OB}from"radix-ui";import{CLASSES as zB}from"@orangecatai/common";import gB from"clsx";import{useCallback as hB,useEffect as fB,useRef as bB}from"react";import{CLASSES as xB,EVENT as RT,KEYS as EB}from"@orangecatai/common";import{DropdownMenu as yB}from"radix-ui";import{forwardRef as LT}from"react";import _T from"clsx";import{jsx as DT}from"react/jsx-runtime";var pB=LT(({children:e,gap:t,align:o,justifyContent:n,className:r,style:i},a)=>DT("div",{className:_T("Stack Stack_horizontal",r),style:{"--gap":t,alignItems:o,justifyContent:n,...i},ref:a,children:e})),uB=LT(({children:e,gap:t,align:o,justifyContent:n,className:r,style:i},a)=>DT("div",{className:_T("Stack Stack_vertical",r),style:{"--gap":t,justifyItems:o,justifyContent:n,...i},ref:a,children:e})),Dt={Row:pB,Col:uB};import{jsx as Pp}from"react/jsx-runtime";var NT=({children:e,onClickOutside:t,className:o="",onSelect:n,open:r=!0,align:i="end",style:a})=>{let s=we(),l=bB(null),c=Fr({onClickOutside:t});cs(l,hB(p=>{l.current?.closest(`.${xB.DROPDOWN_MENU_EVENT_WRAPPER}`)?.contains(p.target)||c.onClickOutside?.()},[c])),fB(()=>{if(!r)return;let p=u=>{u.key===EB.ESCAPE&&(u.stopImmediatePropagation(),c.onClickOutside?.())},d={capture:!0};return document.addEventListener(RT.KEYDOWN,p,d),()=>{document.removeEventListener(RT.KEYDOWN,p,d)}},[c,r]);let m=gB(`dropdown-menu ${o}`,{"dropdown-menu--mobile":s.formFactor==="phone"}).trim();return Pp(qh.Provider,{value:{onSelect:n},children:Pp(yB.Content,{ref:l,className:m,style:a,"data-testid":"dropdown-menu",align:i,sideOffset:8,onCloseAutoFocus:p=>p.preventDefault(),children:s.formFactor==="phone"?Pp(Dt.Col,{className:"dropdown-menu-container",children:e}):Pp(ut,{className:"dropdown-menu-container",padding:2,children:e})})})};NT.displayName="DropdownMenuContent";var BT=NT;import{jsx as vB}from"react/jsx-runtime";var wB=({children:e,className:t="",selected:o,...n})=>vB("div",{...n,className:`dropdown-menu-item-base dropdown-menu-item-custom ${t} ${o?"dropdown-menu-item--selected":""}`.trim(),children:e}),FT=wB;import{DropdownMenu as IB}from"radix-ui";import{jsx as Cb}from"react/jsx-runtime";var OT=({icon:e,shortcut:t,href:o,children:n,onSelect:r,className:i="",selected:a,rel:s="noopener",...l})=>{let c=Nm(r);return Cb(IB.Item,{className:"radix-menu-item",onSelect:c,asChild:!0,children:Cb("a",{...l,href:o,target:"_blank",rel:`noopener ${s}`,className:Wr(i,a),title:l.title??l["aria-label"],children:Cb(Yr,{icon:e,shortcut:t,children:n})})})},Ys=OT;OT.displayName="DropdownMenuItemLink";import{jsx as TB}from"react/jsx-runtime";var zT=()=>TB("div",{style:{height:"1px",backgroundColor:"var(--default-border-color)",margin:"6px 0",flex:"0 0 auto"}}),HT=zT;zT.displayName="DropdownMenuSeparator";import{DropdownMenu as LB}from"radix-ui";import CB from"clsx";import{DropdownMenu as kB}from"radix-ui";import{useCallback as SB,useState as GT}from"react";import{jsx as Sb}from"react/jsx-runtime";var kb=-4,MB=4,UT=({children:e,className:t})=>{let o=we(),n=CB(`dropdown-menu dropdown-submenu ${t}`,{"dropdown-menu--mobile":o.formFactor==="phone"}).trim(),r=SB(c=>{if(c){let p=c.closest(".dropdown-menu-container")?.getBoundingClientRect();if(p){let d=c.getBoundingClientRect().width,h=window.innerWidth-p.right;h<d+20&&(a(h-d+kb),l(kb+8))}}},[]),[i,a]=GT(MB),[s,l]=GT(kb);return Sb(kB.SubContent,{className:n,sideOffset:i,alignOffset:s,collisionPadding:8,ref:r,children:o.formFactor==="phone"?Sb(Dt.Col,{className:"dropdown-menu-container",children:e}):Sb(ut,{className:"dropdown-menu-container",padding:2,style:{zIndex:1},children:e})})},WT=UT;UT.displayName="DropdownMenuSubContent";import{DropdownMenu as PB}from"radix-ui";import{jsx as YT,jsxs as AB}from"react/jsx-runtime";var VT=({children:e,icon:t,shortcut:o,className:n})=>AB(PB.SubTrigger,{className:`${Wr(n)} dropdown-menu__submenu-trigger`,children:[YT(Yr,{icon:t,shortcut:o,children:e}),YT("div",{className:"dropdown-menu__submenu-trigger-icon",children:Qw})]}),$T=VT;VT.displayName="DropdownMenuSubTrigger";import KT from"react";var Ap=e=>t=>{let o=KT.Children.toArray(t).find(n=>KT.isValidElement(n)&&typeof n.type!="string"&&n?.type.displayName&&n.type.displayName===e);return o||null},XT=Ap("DropdownMenuTrigger"),ZT=Ap("DropdownMenuContent"),jT=Ap("DropdownMenuSubTrigger"),qT=Ap("DropdownMenuSubContent");import{jsxs as _B}from"react/jsx-runtime";var Lp=({children:e})=>{let t=jT(e),o=qT(e);return _B(LB.Sub,{children:[t,o]})};Lp.Trigger=$T;Lp.Content=WT;Lp.displayName="DropdownMenuSub";var ei=Lp;import DB from"clsx";import{DropdownMenu as RB}from"radix-ui";import{jsx as NB}from"react/jsx-runtime";var JT=({className:e="",children:t,onToggle:o,title:n,...r})=>{let i=we(),a=DB(`dropdown-menu-button ${e}`,"zen-mode-transition",{"dropdown-menu-button--mobile":i.formFactor==="phone"}).trim();return NB(RB.Trigger,{className:a,onClick:o,type:"button","data-testid":"dropdown-menu-button",title:n,...r,children:t})},QT=JT;JT.displayName="DropdownMenuTrigger";import{jsx as FB}from"react/jsx-runtime";var BB=e=>FB(Qt,{...e,icon:e.checked?cm:Jw}),xr=BB;import{jsx as GB,jsxs as HB}from"react/jsx-runtime";var hn=({children:e,open:t})=>{let o=XT(e),n=ZT(e),r=n&&eC.isValidElement(n)?eC.cloneElement(n,{open:t}):n;return GB(OB.Root,{open:t,modal:!1,children:HB("div",{className:zB.DROPDOWN_MENU_EVENT_WRAPPER,style:{display:"contents"},children:[o,r]})})};hn.Trigger=QT;hn.Content=BT;hn.Item=Qt;hn.ItemCheckbox=xr;hn.ItemLink=Ys;hn.ItemCustom=FT;hn.Group=dc;hn.Separator=HT;hn.Sub=ei;var he=hn;hn.displayName="DropdownMenu";import{jsx as go,jsxs as _p}from"react/jsx-runtime";var VB=(e,t)=>e.filter(o=>t.includes(o.id)),$B=({setAppState:e,selectedItems:t,library:o,onRemoveFromLibrary:n,resetLibrary:r,onSelectItems:i,appState:a,className:s})=>{let[l]=ae(fr),[c,m]=ae(Ws),p=()=>{let P=t.length?f("alerts.removeItemsFromsLibrary",{count:t.length}):f("alerts.resetLibrary"),T=t.length?f("confirmDialog.removeItemsFromLib"):f("confirmDialog.resetLibrary");return go(Sp,{onConfirm:()=>{t.length?n():r(),u(!1)},onCancel:()=>{u(!1)},title:T,children:go("p",{children:P})})},[d,u]=Mb(!1),h=!!t.length,g=h?l.libraryItems.filter(P=>t.includes(P.id)):l.libraryItems,E=h?f("buttons.remove"):f("buttons.resetLibrary"),[w,x]=Mb(!1),[y,v]=Mb(null),I=WB(()=>_p(ht,{onCloseRequest:()=>v(null),title:f("publishSuccessDialog.title"),className:"publish-library-success",size:"small",children:[go("p",{children:go(ro,{i18nKey:"publishSuccessDialog.content",authorName:y.authorName,link:P=>go("a",{href:y?.url,target:"_blank",rel:"noopener noreferrer",children:P})})}),go(ne,{type:"button",title:f("buttons.close"),"aria-label":f("buttons.close"),label:f("buttons.close"),onClick:()=>v(null),"data-testid":"publish-library-success-close",className:"publish-library-success-close"})]}),[v,y]),k=(P,T)=>{x(!1),v({url:P.url,authorName:P.authorName});let M=T.slice();M.forEach(N=>{t.includes(N.id)&&(N.status="published")}),o.setLibrary(M)},L=async()=>{try{await o.updateLibrary({libraryItems:Xd({description:"Excalidraw library files"}),merge:!0,openLibraryMenu:!0})}catch(P){if(P?.name==="AbortError"){console.warn(P);return}e({errorMessage:f("errors.importLibraryError")})}},S=async()=>{let P=h?g:await o.getLatestLibrary();GE(P).catch(YB).catch(T=>{e({errorMessage:T.message})})},_=()=>_p(he,{open:c,children:[go(he.Trigger,{onToggle:()=>m(!c),children:dy}),_p(he.Content,{onClickOutside:()=>m(!1),onSelect:()=>m(!1),className:"library-menu",children:[!h&&go(he.Item,{onSelect:L,icon:qa,"data-testid":"lib-dropdown--load",children:f("buttons.load")}),!!g.length&&go(he.Item,{onSelect:S,icon:zi,"data-testid":"lib-dropdown--export",children:f("buttons.export")}),h&&go(he.Item,{icon:xw,onSelect:()=>x(!0),"data-testid":"lib-dropdown--remove",children:f("buttons.publishLibrary")}),!!g.length&&go(he.Item,{onSelect:()=>u(!0),icon:Ht,children:E})]})]});return _p("div",{className:UB("library-menu-dropdown-container",s),children:[_(),t.length>0&&go("div",{className:"library-actions-counter",children:t.length}),d&&p(),w&&go(AT,{onClose:()=>x(!1),libraryItems:VB(l.libraryItems,t),appState:a,onSuccess:P=>k(P,l.libraryItems),onError:P=>window.alert(P),updateItemsInStorage:()=>o.setLibrary(l.libraryItems),onRemove:P=>i(t.filter(T=>T!==P))}),y&&I()]})},tC=({selectedItems:e,onSelectItems:t,className:o})=>{let{library:n}=Qe(),{clearLibraryCache:r,deleteItemsFromLibraryCache:i}=Hs(),a=ye(),s=ve(),[l]=ae(fr),c=async p=>{let d=p.filter(u=>!e.includes(u.id));n.setLibrary(d).catch(()=>{s({errorMessage:f("alerts.errorRemovingFromLibrary")})}),i(e),t([])};return go($B,{appState:a,setAppState:s,selectedItems:e,onSelectItems:t,library:n,onRemoveFromLibrary:()=>c(l.libraryItems),resetLibrary:()=>{n.resetLibrary(),r()},className:o})};import{memo as eF,useEffect as tF,useState as oF}from"react";import KB,{useCallback as XB}from"react";function ZB(){return[!1,XB(t=>t(),[])]}var oC=KB.useTransition||ZB;import nC from"clsx";import{memo as jB,useRef as qB,useState as JB}from"react";import{jsx as Dp,jsxs as QB}from"react/jsx-runtime";var rC=jB(({id:e,elements:t,isPending:o,onClick:n,selected:r,onToggle:i,onDrag:a,svgCache:s})=>{let l=qB(null),c=wp(e,t,s,l),[m,p]=JB(!1),d=we().formFactor==="phone",u=o&&Dp("div",{className:"library-unit__adder",children:cy});return QB("div",{className:nC("library-unit",{"library-unit__active":t,"library-unit--hover":t&&m,"library-unit--selected":r,"library-unit--skeleton":!c}),onMouseEnter:()=>p(!0),onMouseLeave:()=>p(!1),children:[Dp("div",{className:nC("library-unit__dragger",{"library-unit__pulse":!!o}),ref:l,draggable:!!t,onClick:t||o?h=>{e&&h.shiftKey?i(e,h):n(e)}:void 0,onDragStart:h=>{if(!e){h.preventDefault();return}p(!1),a(e,h)}}),u,e&&t&&(m||d||r)&&Dp(bc,{checked:r,onChange:(h,g)=>i(e,g),className:"library-unit__checkbox"})]})}),iC=()=>Dp("div",{className:"library-unit library-unit--skeleton"});import{Fragment as nF,jsx as Rp}from"react/jsx-runtime";var Np=({children:e})=>Rp("div",{className:"library-menu-items-container__grid",children:e}),Oc=eF(({items:e,onItemSelectToggle:t,onItemDrag:o,isItemSelected:n,onClick:r,svgCache:i,itemsRenderedPerBatch:a})=>{let[,s]=oC(),[l,c]=oF(0);return tF(()=>{l<e.length&&s(()=>{c(l+a)})},[l,e.length,s,a]),Rp(nF,{children:e.map((m,p)=>p<l?Rp(rC,{elements:m?.elements,isPending:!m?.id&&!!m?.elements,onClick:r,svgCache:i,id:m?.id,selected:n(m.id),onToggle:t,onDrag:o},m?.id??p):Rp(iC,{},p))})});import Pb from"clsx";import{forwardRef as sF,useRef as lF,useImperativeHandle as cF,useLayoutEffect as dF,useState as mF}from"react";import rF from"clsx";import{composeEventHandlers as iF}from"@orangecatai/common";import{jsx as aF}from"react/jsx-runtime";var io=({type:e="button",onSelect:t,selected:o,children:n,className:r="",...i})=>aF("button",{onClick:iF(i.onClick,a=>{t()}),type:e,className:rF("excalidraw-button",r,{selected:o}),...i,children:n});import{jsx as Ab,jsxs as aC}from"react/jsx-runtime";var ti=sF(({onChange:e,label:t,fullWidth:o,placeholder:n,readonly:r,selectOnRender:i,onKeyDown:a,isRedacted:s=!1,icon:l,className:c,type:m,...p},d)=>{let u=lF(null);cF(d,()=>u.current),dF(()=>{i&&(u.current?.focus(),u.current?.select())},[i]);let[h,g]=mF(!1);return aC("div",{className:Pb("ExcTextField",c,{"ExcTextField--fullWidth":o,"ExcTextField--hasIcon":!!l}),onClick:()=>{u.current?.focus()},children:[l,t&&Ab("div",{className:"ExcTextField__label",children:t}),aC("div",{className:Pb("ExcTextField__input",{"ExcTextField__input--readonly":r}),children:[Ab("input",{className:Pb({"is-redacted":"value"in p&&p.value&&s&&!h}),readOnly:r,value:"value"in p?p.value:void 0,defaultValue:"defaultValue"in p?p.defaultValue:void 0,placeholder:n,ref:u,onChange:E=>e?.(E.target.value),onKeyDown:a,type:m}),s&&Ab(io,{onSelect:()=>g(!h),style:{border:0,userSelect:"none"},children:h?Sw:ts})]})]})});import{Fragment as cC,jsx as Rt,jsxs as Hn}from"react/jsx-runtime";var bF=17,xF=64;function Db({isLoading:e,libraryItems:t,onAddToLibrary:o,onInsertLibraryItems:n,pendingElements:r,theme:i,id:a,libraryReturnUrl:s,onSelectItems:l,selectedItems:c}){let m=we(),p=sC(null),d=TT(p);Lb(()=>{d>0&&p.current?.scrollTo(0,d)},[]);let{svgCache:u}=Hs(),[h,g]=lC(null),[E,w]=lC(""),x=!t.length&&!r.length,y=!x&&!!E.trim(),v=_b(()=>{let D=Ji(E.trim().toLowerCase());return D?t.filter(F=>{let z=F.name||"";return z.trim()&&Ji(z.toLowerCase()).includes(D)}):[]},[t,E]),I=_b(()=>t.filter(D=>D.status!=="published"),[t]),k=_b(()=>t.filter(D=>D.status==="published"),[t]),L=Vs((D,F)=>{let z=!c.includes(D),$=[...I,...k];if(z){if(F.shiftKey&&h){let V=$.findIndex(Re=>Re.id===h),Q=$.findIndex(Re=>Re.id===D);if(V===-1||Q===-1){l([...c,D]);return}let ee=uF(c),ie=Math.min(V,Q),Ee=Math.max(V,Q),_e=$.reduce((Re,We,lt)=>((lt>=ie&&lt<=Ee||ee.has(We.id))&&Re.push(We.id),Re),[]);l(_e)}else l([...c,D]);g(D)}else g(null),l(c.filter(V=>V!==D))},[h,l,k,c,I]);Lb(()=>{c.length||g(null)},[c]);let S=Vs(D=>{let F;return c.includes(D)?F=t.filter(z=>c.includes(z.id)):F=t.filter(z=>z.id===D),F.map(z=>({...z,elements:hF({type:"everything",elements:z.elements,randomizeSeed:!0}).duplicatedElements}))},[t,c]),_=Vs((D,F)=>{let z={itemIds:c.includes(D)?c:[D]};F.dataTransfer.setData(pF.excalidrawlibIds,JSON.stringify(z))},[c]),P=Vs(D=>D?c.includes(D):!1,[c]),T=Vs(()=>{o(r)},[r,o]),M=Vs(D=>{D&&n(S(D))},[S,n]),N=u.size>=(v.length?v:t).length?xF:bF,O=sC(null);Lb(()=>{gF(()=>{O.current?.focus()})},[]);let B=!y&&Hn(cC,{children:[!x&&Rt("div",{className:"library-menu-items-container__header",children:f("labels.personalLib")}),!r.length&&!I.length?Hn("div",{className:"library-menu-items__no-items",children:[!k.length&&Rt("div",{className:"library-menu-items__no-items__label",children:f("library.noItems")}),Rt("div",{className:"library-menu-items__no-items__hint",children:k.length>0?f("library.hint_emptyPrivateLibrary"):f("library.hint_emptyLibrary")})]}):Hn(Np,{children:[r.length>0&&Rt(Oc,{itemsRenderedPerBatch:N,items:[{id:null,elements:r}],onItemSelectToggle:L,onItemDrag:_,onClick:T,isItemSelected:P,svgCache:u}),Rt(Oc,{itemsRenderedPerBatch:N,items:I,onItemSelectToggle:L,onItemDrag:_,onClick:M,isItemSelected:P,svgCache:u})]}),k.length>0&&Rt("div",{className:"library-menu-items-container__header",style:{marginTop:"0.75rem"},children:f("labels.excalidrawLib")}),k.length>0&&Rt(Np,{children:Rt(Oc,{itemsRenderedPerBatch:N,items:k,onItemSelectToggle:L,onItemDrag:_,onClick:M,isItemSelected:P,svgCache:u})})]}),U=y&&Hn(cC,{children:[Hn("div",{className:"library-menu-items-container__header",children:[f("library.search.heading"),!e&&Hn("div",{className:"library-menu-items-container__header__hint",style:{cursor:"pointer"},onPointerDown:D=>D.preventDefault(),onClick:D=>{w("")},children:[Rt("kbd",{children:"esc"})," to clear"]})]}),v.length>0?Rt(Np,{children:Rt(Oc,{itemsRenderedPerBatch:N,items:v,onItemSelectToggle:L,onItemDrag:_,onClick:M,isItemSelected:P,svgCache:u})}):Hn("div",{className:"library-menu-items__no-items",children:[Rt("div",{className:"library-menu-items__no-items__hint",children:f("library.search.noResults")}),Rt(io,{onPointerDown:D=>D.preventDefault(),onSelect:()=>{w("")},style:{width:"auto",marginTop:"1rem"},children:f("library.search.clearSearch")})]})]});return Hn("div",{className:"library-menu-items-container",style:r.length||I.length||k.length?{justifyContent:"flex-start"}:{borderBottom:0},children:[Hn("div",{className:"library-menu-items-header",children:[!x&&Rt(ti,{ref:O,type:"search",className:fF("library-menu-items-container__search",{hideCancelButton:m.formFactor!=="phone"}),placeholder:f("library.search.inputPlaceholder"),value:E,onChange:D=>w(D)}),Rt(tC,{selectedItems:c,onSelectItems:l,className:"library-menu-dropdown-container--in-heading"})]}),Hn(Dt.Col,{className:"library-menu-items-container__items",align:"start",gap:1,style:{flex:k.length>0?1:"0 1 auto",margin:x?"auto":0},ref:p,children:[e&&Rt("div",{style:{position:"absolute",top:"var(--container-padding-y)",right:"var(--container-padding-x)",transform:"translateY(50%)"},children:Rt(Gt,{})}),B,U,x&&Rt(Cp,{style:{padding:"16px 0",width:"100%"},id:a,libraryReturnUrl:s,theme:i})]})]})}import{jsx as oi,jsxs as pC}from"react/jsx-runtime";var Ws=Ce(!1),mC=({children:e})=>oi("div",{className:"layer-ui__library",children:e}),SF=hC(({onInsertLibraryItems:e,pendingElements:t,onAddToLibrary:o,setAppState:n,libraryReturnUrl:r,library:i,id:a,theme:s,selectedItems:l,onSelectItems:c})=>{let[m]=ae(fr),p=Nb(h=>{(async(E,w)=>{ge("element","addToLibrary","ui");for(let y of yF)if(E.some(v=>v.type===y))return n({errorMessage:f(`errors.libraryElementTypeError.${y}`)});let x=[{status:"unpublished",elements:E,id:wF(),created:Date.now()},...w];o(),i.setLibrary(x).catch(()=>{n({errorMessage:f("alerts.errorAddingToLibrary")})})})(h,m.libraryItems)},[o,i,n,m.libraryItems]),d=gC(()=>m.libraryItems,[m]);if(m.status==="loading"&&!m.isInitialized)return oi(mC,{children:oi("div",{className:"layer-ui__library-message",children:pC("div",{children:[oi(Gt,{size:"2em"}),oi("span",{children:f("labels.libraryLoadingMessage")})]})})});let u=m.libraryItems.length>0||t.length>0;return pC(mC,{children:[oi(Db,{isLoading:m.status==="loading",libraryItems:d,onAddToLibrary:p,onInsertLibraryItems:e,pendingElements:t,id:a,libraryReturnUrl:r,theme:s,onSelectItems:c,selectedItems:l}),u&&oi(Cp,{className:"library-menu-control-buttons--at-bottom",style:{padding:"16px 12px 0 12px"},id:a,libraryReturnUrl:r,theme:s})]})}),Rb=(e,t)=>({elements:e,pending:le(e,{selectedElementIds:t},{includeBoundTextElement:!0,includeElementsInFrames:!0}),selectedElementIds:t}),MF=(e,t)=>{let o=Hr(),[n,r]=uC(()=>Rb(o,e.selectedElementIds)),i=EF(new Map);return Bb(()=>{for(let a of n.pending)i.current.set(a.id,a.version)},[n.pending]),Bb(()=>{t.state.cursorButton==="up"&&t.state.activeTool.type==="selection"&&r(a=>{if(!vF(a.selectedElementIds,e.selectedElementIds))return i.current.clear(),Rb(o,e.selectedElementIds);let s=t.scene.getNonDeletedElementsMap();for(let l of Object.keys(e.selectedElementIds)){let c=s.get(l)?.version;if(c&&c!==i.current.get(l))return Rb(o,e.selectedElementIds)}return a})},[t,t.state.cursorButton,t.state.activeTool.type,e.selectedElementIds,o]),n.pending},fC=hC(()=>{let e=Qe(),{onInsertElements:t}=e,o=Nn(),n=ye(),r=ve(),[i,a]=uC([]),s=gC(()=>e.library,[e.library]),l=MF(n,e);Bb(()=>CF(document,kF.KEYDOWN,p=>{if(p.key===IF.ESCAPE&&p.target instanceof HTMLElement){let d=p.target;if(d.closest(`.${dC.SIDEBAR}`))i.length>0?(p.stopPropagation(),a([])):TF(d)&&d instanceof HTMLInputElement&&!d.value&&(p.stopPropagation(),r({openSidebar:null}),e.focusContainer());else if(i.length>0){let{x:u,y:h}=e.lastViewportPosition;document.elementFromPoint(u,h)?.closest(`.${dC.SIDEBAR}`)&&(p.stopPropagation(),a([]))}}},{capture:!0}),[i,r,e]);let c=Nb(p=>{t(Us(p)),e.focusContainer()},[t,e]),m=Nb(()=>{r({selectedElementIds:{},selectedGroupIds:{},activeEmbeddable:null})},[r]);return oi(SF,{pendingElements:l,onInsertLibraryItems:c,onAddToLibrary:m,setAppState:r,libraryReturnUrl:o.libraryReturnUrl,library:s,id:e.id,theme:n.theme,selectedItems:i,onSelectItems:a})});import PF from"clsx";import{useRef as AF}from"react";import{createPortal as LF}from"react-dom";import{KEYS as _F}from"@orangecatai/common";import{jsx as bC,jsxs as DF}from"react/jsx-runtime";var xC=e=>{let{closeOnClickOutside:t=!0}=e,o=km({className:"excalidraw-modal-container"}),n=AF(document.body.classList.contains("excalidraw-animations-disabled"));if(!o)return null;let r=i=>{i.key===_F.ESCAPE&&(i.nativeEvent.stopImmediatePropagation(),i.stopPropagation(),e.onCloseRequest())};return LF(DF("div",{className:PF("Modal",e.className,{"animations-disabled":n.current}),role:"dialog","aria-modal":"true",onKeyDown:r,"aria-labelledby":e.labelledBy,children:[bC("div",{className:"Modal__background",onClick:t?e.onCloseRequest:void 0}),bC("div",{className:"Modal__content",style:{"--max-width":`${e.maxWidth}px`},tabIndex:0,children:e.children})]}),o)};import{jsx as zc,jsxs as zF}from"react/jsx-runtime";function OF(e){if(e&&typeof e=="number")return e;switch(e){case"small":return 550;case"wide":return 1024;case"regular":default:return 800}}var ht=e=>{let[t,o]=dT(),[n]=BF(document.activeElement),{id:r}=qe(),i=we().formFactor==="phone";NF(()=>{if(!t)return;let c=EC(t);setTimeout(()=>{c.length>0&&e.autofocus!==!1&&(c[1]||c[0]).focus()});let m=p=>{if(p.key===FF.TAB){let d=EC(t),{activeElement:u}=document,h=d.findIndex(g=>g===u);h===0&&p.shiftKey?(d[d.length-1].focus(),p.preventDefault()):h===d.length-1&&!p.shiftKey&&(d[0].focus(),p.preventDefault())}};return t.addEventListener("keydown",m),()=>t.removeEventListener("keydown",m)},[t,e.autofocus]);let a=ve(),s=Pn(Ws),l=()=>{a({openMenu:null}),s(!1),n.focus(),e.onCloseRequest()};return zc(xC,{className:RF("Dialog",e.className,{"Dialog--fullscreen":i}),labelledBy:"dialog-title",maxWidth:OF(e.size),onCloseRequest:l,closeOnClickOutside:e.closeOnClickOutside,children:zF(ut,{ref:o,children:[e.title&&zc("h2",{id:`${r}-dialog-title`,className:"Dialog__title",children:zc("span",{className:"Dialog__titleContent",children:e.title})}),i&&zc("button",{className:"Dialog__close",onClick:l,title:f("buttons.close"),"aria-label":f("buttons.close"),type:"button",children:Fo}),zc("div",{className:"Dialog__content",children:e.children})]})})};import{KEYS as ct}from"@orangecatai/common";var Bp=[{icon:Ja,value:"hand",key:ct.H,numericKey:null,fillable:!1,toolbar:!0},{icon:Oi,value:"selection",key:ct.V,numericKey:ct[1],fillable:!0,toolbar:!0},{icon:Ya,value:"rectangle",key:ct.R,numericKey:ct[2],fillable:!0,toolbar:!0},{icon:Va,value:"diamond",key:ct.D,numericKey:ct[3],fillable:!0,toolbar:!0},{icon:$a,value:"ellipse",key:ct.O,numericKey:ct[4],fillable:!0,toolbar:!0},{icon:am,value:"arrow",key:ct.A,numericKey:ct[5],fillable:!0,toolbar:!0},{icon:Ka,value:"line",key:ct.L,numericKey:ct[6],fillable:!0,toolbar:!0},{icon:Ln,value:"freedraw",key:[ct.P,ct.X],numericKey:ct[7],fillable:!1,toolbar:!0},{icon:_n,value:"text",key:ct.T,numericKey:ct[8],fillable:!1,toolbar:!0},{icon:Xa,value:"image",key:null,numericKey:ct[9],fillable:!1,toolbar:!0},{icon:sm,value:"eraser",key:ct.E,numericKey:ct[0],fillable:!1,toolbar:!0},{icon:Rn,value:"laser",key:ct.K,numericKey:null,fillable:!1,toolbar:!1}],Fb=e=>e.state.preferredSelectionTool.type==="lasso"?[{value:"lasso",icon:Oi,key:ct.V,numericKey:ct[1],fillable:!0,toolbar:!0},...Bp.slice(1)]:Bp,yC=(e,t)=>Fb(t).find((n,r)=>n.numericKey!=null&&e===n.numericKey.toString()||n.key&&(typeof n.key=="string"?n.key===e:n.key.includes(e)))?.value||null;import Un from"clsx";import{useRef as XF,useState as ZF}from"react";import{Popover as ri}from"radix-ui";import{CLASSES as kC,KEYS as jF,capitalizeString as ni,isTransparent as Op}from"@orangecatai/common";import{shouldAllowVerticalAlign as SC,suppportsHorizontalAlign as MC,hasBoundTextElement as zp,isElbowArrow as Gb,isImageElement as PC,isLinearElement as Ub,isTextElement as Gp,isArrowElement as TC,hasStrokeColor as CC,toolIsArrow as Hp}from"@orangecatai/element";import{createIsolation as HF}from"jotai-scope";import Ob from"react";import Gn from"tunnel-rat";var zb=Ob.createContext(null),Xe=()=>Ob.useContext(zb),GF=HF(),wC=()=>Ob.useMemo(()=>({MainMenuTunnel:Gn(),WelcomeScreenMenuHintTunnel:Gn(),WelcomeScreenToolbarHintTunnel:Gn(),WelcomeScreenHelpHintTunnel:Gn(),WelcomeScreenCenterTunnel:Gn(),FooterCenterTunnel:Gn(),DefaultSidebarTriggerTunnel:Gn(),DefaultSidebarTabTriggersTunnel:Gn(),OverwriteConfirmDialogTunnel:Gn(),TTDDialogTriggerTunnel:Gn(),tunnelsJotai:GF}),[]);import{CODES as UF,KEYS as WF}from"@orangecatai/common";import{CaptureUpdateAction as YF}from"@orangecatai/element";var ea=W({name:"viewMode",label:"labels.viewMode",icon:ts,viewMode:!0,trackEvent:{category:"canvas",predicate:e=>!e.viewModeEnabled},perform(e,t){return{appState:{...t,viewModeEnabled:!this.checked(t)},captureUpdate:YF.EVENTUALLY}},checked:e=>e.viewModeEnabled,predicate:(e,t,o)=>typeof o.viewModeEnabled>"u",keyTest:e=>!e[WF.CTRL_OR_CMD]&&e.altKey&&e.code===UF.R});import{useEffect as VF,useState as $F}from"react";import vC from"clsx";import{capitalizeString as IC}from"@orangecatai/common";import{Popover as Hb}from"radix-ui";import{jsx as Fp,jsxs as KF}from"react/jsx-runtime";var $s=({app:e,options:t,activeTool:o,defaultOption:n,className:r="Shape",namePrefix:i,title:a,"data-testid":s,onToolChange:l,displayedOption:c,fillable:m=!1})=>{let[p,d]=$F(!1),u=o.type,h=c.type===u,g=32/2+10,{container:E}=qe();return!t.some(w=>w.type===u)&&p&&d(!1),VF(()=>{let w=e.onPointerDownEmitter.on(()=>{d(!1)});return()=>w?.()},[e]),KF(Hb.Root,{open:p,children:[Fp(Hb.Trigger,{asChild:!0,children:Fp(ne,{className:vC(r,{fillable:m,active:t.some(w=>w.type===o.type)}),type:"radio",icon:c.icon,checked:h,name:"editor-current-shape",title:a,"aria-label":a,"data-testid":s,onPointerDown:()=>{d(w=>!w),l(n)}})}),Fp(Hb.Content,{className:"tool-popover-content",sideOffset:g,collisionBoundary:E??void 0,children:t.map(({type:w,icon:x,title:y})=>Fp(ne,{className:vC(r,{active:u===w}),type:"radio",icon:x,checked:u===w,name:`${i}-option`,title:y||IC(w),keyBindingLabel:"","aria-label":y||IC(w),"data-testid":`toolbar-${w}`,onChange:()=>{e.state.activeTool.type!==w&&ge("toolbar",w,"ui"),e.setActiveTool({type:w}),l?.(w)}},w))})]})};import{Fragment as Ao,jsx as re,jsxs as Ie}from"react/jsx-runtime";var Wb=Un([kC.SHAPE_ACTIONS_THEME_SCOPE,"properties-content"]),Hc=(e,t)=>{let o=t[0]?.type||null;for(let n of t)if(n.type!==o){o=null;break}return CC(e.activeTool.type)&&o!=="image"&&o!=="frame"&&o!=="magicframe"||t.some(n=>CC(n.type))},Gc=(e,t)=>kn(e.activeTool.type)||t.some(o=>kn(o.type)),AC=({appState:e,elementsMap:t,renderAction:o,app:n})=>{let r=_a(t,e),i=!1;r.length===2&&(zp(r[0])||zp(r[1]))&&(i=!0);let a=!!(e.editingTextElement||e.newElement),s=we(),l=document.documentElement.getAttribute("dir")==="rtl",c=kn(e.activeTool.type)&&!Op(e.currentItemBackgroundColor)||r.some(h=>kn(h.type)&&!Op(h.backgroundColor)),m=r.length===1||i,p=!e.selectedLinearElement?.isEditing&&r.length===1&&Ub(r[0])&&!Gb(r[0]),d=!e.croppingElementId&&r.length===1&&PC(r[0]),u=!i&&no(e,n);return Ie("div",{className:"selected-shape-actions",children:[re("div",{children:Hc(e,r)&&o("changeStrokeColor")}),Gc(e,r)&&re("div",{children:o("changeBackgroundColor")}),c&&o("changeFillStyle"),(Hl(e.activeTool.type)||r.some(h=>Hl(h.type)))&&o("changeStrokeWidth"),(e.activeTool.type==="freedraw"||r.some(h=>h.type==="freedraw"))&&o("changeStrokeShape"),(Gl(e.activeTool.type)||r.some(h=>Gl(h.type)))&&Ie(Ao,{children:[o("changeStrokeStyle"),o("changeSloppiness")]}),(Ul(e.activeTool.type)||r.some(h=>Ul(h.type)))&&re(Ao,{children:o("changeRoundness")}),(Hp(e.activeTool.type)||r.some(h=>Hp(h.type)))&&re(Ao,{children:o("changeArrowType")}),(e.activeTool.type==="text"||r.some(Gp))&&Ie(Ao,{children:[o("changeFontFamily"),o("changeFontSize"),(e.activeTool.type==="text"||MC(r,t))&&o("changeTextAlign")]}),SC(r,t)&&o("changeVerticalAlign"),(Da(e.activeTool.type)||r.some(h=>Da(h.type)))&&re(Ao,{children:o("changeArrowhead")}),o("changeOpacity"),Ie("fieldset",{children:[re("legend",{children:f("labels.layers")}),Ie("div",{className:"buttonList",children:[o("sendToBack"),o("sendBackward"),o("bringForward"),o("bringToFront")]})]}),u&&!i&&Ie("fieldset",{children:[re("legend",{children:f("labels.align")}),Ie("div",{className:"buttonList",children:[l?Ie(Ao,{children:[o("alignRight"),o("alignHorizontallyCentered"),o("alignLeft")]}):Ie(Ao,{children:[o("alignLeft"),o("alignHorizontallyCentered"),o("alignRight")]}),r.length>2&&o("distributeHorizontally"),re("div",{style:{flexBasis:"100%",height:0}}),Ie("div",{style:{display:"flex",flexWrap:"wrap",gap:".5rem",marginTop:"-0.5rem"},children:[o("alignTop"),o("alignVerticallyCentered"),o("alignBottom"),r.length>2&&o("distributeVertically")]})]})]}),!a&&r.length>0&&Ie("fieldset",{children:[re("legend",{children:f("labels.actions")}),Ie("div",{className:"buttonList",children:[s.formFactor!=="phone"&&o("duplicateSelection"),s.formFactor!=="phone"&&o("deleteSelectedElements"),o("group"),o("ungroup"),m&&o("hyperlink"),d&&o("cropEditor"),p&&o("toggleLinearEditor")]})]})]})},LC=({appState:e,renderAction:t,setAppState:o,targetElements:n,container:r})=>{let i=kn(e.activeTool.type)&&!Op(e.currentItemBackgroundColor)||n.some(l=>kn(l.type)&&!Op(l.backgroundColor)),a=n.length>0||e.activeTool.type!=="selection"&&e.activeTool.type!=="eraser"&&e.activeTool.type!=="hand"&&e.activeTool.type!=="laser"&&e.activeTool.type!=="lasso",s=e.openPopup==="compactStrokeStyles";return a?re("div",{className:"compact-action-item",children:Ie(ri.Root,{open:s,onOpenChange:l=>{o(l?{openPopup:"compactStrokeStyles"}:{openPopup:null})},children:[re(ri.Trigger,{asChild:!0,children:re("button",{type:"button",className:Un("compact-action-button properties-trigger",{active:s}),title:f("labels.stroke"),onClick:l=>{l.preventDefault(),l.stopPropagation(),o({openPopup:s?null:"compactStrokeStyles"})},children:Xw})}),s&&re(cr,{className:Wb,container:r,style:{maxWidth:"13rem"},onClose:()=>{},children:Ie("div",{className:"selected-shape-actions",children:[i&&t("changeFillStyle"),(Hl(e.activeTool.type)||n.some(l=>Hl(l.type)))&&t("changeStrokeWidth"),(Gl(e.activeTool.type)||n.some(l=>Gl(l.type)))&&Ie(Ao,{children:[t("changeStrokeStyle"),t("changeSloppiness")]}),(Ul(e.activeTool.type)||n.some(l=>Ul(l.type)))&&t("changeRoundness"),t("changeOpacity")]})})]})}):null},_C=({appState:e,renderAction:t,setAppState:o,targetElements:n,container:r,app:i})=>{let a=Hp(e.activeTool.type)||n.some(l=>Hp(l.type)),s=e.openPopup==="compactArrowProperties";return a?re("div",{className:"compact-action-item",children:Ie(ri.Root,{open:s,onOpenChange:l=>{o(l?{openPopup:"compactArrowProperties"}:{openPopup:null})},children:[re(ri.Trigger,{asChild:!0,children:re("button",{type:"button",className:Un("compact-action-button properties-trigger",{active:s}),title:f("labels.arrowtypes"),onClick:l=>{l.preventDefault(),l.stopPropagation(),o({openPopup:s?null:"compactArrowProperties"})},children:(()=>{let l=Yt(n,i,c=>TC(c)?c.elbowed?"elbow":c.roundness?"round":"sharp":null,c=>TC(c),c=>c?null:e.currentItemArrowType);return l==="elbow"?rs:l==="round"?is:ns})()})}),s&&re(cr,{container:r,className:"properties-content",style:{maxWidth:"13rem"},onClose:()=>{},children:t("changeArrowProperties")})]})}):null},DC=({appState:e,renderAction:t,setAppState:o,targetElements:n,container:r,elementsMap:i})=>{let{saveCaretPosition:a,restoreCaretPosition:s}=fv(),l=e.openPopup==="compactTextProperties";return re("div",{className:"compact-action-item",children:Ie(ri.Root,{open:l,onOpenChange:c=>{c?(e.editingTextElement&&a(),o({openPopup:"compactTextProperties"})):(o({openPopup:null}),e.editingTextElement&&s())},children:[re(ri.Trigger,{asChild:!0,children:re("button",{type:"button",className:Un("compact-action-button properties-trigger",{active:l}),title:f("labels.textAlign"),onClick:c=>{c.preventDefault(),c.stopPropagation(),l?o({openPopup:null}):(e.editingTextElement&&a(),o({openPopup:"compactTextProperties"}))},children:xy})}),e.openPopup==="compactTextProperties"&&re(cr,{className:Wb,container:r,style:{maxWidth:"13rem"},preventAutoFocusOnTouch:!!e.editingTextElement,onClose:()=>{e.editingTextElement&&s()},children:Ie("div",{className:"selected-shape-actions",children:[(e.activeTool.type==="text"||n.some(Gp))&&t("changeFontSize"),(e.activeTool.type==="text"||MC(n,i))&&t("changeTextAlign"),SC(n,i)&&t("changeVerticalAlign")]})})]})})},RC=({appState:e,renderAction:t,targetElements:o,setAppState:n,container:r,app:i,showDuplicate:a,showDelete:s})=>{let l=!!(e.editingTextElement||e.newElement),c=!e.croppingElementId&&o.length===1&&PC(o[0]),m=o.length===1,p=no(e,i),d=!1;o.length===2&&(zp(o[0])||zp(o[1]))&&(d=!0);let u=document.documentElement.getAttribute("dir")==="rtl",h=e.openPopup==="compactOtherProperties";return l||o.length===0?null:re("div",{className:"compact-action-item",children:Ie(ri.Root,{open:h,onOpenChange:g=>{n(g?{openPopup:"compactOtherProperties"}:{openPopup:null})},children:[re(ri.Trigger,{asChild:!0,children:re("button",{type:"button",className:Un("compact-action-button properties-trigger",{active:h}),title:f("labels.actions"),onClick:g=>{g.preventDefault(),g.stopPropagation(),n({openPopup:h?null:"compactOtherProperties"})},children:my})}),h&&re(cr,{className:Wb,container:r,style:{maxWidth:"12rem",justifyContent:"center",alignItems:"center"},onClose:()=>{},children:Ie("div",{className:"selected-shape-actions",children:[Ie("fieldset",{children:[re("legend",{children:f("labels.layers")}),Ie("div",{className:"buttonList",children:[t("sendToBack"),t("sendBackward"),t("bringForward"),t("bringToFront")]})]}),p&&!d&&Ie("fieldset",{children:[re("legend",{children:f("labels.align")}),Ie("div",{className:"buttonList",children:[u?Ie(Ao,{children:[t("alignRight"),t("alignHorizontallyCentered"),t("alignLeft")]}):Ie(Ao,{children:[t("alignLeft"),t("alignHorizontallyCentered"),t("alignRight")]}),o.length>2&&t("distributeHorizontally"),re("div",{style:{flexBasis:"100%",height:0}}),Ie("div",{style:{display:"flex",flexWrap:"wrap",gap:".5rem",marginTop:"-0.5rem"},children:[t("alignTop"),t("alignVerticallyCentered"),t("alignBottom"),o.length>2&&t("distributeVertically")]})]})]}),Ie("fieldset",{children:[re("legend",{children:f("labels.actions")}),Ie("div",{className:"buttonList",children:[t("group"),t("ungroup"),m&&t("hyperlink"),c&&t("cropEditor"),a&&t("duplicateSelection"),s&&t("deleteSelectedElements")]})]})]})})]})})},qF=({appState:e,renderAction:t,targetElements:o})=>!e.selectedLinearElement?.isEditing&&o.length===1&&Ub(o[0])&&!Gb(o[0])?re("div",{className:"compact-action-item",children:t("toggleLinearEditor")}):null,NC=({appState:e,elementsMap:t,renderAction:o,app:n,setAppState:r})=>{let i=_a(t,e),{container:a}=qe(),s=!!(e.editingTextElement||e.newElement),l=!e.selectedLinearElement?.isEditing&&i.length===1&&Ub(i[0])&&!Gb(i[0]);return Ie("div",{className:"compact-shape-actions",children:[Hc(e,i)&&re("div",{className:Un("compact-action-item"),children:o("changeStrokeColor")}),Gc(e,i)&&re("div",{className:"compact-action-item",children:o("changeBackgroundColor")}),re(LC,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a}),re(_C,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a,app:n}),l&&re("div",{className:"compact-action-item",children:o("toggleLinearEditor")}),(e.activeTool.type==="text"||i.some(Gp))&&Ie(Ao,{children:[re("div",{className:"compact-action-item",children:o("changeFontFamily")}),re(DC,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a,elementsMap:t})]}),!s&&i.length>0&&re("div",{className:"compact-action-item",children:o("duplicateSelection")}),!s&&i.length>0&&re("div",{className:"compact-action-item",children:o("deleteSelectedElements")}),re(RC,{appState:e,renderAction:o,targetElements:i,setAppState:r,container:a,app:n})]})},BC=({appState:e,elementsMap:t,renderAction:o,app:n,setAppState:r})=>{let i=_a(t,e),{container:a}=qe(),s=XF(null),l=s.current?.getBoundingClientRect()?.width??0,c=9,m=6,p=32,d=c*p+(c-1)*m,u=p+m,h=l>=d+u,g=l>=d+2*u;return Ie(ut,{className:"compact-shape-actions mobile-shape-actions",style:{flexDirection:"row",boxShadow:"none",padding:0,zIndex:2,backgroundColor:"transparent",height:p*1.35,marginBottom:4,alignItems:"center",gap:m,pointerEvents:"none"},ref:s,children:[Ie("div",{style:{display:"flex",flexDirection:"row",gap:m,flex:1},children:[Hc(e,i)&&re("div",{className:Un("compact-action-item"),children:o("changeStrokeColor")}),Gc(e,i)&&re("div",{className:"compact-action-item",children:o("changeBackgroundColor")}),re(LC,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a}),re(_C,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a,app:n}),re(qF,{appState:e,renderAction:o,targetElements:i}),(e.activeTool.type==="text"||i.some(Gp))&&Ie(Ao,{children:[re("div",{className:"compact-action-item",children:o("changeFontFamily")}),re(DC,{appState:e,renderAction:o,setAppState:r,targetElements:i,container:a,elementsMap:t})]}),re(RC,{appState:e,renderAction:o,targetElements:i,setAppState:r,container:a,app:n,showDuplicate:!g,showDelete:!h})]}),Ie("div",{style:{display:"flex",flexDirection:"row",gap:m},children:[re("div",{className:"compact-action-item",children:o("undo")}),re("div",{className:"compact-action-item",children:o("redo")}),g&&re("div",{className:"compact-action-item",children:o("duplicateSelection")}),h&&re("div",{className:"compact-action-item",children:o("deleteSelectedElements")})]})]})},FC=({activeTool:e,setAppState:t,app:o,UIOptions:n})=>{let[r,i]=ZF(!1),a=_t(),s=a==="full",l=a==="compact",c=[{type:"selection",icon:Oi,title:ni(f("toolBar.selection"))},{type:"lasso",icon:Nr,title:ni(f("toolBar.lasso"))}],m=e.type==="frame",p=e.type==="laser",d=s&&e.type==="lasso"&&o.state.preferredSelectionTool.type!=="lasso",u=e.type==="embeddable",{TTDDialogTriggerTunnel:h}=Xe();return Ie(Ao,{children:[Fb(o).map(({value:g,icon:E,key:w,numericKey:x,fillable:y,toolbar:v})=>{if(v===!1||n.tools?.[g]===!1)return null;let I=f(`toolBar.${g}`),k=w&&ni(typeof w=="string"?w:w[0]),L=k?`${k} ${f("helpDialog.or")} ${x}`:`${x}`,S=g==="hand"?void 0:x||k;return(g==="selection"||g==="lasso")&&l?re($s,{app:o,options:c,activeTool:e,defaultOption:o.state.preferredSelectionTool.type,namePrefix:"selectionType",title:ni(f("toolBar.selection")),"data-testid":"toolbar-selection",onToolChange:_=>{(_==="selection"||_==="lasso")&&(o.setActiveTool({type:_}),t({preferredSelectionTool:{type:_,initialized:!0}}))},displayedOption:c.find(_=>_.type===o.state.preferredSelectionTool.type)||c[0],fillable:e.type==="selection"},"selection-popover"):re(ne,{className:Un("Shape",{fillable:y}),type:"radio",icon:E,checked:e.type===g,name:"editor-current-shape",title:`${ni(I)} \u2014 ${L}`,keyBindingLabel:S,"aria-label":ni(I),"aria-keyshortcuts":L,"data-testid":`toolbar-${g}`,onPointerDown:({pointerType:_})=>{!o.state.penDetected&&_==="pen"&&o.togglePenMode(!0),g==="selection"&&(o.state.activeTool.type==="selection"?o.setActiveTool({type:"lasso"}):o.setActiveTool({type:"selection"}))},onChange:({pointerType:_})=>{o.state.activeTool.type!==g&&ge("toolbar",g,"ui"),g==="image"?o.setActiveTool({type:g}):o.setActiveTool({type:g})}},g)}),re("div",{className:"App-toolbar__divider"}),re(ne,{className:"Shape",type:"radio",icon:Iw,checked:!1,name:"editor-current-shape",title:"Image Generator \u2014 A",keyBindingLabel:"A","aria-label":"Image Generator","data-testid":"toolbar-image-generator",onChange:()=>{ge("toolbar","imageGenerator","ui"),o.onImageGeneratorSelect()}}),re(ne,{className:"Shape",type:"radio",icon:Dn,checked:m,name:"editor-current-shape",title:`${ni(f("toolBar.frame"))} \u2014 F`,keyBindingLabel:"F","aria-label":ni(f("toolBar.frame")),"data-testid":"toolbar-frame",onChange:()=>{ge("toolbar","frame","ui"),o.setActiveTool({type:"frame"})}}),Ie(he,{open:r,children:[re(he.Trigger,{className:Un("App-toolbar__extra-tools-trigger",{"App-toolbar__extra-tools-trigger--selected":u||d||p&&!o.props.isCollaborating}),onToggle:()=>{i(!r),t({openMenu:null,openPopup:null})},title:f("toolBar.extraTools"),children:u?Za:p&&!o.props.isCollaborating?Rn:d?Nr:Ql}),Ie(he.Content,{onClickOutside:()=>i(!1),onSelect:()=>i(!1),className:"App-toolbar__extra-tools-dropdown",children:[re(he.Item,{onSelect:()=>o.setActiveTool({type:"embeddable"}),icon:Za,"data-testid":"toolbar-embeddable",selected:u,children:f("toolBar.embeddable")}),re(he.Item,{onSelect:()=>o.setActiveTool({type:"laser"}),icon:Rn,"data-testid":"toolbar-laser",selected:p,shortcut:jF.K.toLocaleUpperCase(),children:f("toolBar.laser")}),s&&re(he.Item,{onSelect:()=>o.setActiveTool({type:"lasso"}),icon:Nr,"data-testid":"toolbar-lasso",selected:d,children:f("toolBar.lasso")}),re("div",{style:{margin:"6px 0",fontSize:14,fontWeight:600},children:"Generate"}),o.props.aiEnabled!==!1&&re(h.Out,{}),re(he.Item,{onSelect:()=>o.setOpenDialog({name:"ttd",tab:"mermaid"}),icon:es,"data-testid":"toolbar-mermaid",children:f("toolBar.mermaidToExcalidraw")}),o.props.aiEnabled!==!1&&o.plugins.diagramToCode&&re(he.Item,{onSelect:()=>o.onMagicframeToolSelect(),icon:Gi,"data-testid":"toolbar-magicframe",badge:re(he.Item.Badge,{children:"AI"}),children:f("toolBar.magicframe")})]})]})]})},OC=({renderAction:e})=>e("scrollBackToContent"),zC=({renderAction:e,zoom:t})=>Ie(Dt.Row,{align:"center",className:kC.ZOOM_ACTIONS,children:[e("zoomOut"),e("resetZoom"),e("zoomIn")]}),HC=({renderAction:e,className:t})=>Ie("div",{className:`undo-redo-buttons ${t}`,children:[re("div",{className:"undo-button-container",children:re(Vt,{label:f("buttons.undo"),children:e("undo")})}),re("div",{className:"redo-button-container",children:Ie(Vt,{label:f("buttons.redo"),children:[" ",e("redo")]})})]}),GC=({actionManager:e,showExitZenModeBtn:t})=>re("button",{type:"button",className:Un("disable-zen-mode",{"disable-zen-mode--visible":t}),onClick:()=>e.executeAction(jr),children:f("buttons.exitZenMode")}),UC=({actionManager:e})=>re("button",{type:"button",className:"disable-view-mode",onClick:()=>e.executeAction(ea),children:jw});import{useRef as JF}from"react";var Yb=e=>{let t=JF({userFn:e});return t.current.userFn=e,t.current.stableFn||(t.current.stableFn=(...o)=>t.current.userFn(...o)),t.current.stableFn};import{jsx as eO,jsxs as QF}from"react/jsx-runtime";var ta=Ce(null),WC=()=>{let[e,t]=ae(ta),o=nt();return e&&e==="clearCanvas"?eO(Sp,{onConfirm:()=>{o.executeAction(gr),t(null)},onCancel:()=>t(null),title:f("clearCanvasDialog.title"),children:QF("p",{className:"clear-canvas__content",children:[" ",f("alerts.clearReset")]})}):null};var Vb={};NE(Vb,{toggleTheme:()=>tO});var tO={...Vi,category:"App",label:"Toggle theme",perform:({actionManager:e})=>{e.executeAction(Vi,"commandPalette")}};import{jsx as Nt,jsxs as Wn}from"react/jsx-runtime";var aO=Ce(null),rt={app:"App",export:"Export",tools:"Tools",editor:"Editor",elements:"Elements",links:"Links",library:"Library"},VC=e=>{switch(e){case rt.app:return 1;case rt.export:return 2;case rt.editor:return 3;case rt.tools:return 4;case rt.elements:return 5;case rt.links:return 6;default:return 10}},Yp=({shortcut:e,className:t,children:o})=>{let n=e.replace("++","+$").split("+");return Wn("div",{className:KC("shortcut",t),children:[n.map((r,i)=>Nt("div",{className:"shortcut-wrapper",children:Nt("div",{className:"shortcut-key",children:r==="$"?"+":r})},r)),Nt("div",{className:"shortcut-desc",children:o})]})},ZC=e=>!e.altKey&&e[fn.CTRL_OR_CMD]&&(e.shiftKey&&e.key.toLowerCase()===fn.P||e.key===fn.SLASH),sO=Object.assign(e=>{let t=ye(),o=ve();return Wp(()=>{let n=r=>{ZC(r)&&(r.preventDefault(),r.stopPropagation(),o(i=>{let a=i.openDialog?.name==="commandPalette"?null:{name:"commandPalette"};return a&&ge("command_palette","open","shortcut"),{openDialog:a}}))};return window.addEventListener(Vp.KEYDOWN,n,{capture:!0}),()=>window.removeEventListener(Vp.KEYDOWN,n,{capture:!0})},[o]),t.openDialog?.name!=="commandPalette"?null:Nt(lO,{...e})},{defaultItems:Vb});function lO({customCommandPaletteItems:e}){let t=Qe(),o=ye(),n=ve(),r=Nn(),i=nt(),[a,s]=ae(aO),[l,c]=Up(null),m=XC(null),p=Fr({uiAppState:o,customCommandPaletteItems:e,appProps:r}),[d]=ae(fr),u=nO(()=>d.libraryItems?.filter(S=>!!S.name).map(S=>({label:S.name,icon:Nt(cO,{id:S.id,elements:S.elements}),category:"Library",order:VC("Library"),haystack:Ji(S.name),perform:()=>{t.onInsertElements(Us([S]))}}))||[],[t,d.libraryItems]);Wp(()=>{let{uiAppState:S,customCommandPaletteItems:_,appProps:P}=p,T=B=>{let U="";return B.label&&(typeof B.label=="function"?U=f(B.label(t.scene.getNonDeletedElements(),S,t)):U=f(B.label)),U},M=B=>typeof B.icon=="function"?B.icon(S,t.scene.getNonDeletedElements()):B.icon,N=[],O=(B,U,D)=>{let F={label:T(B),icon:M(B),category:U,shortcut:Ke(B.name),keywords:B.keywords,predicate:B.predicate,viewMode:B.viewMode,perform:()=>{i.executeAction(B,"commandPalette")}};return D?D(F,B):F};if(S&&t.scene&&i){let B=[i.actions.group,i.actions.ungroup,i.actions.cut,i.actions.copy,i.actions.deleteSelectedElements,i.actions.wrapSelectionInFrame,i.actions.copyStyles,i.actions.pasteStyles,i.actions.bringToFront,i.actions.bringForward,i.actions.sendBackward,i.actions.sendToBack,i.actions.alignTop,i.actions.alignBottom,i.actions.alignLeft,i.actions.alignRight,i.actions.alignVerticallyCentered,i.actions.alignHorizontallyCentered,i.actions.duplicateSelection,i.actions.flipHorizontal,i.actions.flipVertical,i.actions.zoomToFitSelection,i.actions.zoomToFitSelectionInViewport,i.actions.increaseFontSize,i.actions.decreaseFontSize,i.actions.toggleLinearEditor,i.actions.cropEditor,i.actions.togglePolygon,Mc,yp,lT].map(V=>O(V,rt.elements,(Q,ee)=>({...Q,predicate:ee.predicate?ee.predicate:(ie,Ee,_e,Re)=>le(ie,Ee).length>0}))),U=[i.actions.toggleHandTool,i.actions.setFrameAsActiveTool,i.actions.toggleLassoTool].map(V=>O(V,rt.tools)),D=[i.actions.undo,i.actions.redo,i.actions.zoomIn,i.actions.zoomOut,i.actions.resetZoom,i.actions.zoomToFit,i.actions.zenMode,i.actions.viewMode,i.actions.gridMode,i.actions.objectsSnapMode,i.actions.toggleShortcuts,i.actions.selectAll,i.actions.toggleElementLock,i.actions.unlockAllElements,i.actions.stats].map(V=>O(V,rt.editor)),F=[i.actions.saveToActiveFile,i.actions.saveFileToDisk,i.actions.copyAsPng,i.actions.copyAsSvg].map(V=>O(V,rt.export));N=[...B,...D,{label:T(gr),icon:M(gr),shortcut:Ke(gr.name),category:rt.editor,keywords:["delete","destroy"],viewMode:!1,perform:()=>{xt.set(ta,"clearCanvas")}},{label:f("buttons.exportImage"),category:rt.export,icon:mm,shortcut:Ke("imageExport"),keywords:["export","image","png","jpeg","svg","clipboard","picture"],perform:()=>{n({openDialog:{name:"imageExport"}})}},...F];let z=[{label:f("toolBar.library"),category:rt.app,icon:im,viewMode:!1,perform:()=>{S.openSidebar?n({openSidebar:null}):n({openSidebar:{name:YC.name,tab:YC.defaultTab}})}},{label:f("search.title"),category:rt.app,icon:Co,viewMode:!0,perform:()=>{i.executeAction(Uc)}},{label:f("labels.shapeSwitch"),category:rt.elements,icon:ec,perform:()=>{i.executeAction(sT)}},{label:f("labels.changeStroke"),keywords:["color","outline"],category:rt.elements,icon:dm,viewMode:!1,predicate:(V,Q)=>{let ee=le(V,Q);return ee.length>0&&Hc(Q,ee)},perform:()=>{n(V=>({openPopup:"elementStroke"}))}},{label:f("labels.changeBackground"),keywords:["color","fill"],icon:dm,category:rt.elements,viewMode:!1,predicate:(V,Q)=>{let ee=le(V,Q);return ee.length>0&&Gc(Q,ee)},perform:()=>{n(V=>({openPopup:"elementBackground"}))}},{label:f("labels.canvasBackground"),keywords:["color"],icon:dm,category:rt.editor,viewMode:!1,perform:()=>{n(V=>({openMenu:V.openMenu==="canvas"?null:"canvas",openPopup:"canvasBackground"}))}},...Bp.reduce((V,Q)=>{let{value:ee,icon:ie,key:Ee,numericKey:_e}=Q;if(P.UIOptions.tools?.[ee]===!1)return V;let We=Ee&&rO(typeof Ee=="string"?Ee:Ee[0])||_e,lt={label:f(`toolBar.${ee}`),category:rt.tools,shortcut:We,icon:ie,keywords:["toolbar"],viewMode:!1,perform:({event:qt})=>{ee==="image"?t.setActiveTool({type:ee}):t.setActiveTool({type:ee})}};return V.push(lt),V},[]),...U,{label:f("toolBar.lock"),category:rt.tools,icon:S.activeTool.locked?Wa:Fi,shortcut:fn.Q.toLocaleUpperCase(),viewMode:!1,perform:()=>{t.toggleLock()}},{label:`${f("labels.textToDiagram")}...`,category:rt.tools,icon:Pw,viewMode:!1,predicate:P.aiEnabled,perform:()=>{n(V=>({...V,openDialog:{name:"ttd",tab:"text-to-diagram"}}))}},{label:`${f("toolBar.mermaidToExcalidraw")}...`,category:rt.tools,icon:es,viewMode:!1,predicate:P.aiEnabled,perform:()=>{n(V=>({...V,openDialog:{name:"ttd",tab:"mermaid"}}))}}],$=[...N,...z,..._||[]].map(V=>({...V,icon:V.icon||ec,order:V.order??VC(V.category),haystack:`${Ji(V.label.toLocaleLowerCase())} ${V.keywords?.join(" ")||""}`}));c($),s([...$,...u].find(V=>V.label===a?.label)??null)}},[p,t,i,c,a?.label,s,n,u]);let[h,g]=Up(""),[E,w]=Up(null),[x,y]=Up({}),v=S=>{n({openDialog:null},S),g("")},I=(S,_)=>{o.openDialog?.name==="commandPalette"&&(_.stopPropagation(),_.preventDefault(),document.body.classList.add("excalidraw-animations-disabled"),v(()=>{S.perform({actionManager:i,event:_}),s(S),requestAnimationFrame(()=>{document.body.classList.remove("excalidraw-animations-disabled")})}))},k=Yb(S=>S.viewMode===!1&&o.viewModeEnabled?!1:typeof S.predicate=="function"?S.predicate(t.scene.getNonDeletedElements(),o,r,t):S.predicate===void 0||S.predicate),L=Yb(S=>{let _=iO(S.target)||ZC(S)||S.key===fn.ESCAPE;if(_&&S.key!==fn.ARROW_UP&&S.key!==fn.ARROW_DOWN&&S.key!==fn.ENTER)return;let P=Object.values(x).flat(),T=a&&!h&&k(a);if(S.key===fn.ARROW_UP){S.preventDefault();let M=P.findIndex(B=>B.label===E?.label);if(T){if(M===0){w(a);return}if(E===a){let B=P[P.length-1];B&&w(B);return}}let N;M===-1?N=P.length-1:N=M===0?P.length-1:(M-1)%P.length;let O=P[N];O&&w(O);return}if(S.key===fn.ARROW_DOWN){S.preventDefault();let M=P.findIndex(B=>B.label===E?.label);if(T){if(!E||M===P.length-1){w(a);return}if(E===a){let B=P[0];B&&w(B);return}}let N=(M+1)%P.length,O=P[N];O&&w(O);return}if(S.key===fn.ENTER&&E&&setTimeout(()=>{I(E,S)}),!_){if(S.stopPropagation(),/^[a-zA-Z0-9]$/.test(S.key)){m?.current?.focus();return}S.preventDefault()}});return Wp(()=>(window.addEventListener(Vp.KEYDOWN,L,{capture:!0}),()=>window.removeEventListener(Vp.KEYDOWN,L,{capture:!0})),[L]),Wp(()=>{if(!l)return;let S=M=>{let N={};for(let O of M)N[O.category]?N[O.category].push(O):N[O.category]=[O];return N},_=h?.length>1?[...l.filter(k).sort((M,N)=>M.order-N.order),...u]:l.filter(k).sort((M,N)=>M.order-N.order),P=!h&&a&&k(a);if(!h){y(S(P?_.filter(M=>M.label!==a?.label):_)),w(P?a:_[0]||null);return}let T=Ji(h.toLocaleLowerCase().replace(/[<>_| -]/g,""));_=oO.filter(T,_,{extract:M=>M.haystack??""}).sort((M,N)=>N.score-M.score).map(M=>M.original),y(S(_)),w(_[0]??null)},[h,l,k,a,u]),Wn(ht,{onCloseRequest:()=>v(),closeOnClickOutside:!0,title:!1,size:720,autofocus:!0,className:"command-palette-dialog",children:[Nt(ti,{value:h,placeholder:f("commandPalette.search.placeholder"),onChange:S=>{g(S)},selectOnRender:!0,ref:m}),t.editorInterface.formFactor!=="phone"&&Wn("div",{className:"shortcuts-wrapper",children:[Nt(Yp,{shortcut:"\u2191\u2193",children:f("commandPalette.shortcuts.select")}),Nt(Yp,{shortcut:"\u21B5",children:f("commandPalette.shortcuts.confirm")}),Nt(Yp,{shortcut:G("Esc"),children:f("commandPalette.shortcuts.close")})]}),Wn("div",{className:"commands",children:[a&&!h&&Wn("div",{className:"command-category",children:[Wn("div",{className:"command-category-title",children:[f("commandPalette.recents"),Nt("div",{className:"icon",style:{marginLeft:"6px"},children:Aw})]}),Nt($C,{command:a,isSelected:a.label===E?.label,onClick:S=>I(a,S),disabled:!k(a),onMouseMove:()=>w(a),showShortcut:t.editorInterface.formFactor!=="phone",appState:o})]}),Object.keys(x).length>0?Object.keys(x).map((S,_)=>Wn("div",{className:"command-category",children:[Nt("div",{className:"command-category-title",children:S}),x[S].map(P=>Nt($C,{command:P,isSelected:P.label===E?.label,onClick:T=>I(P,T),onMouseMove:()=>w(P),showShortcut:t.editorInterface.formFactor!=="phone",appState:o,size:S==="Library"?"large":"small"},P.label))]},S)):l?Wn("div",{className:"no-match",children:[Nt("div",{className:"icon",children:Co})," ",f("commandPalette.search.noMatch")]}):null]})]})}var cO=({id:e,elements:t})=>{let o=XC(null),{svgCache:n}=Hs();return wp(e,t,n,o),Nt("div",{className:"library-item-icon",ref:o})},$C=({command:e,isSelected:t,disabled:o,onMouseMove:n,onClick:r,showShortcut:i,appState:a,size:s="small"})=>{let l=()=>{};return Wn("div",{className:KC("command-item",{"item-selected":t,"item-disabled":o,"command-item-large":s==="large"}),ref:c=>{t&&!o&&c?.scrollIntoView?.({block:"nearest"})},onClick:o?l:r,onMouseMove:o?l:n,title:o?f("commandPalette.itemNotAvailable"):"",children:[Wn("div",{className:"name",children:[e.icon&&Nt(Bn,{className:"icon",size:"var(--icon-size, 1rem)",icon:typeof e.icon=="function"?e.icon(a,[]):e.icon}),Nt(mc,{children:e.label})]}),i&&e.shortcut&&Nt(Yp,{shortcut:e.shortcut})]})};import{getSizeFromPoints as ike,randomInteger as dz,getUpdatedTimestamp as mz}from"@orangecatai/common";import{simplify as ZO}from"points-on-curve";import{getStroke as jO}from"perfect-freehand";import{pointsOnBezierCurves as Vye}from"points-on-curve";import{invariant as Kye}from"@orangecatai/common";import{curve as Zye,lineSegment as jye,pointFrom as qye,pointDistance as Jye,pointFromArray as Qye,pointFromVector as ewe,pointRotateRads as twe,polygon as owe,polygonFromPoints as nwe,PRECISION as rwe,segmentsIntersectAt as iwe,vector as awe,vectorAdd as swe,vectorFromPoint as lwe,vectorScale as cwe}from"@orangecatai/math";import{getElementAbsoluteCoords as mwe}from"@orangecatai/element";var $b=e=>{if(!e)return[];for(let t of e.sets)if(t.type==="path")return t.ops;return e.sets[0].ops};import{pointFrom as qO,pointDistance as u5,pointRotateRads as Y3e}from"@orangecatai/math";import{ROUGHNESS as JO,THEME as d0,isTransparent as $c,assertNever as QO,COLOR_PALETTE as ez,LINE_POLYGON_POINT_MERGE_DISTANCE as $3e,applyDarkModeFilter as tu}from"@orangecatai/common";import{RoughGenerator as tz}from"roughjs/bin/generator";import e3e from"roughjs/bin/rough";import{isRightAngleRads as o3e,lineSegment as n3e,pointFrom as r3e,pointRotateRads as i3e}from"@orangecatai/math";import{BOUND_TEXT_PADDING as s3e,DEFAULT_REDUCED_GLOBAL_ALPHA as l3e,ELEMENT_READY_TO_ERASE_OPACITY as c3e,FRAME_STYLE as d3e,DARK_THEME_FILTER as m3e,MIME_TYPES as m5,THEME as p3e,distance as u3e,getFontString as g3e,isRTL as h3e,getVerticalOffset as f3e,invariant as b3e,applyDarkModeFilter as x3e,isSafari as E3e}from"@orangecatai/common";import pCe from"roughjs/bin/rough";import{arrayToMap as gCe,invariant as r5,rescalePoints as hCe,sizeOf as fCe}from"@orangecatai/common";import{degreesToRadians as r0,lineSegment as xCe,pointDistance as ECe,pointFrom as Ut,pointFromArray as LO,pointRotateRads as qs}from"@orangecatai/math";import{pointsOnBezierCurves as vCe}from"points-on-curve";import{pointCenter as STe,pointFrom as MTe,pointRotateRads as PTe,pointsEqual as ATe,pointDistance as LTe,vectorFromPoint as _Te,curveLength as DTe,curvePointAtLength as RTe}from"@orangecatai/math";import{DRAGGING_THRESHOLD as FTe,KEYS as OTe,shouldRotateWithDiscreteAngle as zTe,getGridPoint as HTe,invariant as GTe,isShallowEqual as UTe,getFeatureFlag as WTe}from"@orangecatai/common";import{deconstructLinearOrFreeDrawElement as VTe,getSnapOutlineMidPoint as $Te,isPathALoop as KTe,moveArrowAboveBindable as XTe,projectFixedPointOntoDiagonal as ZTe}from"@orangecatai/element";import{KEYS as SIe,arrayToMap as MIe,getFeatureFlag as PIe,invariant as AIe,isTransparent as LIe}from"@orangecatai/common";import{PRECISION as DIe,clamp as RIe,lineSegment as NIe,pointDistance as BIe,pointDistanceSq as FIe,pointFrom as OIe,pointFromVector as zIe,pointRotateRads as HIe,pointsEqual as GIe,vectorFromPoint as UIe,vectorNormalize as WIe,vectorScale as YIe}from"@orangecatai/math";import{invariant as Qve,isTransparent as e2e}from"@orangecatai/common";import{curveIntersectLineSegment as o2e,isPointWithinBounds as n2e,lineSegment as r2e,lineSegmentIntersectionPoints as i2e,pointFrom as a2e,pointFromVector as s2e,pointRotateRads as l2e,pointsEqual as c2e,vectorFromPoint as d2e,vectorNormalize as m2e,vectorScale as p2e}from"@orangecatai/math";import{ellipse as g2e,ellipseSegmentInterceptPoints as h2e}from"@orangecatai/math/ellipse";import{DEFAULT_ADAPTIVE_RADIUS as pO,DEFAULT_PROPORTIONAL_RADIUS as Xb,invariant as vwe,LINE_CONFIRM_THRESHOLD as uO,ROUNDNESS as Zb}from"@orangecatai/common";import{bezierEquation as Twe,curve as Cwe,curveCatmullRomCubicApproxPoints as kwe,curveOffsetPoints as Swe,lineSegment as Mwe,lineSegmentIntersectionPoints as Pwe,pointDistance as gO,pointFrom as Awe,pointFromArray as Lwe,pointFromVector as _we,pointRotateRads as Dwe,pointTranslate as Rwe,rectangle as Nwe,vectorFromPoint as Bwe,vectorNormalize as Fwe,vectorScale as Owe}from"@orangecatai/math";import{ROUNDNESS as hwe,assertNever as fwe}from"@orangecatai/common";import{pointsEqual as xwe}from"@orangecatai/math";var jC=e=>!!e&&e.type==="embeddable",qC=e=>!!e&&e.type==="iframe",Kb=e=>!!e&&(e.type==="iframe"||e.type==="embeddable"),oa=e=>e!=null&&e.type==="text";var $p=e=>e!=null&&(e.type==="frame"||e.type==="magicframe");var na=e=>e!=null&&dO(e.type);var ra=e=>e!=null&&e.type==="arrow",Wc=e=>ra(e)&&e.elbowed;var dO=e=>e==="arrow"||e==="line";var Ks=e=>e!==null&&"containerId"in e&&e.containerId!==null&&oa(e);var Kp=(e,t=1)=>{if(e.length>=3){let[o,n]=[e[0],e[e.length-1]];return gO(o,n)<=uO/t}return!1},Yc=(e,t)=>{if(t.roundness?.type===Zb.PROPORTIONAL_RADIUS||t.roundness?.type===Zb.LEGACY)return e*Xb;if(t.roundness?.type===Zb.ADAPTIVE_RADIUS){let o=t.roundness?.value??pO,n=o/Xb;return e<=n?e*Xb:o}return 0};import{ARROW_LABEL_FONT_SIZE_TO_MIN_WIDTH_RATIO as vve,ARROW_LABEL_WIDTH_FRACTION as Ive,BOUND_TEXT_PADDING as Tve,DEFAULT_FONT_SIZE as Cve,TEXT_ALIGN as kve,VERTICAL_ALIGN as Sve,getFontString as Mve,isProdEnv as Pve,invariant as Ave}from"@orangecatai/common";import{pointFrom as _ve,pointRotateRads as Dve}from"@orangecatai/math";import{BOUND_TEXT_PADDING as Qwe,DEFAULT_FONT_SIZE as eve,DEFAULT_FONT_FAMILY as tve,getFontString as ove,isTestEnv as nve,normalizeEOL as rve}from"@orangecatai/common";var ive="ABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".toLocaleUpperCase();import{isDevEnv as pve,isTestEnv as uve}from"@orangecatai/common";import{curvePointDistance as Uve,distanceToLineSegment as Wve,pointRotateRads as Yve}from"@orangecatai/math";import{ellipse as $ve,ellipseDistanceFromPoint as Kve}from"@orangecatai/math/ellipse";import{invariant as P2e,isDevEnv as A2e,isTestEnv as L2e}from"@orangecatai/common";import{pointFrom as D2e,pointFromVector as R2e,pointRotateRads as N2e,pointScaleFromOrigin as B2e,pointsEqual as F2e,triangleIncludesPoint as O2e,vectorCross as z2e,vectorFromPoint as TO,vectorScale as H2e}from"@orangecatai/math";var o0=[1,0],e5=[0,1],n0=[-1,0],t5=[0,-1],jp=e=>{let[t,o]=e,n=Math.abs(t),r=Math.abs(o);return t>r?o0:t<=-r?n0:o>n?e5:t5},o5=(e,t)=>jp(TO(e,t)),qp=(e,t)=>Jp(o5(e,t)),t0=(e,t)=>e[0]===t[0]&&e[1]===t[1],Jp=e=>t0(e,o0)||t0(e,n0);import{clamp as $2e,pointDistance as K2e,pointFrom as X2e,pointScaleFromOrigin as Z2e,pointsEqual as j2e,pointTranslate as q2e,vector as J2e,vectorCross as Q2e,vectorFromPoint as eIe,vectorScale as tIe}from"@orangecatai/math";import{BinaryHeap as nIe,invariant as rIe,isAnyTrue as iIe,getSizeFromPoints as aIe,isDevEnv as sIe,arrayToMap as lIe}from"@orangecatai/common";var oTe=10/1.5;import{SHIFT_LOCKING_ANGLE as sTe,viewportCoordsToSceneCoords as lTe}from"@orangecatai/common";import{normalizeRadians as dTe,radiansBetweenAngles as mTe,radiansDifference as pTe}from"@orangecatai/math";import{pointsEqual as gTe}from"@orangecatai/math";var Xp=e=>{let t=Math.floor(e.width/2)+1,o=0,n=e.width,r=Math.floor(e.height/2)+1,i=t,a=e.height;return[t,o,n,r,i,a,0,r]};var _O=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}},DO=e=>{switch(e){case"bar":return 90;case"arrow":return 20;default:return 25}},i0=(e,t,o,n)=>{if(t.length<1)return null;let r=$b(t[0]);if(r.length<1)return null;let i=o==="start"?1:r.length-1,a=r[i].data;r5(a.length===6,"Op data length is not 6");let s=Ut(a[4],a[5]),l=Ut(a[2],a[3]),c=Ut(a[0],a[1]),m=r[i-1],p=Ut(0,0);if(m.op==="move"){let B=LO(m.data);r5(B!=null,"Op data is not a point"),p=B}else m.op==="bcurveTo"&&(p=Ut(m.data[4],m.data[5]));let d=(B,U)=>Math.pow(1-B,3)*s[U]+3*B*Math.pow(1-B,2)*l[U]+3*Math.pow(B,2)*(1-B)*c[U]+p[U]*Math.pow(B,3),[u,h]=o==="start"?p:s,[g,E]=[d(.3,0),d(.3,1)],w=Math.hypot(u-g,h-E),x=(u-g)/w,y=(h-E)/w,v=_O(n),I=0;{let[B,U]=o==="end"?e.points[e.points.length-1]:e.points[0],[D,F]=e.points.length>1?o==="end"?e.points[e.points.length-2]:e.points[1]:[0,0];I=Math.hypot(B-D,U-F)}let L=Math.min(v,I*(n==="diamond"||n==="diamond_outline"?.25:.5)),S=u-x*L,_=h-y*L;if(n==="dot"||n==="circle"||n==="circle_outline"){let B=Math.hypot(_-h,S-u)+e.strokeWidth-2;return[u,h,B]}let P=DO(n);if(n==="crowfoot_many"||n==="crowfoot_one_or_many"){let[B,U]=qs(Ut(u,h),Ut(S,_),r0(-P)),[D,F]=qs(Ut(u,h),Ut(S,_),r0(P));return[S,_,B,U,D,F]}let[T,M]=qs(Ut(S,_),Ut(u,h),-P*Math.PI/180),[N,O]=qs(Ut(S,_),Ut(u,h),r0(P));if(n==="diamond"||n==="diamond_outline"){let B,U;if(o==="start"){let[D,F]=e.points.length>1?e.points[1]:[0,0];[B,U]=qs(Ut(u+L*2,h),Ut(u,h),Math.atan2(F-h,D-u))}else{let[D,F]=e.points.length>1?e.points[e.points.length-2]:[0,0];[B,U]=qs(Ut(u-L*2,h),Ut(u,h),Math.atan2(h-F,u-D))}return[u,h,T,M,B,U,N,O]}return[u,h,T,M,N,O]};import{pointFrom as BCe,pointCenter as FCe,pointRotateRads as OCe,vectorFromPoint as zCe,vectorNormalize as HCe,vectorSubtract as GCe,vectorAdd as UCe,vectorScale as WCe,pointFromVector as YCe,clamp as VCe,isCloseTo as $Ce}from"@orangecatai/math";import{arrayToMap as _5e}from"@orangecatai/common";import{isPointWithinBounds as R5e,pointFrom as N5e}from"@orangecatai/math";import{vectorCross as qCe,vectorFromPoint as JCe}from"@orangecatai/math";import{arrayToMap as RO}from"@orangecatai/common";import{getElementBounds as NO}from"@orangecatai/element";import{isArrowElement as BO,isExcalidrawElement as FO,isFreeDrawElement as OO,isLinearElement as zO,isTextElement as HO}from"@orangecatai/element";import{rangeIncludesValue as Qp,pointFrom as yr,pointRotateRads as GO,rangeInclusive as eu}from"@orangecatai/math";var UO=e=>e.type==="diamond"?[yr(e.width/2,0),yr(e.width,e.height/2),yr(e.width/2,e.height),yr(0,e.height/2)]:[yr(0,0),yr(0+e.width,0),yr(0+e.width,e.height),yr(0,e.height)],WO=e=>zO(e)||OO(e)?e.points:UO(e),a5=e=>{let t=e.reduce((o,[n,r])=>(o.minY=Math.min(o.minY,r),o.minX=Math.min(o.minX,n),o.maxX=Math.max(o.maxX,n),o.maxY=Math.max(o.maxY,r),o),{minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0,cx:0,cy:0});return t.cx=(t.maxX+t.minX)/2,t.cy=(t.maxY+t.minY)/2,t},s5=e=>{let t=WO(e),{cx:o,cy:n}=a5(t),r=yr(o,n),i=t.map(m=>GO(m,r,e.angle)),{minX:a,minY:s,maxX:l,maxY:c}=a5(i);return[a+e.x,s+e.y,l+e.x,c+e.y]},a0=(e,t,o=!1)=>{let n=s5(e),r=t[0]<=n[0]&&t[2]>=n[2]&&t[1]<=n[1]&&t[3]>=n[3];return o?r?!0:n[0]<=t[0]&&n[2]>=t[2]&&n[1]<=t[1]&&n[3]>=t[3]:r},l5=(e,t)=>{let o=s5(e);return(Qp(o[0],eu(t[0],t[2]))||Qp(t[0],eu(o[0],o[2])))&&(Qp(o[1],eu(t[1],t[3]))||Qp(t[1],eu(o[1],o[3])))},c5=({elements:e,bounds:t,type:o,errorMargin:n=0})=>{FO(t)&&(t=NO(t,RO(e)));let r=[t[0]-n,t[1]-n,t[2]+n,t[3]+n],i=new Set;for(let a of e){if(i.has(a.id))continue;if(o==="overlap"?l5(a,r):o==="inside"?a0(a,r):a0(a,r,!0)){if(i.add(a.id),a.boundElements)for(let l of a.boundElements)i.add(l.id);HO(a)&&a.containerId&&i.add(a.containerId),BO(a)&&(a.startBinding&&i.add(a.startBinding.elementId),a.endBinding&&i.add(a.endBinding?.elementId))}}return e.filter(a=>i.has(a.id))};import{arrayToMap as g5e,isShallowEqual as VO}from"@orangecatai/common";var YO=function(){let e=null,t=null,o=null,n=(i,a,s,l)=>{if(o!==void 0&&a===t&&i===e&&s.editingGroupId===o?.editingGroupId)return o;let c={};for(let d of i){let u=d.groupIds;if(s.editingGroupId){let h=u.indexOf(s.editingGroupId);h>-1&&(u=u.slice(0,h))}if(u.length>0){let h=u[u.length-1];c[h]=!0}}let m={},p=a.reduce((d,u)=>{if(u.isDeleted)return d;let h=u.groupIds.find(g=>c[g]);return h&&(d[u.id]=!0,Array.isArray(m[h])?m[h].push(u.id):m[h]=[u.id]),d},{});for(let d of Object.keys(m))m[d].length<2&&c[d]&&(c[d]=!1);return t=a,e=i,o={editingGroupId:s.editingGroupId,selectedGroupIds:c,selectedElementIds:s0({...s.selectedElementIds,...p},l)},o},r=(i,a,s,l)=>{let c=l?l.scene.getSelectedElements({selectedElementIds:i.selectedElementIds,elements:a}):l0(a,i);return c.length?n(c,a,i,s):{selectedGroupIds:{},editingGroupId:null,selectedElementIds:s0(i.selectedElementIds,s)}};return r.clearCache=()=>{t=null,e=null,o=null},r}();var w5e=function(){let e=null,t=null,o=null,n=(r,i)=>(o!=null&&r===e&&i.selectedElementIds===t||(o=r.some(a=>i.selectedElementIds[a.id]),e=r,t=i.selectedElementIds),o);return n.clearCache=()=>{e=null,t=null,o=null},n}(),l0=(e,t,o)=>{let n=new Set,r=[];for(let i of e.values()){if(t.selectedElementIds[i.id]){r.push(i),n.add(i.id);continue}if(o?.includeBoundTextElement&&Ks(i)&&t.selectedElementIds[i?.containerId]){r.push(i),n.add(i.id);continue}}if(o?.includeElementsInFrames){let i=[];return r.forEach(a=>{$p(a)&&d5(e,a.id).forEach(s=>!n.has(s.id)&&i.push(s)),i.push(a)}),i}return r};var s0=(e,t)=>VO(t.selectedElementIds,e)?t.selectedElementIds:e;var d5=(e,t)=>{let o=[];for(let n of e.values())n.frameId===t&&o.push(n);return o};var KO=typeof document<"u"?document.createElement("img"):{src:""};KO.src=`data:${m5.svg},${encodeURIComponent('<svg aria-hidden="true" focusable="false" data-prefix="fas" data-icon="image" class="svg-inline--fa fa-image fa-w-16" role="img" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 512 512"><path fill="#888" d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48zM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56zM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48z"></path></svg>')}`;var XO=typeof document<"u"?document.createElement("img"):{src:""};XO.src=`data:${m5.svg},${encodeURIComponent('<svg viewBox="0 0 668 668" xmlns="http://www.w3.org/2000/svg" xml:space="preserve" style="fill-rule:evenodd;clip-rule:evenodd;stroke-linejoin:round;stroke-miterlimit:2"><path d="M464 448H48c-26.51 0-48-21.49-48-48V112c0-26.51 21.49-48 48-48h416c26.51 0 48 21.49 48 48v288c0 26.51-21.49 48-48 48ZM112 120c-30.928 0-56 25.072-56 56s25.072 56 56 56 56-25.072 56-56-25.072-56-56-56ZM64 384h384V272l-87.515-87.515c-4.686-4.686-12.284-4.686-16.971 0L208 320l-55.515-55.515c-4.686-4.686-12.284-4.686-16.971 0L64 336v48Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.81709 0 0 .81709 124.825 145.825)"/><path d="M256 8C119.034 8 8 119.033 8 256c0 136.967 111.034 248 248 248s248-111.034 248-248S392.967 8 256 8Zm130.108 117.892c65.448 65.448 70 165.481 20.677 235.637L150.47 105.216c70.204-49.356 170.226-44.735 235.638 20.676ZM125.892 386.108c-65.448-65.448-70-165.481-20.677-235.637L361.53 406.784c-70.203 49.356-170.226 44.736-235.638-20.676Z" style="fill:#888;fill-rule:nonzero" transform="matrix(.30366 0 0 .30366 506.822 60.065)"/></svg>')}`;var c0=new WeakMap;var p5=e=>e==="rectangle"||e==="iframe"||e==="embeddable"||e==="line"||e==="diamond"||e==="image";var ho=class ho{};A(ho,"rg",new tz),A(ho,"cache",new WeakMap),A(ho,"get",(t,o)=>{let n=ho.cache.get(t);if(n&&(o===null||n.theme===o))return n.shape}),A(ho,"delete",t=>{ho.cache.delete(t),c0.delete(t)}),A(ho,"destroy",()=>{ho.cache=new WeakMap}),A(ho,"generateElementShape",(t,o)=>{let n=o?.isExporting?void 0:ho.get(t,o?o.theme:null);if(n!==void 0)return n;c0.delete(t);let r=rz(t,ho.rg,o||{isExporting:!1,canvasBackgroundColor:ez.white,embedsValidationStatus:null,theme:d0.LIGHT});return o?.isExporting||ho.cache.set(t,{shape:r,theme:o?.theme||d0.LIGHT}),r});var js=ho,oz=e=>[8,8+e],b5=e=>[1.5,6+e];function nz(e){let t=e.roughness,o=Math.max(e.width,e.height),n=Math.min(e.width,e.height);return n>=20&&o>=50||n>=15&&e.roundness&&p5(e.type)||na(e)&&o>=50?t:Math.min(t/(o<10?3:2),2.5)}var Er=(e,t=!1,o=!1)=>{let n={seed:e.seed,strokeLineDash:e.strokeStyle==="dashed"?oz(e.strokeWidth):e.strokeStyle==="dotted"?b5(e.strokeWidth):void 0,disableMultiStroke:e.strokeStyle!=="solid",strokeWidth:e.strokeStyle!=="solid"?e.strokeWidth+.5:e.strokeWidth,fillWeight:e.strokeWidth/2,hachureGap:e.strokeWidth*4,roughness:nz(e),stroke:o?tu(e.strokeColor):e.strokeColor,preserveVertices:t||e.roughness<JO.cartoonist};switch(e.type){case"rectangle":case"iframe":case"embeddable":case"diamond":case"ellipse":return n.fillStyle=e.fillStyle,n.fill=$c(e.backgroundColor)?void 0:o?tu(e.backgroundColor):e.backgroundColor,e.type==="ellipse"&&(n.curveFitting=1),n;case"line":case"freedraw":return Kp(e.points)&&(n.fillStyle=e.fillStyle,n.fill=e.backgroundColor==="transparent"?void 0:o?tu(e.backgroundColor):e.backgroundColor),n;case"arrow":return n;default:throw new Error(`Unimplemented type ${e.type}`)}},g5=(e,t,o)=>Kb(e)&&(t||jC(e)&&o?.get(e.id)!==!0)&&$c(e.backgroundColor)&&$c(e.strokeColor)?{...e,roughness:0,backgroundColor:"#d3d3d3",fillStyle:"solid"}:qC(e)?{...e,strokeColor:$c(e.strokeColor)?"#000000":e.strokeColor,backgroundColor:$c(e.backgroundColor)?"#f4f4f6":e.backgroundColor}:e,h5=(e,t,o,n,r,i,a,s)=>{let l=i0(e,t,o,n);if(l===null)return[];let c=(p,d)=>{if(p===null)return[];let[,,u,h,g,E]=p;return[r.line(u,h,g,E,d)]},m=s?tu(e.strokeColor):e.strokeColor;switch(n){case"dot":case"circle":case"circle_outline":{let[p,d,u]=l;return delete i.strokeLineDash,[r.circle(p,d,u,{...i,fill:n==="circle_outline"?a:m,fillStyle:"solid",stroke:m,roughness:Math.min(.5,i.roughness||0)})]}case"triangle":case"triangle_outline":{let[p,d,u,h,g,E]=l;return delete i.strokeLineDash,[r.polygon([[p,d],[u,h],[g,E],[p,d]],{...i,fill:n==="triangle_outline"?a:m,fillStyle:"solid",roughness:Math.min(1,i.roughness||0)})]}case"diamond":case"diamond_outline":{let[p,d,u,h,g,E,w,x]=l;return delete i.strokeLineDash,[r.polygon([[p,d],[u,h],[g,E],[w,x],[p,d]],{...i,fill:n==="diamond_outline"?a:m,fillStyle:"solid",roughness:Math.min(1,i.roughness||0)})]}case"crowfoot_one":return c(l,i);case"bar":case"arrow":case"crowfoot_many":case"crowfoot_one_or_many":default:{let[p,d,u,h,g,E]=l;if(e.strokeStyle==="dotted"){let w=b5(e.strokeWidth-1);i.strokeLineDash=[w[0],w[1]-1]}else delete i.strokeLineDash;return i.roughness=Math.min(1,i.roughness||0),[r.line(u,h,p,d,i),r.line(g,E,p,d,i),...n==="crowfoot_one_or_many"?c(i0(e,t,o,"crowfoot_one"),i):[]]}}};var rz=(e,t,{isExporting:o,canvasBackgroundColor:n,embedsValidationStatus:r,theme:i})=>{let a=i===d0.DARK;switch(e.type){case"rectangle":case"iframe":case"embeddable":{let s;if(e.roundness){let l=e.width,c=e.height,m=Yc(Math.min(l,c),e);s=t.path(`M ${m} 0 L ${l-m} 0 Q ${l} 0, ${l} ${m} L ${l} ${c-m} Q ${l} ${c}, ${l-m} ${c} L ${m} ${c} Q 0 ${c}, 0 ${c-m} L 0 ${m} Q 0 0, ${m} 0`,Er(g5(e,o,r),!0,a))}else s=t.rectangle(0,0,e.width,e.height,Er(g5(e,o,r),!1,a));return s}case"diamond":{let s,[l,c,m,p,d,u,h,g]=Xp(e);if(e.roundness){let E=Yc(Math.abs(l-h),e),w=Yc(Math.abs(p-c),e);s=t.path(`M ${l+E} ${c+w} L ${m-E} ${p-w}
8
8
  C ${m} ${p}, ${m} ${p}, ${m-E} ${p+w}
9
9
  L ${d+E} ${u-w}
10
10
  C ${d} ${u}, ${d} ${u}, ${d-E} ${u-w}
11
11
  L ${h+E} ${g+w}
12
12
  C ${h} ${g}, ${h} ${g}, ${h+E} ${g-w}
13
13
  L ${l-E} ${c+w}
14
- C ${l} ${c}, ${l} ${c}, ${l+E} ${c+w}`,Er(e,!0,a))}else s=t.polygon([[l,c],[m,p],[d,u],[h,g]],Er(e,!1,a));return s}case"ellipse":return t.ellipse(e.width/2,e.height/2,e.width,e.height,Er(e,!1,a));case"line":case"arrow":{let s,l=Er(e,!1,a),c=e.points.length?e.points:[qO(0,0)];if(Wc(e)?c.every(m=>Math.abs(m[0])<=1e6&&Math.abs(m[1])<=1e6)?s=[t.path(iz(c,16),Er(e,!0,a))]:(console.error("Elbow arrow with extreme point positions detected. Arrow not rendered.",e.id,JSON.stringify(c)),s=[]):e.roundness?s=[t.curve(c,l)]:l.fill?s=[t.polygon(c,l)]:s=[t.linearPath(c,l)],e.type==="arrow"){let{startArrowhead:m=null,endArrowhead:p="arrow"}=e;if(m!==null){let d=h5(e,s,"start",m,t,l,n,a);s.push(...d)}if(p!==null){let d=h5(e,s,"end",p,t,l,n,a);s.push(...d)}}return s}case"freedraw":{let s=[];if(Kp(e.points)){let l=ZO(e.points,.75);s.push(t.curve(l,{...Er(e,!1,a),stroke:"none"}))}return s.push(az(e)),s}case"frame":case"magicframe":case"text":case"image":return null;default:return QO(e,`generateElementShape(): Unimplemented type ${e?.type}`),null}},iz=(e,t)=>{let o=[];for(let r=1;r<e.length-1;r+=1){let i=e[r-1],a=e[r+1],s=e[r],l=qp(s,i),c=qp(a,s),m=Math.min(t,u5(e[r],a)/2,u5(e[r],i)/2);l?i[0]<s[0]?o.push([e[r][0]-m,e[r][1]]):o.push([e[r][0]+m,e[r][1]]):i[1]<s[1]?o.push([e[r][0],e[r][1]-m]):o.push([e[r][0],e[r][1]+m]),o.push(e[r]),c?a[0]<s[0]?o.push([e[r][0]-m,e[r][1]]):o.push([e[r][0]+m,e[r][1]]):a[1]<s[1]?o.push([e[r][0],e[r][1]-m]):o.push([e[r][0],e[r][1]+m])}let n=[`M ${e[0][0]} ${e[0][1]}`];for(let r=0;r<o.length;r+=3)n.push(`L ${o[r][0]} ${o[r][1]}`),n.push(`Q ${o[r+1][0]} ${o[r+1][1]}, ${o[r+2][0]} ${o[r+2][1]}`);return n.push(`L ${e[e.length-1][0]} ${e[e.length-1][1]}`),n.join(" ")};var az=e=>cz(sz(e)),sz=e=>{let t=e.simulatePressure?e.points:e.points.length?e.points.map(([o,n],r)=>[o,n,e.pressures[r]]):[[0,0,.5]];return jO(t,{simulatePressure:e.simulatePressure,size:e.strokeWidth*4.25,thinning:.6,smoothing:.5,streamline:.5,easing:o=>Math.sin(o*Math.PI/2),last:!0})},f5=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],lz=/(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g,cz=e=>{if(!e.length)return"";let t=e.length-1;return e.reduce((o,n,r,i)=>(r===t?o.push(n,f5(n,i[0]),"L",i[0],"Z"):o.push(n,f5(n,i[r+1])),o),["M",e[0],"Q"]).join(" ").replace(lz,"$1")};var x5=(e,t,o=!1)=>{let n=!1;for(let r in t){let i=t[r];if(typeof i<"u"){if(e[r]===i&&(typeof i!="object"||i===null))continue;n=!0}}return!n&&!o?e:{...e,...t,version:t.version??e.version+1,versionNonce:t.versionNonce??dz(),updated:mz()}};import{jsx as y5}from"react/jsx-runtime";var Qs=W({name:"toggleLinearEditor",category:rt.elements,label:(e,t,o)=>o.scene.getSelectedElements({selectedElementIds:t.selectedElementIds})[0]?.type==="arrow"?"labels.lineEditor.editArrow":"labels.lineEditor.edit",keywords:["line"],trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return!!(!t.selectedLinearElement?.isEditing&&r.length===1&&uz(r[0])&&!pz(r[0]))},perform(e,t,o,n){let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0})[0];m0(r,"No selected element found"),m0(t.selectedLinearElement,"No selected linear element found"),m0(r.id===t.selectedLinearElement.elementId,"Selected element ID and linear editor elementId does not match");let i={...t.selectedLinearElement,isEditing:!t.selectedLinearElement.isEditing};return{appState:{...t,selectedLinearElement:i},captureUpdate:E5.IMMEDIATELY}},PanelComponent:({appState:e,updateData:t,app:o})=>{let n=o.scene.getSelectedElements({selectedElementIds:e.selectedElementIds})[0];if(!n)return null;let r=f(n.type==="arrow"?"labels.lineEditor.editArrow":"labels.lineEditor.edit");return y5(ne,{type:"button",icon:Vw,title:r,"aria-label":r,onClick:()=>t(null)})}}),wke=W({name:"togglePolygon",category:rt.elements,icon:nh,keywords:["loop"],label:(e,t,o)=>!o.scene.getSelectedElements({selectedElementIds:t.selectedElementIds}).some(i=>!Js(i)||!i.polygon)?"labels.polygon.breakPolygon":"labels.polygon.convertToPolygon",trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds});return r.length>0&&r.every(i=>Js(i)&&i.points.length>=4)},perform(e,t,o,n){let r=n.scene.getSelectedElements(t);if(r.some(l=>!Js(l)))return!1;let i=r,a=i.some(l=>!l.polygon),s=gz(i);return{elements:e.map(l=>!s.has(l.id)||!Js(l)?l:x5(l,{backgroundColor:a?l.backgroundColor:"transparent",...hz(l,a)})),appState:t,captureUpdate:E5.IMMEDIATELY}},PanelComponent:({appState:e,updateData:t,app:o})=>{let n=o.scene.getSelectedElements({selectedElementIds:e.selectedElementIds});if(n.length===0||n.some(a=>!Js(a)||!a.polygon||a.points.length<3))return null;let r=n.every(a=>Js(a)&&a.polygon),i=f(r?"labels.polygon.breakPolygon":"labels.polygon.convertToPolygon");return y5(ls,{icon:nh,title:i,"aria-label":i,active:r,onClick:()=>t(null),style:{marginLeft:"auto"}})}});import{KEYS as w5,CANVAS_SEARCH_TAB as v5,CLASSES as fz,DEFAULT_SIDEBAR as I5}from"@orangecatai/common";import{CaptureUpdateAction as bz}from"@orangecatai/element";var Uc=W({name:"searchMenu",icon:ko,keywords:["search","find"],label:"search.title",viewMode:!0,trackEvent:{category:"search_menu",action:"toggle",predicate:e=>e.gridModeEnabled},perform(e,t,o,n){if(t.openDialog)return!1;if(t.openSidebar?.name===I5.name&&t.openSidebar.tab===v5){let r=n.excalidrawContainerValue.container?.querySelector(`.${fz.SEARCH_MENU_INPUT_WRAPPER} input`);return r?.focus(),r?.select(),!1}return{appState:{...t,openSidebar:{name:I5.name,tab:v5},openDialog:null},captureUpdate:bz.EVENTUALLY}},checked:e=>e.gridModeEnabled,predicate:(e,t,o)=>o.gridModeEnabled===void 0,keyTest:e=>e[w5.CTRL_OR_CMD]&&e.key===w5.F});import{isImageElement as xz}from"@orangecatai/element";import{CaptureUpdateAction as Ez}from"@orangecatai/element";import{jsx as yz}from"react/jsx-runtime";var Kc=W({name:"cropEditor",label:"helpDialog.cropStart",icon:Ch,viewMode:!0,trackEvent:{category:"menu"},keywords:["image","crop"],perform(e,t,o,n){let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0})[0];return{appState:{...t,isCropping:!1,croppingElementId:r.id},captureUpdate:Ez.IMMEDIATELY}},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return!!(!t.croppingElementId&&r.length===1&&xz(r[0]))},PanelComponent:({appState:e,updateData:t,app:o})=>{let n=f("helpDialog.cropStart");return yz(ne,{type:"button",icon:Ch,title:n,"aria-label":n,onClick:()=>t(null)})}});import{getNonDeletedElements as wz}from"@orangecatai/element";import{mutateElement as vz}from"@orangecatai/element";import{newFrameElement as Iz}from"@orangecatai/element";import{isFrameLikeElement as ou}from"@orangecatai/element";import{addElementsToFrame as Tz,removeAllElementsFromFrame as Cz}from"@orangecatai/element";import{getFrameChildren as kz}from"@orangecatai/element";import{KEYS as T5,updateActiveTool as C5}from"@orangecatai/common";import{getElementsInGroup as Sz}from"@orangecatai/element";import{getCommonBounds as Mz}from"@orangecatai/element";import{CaptureUpdateAction as ia}from"@orangecatai/element";var k5=(e,t)=>{let o=t.scene.getSelectedElements(e);return o.length===1&&ou(o[0])},S5=W({name:"selectAllElementsInFrame",label:"labels.selectAllElementsInFrame",trackEvent:{category:"canvas"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t).at(0)||null;if(ou(r)){let i=kz(wz(e),r.id).filter(a=>!(a.type==="text"&&a.containerId));return{elements:e,appState:{...t,selectedElementIds:i.reduce((a,s)=>(a[s.id]=!0,a),{})},captureUpdate:ia.IMMEDIATELY}}return{elements:e,appState:t,captureUpdate:ia.EVENTUALLY}},predicate:(e,t,o,n)=>k5(t,n)}),M5=W({name:"removeAllElementsFromFrame",label:"labels.removeAllElementsFromFrame",trackEvent:{category:"history"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t).at(0)||null;return ou(r)?{elements:Cz(e,r),appState:{...t,selectedElementIds:{[r.id]:!0}},captureUpdate:ia.IMMEDIATELY}:{elements:e,appState:t,captureUpdate:ia.EVENTUALLY}},predicate:(e,t,o,n)=>k5(t,n)}),ASe=W({name:"updateFrameRendering",label:"labels.updateFrameRendering",viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t)=>({elements:e,appState:{...t,frameRendering:{...t.frameRendering,enabled:!t.frameRendering.enabled}},captureUpdate:ia.EVENTUALLY}),checked:e=>e.frameRendering.enabled}),LSe=W({name:"setFrameAsActiveTool",label:"toolBar.frame",trackEvent:{category:"toolbar"},icon:Dn,viewMode:!1,perform:(e,t,o,n)=>{let r=C5(t,{type:"frame"});return Mo(n.interactiveCanvas,{...t,activeTool:r}),{elements:e,appState:{...t,activeTool:C5(t,{type:"frame"})},captureUpdate:ia.EVENTUALLY}},keyTest:e=>!e[T5.CTRL_OR_CMD]&&!e.shiftKey&&!e.altKey&&e.key.toLocaleLowerCase()===T5.F}),P5=W({name:"wrapSelectionInFrame",label:"labels.wrapSelectionInFrame",trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=le(e,t);return r.length>0&&!r.some(i=>ou(i))},perform:(e,t,o,n)=>{let r=le(e,t),i=n.scene.getNonDeletedElementsMap(),[a,s,l,c]=Mz(r,i),m=16,p=Iz({x:a-m,y:s-m,width:l-a+m*2,height:c-s+m*2});if(t.editingGroupId){let u=Sz(r,t.editingGroupId);for(let h of u){let g=h.groupIds.indexOf(t.editingGroupId);vz(h,i,{groupIds:h.groupIds.slice(0,g)})}}return{elements:Tz([...n.scene.getElementsIncludingDeleted(),p],r,p,t),appState:{selectedElementIds:{[p.id]:!0}},captureUpdate:ia.IMMEDIATELY}}});import{isWindows as Nz,KEYS as Zc,matchKey as g0,arrayToMap as A5,MOBILE_ACTION_BUTTON_BG as L5}from"@orangecatai/common";import{CaptureUpdateAction as u0}from"@orangecatai/element";import{orderByFractionalIndex as Bz}from"@orangecatai/element";import{Emitter as Pz}from"@orangecatai/common";import{CaptureUpdateAction as Az,StoreChange as Lz,StoreDelta as _z}from"@orangecatai/element";var el=class extends _z{applyTo(t,o,n){let[r,i]=this.elements.applyTo(t,n.elements,{excludedProperties:new Set(["version","versionNonce"])}),[a,s]=this.appState.applyTo(o,r);return[r,a,i||s]}static calculate(t,o){return super.calculate(t,o)}static inverse(t){return super.inverse(t)}static applyLatestChanges(t,o,n,r){return super.applyLatestChanges(t,o,n,r)}},aa=class{constructor(t=!0,o=!0){this.isUndoStackEmpty=t;this.isRedoStackEmpty=o}},Xc=class e{constructor(t){this.store=t;A(this,"onHistoryChangedEmitter",new Pz);A(this,"undoStack",[]);A(this,"redoStack",[])}get isUndoStackEmpty(){return this.undoStack.length===0}get isRedoStackEmpty(){return this.redoStack.length===0}clear(){this.undoStack.length=0,this.redoStack.length=0}record(t){if(t.isEmpty()||t instanceof el)return;let o=el.inverse(t);this.undoStack.push(o),o.elements.isEmpty()||(this.redoStack.length=0),this.onHistoryChangedEmitter.trigger(new aa(this.isUndoStackEmpty,this.isRedoStackEmpty))}undo(t,o){return this.perform(t,o,()=>e.pop(this.undoStack),n=>e.push(this.redoStack,n))}redo(t,o){return this.perform(t,o,()=>e.pop(this.redoStack),n=>e.push(this.undoStack,n))}perform(t,o,n,r){try{let i=n();if(i===null)return;let a=Az.IMMEDIATELY,s=this.store.snapshot,l=t,c=o,m=!1;for(;i;){try{[l,c,m]=i.applyTo(l,c,s);let p=s.elements,d=s.maybeClone(a,l,c),u=Lz.create(s,d),h=el.applyLatestChanges(i,p,l);h.isEmpty()||(this.store.scheduleMicroAction({action:a,change:u,delta:h}),i=h),s=d}finally{r(i)}if(m)break;i=n()}return[l,c]}finally{this.onHistoryChangedEmitter.trigger(new aa(this.isUndoStackEmpty,this.isRedoStackEmpty))}}static pop(t){if(!t.length)return null;let o=t.pop();return o!==void 0?o:null}static push(t,o){let n=el.inverse(o);return t.push(n)}};import{useEffect as Dz,useState as Rz}from"react";var p0=(e,t)=>{let[o,n]=Rz(t);return Dz(()=>{let r=e.on(i=>{n(i)});return()=>{r()}},[e]),o};import{jsx as N5}from"react/jsx-runtime";var _5=(e,t,o)=>{if(!t.multiElement&&!t.resizingElement&&!t.editingTextElement&&!t.newElement&&!t.selectedElementsAreBeingDragged&&!t.selectionElement&&!e.flowChartCreator.isCreatingChart){let n=o();if(!n)return{captureUpdate:u0.EVENTUALLY};let[r,i]=n,a=Bz(Array.from(r.values()));return{appState:i,elements:a,captureUpdate:u0.NEVER}}return{captureUpdate:u0.EVENTUALLY}},D5=e=>({name:"undo",label:"buttons.undo",icon:sh,trackEvent:{category:"history"},viewMode:!1,perform:(t,o,n,r)=>_5(r,o,()=>e.undo(A5(t),o)),keyTest:t=>t[Zc.CTRL_OR_CMD]&&g0(t,Zc.Z)&&!t.shiftKey,PanelComponent:({appState:t,updateData:o,data:n,app:r})=>{let{isUndoStackEmpty:i}=p0(e.onHistoryChangedEmitter,new aa(e.isUndoStackEmpty,e.isRedoStackEmpty)),a=_t()==="mobile";return N5(ne,{type:"button",icon:sh,"aria-label":f("buttons.undo"),onClick:o,size:n?.size||"medium",disabled:i,"data-testid":"button-undo",style:{...a?L5:{}}})}}),R5=e=>({name:"redo",label:"buttons.redo",icon:lh,trackEvent:{category:"history"},viewMode:!1,perform:(t,o,n,r)=>_5(r,o,()=>e.redo(A5(t),o)),keyTest:t=>t[Zc.CTRL_OR_CMD]&&t.shiftKey&&g0(t,Zc.Z)||Nz&&t.ctrlKey&&!t.shiftKey&&g0(t,Zc.Y),PanelComponent:({appState:t,updateData:o,data:n,app:r})=>{let{isRedoStackEmpty:i}=p0(e.onHistoryChangedEmitter,new aa(e.isUndoStackEmpty,e.isRedoStackEmpty)),a=_t()==="mobile";return N5(ne,{type:"button",icon:lh,"aria-label":f("buttons.redo"),onClick:o,size:n?.size||"medium",disabled:i,"data-testid":"button-redo",style:{...a?L5:{}}})}});import{getFontString as Fz}from"@orangecatai/common";import{newElementWith as Oz}from"@orangecatai/element";import{measureText as zz}from"@orangecatai/element";import{isTextElement as B5}from"@orangecatai/element";import{CaptureUpdateAction as Hz}from"@orangecatai/element";var F5=W({name:"autoResize",label:"labels.autoResize",icon:null,trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=le(e,t);return r.length===1&&B5(r[0])&&!r[0].autoResize},perform:(e,t,o,n)=>{let r=le(e,t);return{appState:t,elements:e.map(i=>{if(i.id===r[0].id&&B5(i)){let a=zz(i.originalText,Fz(i),i.lineHeight);return Oz(i,{autoResize:!0,width:a.width,height:a.height,text:i.originalText})}return i}),captureUpdate:Hz.IMMEDIATELY}}});import{isPromiseLike as Gz}from"@orangecatai/common";import{jsx as Uz}from"react/jsx-runtime";var h0=(e,t,o,n,r,i)=>{if(e.trackEvent)try{typeof e.trackEvent=="object"&&(!e.trackEvent.predicate||e.trackEvent.predicate(o,n,i))&&ge(e.trackEvent.category,e.trackEvent.action||e.name,`${t} (${r.editorInterface.formFactor==="phone"?"mobile":"desktop"})`)}catch(a){console.error("error while logging action:",a)}},nu=class{constructor(t,o,n,r){A(this,"actions",{});A(this,"updater");A(this,"getAppState");A(this,"getElementsIncludingDeleted");A(this,"app");A(this,"renderAction",(t,o)=>{let n=this.app.props.UIOptions.canvasActions;if(this.actions[t]&&"PanelComponent"in this.actions[t]&&(!(t in n)||n[t])){let r=this.actions[t],i=r.PanelComponent;i.displayName="PanelComponent";let a=this.getElementsIncludingDeleted(),s=this.getAppState(),l=c=>{h0(r,"ui",s,a,this.app,c),this.updater(r.perform(this.getElementsIncludingDeleted(),this.getAppState(),c,this.app))};return Uz(i,{elements:this.getElementsIncludingDeleted(),appState:this.getAppState(),updateData:l,appProps:this.app.props,app:this.app,data:o,renderAction:this.renderAction})}return null});A(this,"isActionEnabled",t=>{let o=this.getElementsIncludingDeleted(),n=this.getAppState();return!t.predicate||t.predicate(o,n,this.app.props,this.app)});this.updater=i=>{if(Gz(i))i.then(a=>t(a));else return t(i)},this.getAppState=o,this.getElementsIncludingDeleted=n,this.app=r}registerAction(t){this.actions[t.name]=t}registerAll(t){t.forEach(o=>this.registerAction(o))}handleKeyDown(t){let o=this.app.props.UIOptions.canvasActions,n=Object.values(this.actions).sort((l,c)=>(c.keyPriority||0)-(l.keyPriority||0)).filter(l=>(l.name in o?o[l.name]:!0)&&l.keyTest&&l.keyTest(t,this.getAppState(),this.getElementsIncludingDeleted(),this.app));if(n.length!==1)return n.length>1&&console.warn("Canceling as multiple actions match this shortcut",n),!1;let r=n[0];if(this.getAppState().viewModeEnabled&&r.viewMode!==!0)return!1;let i=this.getElementsIncludingDeleted(),a=this.getAppState(),s=null;return h0(r,"keyboard",a,i,this.app,null),t.preventDefault(),t.stopPropagation(),this.updater(n[0].perform(i,a,s,this.app)),!0}executeAction(t,o="api",n=null){let r=this.getElementsIncludingDeleted(),i=this.getAppState();h0(t,o,i,r,this.app,n),this.updater(t.perform(r,i,n,this.app))}};var ru=class{constructor(){A(this,"targets",new WeakMap);A(this,"rafIds",new WeakMap)}register(t,o){this.targets.set(t,{callback:o,stopped:!0})}start(t){let o=this.targets.get(t);o&&(this.rafIds.has(t)||(this.targets.set(t,{...o,stopped:!1}),this.scheduleFrame(t)))}stop(t){let o=this.targets.get(t);o&&!o.stopped&&this.targets.set(t,{...o,stopped:!0}),this.cancelFrame(t)}constructFrame(t){return o=>{let n=this.targets.get(t);if(!n)return;let r=this.onFrame(n,o);!n.stopped&&!r?this.scheduleFrame(t):this.cancelFrame(t)}}scheduleFrame(t){let o=requestAnimationFrame(this.constructFrame(t));this.rafIds.set(t,o)}cancelFrame(t){if(this.rafIds.has(t)){let o=this.rafIds.get(t);cancelAnimationFrame(o)}this.rafIds.delete(t)}onFrame(t,o){return t.callback(o)??!1}};var f0=e=>{let t=Array.from(e.values());return{x:O5(t,o=>o.x)/t.length,y:O5(t,o=>o.y)/t.length}},b0=([e,t])=>Math.hypot(e.x-t.x,e.y-t.y),O5=(e,t)=>e.reduce((o,n)=>o+t(n),0);import{pointFrom as q,pointRotateRads as ii,rangeInclusive as Vo,rangeIntersection as iu,rangesOverlap as au}from"@orangecatai/math";import{TOOL_TYPE as sa,KEYS as z5}from"@orangecatai/common";import{getCommonBounds as x0,getDraggedElementsBounds as E0,getElementAbsoluteCoords as Wz}from"@orangecatai/element";import{isBoundToContainer as W5}from"@orangecatai/element";import{getMaximumGroups as Y5}from"@orangecatai/element";import{getSelectedElements as Yz,getVisibleAndNonSelectedElements as V5}from"@orangecatai/element";var Vz=8,H5=99999,su=e=>Vz/e,io=class io{};A(io,"referenceSnapPoints",null),A(io,"visibleGaps",null),A(io,"setReferenceSnapPoints",t=>{io.referenceSnapPoints=t}),A(io,"getReferenceSnapPoints",()=>io.referenceSnapPoints),A(io,"setVisibleGaps",t=>{io.visibleGaps=t}),A(io,"getVisibleGaps",()=>io.visibleGaps),A(io,"destroy",()=>{io.referenceSnapPoints=null,io.visibleGaps=null});var $o=io,ai=e=>e.props.gridModeEnabled??e.state.gridModeEnabled,wr=({event:e,app:t,selectedElements:o})=>{if(e){let n=t.state.activeTool.type==="lasso"&&t.state.selectedElementsAreBeingDragged;return(t.state.activeTool.type!=="lasso"||n)&&(t.state.objectsSnapModeEnabled&&!e[z5.CTRL_OR_CMD]||!t.state.objectsSnapModeEnabled&&e[z5.CTRL_OR_CMD]&&!ai(t))}return o.length===1&&o[0].type==="arrow"?!1:t.state.objectsSnapModeEnabled},$z=(e,t,o=.01)=>Math.abs(e-t)<=o,jc=(e,t,{omitCenter:o,boundingBoxCorners:n,dragOffset:r}={omitCenter:!1,boundingBoxCorners:!1})=>{let i=[];if(e.length===1){let a=e[0],[s,l,c,m,p,d]=Wz(a,t);r&&(s+=r.x,c+=r.x,p+=r.x,l+=r.y,m+=r.y,d+=r.y);let u=(c-s)/2,h=(m-l)/2;if((a.type==="diamond"||a.type==="ellipse")&&!n){let g=ii(q(s,l+h),q(p,d),a.angle),E=ii(q(s+u,l),q(p,d),a.angle),w=ii(q(c,l+h),q(p,d),a.angle),x=ii(q(s+u,m),q(p,d),a.angle),y=q(p,d);i=o?[g,E,w,x]:[g,E,w,x,y]}else{let g=ii(q(s,l),q(p,d),a.angle),E=ii(q(c,l),q(p,d),a.angle),w=ii(q(s,m),q(p,d),a.angle),x=ii(q(c,m),q(p,d),a.angle),y=q(p,d);i=o?[g,E,w,x]:[g,E,w,x,y]}}else if(e.length>1){let[a,s,l,c]=E0(e,r??{x:0,y:0}),m=l-a,p=c-s,d=q(a,s),u=q(l,s),h=q(a,c),g=q(l,c),E=q(a+m/2,s+p/2);i=o?[d,u,h,g]:[d,u,h,g,E]}return i.map(a=>q(dt(a[0]),dt(a[1])))},$5=(e,t,o,n)=>V5(e,t,o,n),K5=(e,t,o,n)=>{let r=$5(e,t,o,n),i=Y5(r,n).filter(p=>!(p.length===1&&W5(p[0]))).map(p=>x0(p).map(d=>dt(d))),a=i.sort((p,d)=>p[0]-d[0]),s=[],l=0;e:for(let p=0;p<a.length;p++){let d=a[p];for(let u=p+1;u<a.length;u++){if(++l>H5)break e;let h=a[u],[,g,E,w]=d,[x,y,,v]=h;E<x&&au(Vo(g,w),Vo(y,v))&&s.push({startBounds:d,endBounds:h,startSide:[q(E,g),q(E,w)],endSide:[q(x,y),q(x,v)],length:x-E,overlap:iu(Vo(g,w),Vo(y,v))})}}let c=i.sort((p,d)=>p[1]-d[1]),m=[];l=0;e:for(let p=0;p<c.length;p++){let d=c[p];for(let u=p+1;u<c.length;u++){if(++l>H5)break e;let h=c[u],[g,,E,w]=d,[x,y,v]=h;w<y&&au(Vo(g,E),Vo(x,v))&&m.push({startBounds:d,endBounds:h,startSide:[q(g,w),q(E,w)],endSide:[q(x,y),q(v,y)],length:y-w,overlap:iu(Vo(g,E),Vo(x,v))})}}return{horizontalGaps:s,verticalGaps:m}},G5=(e,t,o,n,r,i,a)=>{if(!wr({app:o,event:n,selectedElements:e}))return[];if(e.length===0)return[];let s=$o.getVisibleGaps();if(s){let{horizontalGaps:l,verticalGaps:c}=s,[m,p,d,u]=E0(e,t).map(E=>dt(E)),h=(m+d)/2,g=(p+u)/2;for(let E of l){if(!au(Vo(p,u),E.overlap))continue;let w=E.startSide[0][0]+E.length/2,x=dt(w-h);if(E.length>d-m&&Math.abs(x)<=a.x){Math.abs(x)<a.x&&(r.length=0),a.x=Math.abs(x);let P={type:"gap",direction:"center_horizontal",gap:E,offset:x};r.push(P);continue}let[,,v]=E.endBounds,I=m-v,k=dt(E.length-I);if(Math.abs(k)<=a.x){Math.abs(k)<a.x&&(r.length=0),a.x=Math.abs(k);let P={type:"gap",direction:"side_right",gap:E,offset:k};r.push(P);continue}let[L,,,]=E.startBounds,S=L-d,_=dt(S-E.length);if(Math.abs(_)<=a.x){Math.abs(_)<a.x&&(r.length=0),a.x=Math.abs(_);let P={type:"gap",direction:"side_left",gap:E,offset:_};r.push(P);continue}}for(let E of c){if(!au(Vo(m,d),E.overlap))continue;let w=E.startSide[0][1]+E.length/2,x=dt(w-g);if(E.length>u-p&&Math.abs(x)<=a.y){Math.abs(x)<a.y&&(i.length=0),a.y=Math.abs(x);let P={type:"gap",direction:"center_vertical",gap:E,offset:x};i.push(P);continue}let[,v,,]=E.startBounds,I=v-u,k=dt(I-E.length);if(Math.abs(k)<=a.y){Math.abs(k)<a.y&&(i.length=0),a.y=Math.abs(k);let P={type:"gap",direction:"side_top",gap:E,offset:k};i.push(P);continue}let[,,,L]=E.endBounds,S=dt(p-L),_=E.length-S;if(Math.abs(_)<=a.y){Math.abs(_)<a.y&&(i.length=0),a.y=Math.abs(_);let P={type:"gap",direction:"side_bottom",gap:E,offset:_};i.push(P);continue}}}},X5=(e,t,o,n)=>{let r=$5(e,t,o,n);return Y5(r,n).filter(i=>!(i.length===1&&W5(i[0]))).flatMap(i=>jc(i,n))},tl=(e,t,o,n,r,i,a)=>{if(!wr({app:o,event:n,selectedElements:e})||e.length===0&&t.length===0)return[];let s=$o.getReferenceSnapPoints();if(s)for(let l of t)for(let c of s){let m=c[0]-l[0],p=c[1]-l[1];Math.abs(m)<=a.x&&(Math.abs(m)<a.x&&(r.length=0),r.push({type:"point",points:[l,c],offset:m}),a.x=Math.abs(m)),Math.abs(p)<=a.y&&(Math.abs(p)<a.y&&(i.length=0),i.push({type:"point",points:[l,c],offset:p}),a.y=Math.abs(p))}},Z5=(e,t,o,n,r)=>{let i=o.state,a=Yz(e,i);if(!wr({app:o,event:n,selectedElements:a})||a.length===0)return{snapOffset:{x:0,y:0},snapLines:[]};t.x=dt(t.x),t.y=dt(t.y);let s=[],l=[],c=su(i.zoom.value),m={x:c,y:c},p=jc(a,r,{dragOffset:t});tl(a,p,o,n,s,l,m),G5(a,t,o,n,s,l,m);let d={x:s[0]?.offset??0,y:l[0]?.offset??0};m.x=0,m.y=0,s.length=0,l.length=0;let u={x:dt(t.x+d.x),y:dt(t.y+d.y)};tl(a,jc(a,r,{dragOffset:u}),o,n,s,l,m),G5(a,u,o,n,s,l,m);let h=y0(s,l),g=Xz(a,u,[...s,...l].filter(E=>E.type==="gap"));return{snapOffset:d,snapLines:[...h,...g]}},dt=e=>Math.round(e*10**6)/10**6,U5=e=>{let t=new Map;for(let o of e){let n=o.join(",");t.has(n)||t.set(n,o)}return Array.from(t.values())},y0=(e,t)=>{let o={},n={};if(e.length>0){for(let r of e)if(r.type==="point"){let i=dt(r.points[0][0]);o[i]||(o[i]=[]),o[i].push(...r.points.map(a=>q(dt(a[0]),dt(a[1]))))}}if(t.length>0){for(let r of t)if(r.type==="point"){let i=dt(r.points[0][1]);n[i]||(n[i]=[]),n[i].push(...r.points.map(a=>q(dt(a[0]),dt(a[1]))))}}return Object.entries(o).map(([r,i])=>({type:"points",points:U5(i.map(a=>q(Number(r),a[1])).sort((a,s)=>a[1]-s[1]))})).concat(Object.entries(n).map(([r,i])=>({type:"points",points:U5(i.map(a=>q(a[0],Number(r))).sort((a,s)=>a[0]-s[0]))})))},Kz=e=>{let t=new Map;for(let o of e){let n=o.points.flat().map(r=>[dt(r)]).join(",");t.has(n)||t.set(n,o)}return Array.from(t.values())},Xz=(e,t,o)=>{let[n,r,i,a]=E0(e,t),s=[];for(let l of o){let[c,m,p,d]=l.gap.startBounds,[u,h,g,E]=l.gap.endBounds,w=iu(Vo(r,a),l.gap.overlap),x=iu(Vo(n,i),l.gap.overlap);switch(l.direction){case"center_horizontal":{if(w){let y=(w[0]+w[1])/2;s.push({type:"gap",direction:"horizontal",points:[q(l.gap.startSide[0][0],y),q(n,y)]},{type:"gap",direction:"horizontal",points:[q(i,y),q(l.gap.endSide[0][0],y)]})}break}case"center_vertical":{if(x){let y=(x[0]+x[1])/2;s.push({type:"gap",direction:"vertical",points:[q(y,l.gap.startSide[0][1]),q(y,r)]},{type:"gap",direction:"vertical",points:[q(y,a),q(y,l.gap.endSide[0][1])]})}break}case"side_right":{if(w){let y=(w[0]+w[1])/2;s.push({type:"gap",direction:"horizontal",points:[q(p,y),q(u,y)]},{type:"gap",direction:"horizontal",points:[q(g,y),q(n,y)]})}break}case"side_left":{if(w){let y=(w[0]+w[1])/2;s.push({type:"gap",direction:"horizontal",points:[q(i,y),q(c,y)]},{type:"gap",direction:"horizontal",points:[q(p,y),q(u,y)]})}break}case"side_top":{if(x){let y=(x[0]+x[1])/2;s.push({type:"gap",direction:"vertical",points:[q(y,a),q(y,m)]},{type:"gap",direction:"vertical",points:[q(y,d),q(y,h)]})}break}case"side_bottom":{if(x){let y=(x[0]+x[1])/2;s.push({type:"gap",direction:"vertical",points:[q(y,d),q(y,h)]},{type:"gap",direction:"vertical",points:[q(y,E),q(y,r)]})}break}}}return Kz(s.map(l=>({...l,points:l.points.map(c=>q(dt(c[0]),dt(c[1])))})))},w0=(e,t,o,n,r,i)=>{if(!wr({event:n,selectedElements:e,app:o})||e.length===0||e.length===1&&!$z(e[0].angle,0))return{snapOffset:{x:0,y:0},snapLines:[]};let[a,s,l,c]=x0(t);i&&(i.includes("e")?l+=r.x:i.includes("w")&&(a+=r.x),i.includes("n")?s+=r.y:i.includes("s")&&(c+=r.y));let m=[];if(i)switch(i){case"e":{m.push(q(l,s),q(l,c));break}case"w":{m.push(q(a,s),q(a,c));break}case"n":{m.push(q(a,s),q(l,s));break}case"s":{m.push(q(a,c),q(l,c));break}case"ne":{m.push(q(l,s));break}case"nw":{m.push(q(a,s));break}case"se":{m.push(q(l,c));break}case"sw":{m.push(q(a,c));break}}let p=su(o.state.zoom.value),d={x:p,y:p},u=[],h=[];tl(t,m,o,n,u,h,d);let g={x:u[0]?.offset??0,y:h[0]?.offset??0};d.x=0,d.y=0,u.length=0,h.length=0;let[E,w,x,y]=x0(e).map(k=>dt(k)),v=[q(E,w),q(E,y),q(x,w),q(x,y)];tl(e,v,o,n,u,h,d);let I=y0(u,h);return{snapOffset:g,snapLines:I}},j5=(e,t,o,n,r,i)=>{if(!wr({event:o,selectedElements:[e],app:t}))return{snapOffset:{x:0,y:0},snapLines:[]};let a=[q(n.x+r.x,n.y+r.y)],s=su(t.state.zoom.value),l={x:s,y:s},c=[],m=[];tl([e],a,t,o,c,m,l);let p={x:c[0]?.offset??0,y:m[0]?.offset??0};l.x=0,l.y=0,c.length=0,m.length=0;let d=jc([e],i,{boundingBoxCorners:!0,omitCenter:!0});tl([e],d,t,o,c,m,l);let u=y0(c,m);return{snapOffset:p,snapLines:u}},q5=(e,t,o,n,r)=>{if(!wr({event:n,selectedElements:[],app:t}))return{originOffset:{x:0,y:0},snapLines:[]};let i=V5(e,[],t.state,r),a=su(t.state.zoom.value),s={x:a,y:a},l=[],c=[];for(let m of i){let p=jc([m],r);for(let d of p){let u=d[0]-o.x;Math.abs(u)<=Math.abs(s.x)&&(Math.abs(u)<Math.abs(s.x)&&(c.length=0),c.push({type:"pointer",points:[d,q(d[0],o.y)],direction:"vertical"}),s.x=u);let h=d[1]-o.y;Math.abs(h)<=Math.abs(s.y)&&(Math.abs(h)<Math.abs(s.y)&&(l.length=0),l.push({type:"pointer",points:[d,q(o.x,d[1])],direction:"horizontal"}),s.y=h)}}return{originOffset:{x:c.length>0?c[0].points[0][0]-o.x:0,y:l.length>0?l[0].points[0][1]-o.y:0},snapLines:[...c,...l]}},J5=e=>e===sa.rectangle||e===sa.ellipse||e===sa.diamond||e===sa.frame||e===sa.magicframe||e===sa.image||e===sa.text;import{isElementInViewport as Zz}from"@orangecatai/element";import{memoize as jz,toBrandedType as qz}from"@orangecatai/common";var qc=class{constructor(t){A(this,"scene");A(this,"getRenderableElements",(()=>{let t=({elementsMap:n,zoom:r,offsetLeft:i,offsetTop:a,scrollX:s,scrollY:l,height:c,width:m})=>{let p=[];for(let d of n.values())Zz(d,m,c,{zoom:r,offsetLeft:i,offsetTop:a,scrollX:s,scrollY:l},n)&&p.push(d);return p},o=({elements:n,editingTextElement:r,newElementId:i})=>{let a=qz(new Map);for(let s of n)i!==s.id&&(!r||r.type!=="text"||s.id!==r.id)&&a.set(s.id,s);return a};return jz(({zoom:n,offsetLeft:r,offsetTop:i,scrollX:a,scrollY:s,height:l,width:c,editingTextElement:m,newElementId:p,sceneNonce:d})=>{let u=this.scene.getNonDeletedElements(),h=o({elements:u,editingTextElement:m,newElementId:p}),g=t({elementsMap:h,zoom:n,offsetLeft:r,offsetTop:i,scrollX:a,scrollY:s,height:l,width:c});return{elementsMap:h,visibleElements:g}})})());this.scene=t}destroy(){YE.cancel(),this.getRenderableElements.clear()}};import{sceneCoordsToViewportCoords as Jz}from"@orangecatai/common";import{getElementAbsoluteCoords as Qz}from"@orangecatai/element";import{jsx as oH}from"react/jsx-runtime";var eH=5,tH=(e,t,o)=>{let[n,r]=Qz(e,o),{x:i,y:a}=Jz({sceneX:n+e.width,sceneY:r},t),s=i-t.offsetLeft+10,l=a-t.offsetTop;return{x:s,y:l}},v0=({children:e,element:t,elementsMap:o})=>{let n=Go();if(n.contextMenu||n.newElement||n.resizingElement||n.isRotating||n.openMenu||n.viewModeEnabled)return null;let{x:r,y:i}=tH(t,n,o);return oH("div",{className:"excalidraw-canvas-buttons",style:{top:`${i}px`,left:`${r}px`,padding:eH},children:e})};import{useCallback as Jc,useEffect as C0,useRef as nH,useState as Qc}from"react";import{sceneCoordsToViewportCoords as rH}from"@orangecatai/common";import{getElementAbsoluteCoords as iH}from"@orangecatai/element";import{isFrameLikeElement as aH}from"@orangecatai/element";var la={element:null,isOpen:!1,isRunning:!1},T0=new Set;function I0(){T0.forEach(e=>e(la))}var bn={open(e){la={...la,element:e,isOpen:!0},I0()},close(){la={element:null,isOpen:!1,isRunning:!1},I0()},setRunning(e){la={...la,isRunning:e},I0()},getState(){return la},subscribe(e){return T0.add(e),()=>T0.delete(e)}};import{Fragment as Q5,jsx as Te,jsxs as _o}from"react/jsx-runtime";var e3=[{label:"1:1",width:1024,height:1024,icon:"square"},{label:"2:3",width:1024,height:1536,icon:"portrait"},{label:"9:16",width:1080,height:1920,icon:"portrait-tall"},{label:"3:2",width:1536,height:1024,icon:"landscape"},{label:"16:9",width:1920,height:1080,icon:"landscape-wide"},{label:"A4",width:1024,height:1754,icon:"portrait"},{label:"Website",width:1366,height:768,icon:"landscape-wide"}],k0=e=>{let t={border:"1.5px solid currentColor",borderRadius:2,boxSizing:"border-box"};switch(e){case"square":return Te("div",{style:{...t,width:14,height:14}});case"portrait":return Te("div",{style:{...t,width:10,height:14}});case"portrait-tall":return Te("div",{style:{...t,width:8,height:14}});case"landscape":return Te("div",{style:{...t,width:14,height:10}});case"landscape-wide":return Te("div",{style:{...t,width:14,height:8}});default:return Te("div",{style:{...t,width:14,height:14}})}},sH=({active:e})=>Te("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e?_o(Q5,{children:[Te("path",{d:"M5 3H4C3.44772 3 3 3.44772 3 4V10C3 10.5523 3.44772 11 4 11H5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),Te("path",{d:"M9 3H10C10.5523 3 11 3.44772 11 4V10C11 10.5523 10.5523 11 10 11H9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),Te("line",{x1:"5",y1:"7",x2:"9",y2:"7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}):_o(Q5,{children:[Te("path",{d:"M5 3H4C3.44772 3 3 3.44772 3 4V10C3 10.5523 3.44772 11 4 11H5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),Te("path",{d:"M9 3H10C10.5523 3 11 3.44772 11 4V10C11 10.5523 10.5523 11 10 11H9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})}),lH=()=>_o("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[Te("path",{d:"M8 2V10M8 10L5 7M8 10L11 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),Te("path",{d:"M3 12H13",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),cH=()=>Te("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:Te("path",{d:"M2.5 3.75L5 6.25L7.5 3.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),dH=()=>Te("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:Te("path",{d:"M3.5 8.5L6.5 11.5L12.5 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),mH=()=>_o("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:[Te("rect",{x:"1.5",y:"1.5",width:"6.5",height:"6.5",rx:"1",stroke:"currentColor",strokeWidth:"1.4"}),Te("rect",{x:"8",y:"8",width:"6.5",height:"6.5",rx:"1",stroke:"currentColor",strokeWidth:"1.4",strokeDasharray:"2 1.2",opacity:"0.65"}),Te("path",{d:"M10.5 5.5H13.5V2.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),pH=(e,t)=>e3.find(o=>o.width===e&&o.height===t)||null,t3=({element:e,app:t})=>{let o=t.state,[n,r]=Qc(!1),[i,a]=Qc(!0),[s,l]=Qc(Math.round(e.width)),[c,m]=Qc(Math.round(e.height)),[p,d]=Qc(bn.getState()),u=nH(null);C0(()=>bn.subscribe(d),[]),C0(()=>{l(Math.round(e.width)),m(Math.round(e.height))},[e.width,e.height]),C0(()=>{let P=T=>{u.current&&!u.current.contains(T.target)&&r(!1)};if(n)return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[n]);let h=pH(Math.round(e.width),Math.round(e.height)),[g,E]=iH(e,t.scene.getNonDeletedElementsMap()),{x:w,y:x}=rH({sceneX:g+e.width/2,sceneY:E},o),y=w-o.offsetLeft,v=Math.max(x-o.offsetTop-82,8),I=Jc((P,T)=>{P>0&&T>0&&t.scene.mutateElement(e,{width:P,height:T})},[t.scene,e]),k=Jc(P=>{let T=parseInt(P,10);if(!isNaN(T)&&T>0)if(l(T),i){let M=e.height/e.width,N=Math.round(T*M);m(N),I(T,N)}else I(T,e.height)},[i,e.width,e.height,I]),L=Jc(P=>{let T=parseInt(P,10);if(!isNaN(T)&&T>0)if(m(T),i){let M=e.width/e.height,N=Math.round(T*M);l(N),I(N,T)}else I(e.width,T)},[i,e.width,e.height,I]),S=Jc(P=>{l(P.width),m(P.height),I(P.width,P.height),r(!1)},[I]),_=Jc(()=>{aH(e)&&t.onExportImage("png",t.getSceneElements(),{exportingFrame:e})},[t,e]);return o.contextMenu||o.newElement||o.resizingElement||o.isRotating||o.openMenu||o.viewModeEnabled||o.selectedElementsAreBeingDragged?null:_o("div",{className:"frame-toolbar",style:{left:`${y}px`,top:`${v}px`},onPointerDown:P=>P.stopPropagation(),onClick:P=>P.stopPropagation(),children:[_o("div",{className:"frame-toolbar__section",ref:u,children:[_o("button",{className:"frame-toolbar__ratio-btn",onClick:()=>r(!n),title:"Frame format",children:[k0(h?h.icon:"square"),Te("span",{children:h?.label||"Custom"}),Te(cH,{})]}),n&&_o("div",{className:"frame-toolbar__dropdown",children:[Te("div",{style:{padding:"6px 12px",fontSize:11,fontWeight:600,color:"var(--text-secondary-color, #888)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Format"}),e3.map(P=>{let T=h?.label===P.label;return _o("button",{className:"frame-toolbar__dropdown-item",onClick:()=>S(P),children:[k0(P.icon),Te("span",{className:"frame-toolbar__dropdown-item-label",children:P.label}),_o("span",{className:"frame-toolbar__dropdown-item-dims",children:[P.width,"*",P.height]}),T&&Te("span",{className:"frame-toolbar__dropdown-item-check",children:Te(dH,{})})]},P.label)})]})]}),Te("div",{className:"frame-toolbar__divider"}),_o("div",{className:"frame-toolbar__input-group",children:[Te("label",{children:"W"}),Te("input",{type:"number",value:s,onChange:P=>k(P.target.value),onPointerDown:P=>P.stopPropagation(),min:1})]}),Te("button",{className:`frame-toolbar__constrain-btn ${i?"frame-toolbar__constrain-btn--active":""}`,onClick:()=>a(!i),title:i?"Unlock proportions":"Constrain proportions",children:Te(sH,{active:i})}),_o("div",{className:"frame-toolbar__input-group",children:[Te("label",{children:"H"}),Te("input",{type:"number",value:c,onChange:P=>L(P.target.value),onPointerDown:P=>P.stopPropagation(),min:1})]}),Te("div",{className:"frame-toolbar__divider"}),Te("button",{className:"frame-toolbar__export-btn",onClick:_,title:"Export frame as PNG",children:Te(lH,{})}),Te("div",{className:"frame-toolbar__divider"}),Te("div",{className:"frame-toolbar__section",children:_o("button",{className:`frame-toolbar__btn ${p.isOpen&&p.element?.id===e.id?"frame-toolbar__btn--active":""}`,onClick:()=>{p.isOpen&&p.element?.id===e.id?p.isRunning||bn.close():bn.open(e)},title:"Auto resize to multiple dimensions",children:[Te(mH,{}),Te("span",{children:"Resize"})]})})]})};import{useEffect as uH,useReducer as gH}from"react";import{sceneCoordsToViewportCoords as hH}from"@orangecatai/common";var ed=[],M0=new Set;function S0(){M0.forEach(e=>e())}var vr={setLoadingFrames(e){ed=[...e],S0()},markComplete(e){ed=ed.filter(t=>t.frameId!==e),S0()},clear(){ed=[],S0()},getLoadingFrames(){return ed},subscribe(e){return M0.add(e),()=>M0.delete(e)}};import{Fragment as fH,jsx as o3}from"react/jsx-runtime";var n3=()=>{let e=Go(),[,t]=gH(r=>r+1,0);uH(()=>vr.subscribe(t),[]);let o=vr.getLoadingFrames();if(o.length===0)return null;let n=e.zoom.value;return o3(fH,{children:o.map(r=>{let{x:i,y:a}=hH({sceneX:r.x,sceneY:r.y},e),s=i-e.offsetLeft,l=a-e.offsetTop,c=r.width*n,m=r.height*n;return o3("div",{className:"ars-shimmer",style:{position:"absolute",left:s,top:l,width:c,height:m,pointerEvents:"none",zIndex:5,overflow:"hidden",boxSizing:"border-box"}},r.frameId)})})};import{useEffect as k3,useRef as bG,useState as xG}from"react";import{sceneCoordsToViewportCoords as EG}from"@orangecatai/common";import{getElementAbsoluteCoords as yG}from"@orangecatai/element";import{useCallback as R0,useEffect as pG,useRef as uG,useState as ga}from"react";function ol(e){let t=e?.trim();return(t||void 0)??(typeof import.meta<"u"&&C?.VITE_APP_GEMINI_API_KEY?C.VITE_APP_GEMINI_API_KEY:"")??""}import{nanoid as p3}from"nanoid";import{newFrameElement as f3,newElement as u3,newTextElement as XH,newImageElement as g3,getFrameChildren as b3,syncMovedIndices as yu}from"@orangecatai/element";import{FRAME_STYLE as x3,arrayToMap as wu}from"@orangecatai/common";import{useCallback as ma,useEffect as od,useRef as li,useState as Yn}from"react";import{sceneCoordsToViewportCoords as SH}from"@orangecatai/common";import{CaptureUpdateAction as A0,getElementAbsoluteCoords as MH}from"@orangecatai/element";import{ArrowUp as PH,ImagePlus as AH,X as LH}from"lucide-react";var Ir=new Map;function lu(e,t,o,n){Ir.set(e,{subscribers:new Set,prompt:t,settings:o,controller:n})}function cu(e,t){let o=Ir.get(e);o&&(o.finishedError=t,o.subscribers.forEach(n=>n(t)))}function du(e,t){let o=Ir.get(e);return o?(o.subscribers.add(t),o.finishedError!==void 0&&t(o.finishedError),!0):!1}function mu(e,t){Ir.get(e)?.subscribers.delete(t)}function pu(e){Ir.delete(e)}function uu(e){Ir.get(e)?.controller.abort()}function gu(e){return Ir.get(e)?.prompt??""}function si(e){return Ir.get(e)?.settings??null}function ca(e){return Ir.has(e)}import yH,{createContext as wH,useContext as vH,useLayoutEffect as IH,useRef as TH,useState as CH}from"react";import{clsx as bH}from"clsx";import{twMerge as xH}from"tailwind-merge";function Ze(...e){return xH(bH(e))}import*as r3 from"react";import{jsx as EH}from"react/jsx-runtime";var P0=r3.forwardRef(({className:e,...t},o)=>EH("textarea",{className:Ze("flex min-h-[60px] w-full rounded-md border border-zinc-200 bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-zinc-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-950 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:border-zinc-800 dark:placeholder:text-zinc-400 dark:focus-visible:ring-zinc-300",e),ref:o,...t}));P0.displayName="Textarea";import*as a3 from"react";import*as xn from"@radix-ui/react-tooltip";import{jsx as i3}from"react/jsx-runtime";var hu=xn.Provider,fu=xn.Root,bu=xn.Trigger,td=a3.forwardRef(({className:e,sideOffset:t=4,...o},n)=>i3(xn.Portal,{children:i3(xn.Content,{ref:n,sideOffset:t,className:Ze("z-50 overflow-hidden rounded-md bg-zinc-900 px-3 py-1.5 text-xs text-zinc-50 animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin] dark:bg-zinc-50 dark:text-zinc-900",e),...o})}));td.displayName=xn.Content.displayName;import{jsx as da,jsxs as kH}from"react/jsx-runtime";var s3=wH({isLoading:!1,value:"",setValue:()=>{},maxHeight:320,onSubmit:void 0,disabled:!1,textareaRef:yH.createRef()});function l3(){return vH(s3)}function nl({className:e,isLoading:t=!1,maxHeight:o=320,value:n,onValueChange:r,onSubmit:i,children:a,disabled:s=!1,onClick:l,...c}){let[m,p]=CH(n||""),d=TH(null),u=g=>{p(g),r?.(g)},h=g=>{s||d.current?.focus(),l?.(g)};return da(hu,{children:da(s3.Provider,{value:{isLoading:t,value:n??m,setValue:r??u,maxHeight:o,onSubmit:i,disabled:s,textareaRef:d},children:da("div",{onClick:h,className:Ze("border-zinc-200 bg-white cursor-text rounded-3xl border p-2 shadow-xs dark:border-zinc-800 dark:bg-zinc-950",s&&"cursor-not-allowed opacity-60",e),...c,children:a})})})}function rl({className:e,onKeyDown:t,disableAutosize:o=!1,...n}){let{value:r,setValue:i,maxHeight:a,onSubmit:s,disabled:l,textareaRef:c}=l3(),m=h=>{if(!h||o)return;h.style.height="auto";let g;typeof a=="number"?(h.style.height=`${Math.min(h.scrollHeight,a)}px`,g=a):(h.style.height=`min(${h.scrollHeight}px, ${a})`,g=1/0),h.style.overflowY=h.scrollHeight>g?"auto":"hidden"},p=h=>{c.current=h,m(h)};return IH(()=>{m(c.current)},[r,a,o]),da(P0,{ref:p,value:r,onChange:h=>{m(h.target),i(h.target.value)},onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),s?.()),t?.(h)},onWheel:h=>{h.stopPropagation()},className:Ze("text-zinc-900 min-h-[44px] w-full resize-none border-none bg-transparent shadow-none outline-none focus-visible:ring-0 focus-visible:ring-offset-0 dark:text-zinc-50",e),rows:1,disabled:l,...n})}function il({children:e,className:t,...o}){return da("div",{className:Ze("flex items-center gap-2",t),...o,children:e})}function Tr({tooltip:e,children:t,className:o,side:n="top",...r}){let{disabled:i}=l3();return kH(fu,{...r,children:[da(bu,{asChild:!0,disabled:i,onClick:a=>a.stopPropagation(),children:t}),da(td,{side:n,className:o,children:e})]})}import{jsx as be,jsxs as Mt}from"react/jsx-runtime";var ci={"Gemini 2.5 Flash":{geminiModelId:"gemini-3.1-flash-image-preview",supportsImageSize:!1,supportsThinking:!1,supportedResolutions:["1K"],supportedRatios:["21:9","16:9","4:3","3:2","1:1","9:16","3:4","2:3","5:4","4:5"]},"Gemini 3.1 Flash":{geminiModelId:"gemini-3.1-flash-image-preview",supportsImageSize:!0,supportsThinking:!0,supportedResolutions:["0.5K","1K","2K","4K"],supportedRatios:["21:9","16:9","4:3","3:2","1:1","9:16","3:4","2:3","5:4","4:5","4:1","1:4","8:1","1:8"]},"Gemini 3 Pro":{geminiModelId:"gemini-3-pro-image-preview",supportsImageSize:!0,supportsThinking:!1,supportedResolutions:["1K","2K","4K"],supportedRatios:["21:9","16:9","4:3","3:2","1:1","9:16","3:4","2:3","5:4","4:5"]}},D0=Object.keys(ci),_H={"Gemini 2.5 Flash":{"1:1":{"1K":{w:1024,h:1024}},"2:3":{"1K":{w:832,h:1248}},"3:2":{"1K":{w:1248,h:832}},"3:4":{"1K":{w:864,h:1184}},"4:3":{"1K":{w:1184,h:864}},"4:5":{"1K":{w:896,h:1152}},"5:4":{"1K":{w:1152,h:896}},"9:16":{"1K":{w:768,h:1344}},"16:9":{"1K":{w:1344,h:768}},"21:9":{"1K":{w:1536,h:672}}},"Gemini 3.1 Flash":{"1:1":{"0.5K":{w:512,h:512},"1K":{w:1024,h:1024},"2K":{w:2048,h:2048},"4K":{w:4096,h:4096}},"1:4":{"0.5K":{w:256,h:1024},"1K":{w:512,h:2048},"2K":{w:1024,h:4096},"4K":{w:2048,h:8192}},"1:8":{"0.5K":{w:192,h:1536},"1K":{w:384,h:3072},"2K":{w:768,h:6144},"4K":{w:1536,h:12288}},"2:3":{"0.5K":{w:424,h:632},"1K":{w:848,h:1264},"2K":{w:1696,h:2528},"4K":{w:3392,h:5056}},"3:2":{"0.5K":{w:632,h:424},"1K":{w:1264,h:848},"2K":{w:2528,h:1696},"4K":{w:5056,h:3392}},"3:4":{"0.5K":{w:448,h:600},"1K":{w:896,h:1200},"2K":{w:1792,h:2400},"4K":{w:3584,h:4800}},"4:1":{"0.5K":{w:1024,h:256},"1K":{w:2048,h:512},"2K":{w:4096,h:1024},"4K":{w:8192,h:2048}},"4:3":{"0.5K":{w:600,h:448},"1K":{w:1200,h:896},"2K":{w:2400,h:1792},"4K":{w:4800,h:3584}},"4:5":{"0.5K":{w:464,h:576},"1K":{w:928,h:1152},"2K":{w:1856,h:2304},"4K":{w:3712,h:4608}},"5:4":{"0.5K":{w:576,h:464},"1K":{w:1152,h:928},"2K":{w:2304,h:1856},"4K":{w:4608,h:3712}},"8:1":{"0.5K":{w:1536,h:192},"1K":{w:3072,h:384},"2K":{w:6144,h:768},"4K":{w:12288,h:1536}},"9:16":{"0.5K":{w:384,h:688},"1K":{w:768,h:1376},"2K":{w:1536,h:2752},"4K":{w:3072,h:5504}},"16:9":{"0.5K":{w:688,h:384},"1K":{w:1376,h:768},"2K":{w:2752,h:1536},"4K":{w:5504,h:3072}},"21:9":{"0.5K":{w:792,h:168},"1K":{w:1584,h:672},"2K":{w:3168,h:1344},"4K":{w:6336,h:2688}}},"Gemini 3 Pro":{"1:1":{"1K":{w:1024,h:1024},"2K":{w:2048,h:2048},"4K":{w:4096,h:4096}},"2:3":{"1K":{w:848,h:1264},"2K":{w:1696,h:2528},"4K":{w:3392,h:5056}},"3:2":{"1K":{w:1264,h:848},"2K":{w:2528,h:1696},"4K":{w:5056,h:3392}},"3:4":{"1K":{w:896,h:1200},"2K":{w:1792,h:2400},"4K":{w:3584,h:4800}},"4:3":{"1K":{w:1200,h:896},"2K":{w:2400,h:1792},"4K":{w:4800,h:3584}},"4:5":{"1K":{w:928,h:1152},"2K":{w:1856,h:2304},"4K":{w:3712,h:4608}},"5:4":{"1K":{w:1152,h:928},"2K":{w:2304,h:1856},"4K":{w:4608,h:3712}},"9:16":{"1K":{w:768,h:1376},"2K":{w:1536,h:2752},"4K":{w:3072,h:5504}},"16:9":{"1K":{w:1376,h:768},"2K":{w:2752,h:1536},"4K":{w:5504,h:3072}},"21:9":{"1K":{w:1584,h:672},"2K":{w:3168,h:1344},"4K":{w:6336,h:2688}}}};function pa(e,t,o){let r=_H[e][t];if(!r)return{width:1024,height:1024};let i=r[o];if(!i){let a=Object.values(r)[0];return{width:a.w,height:a.h}}return{width:i.w,height:i.h}}function DH(e){return e==="0.5K"?"512px":e}async function ua(e,t,o,n,r,i,a,s,l){let c=[{text:e}];if(s){let x=s.match(/^data:([^;]+);base64,(.+)$/);x&&c.unshift({inlineData:{mimeType:x[1],data:x[2]}})}let m={aspectRatio:o};r&&(m.imageSize=DH(n));let p={responseModalities:["IMAGE","TEXT"],imageConfig:m,temperature:.1};i&&(p.thinkingConfig={thinkingLevel:"High",includeThoughts:!0});let d={contents:[{parts:c}],generationConfig:p},u=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${t}:generateContent`,{method:"POST",signal:l,headers:{"x-goog-api-key":a,"Content-Type":"application/json"},body:JSON.stringify(d)});if(!u.ok){let x=`Gemini API error ${u.status}`;try{let y=await u.json();y?.error?.message&&(x=y.error.message)}catch{}throw new Error(x)}let E=((await u.json())?.candidates?.[0]?.content?.parts??[]).find(x=>x.inlineData?.data);if(!E?.inlineData?.data)throw new Error("No image was returned by the API.");return`data:${E.inlineData.mimeType??"image/png"};base64,${E.inlineData.data}`}var L0=()=>be("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",children:be("path",{d:"M2.5 3.75L5 6.25L7.5 3.75",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})}),_0=()=>be("svg",{width:"12",height:"12",viewBox:"0 0 14 14",fill:"none",children:be("path",{d:"M2.5 7.5L5.5 10.5L11.5 3.5",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})}),RH=()=>be("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",children:be("path",{d:"M8 2L10.5 5.5H13.5L11.5 8L13 11.5L8 9.5L3 11.5L4.5 8L2.5 5.5H5.5L8 2Z",stroke:"currentColor",strokeWidth:"1.3",strokeLinejoin:"round"})}),NH=()=>Mt("svg",{width:"12",height:"12",viewBox:"0 0 14 14",fill:"none",children:[be("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.2"}),be("path",{d:"M7 6.5V10",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),be("circle",{cx:"7",cy:"4.5",r:"0.75",fill:"currentColor"})]}),BH=()=>be("svg",{width:"15",height:"15",viewBox:"0 0 14 14",fill:"none",className:"igp-spinner",children:be("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:"20 14"})}),FH=({label:e})=>{let o={"21:9":{width:21,height:9},"16:9":{width:18,height:10},"4:3":{width:16,height:12},"3:2":{width:15,height:10},"1:1":{width:13,height:13},"9:16":{width:10,height:18},"3:4":{width:12,height:16},"2:3":{width:10,height:15},"5:4":{width:15,height:12},"4:5":{width:12,height:15},"4:1":{width:24,height:6},"1:4":{width:6,height:24},"8:1":{width:24,height:3},"1:8":{width:3,height:24}}[e]??{width:13,height:13};return be("div",{style:{border:"1.5px solid currentColor",borderRadius:2,boxSizing:"border-box",display:"inline-block",flexShrink:0,color:"#999",...o}})},c3=({element:e,app:t,onBeforeImageGen:o,onAfterImageGen:n})=>{let r=Y=>{let te=Y.customData?.imageGenerator;return te?{model:te.model,ratio:te.ratio,resolution:te.resolution}:null},i=t.state,a=ol(t.props.geminiApiKey),[s,l]=Yn(()=>gu(e.id)),[c,m]=Yn(()=>{let Y=r(e),te=si(e.id);return Y?.model??te?.model??"Gemini 3.1 Flash"}),p=ci[c],d=p.supportedRatios,u=p.supportedResolutions,h=d.includes("2:3")?"2:3":d[0],g=u.includes("2K")?"2K":u[u.length-1],[E,w]=Yn(()=>{let Y=r(e),te=si(e.id);return Y?.ratio??te?.ratio??h}),[x,y]=Yn(()=>{let Y=r(e),te=si(e.id);return Y?.resolution??te?.resolution??g}),v=ma(Y=>{t.scene.mutateElement(e,{customData:{...e.customData??{},imageGenerator:Y}})},[t.scene,e]),I=ma((Y,te=!1)=>{t.scrollToContent(Y,{fitToViewport:!0,viewportZoomFactor:.8,animate:te,canvasOffsets:t.getEditorUIOffsets()})},[t]),k=li(!0);od(()=>{if(k.current){k.current=!1;return}let Y=ci[c],te=Y.supportedRatios,Fe=te.includes(E),ft=E;Fe||(ft=te.includes("2:3")?"2:3":te[0],w(ft));let Co=Y.supportedResolutions,Dr=Co.includes(x),ir=x;Dr||(ir=Co.includes("2K")?"2K":Co[Co.length-1],y(ir));let Fl=pa(c,ft,ir);t.scene.mutateElement(e,{width:Fl.width,height:Fl.height}),v({model:c,ratio:ft,resolution:ir}),t.syncActionResult({captureUpdate:A0.IMMEDIATELY})},[c,t,e,v]);let[L,S]=Yn(()=>ca(e.id)),[_,P]=Yn(null),[T,M]=Yn(null),[N,O]=Yn(!1),[B,U]=Yn(!1),[D,F]=Yn(!1),z=li(null),$=li(null),V=li(null),Q=li(null),ee=li(null),ie=li(e),Ee=li(t);od(()=>{ie.current=e,Ee.current=t}),od(()=>{if(!e.customData?.imageGeneratorAutoFitPending)return;let Y=0,te=!1,Fe=()=>{te||(I(e),t.scene.mutateElement(e,{customData:{...e.customData??{},imageGeneratorAutoFitPending:!1}}))};return Y=window.requestAnimationFrame(()=>{Y=window.requestAnimationFrame(Fe)}),()=>{te=!0,window.cancelAnimationFrame(Y)}},[t.scene,e,I]);let Le=ma(Y=>{w(Y),O(!1);let te=pa(c,Y,x);Ee.current.scene.mutateElement(ie.current,{width:te.width,height:te.height,customData:{...ie.current.customData??{},imageGenerator:{model:c,ratio:Y,resolution:x}}}),Ee.current.syncActionResult({captureUpdate:A0.IMMEDIATELY})},[c,x]),De=ma(Y=>{y(Y),U(!1);let te=pa(c,E,Y);Ee.current.scene.mutateElement(ie.current,{width:te.width,height:te.height,customData:{...ie.current.customData??{},imageGenerator:{model:c,ratio:E,resolution:Y}}}),Ee.current.syncActionResult({captureUpdate:A0.IMMEDIATELY})},[c,E]);od(()=>{let Y=te=>{z.current&&!z.current.contains(te.target)&&O(!1),$.current&&!$.current.contains(te.target)&&U(!1),V.current&&!V.current.contains(te.target)&&F(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[]),od(()=>{let Y=te=>{S(!1),te?te!=="aborted"&&P(te):P(null)};return du(e.id,Y),()=>mu(e.id,Y)},[e.id]);let We=ma(Y=>{let te=Y.target.files?.[0];if(!te)return;let Fe=new FileReader;Fe.onload=()=>M(Fe.result),Fe.readAsDataURL(te),Y.target.value=""},[]),lt=ma(()=>{uu(e.id)},[e.id]),qt=ma(async()=>{if(!s.trim()){P("Please enter a prompt.");return}if(!a){P("No Gemini API key found. Set VITE_APP_GEMINI_API_KEY in .env.");return}if(o)try{let{allowed:Fe,error:ft}=await o();if(!Fe){P(ft||"Insufficient credits for image generation");return}}catch{P("Credit check failed");return}let Y=new AbortController;ee.current=Y,lu(e.id,s,{model:c,ratio:E,resolution:x},Y),S(!0),P(null);let te=null;try{let Fe=ci[c],ft=await ua(s,Fe.geminiModelId,E,x,Fe.supportsImageSize,Fe.supportsThinking,a,T??void 0,Y.signal);await t.insertGeneratedImageIntoFrame(ft,e),n?.()}catch(Fe){Fe instanceof Error&&(Fe.name==="AbortError"?te="aborted":te=Fe.message)}finally{ee.current=null,cu(e.id,te),S(!1),te===null?(pu(e.id),l(""),M(null),P(null)):te!=="aborted"&&P(te)}},[s,a,c,E,x,T,t,e,o,n]);if(i.contextMenu||i.newElement||i.resizingElement||i.isRotating||i.openMenu||i.viewModeEnabled||i.selectedElementsAreBeingDragged)return null;let[rr,,,In]=MH(e,t.scene.getNonDeletedElementsMap()),{x:lo,y:Ct}=SH({sceneX:rr+e.width/2,sceneY:In},i),xt=lo-i.offsetLeft,To=Ct-i.offsetTop+16;return Mt("div",{className:"igp",style:{left:`${xt}px`,top:`${To}px`},onPointerDown:Y=>Y.stopPropagation(),onClick:Y=>Y.stopPropagation(),children:[be("input",{ref:Q,type:"file",accept:"image/*",style:{display:"none"},onChange:We}),Mt(nl,{isLoading:L,value:s,onValueChange:l,onSubmit:qt,className:"igp-container",children:[T&&Mt("div",{className:"igp-ref-chip",children:[be("img",{src:T,alt:"Reference"}),be("span",{children:"Reference image"}),be("button",{onClick:()=>M(null),title:"Remove",children:be(LH,{size:10})})]}),be(rl,{placeholder:"What are we creating today\u2026",className:"igp-textarea",disableAutosize:!1}),_&&be("div",{className:"igp-error",children:_}),Mt(il,{className:"igp-actions",children:[Mt("div",{className:"igp-actions-left",children:[Mt("div",{className:"igp-dropdown-root",ref:V,children:[be(Tr,{tooltip:"Select model",side:"top",children:Mt("button",{className:"igp-btn",onClick:()=>{F(Y=>!Y),O(!1),U(!1)},disabled:L,children:[be(RH,{}),be("span",{children:c}),be(L0,{})]})}),D&&be("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--left",children:D0.map(Y=>Mt("button",{className:"igp-dropdown-item",onClick:()=>{v({model:Y,ratio:E,resolution:x}),m(Y),F(!1)},children:[be("span",{style:{flex:1},children:Y}),Y===c&&be("span",{className:"igp-check",children:be(_0,{})})]},Y))})]}),be(Tr,{tooltip:"Add reference image",side:"top",children:be("button",{className:`igp-btn igp-btn--icon${T?" igp-btn--active":""}`,onClick:()=>Q.current?.click(),disabled:L,children:be(AH,{size:15})})})]}),Mt("div",{className:"igp-actions-right",children:[Mt("div",{className:"igp-dropdown-root",ref:$,children:[Mt("button",{className:"igp-btn igp-btn--compact",onClick:()=>{u.length<=1||(U(Y=>!Y),O(!1),F(!1))},disabled:L||u.length<=1,title:u.length<=1?"Fixed resolution for this model":void 0,children:[be("span",{children:x}),u.length>1&&be(L0,{})]}),B&&u.length>1&&be("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--right",children:u.map(Y=>Mt("button",{className:"igp-dropdown-item",onClick:()=>De(Y),children:[be("span",{style:{flex:1},children:Y}),Y===x&&be("span",{className:"igp-check",children:be(_0,{})})]},Y))})]}),Mt("div",{className:"igp-dropdown-root",ref:z,children:[Mt("button",{className:"igp-btn igp-btn--compact",onClick:()=>{O(Y=>!Y),U(!1),F(!1)},disabled:L,children:[be("span",{children:E}),be(L0,{})]}),N&&Mt("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--right igp-dropdown--ratio",children:[Mt("div",{className:"igp-dropdown-header",children:[be("span",{children:"Format"}),be(NH,{})]}),d.map(Y=>{let te=pa(c,Y,x);return Mt("button",{className:"igp-dropdown-item",onClick:()=>Le(Y),children:[be(FH,{label:Y}),be("span",{style:{flex:1},children:Y}),Mt("span",{className:"igp-dims",children:[te.width,"\xD7",te.height]}),Y===E&&be("span",{className:"igp-check",children:be(_0,{})})]},Y)})]})]}),be("button",{className:"igp-generate",onClick:L?lt:qt,disabled:!L&&!s.trim(),title:L?"Stop generation":"Generate image",children:L?be(BH,{}):be(PH,{size:16})})]})]})]})]})};function di(e){if(!e||e==="transparent"||e==="rgba(0, 0, 0, 0)")return"transparent";if(e.startsWith("#"))return e;let t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([0-9.]+))?\)/);if(!t)return e;let o=parseInt(t[1],10),n=parseInt(t[2],10),r=parseInt(t[3],10);return`#${o.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}function OH(e){let t=e.match(/rgba\(\d+,\s*\d+,\s*\d+,\s*([0-9.]+)\)/);return t?Math.round(parseFloat(t[1])*100):100}function zH(e,t){let o=e.toLowerCase();if(t){for(let[n,r]of Object.entries(t))if(o.includes(n))return r}return o.includes("sans-serif")||o.includes("arial")||o.includes("helvetica")||o.includes("verdana")||o.includes("impact")||o.includes("nunito")||o.includes("roboto")||o.includes("inter")||o.includes("liberation sans")||o.includes("tahoma")||o.includes("trebuchet")?2:o.includes("georgia")||o.includes("serif")||o.includes("cursive")||o.includes("script")||o.includes("times")||o.includes("playfair")?1:o.includes("courier")||o.includes("mono")||o.includes("cascadia")?3:2}function HH(e,t){switch(t){case"uppercase":return e.toUpperCase();case"lowercase":return e.toLowerCase();case"capitalize":return e.replace(/\b\w/g,o=>o.toUpperCase());default:return e}}function GH(e){let t=parseFloat(e);return isNaN(t)?16:Math.round(t)}function UH(e){let t=e.borderTopLeftRadius||"0",o=parseFloat(t);return isNaN(o)?0:Math.round(o)}function WH(e,t,o){let n=e.borderTopLeftRadius||"0";if(n.includes("%")){let r=parseFloat(n);if(!isNaN(r)&&r>=50)return!0}else{let r=parseFloat(n);if(!isNaN(r)&&r>0&&r>=t/2&&r>=o/2)return!0}return!1}function YH(e){return e!=="none"&&(e.includes("linear-gradient")||e.includes("radial-gradient"))}function VH(e){let t=[...e.matchAll(/(#[\da-fA-F]{3,8}|rgba?\([^)]+\))/g)];if(t.length===0)return"#1a1a2e";if(t.length===1||e.includes("repeating"))return di(t[0][1]);let o=di(t[0][1]).replace("#","").padEnd(6,"0"),n=di(t[t.length-1][1]).replace("#","").padEnd(6,"0"),r=parseInt(o.slice(0,2),16),i=parseInt(o.slice(2,4),16),a=parseInt(o.slice(4,6),16),s=parseInt(n.slice(0,2),16),l=parseInt(n.slice(2,4),16),c=parseInt(n.slice(4,6),16),m=(p,d)=>Math.round((p+d)/2).toString(16).padStart(2,"0");return`#${m(r,s)}${m(i,l)}${m(a,c)}`}function $H(e){let t=e.match(/url\("?(data:[^")]+)"?\)/);return t?t[1]:null}function KH(e){return e==="center"?"center":e==="right"||e==="end"?"right":"left"}var m3=new Set(["SPAN","EM","STRONG","B","I","A","LABEL"]);function d3(e){let t="",o=!1;for(let r of e.childNodes)if(r.nodeType===Node.TEXT_NODE){let i=r.textContent||"";i.trim()&&(o=!0),t+=i}else if(r.nodeType===Node.ELEMENT_NODE){let i=r;if(i.tagName==="BR")t+=`
14
+ C ${l} ${c}, ${l} ${c}, ${l+E} ${c+w}`,Er(e,!0,a))}else s=t.polygon([[l,c],[m,p],[d,u],[h,g]],Er(e,!1,a));return s}case"ellipse":return t.ellipse(e.width/2,e.height/2,e.width,e.height,Er(e,!1,a));case"line":case"arrow":{let s,l=Er(e,!1,a),c=e.points.length?e.points:[qO(0,0)];if(Wc(e)?c.every(m=>Math.abs(m[0])<=1e6&&Math.abs(m[1])<=1e6)?s=[t.path(iz(c,16),Er(e,!0,a))]:(console.error("Elbow arrow with extreme point positions detected. Arrow not rendered.",e.id,JSON.stringify(c)),s=[]):e.roundness?s=[t.curve(c,l)]:l.fill?s=[t.polygon(c,l)]:s=[t.linearPath(c,l)],e.type==="arrow"){let{startArrowhead:m=null,endArrowhead:p="arrow"}=e;if(m!==null){let d=h5(e,s,"start",m,t,l,n,a);s.push(...d)}if(p!==null){let d=h5(e,s,"end",p,t,l,n,a);s.push(...d)}}return s}case"freedraw":{let s=[];if(Kp(e.points)){let l=ZO(e.points,.75);s.push(t.curve(l,{...Er(e,!1,a),stroke:"none"}))}return s.push(az(e)),s}case"frame":case"magicframe":case"text":case"image":return null;default:return QO(e,`generateElementShape(): Unimplemented type ${e?.type}`),null}},iz=(e,t)=>{let o=[];for(let r=1;r<e.length-1;r+=1){let i=e[r-1],a=e[r+1],s=e[r],l=qp(s,i),c=qp(a,s),m=Math.min(t,u5(e[r],a)/2,u5(e[r],i)/2);l?i[0]<s[0]?o.push([e[r][0]-m,e[r][1]]):o.push([e[r][0]+m,e[r][1]]):i[1]<s[1]?o.push([e[r][0],e[r][1]-m]):o.push([e[r][0],e[r][1]+m]),o.push(e[r]),c?a[0]<s[0]?o.push([e[r][0]-m,e[r][1]]):o.push([e[r][0]+m,e[r][1]]):a[1]<s[1]?o.push([e[r][0],e[r][1]-m]):o.push([e[r][0],e[r][1]+m])}let n=[`M ${e[0][0]} ${e[0][1]}`];for(let r=0;r<o.length;r+=3)n.push(`L ${o[r][0]} ${o[r][1]}`),n.push(`Q ${o[r+1][0]} ${o[r+1][1]}, ${o[r+2][0]} ${o[r+2][1]}`);return n.push(`L ${e[e.length-1][0]} ${e[e.length-1][1]}`),n.join(" ")};var az=e=>cz(sz(e)),sz=e=>{let t=e.simulatePressure?e.points:e.points.length?e.points.map(([o,n],r)=>[o,n,e.pressures[r]]):[[0,0,.5]];return jO(t,{simulatePressure:e.simulatePressure,size:e.strokeWidth*4.25,thinning:.6,smoothing:.5,streamline:.5,easing:o=>Math.sin(o*Math.PI/2),last:!0})},f5=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],lz=/(\s?[A-Z]?,?-?[0-9]*\.[0-9]{0,2})(([0-9]|e|-)*)/g,cz=e=>{if(!e.length)return"";let t=e.length-1;return e.reduce((o,n,r,i)=>(r===t?o.push(n,f5(n,i[0]),"L",i[0],"Z"):o.push(n,f5(n,i[r+1])),o),["M",e[0],"Q"]).join(" ").replace(lz,"$1")};var x5=(e,t,o=!1)=>{let n=!1;for(let r in t){let i=t[r];if(typeof i<"u"){if(e[r]===i&&(typeof i!="object"||i===null))continue;n=!0}}return!n&&!o?e:{...e,...t,version:t.version??e.version+1,versionNonce:t.versionNonce??dz(),updated:mz()}};import{jsx as y5}from"react/jsx-runtime";var Qs=W({name:"toggleLinearEditor",category:rt.elements,label:(e,t,o)=>o.scene.getSelectedElements({selectedElementIds:t.selectedElementIds})[0]?.type==="arrow"?"labels.lineEditor.editArrow":"labels.lineEditor.edit",keywords:["line"],trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return!!(!t.selectedLinearElement?.isEditing&&r.length===1&&uz(r[0])&&!pz(r[0]))},perform(e,t,o,n){let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0})[0];m0(r,"No selected element found"),m0(t.selectedLinearElement,"No selected linear element found"),m0(r.id===t.selectedLinearElement.elementId,"Selected element ID and linear editor elementId does not match");let i={...t.selectedLinearElement,isEditing:!t.selectedLinearElement.isEditing};return{appState:{...t,selectedLinearElement:i},captureUpdate:E5.IMMEDIATELY}},PanelComponent:({appState:e,updateData:t,app:o})=>{let n=o.scene.getSelectedElements({selectedElementIds:e.selectedElementIds})[0];if(!n)return null;let r=f(n.type==="arrow"?"labels.lineEditor.editArrow":"labels.lineEditor.edit");return y5(ne,{type:"button",icon:Vw,title:r,"aria-label":r,onClick:()=>t(null)})}}),wke=W({name:"togglePolygon",category:rt.elements,icon:nh,keywords:["loop"],label:(e,t,o)=>!o.scene.getSelectedElements({selectedElementIds:t.selectedElementIds}).some(i=>!Js(i)||!i.polygon)?"labels.polygon.breakPolygon":"labels.polygon.convertToPolygon",trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds});return r.length>0&&r.every(i=>Js(i)&&i.points.length>=4)},perform(e,t,o,n){let r=n.scene.getSelectedElements(t);if(r.some(l=>!Js(l)))return!1;let i=r,a=i.some(l=>!l.polygon),s=gz(i);return{elements:e.map(l=>!s.has(l.id)||!Js(l)?l:x5(l,{backgroundColor:a?l.backgroundColor:"transparent",...hz(l,a)})),appState:t,captureUpdate:E5.IMMEDIATELY}},PanelComponent:({appState:e,updateData:t,app:o})=>{let n=o.scene.getSelectedElements({selectedElementIds:e.selectedElementIds});if(n.length===0||n.some(a=>!Js(a)||!a.polygon||a.points.length<3))return null;let r=n.every(a=>Js(a)&&a.polygon),i=f(r?"labels.polygon.breakPolygon":"labels.polygon.convertToPolygon");return y5(ls,{icon:nh,title:i,"aria-label":i,active:r,onClick:()=>t(null),style:{marginLeft:"auto"}})}});import{KEYS as w5,CANVAS_SEARCH_TAB as v5,CLASSES as fz,DEFAULT_SIDEBAR as I5}from"@orangecatai/common";import{CaptureUpdateAction as bz}from"@orangecatai/element";var Uc=W({name:"searchMenu",icon:Co,keywords:["search","find"],label:"search.title",viewMode:!0,trackEvent:{category:"search_menu",action:"toggle",predicate:e=>e.gridModeEnabled},perform(e,t,o,n){if(t.openDialog)return!1;if(t.openSidebar?.name===I5.name&&t.openSidebar.tab===v5){let r=n.excalidrawContainerValue.container?.querySelector(`.${fz.SEARCH_MENU_INPUT_WRAPPER} input`);return r?.focus(),r?.select(),!1}return{appState:{...t,openSidebar:{name:I5.name,tab:v5},openDialog:null},captureUpdate:bz.EVENTUALLY}},checked:e=>e.gridModeEnabled,predicate:(e,t,o)=>o.gridModeEnabled===void 0,keyTest:e=>e[w5.CTRL_OR_CMD]&&e.key===w5.F});import{isImageElement as xz}from"@orangecatai/element";import{CaptureUpdateAction as Ez}from"@orangecatai/element";import{jsx as yz}from"react/jsx-runtime";var Kc=W({name:"cropEditor",label:"helpDialog.cropStart",icon:Ch,viewMode:!0,trackEvent:{category:"menu"},keywords:["image","crop"],perform(e,t,o,n){let r=n.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!0})[0];return{appState:{...t,isCropping:!1,croppingElementId:r.id},captureUpdate:Ez.IMMEDIATELY}},predicate:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t);return!!(!t.croppingElementId&&r.length===1&&xz(r[0]))},PanelComponent:({appState:e,updateData:t,app:o})=>{let n=f("helpDialog.cropStart");return yz(ne,{type:"button",icon:Ch,title:n,"aria-label":n,onClick:()=>t(null)})}});import{getNonDeletedElements as wz}from"@orangecatai/element";import{mutateElement as vz}from"@orangecatai/element";import{newFrameElement as Iz}from"@orangecatai/element";import{isFrameLikeElement as ou}from"@orangecatai/element";import{addElementsToFrame as Tz,removeAllElementsFromFrame as Cz}from"@orangecatai/element";import{getFrameChildren as kz}from"@orangecatai/element";import{KEYS as T5,updateActiveTool as C5}from"@orangecatai/common";import{getElementsInGroup as Sz}from"@orangecatai/element";import{getCommonBounds as Mz}from"@orangecatai/element";import{CaptureUpdateAction as ia}from"@orangecatai/element";var k5=(e,t)=>{let o=t.scene.getSelectedElements(e);return o.length===1&&ou(o[0])},S5=W({name:"selectAllElementsInFrame",label:"labels.selectAllElementsInFrame",trackEvent:{category:"canvas"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t).at(0)||null;if(ou(r)){let i=kz(wz(e),r.id).filter(a=>!(a.type==="text"&&a.containerId));return{elements:e,appState:{...t,selectedElementIds:i.reduce((a,s)=>(a[s.id]=!0,a),{})},captureUpdate:ia.IMMEDIATELY}}return{elements:e,appState:t,captureUpdate:ia.EVENTUALLY}},predicate:(e,t,o,n)=>k5(t,n)}),M5=W({name:"removeAllElementsFromFrame",label:"labels.removeAllElementsFromFrame",trackEvent:{category:"history"},perform:(e,t,o,n)=>{let r=n.scene.getSelectedElements(t).at(0)||null;return ou(r)?{elements:Cz(e,r),appState:{...t,selectedElementIds:{[r.id]:!0}},captureUpdate:ia.IMMEDIATELY}:{elements:e,appState:t,captureUpdate:ia.EVENTUALLY}},predicate:(e,t,o,n)=>k5(t,n)}),ASe=W({name:"updateFrameRendering",label:"labels.updateFrameRendering",viewMode:!0,trackEvent:{category:"canvas"},perform:(e,t)=>({elements:e,appState:{...t,frameRendering:{...t.frameRendering,enabled:!t.frameRendering.enabled}},captureUpdate:ia.EVENTUALLY}),checked:e=>e.frameRendering.enabled}),LSe=W({name:"setFrameAsActiveTool",label:"toolBar.frame",trackEvent:{category:"toolbar"},icon:Dn,viewMode:!1,perform:(e,t,o,n)=>{let r=C5(t,{type:"frame"});return So(n.interactiveCanvas,{...t,activeTool:r}),{elements:e,appState:{...t,activeTool:C5(t,{type:"frame"})},captureUpdate:ia.EVENTUALLY}},keyTest:e=>!e[T5.CTRL_OR_CMD]&&!e.shiftKey&&!e.altKey&&e.key.toLocaleLowerCase()===T5.F}),P5=W({name:"wrapSelectionInFrame",label:"labels.wrapSelectionInFrame",trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=le(e,t);return r.length>0&&!r.some(i=>ou(i))},perform:(e,t,o,n)=>{let r=le(e,t),i=n.scene.getNonDeletedElementsMap(),[a,s,l,c]=Mz(r,i),m=16,p=Iz({x:a-m,y:s-m,width:l-a+m*2,height:c-s+m*2});if(t.editingGroupId){let u=Sz(r,t.editingGroupId);for(let h of u){let g=h.groupIds.indexOf(t.editingGroupId);vz(h,i,{groupIds:h.groupIds.slice(0,g)})}}return{elements:Tz([...n.scene.getElementsIncludingDeleted(),p],r,p,t),appState:{selectedElementIds:{[p.id]:!0}},captureUpdate:ia.IMMEDIATELY}}});import{isWindows as Nz,KEYS as Zc,matchKey as g0,arrayToMap as A5,MOBILE_ACTION_BUTTON_BG as L5}from"@orangecatai/common";import{CaptureUpdateAction as u0}from"@orangecatai/element";import{orderByFractionalIndex as Bz}from"@orangecatai/element";import{Emitter as Pz}from"@orangecatai/common";import{CaptureUpdateAction as Az,StoreChange as Lz,StoreDelta as _z}from"@orangecatai/element";var el=class extends _z{applyTo(t,o,n){let[r,i]=this.elements.applyTo(t,n.elements,{excludedProperties:new Set(["version","versionNonce"])}),[a,s]=this.appState.applyTo(o,r);return[r,a,i||s]}static calculate(t,o){return super.calculate(t,o)}static inverse(t){return super.inverse(t)}static applyLatestChanges(t,o,n,r){return super.applyLatestChanges(t,o,n,r)}},aa=class{constructor(t=!0,o=!0){this.isUndoStackEmpty=t;this.isRedoStackEmpty=o}},Xc=class e{constructor(t){this.store=t;A(this,"onHistoryChangedEmitter",new Pz);A(this,"undoStack",[]);A(this,"redoStack",[])}get isUndoStackEmpty(){return this.undoStack.length===0}get isRedoStackEmpty(){return this.redoStack.length===0}clear(){this.undoStack.length=0,this.redoStack.length=0}record(t){if(t.isEmpty()||t instanceof el)return;let o=el.inverse(t);this.undoStack.push(o),o.elements.isEmpty()||(this.redoStack.length=0),this.onHistoryChangedEmitter.trigger(new aa(this.isUndoStackEmpty,this.isRedoStackEmpty))}undo(t,o){return this.perform(t,o,()=>e.pop(this.undoStack),n=>e.push(this.redoStack,n))}redo(t,o){return this.perform(t,o,()=>e.pop(this.redoStack),n=>e.push(this.undoStack,n))}perform(t,o,n,r){try{let i=n();if(i===null)return;let a=Az.IMMEDIATELY,s=this.store.snapshot,l=t,c=o,m=!1;for(;i;){try{[l,c,m]=i.applyTo(l,c,s);let p=s.elements,d=s.maybeClone(a,l,c),u=Lz.create(s,d),h=el.applyLatestChanges(i,p,l);h.isEmpty()||(this.store.scheduleMicroAction({action:a,change:u,delta:h}),i=h),s=d}finally{r(i)}if(m)break;i=n()}return[l,c]}finally{this.onHistoryChangedEmitter.trigger(new aa(this.isUndoStackEmpty,this.isRedoStackEmpty))}}static pop(t){if(!t.length)return null;let o=t.pop();return o!==void 0?o:null}static push(t,o){let n=el.inverse(o);return t.push(n)}};import{useEffect as Dz,useState as Rz}from"react";var p0=(e,t)=>{let[o,n]=Rz(t);return Dz(()=>{let r=e.on(i=>{n(i)});return()=>{r()}},[e]),o};import{jsx as N5}from"react/jsx-runtime";var _5=(e,t,o)=>{if(!t.multiElement&&!t.resizingElement&&!t.editingTextElement&&!t.newElement&&!t.selectedElementsAreBeingDragged&&!t.selectionElement&&!e.flowChartCreator.isCreatingChart){let n=o();if(!n)return{captureUpdate:u0.EVENTUALLY};let[r,i]=n,a=Bz(Array.from(r.values()));return{appState:i,elements:a,captureUpdate:u0.NEVER}}return{captureUpdate:u0.EVENTUALLY}},D5=e=>({name:"undo",label:"buttons.undo",icon:sh,trackEvent:{category:"history"},viewMode:!1,perform:(t,o,n,r)=>_5(r,o,()=>e.undo(A5(t),o)),keyTest:t=>t[Zc.CTRL_OR_CMD]&&g0(t,Zc.Z)&&!t.shiftKey,PanelComponent:({appState:t,updateData:o,data:n,app:r})=>{let{isUndoStackEmpty:i}=p0(e.onHistoryChangedEmitter,new aa(e.isUndoStackEmpty,e.isRedoStackEmpty)),a=_t()==="mobile";return N5(ne,{type:"button",icon:sh,"aria-label":f("buttons.undo"),onClick:o,size:n?.size||"medium",disabled:i,"data-testid":"button-undo",style:{...a?L5:{}}})}}),R5=e=>({name:"redo",label:"buttons.redo",icon:lh,trackEvent:{category:"history"},viewMode:!1,perform:(t,o,n,r)=>_5(r,o,()=>e.redo(A5(t),o)),keyTest:t=>t[Zc.CTRL_OR_CMD]&&t.shiftKey&&g0(t,Zc.Z)||Nz&&t.ctrlKey&&!t.shiftKey&&g0(t,Zc.Y),PanelComponent:({appState:t,updateData:o,data:n,app:r})=>{let{isRedoStackEmpty:i}=p0(e.onHistoryChangedEmitter,new aa(e.isUndoStackEmpty,e.isRedoStackEmpty)),a=_t()==="mobile";return N5(ne,{type:"button",icon:lh,"aria-label":f("buttons.redo"),onClick:o,size:n?.size||"medium",disabled:i,"data-testid":"button-redo",style:{...a?L5:{}}})}});import{getFontString as Fz}from"@orangecatai/common";import{newElementWith as Oz}from"@orangecatai/element";import{measureText as zz}from"@orangecatai/element";import{isTextElement as B5}from"@orangecatai/element";import{CaptureUpdateAction as Hz}from"@orangecatai/element";var F5=W({name:"autoResize",label:"labels.autoResize",icon:null,trackEvent:{category:"element"},predicate:(e,t,o,n)=>{let r=le(e,t);return r.length===1&&B5(r[0])&&!r[0].autoResize},perform:(e,t,o,n)=>{let r=le(e,t);return{appState:t,elements:e.map(i=>{if(i.id===r[0].id&&B5(i)){let a=zz(i.originalText,Fz(i),i.lineHeight);return Oz(i,{autoResize:!0,width:a.width,height:a.height,text:i.originalText})}return i}),captureUpdate:Hz.IMMEDIATELY}}});import{isPromiseLike as Gz}from"@orangecatai/common";import{jsx as Uz}from"react/jsx-runtime";var h0=(e,t,o,n,r,i)=>{if(e.trackEvent)try{typeof e.trackEvent=="object"&&(!e.trackEvent.predicate||e.trackEvent.predicate(o,n,i))&&ge(e.trackEvent.category,e.trackEvent.action||e.name,`${t} (${r.editorInterface.formFactor==="phone"?"mobile":"desktop"})`)}catch(a){console.error("error while logging action:",a)}},nu=class{constructor(t,o,n,r){A(this,"actions",{});A(this,"updater");A(this,"getAppState");A(this,"getElementsIncludingDeleted");A(this,"app");A(this,"renderAction",(t,o)=>{let n=this.app.props.UIOptions.canvasActions;if(this.actions[t]&&"PanelComponent"in this.actions[t]&&(!(t in n)||n[t])){let r=this.actions[t],i=r.PanelComponent;i.displayName="PanelComponent";let a=this.getElementsIncludingDeleted(),s=this.getAppState(),l=c=>{h0(r,"ui",s,a,this.app,c),this.updater(r.perform(this.getElementsIncludingDeleted(),this.getAppState(),c,this.app))};return Uz(i,{elements:this.getElementsIncludingDeleted(),appState:this.getAppState(),updateData:l,appProps:this.app.props,app:this.app,data:o,renderAction:this.renderAction})}return null});A(this,"isActionEnabled",t=>{let o=this.getElementsIncludingDeleted(),n=this.getAppState();return!t.predicate||t.predicate(o,n,this.app.props,this.app)});this.updater=i=>{if(Gz(i))i.then(a=>t(a));else return t(i)},this.getAppState=o,this.getElementsIncludingDeleted=n,this.app=r}registerAction(t){this.actions[t.name]=t}registerAll(t){t.forEach(o=>this.registerAction(o))}handleKeyDown(t){let o=this.app.props.UIOptions.canvasActions,n=Object.values(this.actions).sort((l,c)=>(c.keyPriority||0)-(l.keyPriority||0)).filter(l=>(l.name in o?o[l.name]:!0)&&l.keyTest&&l.keyTest(t,this.getAppState(),this.getElementsIncludingDeleted(),this.app));if(n.length!==1)return n.length>1&&console.warn("Canceling as multiple actions match this shortcut",n),!1;let r=n[0];if(this.getAppState().viewModeEnabled&&r.viewMode!==!0)return!1;let i=this.getElementsIncludingDeleted(),a=this.getAppState(),s=null;return h0(r,"keyboard",a,i,this.app,null),t.preventDefault(),t.stopPropagation(),this.updater(n[0].perform(i,a,s,this.app)),!0}executeAction(t,o="api",n=null){let r=this.getElementsIncludingDeleted(),i=this.getAppState();h0(t,o,i,r,this.app,n),this.updater(t.perform(r,i,n,this.app))}};var ru=class{constructor(){A(this,"targets",new WeakMap);A(this,"rafIds",new WeakMap)}register(t,o){this.targets.set(t,{callback:o,stopped:!0})}start(t){let o=this.targets.get(t);o&&(this.rafIds.has(t)||(this.targets.set(t,{...o,stopped:!1}),this.scheduleFrame(t)))}stop(t){let o=this.targets.get(t);o&&!o.stopped&&this.targets.set(t,{...o,stopped:!0}),this.cancelFrame(t)}constructFrame(t){return o=>{let n=this.targets.get(t);if(!n)return;let r=this.onFrame(n,o);!n.stopped&&!r?this.scheduleFrame(t):this.cancelFrame(t)}}scheduleFrame(t){let o=requestAnimationFrame(this.constructFrame(t));this.rafIds.set(t,o)}cancelFrame(t){if(this.rafIds.has(t)){let o=this.rafIds.get(t);cancelAnimationFrame(o)}this.rafIds.delete(t)}onFrame(t,o){return t.callback(o)??!1}};var f0=e=>{let t=Array.from(e.values());return{x:O5(t,o=>o.x)/t.length,y:O5(t,o=>o.y)/t.length}},b0=([e,t])=>Math.hypot(e.x-t.x,e.y-t.y),O5=(e,t)=>e.reduce((o,n)=>o+t(n),0);import{pointFrom as q,pointRotateRads as ii,rangeInclusive as Vo,rangeIntersection as iu,rangesOverlap as au}from"@orangecatai/math";import{TOOL_TYPE as sa,KEYS as z5}from"@orangecatai/common";import{getCommonBounds as x0,getDraggedElementsBounds as E0,getElementAbsoluteCoords as Wz}from"@orangecatai/element";import{isBoundToContainer as W5}from"@orangecatai/element";import{getMaximumGroups as Y5}from"@orangecatai/element";import{getSelectedElements as Yz,getVisibleAndNonSelectedElements as V5}from"@orangecatai/element";var Vz=8,H5=99999,su=e=>Vz/e,ao=class ao{};A(ao,"referenceSnapPoints",null),A(ao,"visibleGaps",null),A(ao,"setReferenceSnapPoints",t=>{ao.referenceSnapPoints=t}),A(ao,"getReferenceSnapPoints",()=>ao.referenceSnapPoints),A(ao,"setVisibleGaps",t=>{ao.visibleGaps=t}),A(ao,"getVisibleGaps",()=>ao.visibleGaps),A(ao,"destroy",()=>{ao.referenceSnapPoints=null,ao.visibleGaps=null});var $o=ao,ai=e=>e.props.gridModeEnabled??e.state.gridModeEnabled,wr=({event:e,app:t,selectedElements:o})=>{if(e){let n=t.state.activeTool.type==="lasso"&&t.state.selectedElementsAreBeingDragged;return(t.state.activeTool.type!=="lasso"||n)&&(t.state.objectsSnapModeEnabled&&!e[z5.CTRL_OR_CMD]||!t.state.objectsSnapModeEnabled&&e[z5.CTRL_OR_CMD]&&!ai(t))}return o.length===1&&o[0].type==="arrow"?!1:t.state.objectsSnapModeEnabled},$z=(e,t,o=.01)=>Math.abs(e-t)<=o,jc=(e,t,{omitCenter:o,boundingBoxCorners:n,dragOffset:r}={omitCenter:!1,boundingBoxCorners:!1})=>{let i=[];if(e.length===1){let a=e[0],[s,l,c,m,p,d]=Wz(a,t);r&&(s+=r.x,c+=r.x,p+=r.x,l+=r.y,m+=r.y,d+=r.y);let u=(c-s)/2,h=(m-l)/2;if((a.type==="diamond"||a.type==="ellipse")&&!n){let g=ii(q(s,l+h),q(p,d),a.angle),E=ii(q(s+u,l),q(p,d),a.angle),w=ii(q(c,l+h),q(p,d),a.angle),x=ii(q(s+u,m),q(p,d),a.angle),y=q(p,d);i=o?[g,E,w,x]:[g,E,w,x,y]}else{let g=ii(q(s,l),q(p,d),a.angle),E=ii(q(c,l),q(p,d),a.angle),w=ii(q(s,m),q(p,d),a.angle),x=ii(q(c,m),q(p,d),a.angle),y=q(p,d);i=o?[g,E,w,x]:[g,E,w,x,y]}}else if(e.length>1){let[a,s,l,c]=E0(e,r??{x:0,y:0}),m=l-a,p=c-s,d=q(a,s),u=q(l,s),h=q(a,c),g=q(l,c),E=q(a+m/2,s+p/2);i=o?[d,u,h,g]:[d,u,h,g,E]}return i.map(a=>q(dt(a[0]),dt(a[1])))},$5=(e,t,o,n)=>V5(e,t,o,n),K5=(e,t,o,n)=>{let r=$5(e,t,o,n),i=Y5(r,n).filter(p=>!(p.length===1&&W5(p[0]))).map(p=>x0(p).map(d=>dt(d))),a=i.sort((p,d)=>p[0]-d[0]),s=[],l=0;e:for(let p=0;p<a.length;p++){let d=a[p];for(let u=p+1;u<a.length;u++){if(++l>H5)break e;let h=a[u],[,g,E,w]=d,[x,y,,v]=h;E<x&&au(Vo(g,w),Vo(y,v))&&s.push({startBounds:d,endBounds:h,startSide:[q(E,g),q(E,w)],endSide:[q(x,y),q(x,v)],length:x-E,overlap:iu(Vo(g,w),Vo(y,v))})}}let c=i.sort((p,d)=>p[1]-d[1]),m=[];l=0;e:for(let p=0;p<c.length;p++){let d=c[p];for(let u=p+1;u<c.length;u++){if(++l>H5)break e;let h=c[u],[g,,E,w]=d,[x,y,v]=h;w<y&&au(Vo(g,E),Vo(x,v))&&m.push({startBounds:d,endBounds:h,startSide:[q(g,w),q(E,w)],endSide:[q(x,y),q(v,y)],length:y-w,overlap:iu(Vo(g,E),Vo(x,v))})}}return{horizontalGaps:s,verticalGaps:m}},G5=(e,t,o,n,r,i,a)=>{if(!wr({app:o,event:n,selectedElements:e}))return[];if(e.length===0)return[];let s=$o.getVisibleGaps();if(s){let{horizontalGaps:l,verticalGaps:c}=s,[m,p,d,u]=E0(e,t).map(E=>dt(E)),h=(m+d)/2,g=(p+u)/2;for(let E of l){if(!au(Vo(p,u),E.overlap))continue;let w=E.startSide[0][0]+E.length/2,x=dt(w-h);if(E.length>d-m&&Math.abs(x)<=a.x){Math.abs(x)<a.x&&(r.length=0),a.x=Math.abs(x);let P={type:"gap",direction:"center_horizontal",gap:E,offset:x};r.push(P);continue}let[,,v]=E.endBounds,I=m-v,k=dt(E.length-I);if(Math.abs(k)<=a.x){Math.abs(k)<a.x&&(r.length=0),a.x=Math.abs(k);let P={type:"gap",direction:"side_right",gap:E,offset:k};r.push(P);continue}let[L,,,]=E.startBounds,S=L-d,_=dt(S-E.length);if(Math.abs(_)<=a.x){Math.abs(_)<a.x&&(r.length=0),a.x=Math.abs(_);let P={type:"gap",direction:"side_left",gap:E,offset:_};r.push(P);continue}}for(let E of c){if(!au(Vo(m,d),E.overlap))continue;let w=E.startSide[0][1]+E.length/2,x=dt(w-g);if(E.length>u-p&&Math.abs(x)<=a.y){Math.abs(x)<a.y&&(i.length=0),a.y=Math.abs(x);let P={type:"gap",direction:"center_vertical",gap:E,offset:x};i.push(P);continue}let[,v,,]=E.startBounds,I=v-u,k=dt(I-E.length);if(Math.abs(k)<=a.y){Math.abs(k)<a.y&&(i.length=0),a.y=Math.abs(k);let P={type:"gap",direction:"side_top",gap:E,offset:k};i.push(P);continue}let[,,,L]=E.endBounds,S=dt(p-L),_=E.length-S;if(Math.abs(_)<=a.y){Math.abs(_)<a.y&&(i.length=0),a.y=Math.abs(_);let P={type:"gap",direction:"side_bottom",gap:E,offset:_};i.push(P);continue}}}},X5=(e,t,o,n)=>{let r=$5(e,t,o,n);return Y5(r,n).filter(i=>!(i.length===1&&W5(i[0]))).flatMap(i=>jc(i,n))},tl=(e,t,o,n,r,i,a)=>{if(!wr({app:o,event:n,selectedElements:e})||e.length===0&&t.length===0)return[];let s=$o.getReferenceSnapPoints();if(s)for(let l of t)for(let c of s){let m=c[0]-l[0],p=c[1]-l[1];Math.abs(m)<=a.x&&(Math.abs(m)<a.x&&(r.length=0),r.push({type:"point",points:[l,c],offset:m}),a.x=Math.abs(m)),Math.abs(p)<=a.y&&(Math.abs(p)<a.y&&(i.length=0),i.push({type:"point",points:[l,c],offset:p}),a.y=Math.abs(p))}},Z5=(e,t,o,n,r)=>{let i=o.state,a=Yz(e,i);if(!wr({app:o,event:n,selectedElements:a})||a.length===0)return{snapOffset:{x:0,y:0},snapLines:[]};t.x=dt(t.x),t.y=dt(t.y);let s=[],l=[],c=su(i.zoom.value),m={x:c,y:c},p=jc(a,r,{dragOffset:t});tl(a,p,o,n,s,l,m),G5(a,t,o,n,s,l,m);let d={x:s[0]?.offset??0,y:l[0]?.offset??0};m.x=0,m.y=0,s.length=0,l.length=0;let u={x:dt(t.x+d.x),y:dt(t.y+d.y)};tl(a,jc(a,r,{dragOffset:u}),o,n,s,l,m),G5(a,u,o,n,s,l,m);let h=y0(s,l),g=Xz(a,u,[...s,...l].filter(E=>E.type==="gap"));return{snapOffset:d,snapLines:[...h,...g]}},dt=e=>Math.round(e*10**6)/10**6,U5=e=>{let t=new Map;for(let o of e){let n=o.join(",");t.has(n)||t.set(n,o)}return Array.from(t.values())},y0=(e,t)=>{let o={},n={};if(e.length>0){for(let r of e)if(r.type==="point"){let i=dt(r.points[0][0]);o[i]||(o[i]=[]),o[i].push(...r.points.map(a=>q(dt(a[0]),dt(a[1]))))}}if(t.length>0){for(let r of t)if(r.type==="point"){let i=dt(r.points[0][1]);n[i]||(n[i]=[]),n[i].push(...r.points.map(a=>q(dt(a[0]),dt(a[1]))))}}return Object.entries(o).map(([r,i])=>({type:"points",points:U5(i.map(a=>q(Number(r),a[1])).sort((a,s)=>a[1]-s[1]))})).concat(Object.entries(n).map(([r,i])=>({type:"points",points:U5(i.map(a=>q(a[0],Number(r))).sort((a,s)=>a[0]-s[0]))})))},Kz=e=>{let t=new Map;for(let o of e){let n=o.points.flat().map(r=>[dt(r)]).join(",");t.has(n)||t.set(n,o)}return Array.from(t.values())},Xz=(e,t,o)=>{let[n,r,i,a]=E0(e,t),s=[];for(let l of o){let[c,m,p,d]=l.gap.startBounds,[u,h,g,E]=l.gap.endBounds,w=iu(Vo(r,a),l.gap.overlap),x=iu(Vo(n,i),l.gap.overlap);switch(l.direction){case"center_horizontal":{if(w){let y=(w[0]+w[1])/2;s.push({type:"gap",direction:"horizontal",points:[q(l.gap.startSide[0][0],y),q(n,y)]},{type:"gap",direction:"horizontal",points:[q(i,y),q(l.gap.endSide[0][0],y)]})}break}case"center_vertical":{if(x){let y=(x[0]+x[1])/2;s.push({type:"gap",direction:"vertical",points:[q(y,l.gap.startSide[0][1]),q(y,r)]},{type:"gap",direction:"vertical",points:[q(y,a),q(y,l.gap.endSide[0][1])]})}break}case"side_right":{if(w){let y=(w[0]+w[1])/2;s.push({type:"gap",direction:"horizontal",points:[q(p,y),q(u,y)]},{type:"gap",direction:"horizontal",points:[q(g,y),q(n,y)]})}break}case"side_left":{if(w){let y=(w[0]+w[1])/2;s.push({type:"gap",direction:"horizontal",points:[q(i,y),q(c,y)]},{type:"gap",direction:"horizontal",points:[q(p,y),q(u,y)]})}break}case"side_top":{if(x){let y=(x[0]+x[1])/2;s.push({type:"gap",direction:"vertical",points:[q(y,a),q(y,m)]},{type:"gap",direction:"vertical",points:[q(y,d),q(y,h)]})}break}case"side_bottom":{if(x){let y=(x[0]+x[1])/2;s.push({type:"gap",direction:"vertical",points:[q(y,d),q(y,h)]},{type:"gap",direction:"vertical",points:[q(y,E),q(y,r)]})}break}}}return Kz(s.map(l=>({...l,points:l.points.map(c=>q(dt(c[0]),dt(c[1])))})))},w0=(e,t,o,n,r,i)=>{if(!wr({event:n,selectedElements:e,app:o})||e.length===0||e.length===1&&!$z(e[0].angle,0))return{snapOffset:{x:0,y:0},snapLines:[]};let[a,s,l,c]=x0(t);i&&(i.includes("e")?l+=r.x:i.includes("w")&&(a+=r.x),i.includes("n")?s+=r.y:i.includes("s")&&(c+=r.y));let m=[];if(i)switch(i){case"e":{m.push(q(l,s),q(l,c));break}case"w":{m.push(q(a,s),q(a,c));break}case"n":{m.push(q(a,s),q(l,s));break}case"s":{m.push(q(a,c),q(l,c));break}case"ne":{m.push(q(l,s));break}case"nw":{m.push(q(a,s));break}case"se":{m.push(q(l,c));break}case"sw":{m.push(q(a,c));break}}let p=su(o.state.zoom.value),d={x:p,y:p},u=[],h=[];tl(t,m,o,n,u,h,d);let g={x:u[0]?.offset??0,y:h[0]?.offset??0};d.x=0,d.y=0,u.length=0,h.length=0;let[E,w,x,y]=x0(e).map(k=>dt(k)),v=[q(E,w),q(E,y),q(x,w),q(x,y)];tl(e,v,o,n,u,h,d);let I=y0(u,h);return{snapOffset:g,snapLines:I}},j5=(e,t,o,n,r,i)=>{if(!wr({event:o,selectedElements:[e],app:t}))return{snapOffset:{x:0,y:0},snapLines:[]};let a=[q(n.x+r.x,n.y+r.y)],s=su(t.state.zoom.value),l={x:s,y:s},c=[],m=[];tl([e],a,t,o,c,m,l);let p={x:c[0]?.offset??0,y:m[0]?.offset??0};l.x=0,l.y=0,c.length=0,m.length=0;let d=jc([e],i,{boundingBoxCorners:!0,omitCenter:!0});tl([e],d,t,o,c,m,l);let u=y0(c,m);return{snapOffset:p,snapLines:u}},q5=(e,t,o,n,r)=>{if(!wr({event:n,selectedElements:[],app:t}))return{originOffset:{x:0,y:0},snapLines:[]};let i=V5(e,[],t.state,r),a=su(t.state.zoom.value),s={x:a,y:a},l=[],c=[];for(let m of i){let p=jc([m],r);for(let d of p){let u=d[0]-o.x;Math.abs(u)<=Math.abs(s.x)&&(Math.abs(u)<Math.abs(s.x)&&(c.length=0),c.push({type:"pointer",points:[d,q(d[0],o.y)],direction:"vertical"}),s.x=u);let h=d[1]-o.y;Math.abs(h)<=Math.abs(s.y)&&(Math.abs(h)<Math.abs(s.y)&&(l.length=0),l.push({type:"pointer",points:[d,q(o.x,d[1])],direction:"horizontal"}),s.y=h)}}return{originOffset:{x:c.length>0?c[0].points[0][0]-o.x:0,y:l.length>0?l[0].points[0][1]-o.y:0},snapLines:[...c,...l]}},J5=e=>e===sa.rectangle||e===sa.ellipse||e===sa.diamond||e===sa.frame||e===sa.magicframe||e===sa.image||e===sa.text;import{isElementInViewport as Zz}from"@orangecatai/element";import{memoize as jz,toBrandedType as qz}from"@orangecatai/common";var qc=class{constructor(t){A(this,"scene");A(this,"getRenderableElements",(()=>{let t=({elementsMap:n,zoom:r,offsetLeft:i,offsetTop:a,scrollX:s,scrollY:l,height:c,width:m})=>{let p=[];for(let d of n.values())Zz(d,m,c,{zoom:r,offsetLeft:i,offsetTop:a,scrollX:s,scrollY:l},n)&&p.push(d);return p},o=({elements:n,editingTextElement:r,newElementId:i})=>{let a=qz(new Map);for(let s of n)i!==s.id&&(!r||r.type!=="text"||s.id!==r.id)&&a.set(s.id,s);return a};return jz(({zoom:n,offsetLeft:r,offsetTop:i,scrollX:a,scrollY:s,height:l,width:c,editingTextElement:m,newElementId:p,sceneNonce:d})=>{let u=this.scene.getNonDeletedElements(),h=o({elements:u,editingTextElement:m,newElementId:p}),g=t({elementsMap:h,zoom:n,offsetLeft:r,offsetTop:i,scrollX:a,scrollY:s,height:l,width:c});return{elementsMap:h,visibleElements:g}})})());this.scene=t}destroy(){YE.cancel(),this.getRenderableElements.clear()}};import{sceneCoordsToViewportCoords as Jz}from"@orangecatai/common";import{getElementAbsoluteCoords as Qz}from"@orangecatai/element";import{jsx as oH}from"react/jsx-runtime";var eH=5,tH=(e,t,o)=>{let[n,r]=Qz(e,o),{x:i,y:a}=Jz({sceneX:n+e.width,sceneY:r},t),s=i-t.offsetLeft+10,l=a-t.offsetTop;return{x:s,y:l}},v0=({children:e,element:t,elementsMap:o})=>{let n=Go();if(n.contextMenu||n.newElement||n.resizingElement||n.isRotating||n.openMenu||n.viewModeEnabled)return null;let{x:r,y:i}=tH(t,n,o);return oH("div",{className:"excalidraw-canvas-buttons",style:{top:`${i}px`,left:`${r}px`,padding:eH},children:e})};import{useCallback as Jc,useEffect as C0,useRef as nH,useState as Qc}from"react";import{sceneCoordsToViewportCoords as rH}from"@orangecatai/common";import{getElementAbsoluteCoords as iH}from"@orangecatai/element";import{isFrameLikeElement as aH}from"@orangecatai/element";var la={element:null,isOpen:!1,isRunning:!1},T0=new Set;function I0(){T0.forEach(e=>e(la))}var bn={open(e){la={...la,element:e,isOpen:!0},I0()},close(){la={element:null,isOpen:!1,isRunning:!1},I0()},setRunning(e){la={...la,isRunning:e},I0()},getState(){return la},subscribe(e){return T0.add(e),()=>T0.delete(e)}};import{Fragment as Q5,jsx as Te,jsxs as Lo}from"react/jsx-runtime";var e3=[{label:"1:1",width:1024,height:1024,icon:"square"},{label:"2:3",width:1024,height:1536,icon:"portrait"},{label:"9:16",width:1080,height:1920,icon:"portrait-tall"},{label:"3:2",width:1536,height:1024,icon:"landscape"},{label:"16:9",width:1920,height:1080,icon:"landscape-wide"},{label:"A4",width:1024,height:1754,icon:"portrait"},{label:"Website",width:1366,height:768,icon:"landscape-wide"}],k0=e=>{let t={border:"1.5px solid currentColor",borderRadius:2,boxSizing:"border-box"};switch(e){case"square":return Te("div",{style:{...t,width:14,height:14}});case"portrait":return Te("div",{style:{...t,width:10,height:14}});case"portrait-tall":return Te("div",{style:{...t,width:8,height:14}});case"landscape":return Te("div",{style:{...t,width:14,height:10}});case"landscape-wide":return Te("div",{style:{...t,width:14,height:8}});default:return Te("div",{style:{...t,width:14,height:14}})}},sH=({active:e})=>Te("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:e?Lo(Q5,{children:[Te("path",{d:"M5 3H4C3.44772 3 3 3.44772 3 4V10C3 10.5523 3.44772 11 4 11H5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),Te("path",{d:"M9 3H10C10.5523 3 11 3.44772 11 4V10C11 10.5523 10.5523 11 10 11H9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),Te("line",{x1:"5",y1:"7",x2:"9",y2:"7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}):Lo(Q5,{children:[Te("path",{d:"M5 3H4C3.44772 3 3 3.44772 3 4V10C3 10.5523 3.44772 11 4 11H5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"}),Te("path",{d:"M9 3H10C10.5523 3 11 3.44772 11 4V10C11 10.5523 10.5523 11 10 11H9",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]})}),lH=()=>Lo("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:[Te("path",{d:"M8 2V10M8 10L5 7M8 10L11 7",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"}),Te("path",{d:"M3 12H13",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})]}),cH=()=>Te("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:Te("path",{d:"M2.5 3.75L5 6.25L7.5 3.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),dH=()=>Te("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",xmlns:"http://www.w3.org/2000/svg",children:Te("path",{d:"M3.5 8.5L6.5 11.5L12.5 4.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),mH=()=>Lo("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:[Te("rect",{x:"1.5",y:"1.5",width:"6.5",height:"6.5",rx:"1",stroke:"currentColor",strokeWidth:"1.4"}),Te("rect",{x:"8",y:"8",width:"6.5",height:"6.5",rx:"1",stroke:"currentColor",strokeWidth:"1.4",strokeDasharray:"2 1.2",opacity:"0.65"}),Te("path",{d:"M10.5 5.5H13.5V2.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),pH=(e,t)=>e3.find(o=>o.width===e&&o.height===t)||null,t3=({element:e,app:t})=>{let o=t.state,[n,r]=Qc(!1),[i,a]=Qc(!0),[s,l]=Qc(Math.round(e.width)),[c,m]=Qc(Math.round(e.height)),[p,d]=Qc(bn.getState()),u=nH(null);C0(()=>bn.subscribe(d),[]),C0(()=>{l(Math.round(e.width)),m(Math.round(e.height))},[e.width,e.height]),C0(()=>{let P=T=>{u.current&&!u.current.contains(T.target)&&r(!1)};if(n)return document.addEventListener("mousedown",P),()=>document.removeEventListener("mousedown",P)},[n]);let h=pH(Math.round(e.width),Math.round(e.height)),[g,E]=iH(e,t.scene.getNonDeletedElementsMap()),{x:w,y:x}=rH({sceneX:g+e.width/2,sceneY:E},o),y=w-o.offsetLeft,v=Math.max(x-o.offsetTop-82,8),I=Jc((P,T)=>{P>0&&T>0&&t.scene.mutateElement(e,{width:P,height:T})},[t.scene,e]),k=Jc(P=>{let T=parseInt(P,10);if(!isNaN(T)&&T>0)if(l(T),i){let M=e.height/e.width,N=Math.round(T*M);m(N),I(T,N)}else I(T,e.height)},[i,e.width,e.height,I]),L=Jc(P=>{let T=parseInt(P,10);if(!isNaN(T)&&T>0)if(m(T),i){let M=e.width/e.height,N=Math.round(T*M);l(N),I(N,T)}else I(e.width,T)},[i,e.width,e.height,I]),S=Jc(P=>{l(P.width),m(P.height),I(P.width,P.height),r(!1)},[I]),_=Jc(()=>{aH(e)&&t.onExportImage("png",t.getSceneElements(),{exportingFrame:e})},[t,e]);return o.contextMenu||o.newElement||o.resizingElement||o.isRotating||o.openMenu||o.viewModeEnabled||o.selectedElementsAreBeingDragged?null:Lo("div",{className:"frame-toolbar",style:{left:`${y}px`,top:`${v}px`},onPointerDown:P=>P.stopPropagation(),onClick:P=>P.stopPropagation(),children:[Lo("div",{className:"frame-toolbar__section",ref:u,children:[Lo("button",{className:"frame-toolbar__ratio-btn",onClick:()=>r(!n),title:"Frame format",children:[k0(h?h.icon:"square"),Te("span",{children:h?.label||"Custom"}),Te(cH,{})]}),n&&Lo("div",{className:"frame-toolbar__dropdown",children:[Te("div",{style:{padding:"6px 12px",fontSize:11,fontWeight:600,color:"var(--text-secondary-color, #888)",textTransform:"uppercase",letterSpacing:"0.5px"},children:"Format"}),e3.map(P=>{let T=h?.label===P.label;return Lo("button",{className:"frame-toolbar__dropdown-item",onClick:()=>S(P),children:[k0(P.icon),Te("span",{className:"frame-toolbar__dropdown-item-label",children:P.label}),Lo("span",{className:"frame-toolbar__dropdown-item-dims",children:[P.width,"*",P.height]}),T&&Te("span",{className:"frame-toolbar__dropdown-item-check",children:Te(dH,{})})]},P.label)})]})]}),Te("div",{className:"frame-toolbar__divider"}),Lo("div",{className:"frame-toolbar__input-group",children:[Te("label",{children:"W"}),Te("input",{type:"number",value:s,onChange:P=>k(P.target.value),onPointerDown:P=>P.stopPropagation(),min:1})]}),Te("button",{className:`frame-toolbar__constrain-btn ${i?"frame-toolbar__constrain-btn--active":""}`,onClick:()=>a(!i),title:i?"Unlock proportions":"Constrain proportions",children:Te(sH,{active:i})}),Lo("div",{className:"frame-toolbar__input-group",children:[Te("label",{children:"H"}),Te("input",{type:"number",value:c,onChange:P=>L(P.target.value),onPointerDown:P=>P.stopPropagation(),min:1})]}),Te("div",{className:"frame-toolbar__divider"}),Te("button",{className:"frame-toolbar__export-btn",onClick:_,title:"Export frame as PNG",children:Te(lH,{})}),Te("div",{className:"frame-toolbar__divider"}),Te("div",{className:"frame-toolbar__section",children:Lo("button",{className:`frame-toolbar__btn ${p.isOpen&&p.element?.id===e.id?"frame-toolbar__btn--active":""}`,onClick:()=>{p.isOpen&&p.element?.id===e.id?p.isRunning||bn.close():bn.open(e)},title:"Auto resize to multiple dimensions",children:[Te(mH,{}),Te("span",{children:"Resize"})]})})]})};import{useEffect as uH,useReducer as gH}from"react";import{sceneCoordsToViewportCoords as hH}from"@orangecatai/common";var ed=[],M0=new Set;function S0(){M0.forEach(e=>e())}var vr={setLoadingFrames(e){ed=[...e],S0()},markComplete(e){ed=ed.filter(t=>t.frameId!==e),S0()},clear(){ed=[],S0()},getLoadingFrames(){return ed},subscribe(e){return M0.add(e),()=>M0.delete(e)}};import{Fragment as fH,jsx as o3}from"react/jsx-runtime";var n3=()=>{let e=Go(),[,t]=gH(r=>r+1,0);uH(()=>vr.subscribe(t),[]);let o=vr.getLoadingFrames();if(o.length===0)return null;let n=e.zoom.value;return o3(fH,{children:o.map(r=>{let{x:i,y:a}=hH({sceneX:r.x,sceneY:r.y},e),s=i-e.offsetLeft,l=a-e.offsetTop,c=r.width*n,m=r.height*n;return o3("div",{className:"ars-shimmer",style:{position:"absolute",left:s,top:l,width:c,height:m,pointerEvents:"none",zIndex:5,overflow:"hidden",boxSizing:"border-box"}},r.frameId)})})};import{useEffect as k3,useRef as bG,useState as xG}from"react";import{sceneCoordsToViewportCoords as EG}from"@orangecatai/common";import{getElementAbsoluteCoords as yG}from"@orangecatai/element";import{useCallback as R0,useEffect as pG,useRef as uG,useState as ga}from"react";function ol(e){let t=e?.trim();return(t||void 0)??(typeof import.meta<"u"&&C?.VITE_APP_GEMINI_API_KEY?C.VITE_APP_GEMINI_API_KEY:"")??""}import{nanoid as p3}from"nanoid";import{newFrameElement as f3,newElement as u3,newTextElement as XH,newImageElement as g3,getFrameChildren as b3,syncMovedIndices as yu}from"@orangecatai/element";import{FRAME_STYLE as x3,arrayToMap as wu}from"@orangecatai/common";import{useCallback as ma,useEffect as od,useRef as li,useState as Yn}from"react";import{sceneCoordsToViewportCoords as SH}from"@orangecatai/common";import{CaptureUpdateAction as A0,getElementAbsoluteCoords as MH}from"@orangecatai/element";import{ArrowUp as PH,ImagePlus as AH,X as LH}from"lucide-react";var Ir=new Map;function lu(e,t,o,n){Ir.set(e,{subscribers:new Set,prompt:t,settings:o,controller:n})}function cu(e,t){let o=Ir.get(e);o&&(o.finishedError=t,o.subscribers.forEach(n=>n(t)))}function du(e,t){let o=Ir.get(e);return o?(o.subscribers.add(t),o.finishedError!==void 0&&t(o.finishedError),!0):!1}function mu(e,t){Ir.get(e)?.subscribers.delete(t)}function pu(e){Ir.delete(e)}function uu(e){Ir.get(e)?.controller.abort()}function gu(e){return Ir.get(e)?.prompt??""}function si(e){return Ir.get(e)?.settings??null}function ca(e){return Ir.has(e)}import yH,{createContext as wH,useContext as vH,useLayoutEffect as IH,useRef as TH,useState as CH}from"react";import{clsx as bH}from"clsx";import{twMerge as xH}from"tailwind-merge";function Ze(...e){return xH(bH(e))}import*as r3 from"react";import{jsx as EH}from"react/jsx-runtime";var P0=r3.forwardRef(({className:e,...t},o)=>EH("textarea",{className:Ze("flex min-h-[60px] w-full rounded-md border border-zinc-200 bg-transparent px-3 py-2 text-base shadow-sm placeholder:text-zinc-500 focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-950 disabled:cursor-not-allowed disabled:opacity-50 md:text-sm dark:border-zinc-800 dark:placeholder:text-zinc-400 dark:focus-visible:ring-zinc-300",e),ref:o,...t}));P0.displayName="Textarea";import*as a3 from"react";import*as xn from"@radix-ui/react-tooltip";import{jsx as i3}from"react/jsx-runtime";var hu=xn.Provider,fu=xn.Root,bu=xn.Trigger,td=a3.forwardRef(({className:e,sideOffset:t=4,...o},n)=>i3(xn.Portal,{children:i3(xn.Content,{ref:n,sideOffset:t,className:Ze("z-50 overflow-hidden rounded-md bg-zinc-900 px-3 py-1.5 text-xs text-zinc-50 animate-in fade-in-0 zoom-in-95 data-[state=closed]:animate-out data-[state=closed]:fade-out-0 data-[state=closed]:zoom-out-95 data-[side=bottom]:slide-in-from-top-2 data-[side=left]:slide-in-from-right-2 data-[side=right]:slide-in-from-left-2 data-[side=top]:slide-in-from-bottom-2 origin-[--radix-tooltip-content-transform-origin] dark:bg-zinc-50 dark:text-zinc-900",e),...o})}));td.displayName=xn.Content.displayName;import{jsx as da,jsxs as kH}from"react/jsx-runtime";var s3=wH({isLoading:!1,value:"",setValue:()=>{},maxHeight:320,onSubmit:void 0,disabled:!1,textareaRef:yH.createRef()});function l3(){return vH(s3)}function nl({className:e,isLoading:t=!1,maxHeight:o=320,value:n,onValueChange:r,onSubmit:i,children:a,disabled:s=!1,onClick:l,...c}){let[m,p]=CH(n||""),d=TH(null),u=g=>{p(g),r?.(g)},h=g=>{s||d.current?.focus(),l?.(g)};return da(hu,{children:da(s3.Provider,{value:{isLoading:t,value:n??m,setValue:r??u,maxHeight:o,onSubmit:i,disabled:s,textareaRef:d},children:da("div",{onClick:h,className:Ze("border-zinc-200 bg-white cursor-text rounded-3xl border p-2 shadow-xs dark:border-zinc-800 dark:bg-zinc-950",s&&"cursor-not-allowed opacity-60",e),...c,children:a})})})}function rl({className:e,onKeyDown:t,disableAutosize:o=!1,...n}){let{value:r,setValue:i,maxHeight:a,onSubmit:s,disabled:l,textareaRef:c}=l3(),m=h=>{if(!h||o)return;h.style.height="auto";let g;typeof a=="number"?(h.style.height=`${Math.min(h.scrollHeight,a)}px`,g=a):(h.style.height=`min(${h.scrollHeight}px, ${a})`,g=1/0),h.style.overflowY=h.scrollHeight>g?"auto":"hidden"},p=h=>{c.current=h,m(h)};return IH(()=>{m(c.current)},[r,a,o]),da(P0,{ref:p,value:r,onChange:h=>{m(h.target),i(h.target.value)},onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),s?.()),t?.(h)},onWheel:h=>{h.stopPropagation()},className:Ze("text-zinc-900 min-h-[44px] w-full resize-none border-none bg-transparent shadow-none outline-none focus-visible:ring-0 focus-visible:ring-offset-0 dark:text-zinc-50",e),rows:1,disabled:l,...n})}function il({children:e,className:t,...o}){return da("div",{className:Ze("flex items-center gap-2",t),...o,children:e})}function Tr({tooltip:e,children:t,className:o,side:n="top",...r}){let{disabled:i}=l3();return kH(fu,{...r,children:[da(bu,{asChild:!0,disabled:i,onClick:a=>a.stopPropagation(),children:t}),da(td,{side:n,className:o,children:e})]})}import{jsx as be,jsxs as Mt}from"react/jsx-runtime";var ci={"Gemini 2.5 Flash":{geminiModelId:"gemini-3.1-flash-image-preview",supportsImageSize:!1,supportsThinking:!1,supportedResolutions:["1K"],supportedRatios:["21:9","16:9","4:3","3:2","1:1","9:16","3:4","2:3","5:4","4:5"]},"Gemini 3.1 Flash":{geminiModelId:"gemini-3.1-flash-image-preview",supportsImageSize:!0,supportsThinking:!0,supportedResolutions:["0.5K","1K","2K","4K"],supportedRatios:["21:9","16:9","4:3","3:2","1:1","9:16","3:4","2:3","5:4","4:5","4:1","1:4","8:1","1:8"]},"Gemini 3 Pro":{geminiModelId:"gemini-3-pro-image-preview",supportsImageSize:!0,supportsThinking:!1,supportedResolutions:["1K","2K","4K"],supportedRatios:["21:9","16:9","4:3","3:2","1:1","9:16","3:4","2:3","5:4","4:5"]}},D0=Object.keys(ci),_H={"Gemini 2.5 Flash":{"1:1":{"1K":{w:1024,h:1024}},"2:3":{"1K":{w:832,h:1248}},"3:2":{"1K":{w:1248,h:832}},"3:4":{"1K":{w:864,h:1184}},"4:3":{"1K":{w:1184,h:864}},"4:5":{"1K":{w:896,h:1152}},"5:4":{"1K":{w:1152,h:896}},"9:16":{"1K":{w:768,h:1344}},"16:9":{"1K":{w:1344,h:768}},"21:9":{"1K":{w:1536,h:672}}},"Gemini 3.1 Flash":{"1:1":{"0.5K":{w:512,h:512},"1K":{w:1024,h:1024},"2K":{w:2048,h:2048},"4K":{w:4096,h:4096}},"1:4":{"0.5K":{w:256,h:1024},"1K":{w:512,h:2048},"2K":{w:1024,h:4096},"4K":{w:2048,h:8192}},"1:8":{"0.5K":{w:192,h:1536},"1K":{w:384,h:3072},"2K":{w:768,h:6144},"4K":{w:1536,h:12288}},"2:3":{"0.5K":{w:424,h:632},"1K":{w:848,h:1264},"2K":{w:1696,h:2528},"4K":{w:3392,h:5056}},"3:2":{"0.5K":{w:632,h:424},"1K":{w:1264,h:848},"2K":{w:2528,h:1696},"4K":{w:5056,h:3392}},"3:4":{"0.5K":{w:448,h:600},"1K":{w:896,h:1200},"2K":{w:1792,h:2400},"4K":{w:3584,h:4800}},"4:1":{"0.5K":{w:1024,h:256},"1K":{w:2048,h:512},"2K":{w:4096,h:1024},"4K":{w:8192,h:2048}},"4:3":{"0.5K":{w:600,h:448},"1K":{w:1200,h:896},"2K":{w:2400,h:1792},"4K":{w:4800,h:3584}},"4:5":{"0.5K":{w:464,h:576},"1K":{w:928,h:1152},"2K":{w:1856,h:2304},"4K":{w:3712,h:4608}},"5:4":{"0.5K":{w:576,h:464},"1K":{w:1152,h:928},"2K":{w:2304,h:1856},"4K":{w:4608,h:3712}},"8:1":{"0.5K":{w:1536,h:192},"1K":{w:3072,h:384},"2K":{w:6144,h:768},"4K":{w:12288,h:1536}},"9:16":{"0.5K":{w:384,h:688},"1K":{w:768,h:1376},"2K":{w:1536,h:2752},"4K":{w:3072,h:5504}},"16:9":{"0.5K":{w:688,h:384},"1K":{w:1376,h:768},"2K":{w:2752,h:1536},"4K":{w:5504,h:3072}},"21:9":{"0.5K":{w:792,h:168},"1K":{w:1584,h:672},"2K":{w:3168,h:1344},"4K":{w:6336,h:2688}}},"Gemini 3 Pro":{"1:1":{"1K":{w:1024,h:1024},"2K":{w:2048,h:2048},"4K":{w:4096,h:4096}},"2:3":{"1K":{w:848,h:1264},"2K":{w:1696,h:2528},"4K":{w:3392,h:5056}},"3:2":{"1K":{w:1264,h:848},"2K":{w:2528,h:1696},"4K":{w:5056,h:3392}},"3:4":{"1K":{w:896,h:1200},"2K":{w:1792,h:2400},"4K":{w:3584,h:4800}},"4:3":{"1K":{w:1200,h:896},"2K":{w:2400,h:1792},"4K":{w:4800,h:3584}},"4:5":{"1K":{w:928,h:1152},"2K":{w:1856,h:2304},"4K":{w:3712,h:4608}},"5:4":{"1K":{w:1152,h:928},"2K":{w:2304,h:1856},"4K":{w:4608,h:3712}},"9:16":{"1K":{w:768,h:1376},"2K":{w:1536,h:2752},"4K":{w:3072,h:5504}},"16:9":{"1K":{w:1376,h:768},"2K":{w:2752,h:1536},"4K":{w:5504,h:3072}},"21:9":{"1K":{w:1584,h:672},"2K":{w:3168,h:1344},"4K":{w:6336,h:2688}}}};function pa(e,t,o){let r=_H[e][t];if(!r)return{width:1024,height:1024};let i=r[o];if(!i){let a=Object.values(r)[0];return{width:a.w,height:a.h}}return{width:i.w,height:i.h}}function DH(e){return e==="0.5K"?"512px":e}async function ua(e,t,o,n,r,i,a,s,l){let c=[{text:e}];if(s){let x=s.match(/^data:([^;]+);base64,(.+)$/);x&&c.unshift({inlineData:{mimeType:x[1],data:x[2]}})}let m={aspectRatio:o};r&&(m.imageSize=DH(n));let p={responseModalities:["IMAGE","TEXT"],imageConfig:m,temperature:.1};i&&(p.thinkingConfig={thinkingLevel:"High",includeThoughts:!0});let d={contents:[{parts:c}],generationConfig:p},u=await fetch(`https://generativelanguage.googleapis.com/v1beta/models/${t}:generateContent`,{method:"POST",signal:l,headers:{"x-goog-api-key":a,"Content-Type":"application/json"},body:JSON.stringify(d)});if(!u.ok){let x=`Gemini API error ${u.status}`;try{let y=await u.json();y?.error?.message&&(x=y.error.message)}catch{}throw new Error(x)}let E=((await u.json())?.candidates?.[0]?.content?.parts??[]).find(x=>x.inlineData?.data);if(!E?.inlineData?.data)throw new Error("No image was returned by the API.");return`data:${E.inlineData.mimeType??"image/png"};base64,${E.inlineData.data}`}var L0=()=>be("svg",{width:"9",height:"9",viewBox:"0 0 10 10",fill:"none",children:be("path",{d:"M2.5 3.75L5 6.25L7.5 3.75",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})}),_0=()=>be("svg",{width:"12",height:"12",viewBox:"0 0 14 14",fill:"none",children:be("path",{d:"M2.5 7.5L5.5 10.5L11.5 3.5",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})}),RH=()=>be("svg",{width:"13",height:"13",viewBox:"0 0 16 16",fill:"none",children:be("path",{d:"M8 2L10.5 5.5H13.5L11.5 8L13 11.5L8 9.5L3 11.5L4.5 8L2.5 5.5H5.5L8 2Z",stroke:"currentColor",strokeWidth:"1.3",strokeLinejoin:"round"})}),NH=()=>Mt("svg",{width:"12",height:"12",viewBox:"0 0 14 14",fill:"none",children:[be("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.2"}),be("path",{d:"M7 6.5V10",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),be("circle",{cx:"7",cy:"4.5",r:"0.75",fill:"currentColor"})]}),BH=()=>be("svg",{width:"15",height:"15",viewBox:"0 0 14 14",fill:"none",className:"igp-spinner",children:be("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:"20 14"})}),FH=({label:e})=>{let o={"21:9":{width:21,height:9},"16:9":{width:18,height:10},"4:3":{width:16,height:12},"3:2":{width:15,height:10},"1:1":{width:13,height:13},"9:16":{width:10,height:18},"3:4":{width:12,height:16},"2:3":{width:10,height:15},"5:4":{width:15,height:12},"4:5":{width:12,height:15},"4:1":{width:24,height:6},"1:4":{width:6,height:24},"8:1":{width:24,height:3},"1:8":{width:3,height:24}}[e]??{width:13,height:13};return be("div",{style:{border:"1.5px solid currentColor",borderRadius:2,boxSizing:"border-box",display:"inline-block",flexShrink:0,color:"#999",...o}})},c3=({element:e,app:t,onBeforeImageGen:o,onAfterImageGen:n})=>{let r=Y=>{let te=Y.customData?.imageGenerator;return te?{model:te.model,ratio:te.ratio,resolution:te.resolution}:null},i=t.state,a=ol(t.props.geminiApiKey),[s,l]=Yn(()=>gu(e.id)),[c,m]=Yn(()=>{let Y=r(e),te=si(e.id);return Y?.model??te?.model??"Gemini 3.1 Flash"}),p=ci[c],d=p.supportedRatios,u=p.supportedResolutions,h=d.includes("2:3")?"2:3":d[0],g=u.includes("2K")?"2K":u[u.length-1],[E,w]=Yn(()=>{let Y=r(e),te=si(e.id);return Y?.ratio??te?.ratio??h}),[x,y]=Yn(()=>{let Y=r(e),te=si(e.id);return Y?.resolution??te?.resolution??g}),v=ma(Y=>{t.scene.mutateElement(e,{customData:{...e.customData??{},imageGenerator:Y}})},[t.scene,e]),I=ma((Y,te=!1)=>{t.scrollToContent(Y,{fitToViewport:!0,viewportZoomFactor:.8,animate:te,canvasOffsets:t.getEditorUIOffsets()})},[t]),k=li(!0);od(()=>{if(k.current){k.current=!1;return}let Y=ci[c],te=Y.supportedRatios,Pe=te.includes(E),ft=E;Pe||(ft=te.includes("2:3")?"2:3":te[0],w(ft));let To=Y.supportedResolutions,Dr=To.includes(x),ir=x;Dr||(ir=To.includes("2K")?"2K":To[To.length-1],y(ir));let Fl=pa(c,ft,ir);t.scene.mutateElement(e,{width:Fl.width,height:Fl.height}),v({model:c,ratio:ft,resolution:ir}),t.syncActionResult({captureUpdate:A0.IMMEDIATELY})},[c,t,e,v]);let[L,S]=Yn(()=>ca(e.id)),[_,P]=Yn(null),[T,M]=Yn(null),[N,O]=Yn(!1),[B,U]=Yn(!1),[D,F]=Yn(!1),z=li(null),$=li(null),V=li(null),Q=li(null),ee=li(null),ie=li(e),Ee=li(t);od(()=>{ie.current=e,Ee.current=t}),od(()=>{if(!e.customData?.imageGeneratorAutoFitPending)return;let Y=0,te=!1,Pe=()=>{te||(I(e),t.scene.mutateElement(e,{customData:{...e.customData??{},imageGeneratorAutoFitPending:!1}}))};return Y=window.requestAnimationFrame(()=>{Y=window.requestAnimationFrame(Pe)}),()=>{te=!0,window.cancelAnimationFrame(Y)}},[t.scene,e,I]);let _e=ma(Y=>{w(Y),O(!1);let te=pa(c,Y,x);Ee.current.scene.mutateElement(ie.current,{width:te.width,height:te.height,customData:{...ie.current.customData??{},imageGenerator:{model:c,ratio:Y,resolution:x}}}),Ee.current.syncActionResult({captureUpdate:A0.IMMEDIATELY})},[c,x]),Re=ma(Y=>{y(Y),U(!1);let te=pa(c,E,Y);Ee.current.scene.mutateElement(ie.current,{width:te.width,height:te.height,customData:{...ie.current.customData??{},imageGenerator:{model:c,ratio:E,resolution:Y}}}),Ee.current.syncActionResult({captureUpdate:A0.IMMEDIATELY})},[c,E]);od(()=>{let Y=te=>{z.current&&!z.current.contains(te.target)&&O(!1),$.current&&!$.current.contains(te.target)&&U(!1),V.current&&!V.current.contains(te.target)&&F(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[]),od(()=>{let Y=te=>{S(!1),te?te!=="aborted"&&P(te):P(null)};return du(e.id,Y),()=>mu(e.id,Y)},[e.id]);let We=ma(Y=>{let te=Y.target.files?.[0];if(!te)return;let Pe=new FileReader;Pe.onload=()=>M(Pe.result),Pe.readAsDataURL(te),Y.target.value=""},[]),lt=ma(()=>{uu(e.id)},[e.id]),qt=ma(async()=>{if(!s.trim()){P("Please enter a prompt.");return}if(!a){P("No Gemini API key found. Set VITE_APP_GEMINI_API_KEY in .env.");return}if(o)try{let{allowed:Pe,error:ft}=await o();if(!Pe){P(ft||"Insufficient credits for image generation");return}}catch{P("Credit check failed");return}let Y=new AbortController;ee.current=Y,lu(e.id,s,{model:c,ratio:E,resolution:x},Y),S(!0),P(null);let te=null;try{let Pe=ci[c],ft=await ua(s,Pe.geminiModelId,E,x,Pe.supportsImageSize,Pe.supportsThinking,a,T??void 0,Y.signal);await t.insertGeneratedImageIntoFrame(ft,e),n?.()}catch(Pe){Pe instanceof Error&&(Pe.name==="AbortError"?te="aborted":te=Pe.message)}finally{ee.current=null,cu(e.id,te),S(!1),te===null?(pu(e.id),l(""),M(null),P(null)):te!=="aborted"&&P(te)}},[s,a,c,E,x,T,t,e,o,n]);if(i.contextMenu||i.newElement||i.resizingElement||i.isRotating||i.openMenu||i.viewModeEnabled||i.selectedElementsAreBeingDragged)return null;let[rr,,,In]=MH(e,t.scene.getNonDeletedElementsMap()),{x:Ro,y:Tt}=SH({sceneX:rr+e.width/2,sceneY:In},i),Ct=Ro-i.offsetLeft,Jt=Tt-i.offsetTop+16;return Mt("div",{className:"igp",style:{left:`${Ct}px`,top:`${Jt}px`},onPointerDown:Y=>Y.stopPropagation(),onClick:Y=>Y.stopPropagation(),children:[be("input",{ref:Q,type:"file",accept:"image/*",style:{display:"none"},onChange:We}),Mt(nl,{isLoading:L,value:s,onValueChange:l,onSubmit:qt,className:"igp-container",children:[T&&Mt("div",{className:"igp-ref-chip",children:[be("img",{src:T,alt:"Reference"}),be("span",{children:"Reference image"}),be("button",{onClick:()=>M(null),title:"Remove",children:be(LH,{size:10})})]}),be(rl,{placeholder:"What are we creating today\u2026",className:"igp-textarea",disableAutosize:!1}),_&&be("div",{className:"igp-error",children:_}),Mt(il,{className:"igp-actions",children:[Mt("div",{className:"igp-actions-left",children:[Mt("div",{className:"igp-dropdown-root",ref:V,children:[be(Tr,{tooltip:"Select model",side:"top",children:Mt("button",{className:"igp-btn",onClick:()=>{F(Y=>!Y),O(!1),U(!1)},disabled:L,children:[be(RH,{}),be("span",{children:c}),be(L0,{})]})}),D&&be("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--left",children:D0.map(Y=>Mt("button",{className:"igp-dropdown-item",onClick:()=>{v({model:Y,ratio:E,resolution:x}),m(Y),F(!1)},children:[be("span",{style:{flex:1},children:Y}),Y===c&&be("span",{className:"igp-check",children:be(_0,{})})]},Y))})]}),be(Tr,{tooltip:"Add reference image",side:"top",children:be("button",{className:`igp-btn igp-btn--icon${T?" igp-btn--active":""}`,onClick:()=>Q.current?.click(),disabled:L,children:be(AH,{size:15})})})]}),Mt("div",{className:"igp-actions-right",children:[Mt("div",{className:"igp-dropdown-root",ref:$,children:[Mt("button",{className:"igp-btn igp-btn--compact",onClick:()=>{u.length<=1||(U(Y=>!Y),O(!1),F(!1))},disabled:L||u.length<=1,title:u.length<=1?"Fixed resolution for this model":void 0,children:[be("span",{children:x}),u.length>1&&be(L0,{})]}),B&&u.length>1&&be("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--right",children:u.map(Y=>Mt("button",{className:"igp-dropdown-item",onClick:()=>Re(Y),children:[be("span",{style:{flex:1},children:Y}),Y===x&&be("span",{className:"igp-check",children:be(_0,{})})]},Y))})]}),Mt("div",{className:"igp-dropdown-root",ref:z,children:[Mt("button",{className:"igp-btn igp-btn--compact",onClick:()=>{O(Y=>!Y),U(!1),F(!1)},disabled:L,children:[be("span",{children:E}),be(L0,{})]}),N&&Mt("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--right igp-dropdown--ratio",children:[Mt("div",{className:"igp-dropdown-header",children:[be("span",{children:"Format"}),be(NH,{})]}),d.map(Y=>{let te=pa(c,Y,x);return Mt("button",{className:"igp-dropdown-item",onClick:()=>_e(Y),children:[be(FH,{label:Y}),be("span",{style:{flex:1},children:Y}),Mt("span",{className:"igp-dims",children:[te.width,"\xD7",te.height]}),Y===E&&be("span",{className:"igp-check",children:be(_0,{})})]},Y)})]})]}),be("button",{className:"igp-generate",onClick:L?lt:qt,disabled:!L&&!s.trim(),title:L?"Stop generation":"Generate image",children:L?be(BH,{}):be(PH,{size:16})})]})]})]})]})};function di(e){if(!e||e==="transparent"||e==="rgba(0, 0, 0, 0)")return"transparent";if(e.startsWith("#"))return e;let t=e.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*([0-9.]+))?\)/);if(!t)return e;let o=parseInt(t[1],10),n=parseInt(t[2],10),r=parseInt(t[3],10);return`#${o.toString(16).padStart(2,"0")}${n.toString(16).padStart(2,"0")}${r.toString(16).padStart(2,"0")}`}function OH(e){let t=e.match(/rgba\(\d+,\s*\d+,\s*\d+,\s*([0-9.]+)\)/);return t?Math.round(parseFloat(t[1])*100):100}function zH(e,t){let o=e.toLowerCase();if(t){for(let[n,r]of Object.entries(t))if(o.includes(n))return r}return o.includes("sans-serif")||o.includes("arial")||o.includes("helvetica")||o.includes("verdana")||o.includes("impact")||o.includes("nunito")||o.includes("roboto")||o.includes("inter")||o.includes("liberation sans")||o.includes("tahoma")||o.includes("trebuchet")?2:o.includes("georgia")||o.includes("serif")||o.includes("cursive")||o.includes("script")||o.includes("times")||o.includes("playfair")?1:o.includes("courier")||o.includes("mono")||o.includes("cascadia")?3:2}function HH(e,t){switch(t){case"uppercase":return e.toUpperCase();case"lowercase":return e.toLowerCase();case"capitalize":return e.replace(/\b\w/g,o=>o.toUpperCase());default:return e}}function GH(e){let t=parseFloat(e);return isNaN(t)?16:Math.round(t)}function UH(e){let t=e.borderTopLeftRadius||"0",o=parseFloat(t);return isNaN(o)?0:Math.round(o)}function WH(e,t,o){let n=e.borderTopLeftRadius||"0";if(n.includes("%")){let r=parseFloat(n);if(!isNaN(r)&&r>=50)return!0}else{let r=parseFloat(n);if(!isNaN(r)&&r>0&&r>=t/2&&r>=o/2)return!0}return!1}function YH(e){return e!=="none"&&(e.includes("linear-gradient")||e.includes("radial-gradient"))}function VH(e){let t=[...e.matchAll(/(#[\da-fA-F]{3,8}|rgba?\([^)]+\))/g)];if(t.length===0)return"#1a1a2e";if(t.length===1||e.includes("repeating"))return di(t[0][1]);let o=di(t[0][1]).replace("#","").padEnd(6,"0"),n=di(t[t.length-1][1]).replace("#","").padEnd(6,"0"),r=parseInt(o.slice(0,2),16),i=parseInt(o.slice(2,4),16),a=parseInt(o.slice(4,6),16),s=parseInt(n.slice(0,2),16),l=parseInt(n.slice(2,4),16),c=parseInt(n.slice(4,6),16),m=(p,d)=>Math.round((p+d)/2).toString(16).padStart(2,"0");return`#${m(r,s)}${m(i,l)}${m(a,c)}`}function $H(e){let t=e.match(/url\("?(data:[^")]+)"?\)/);return t?t[1]:null}function KH(e){return e==="center"?"center":e==="right"||e==="end"?"right":"left"}var m3=new Set(["SPAN","EM","STRONG","B","I","A","LABEL"]);function d3(e){let t="",o=!1;for(let r of e.childNodes)if(r.nodeType===Node.TEXT_NODE){let i=r.textContent||"";i.trim()&&(o=!0),t+=i}else if(r.nodeType===Node.ELEMENT_NODE){let i=r;if(i.tagName==="BR")t+=`
15
15
  `,o=!0;else if(m3.has(i.tagName)){let a=i.textContent||"";a.trim()&&(o=!0),t+=a}}let n=t.replace(/^\s+|\s+$/g,"");return o&&n?n:null}async function xu(e,t,o,n,r,i){let a=document.createElement("iframe");a.style.cssText=`
16
16
  position: fixed;
17
17
  left: -${n+200}px;
@@ -101,16 +101,16 @@ Only change positions and sizes.
101
101
  11. border-radius in px if needed.
102
102
  12. One purpose per div: background fill OR image OR text (never mixed).
103
103
 
104
- Return ONLY the raw HTML. No markdown, no code fences, no explanation.`,imagePlaceholders:l}}async function cG(e,t,o,n){let r=await fetch("https://openrouter.ai/api/v1/chat/completions",{method:"POST",signal:n,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({model:o,messages:[{role:"user",content:e}],stream:!1,temperature:.3})});if(!r.ok){let l=`OpenRouter API error ${r.status}`;try{let c=await r.json();c?.error?.message&&(l=c.error.message)}catch{}throw new Error(l)}return((await r.json())?.choices?.[0]?.message?.content??"").replace(/^```(?:html)?\s*/i,"").replace(/\s*```\s*$/i,"").trim()}function dG(e,t){let o=e.findIndex(r=>r.id===t);if(o<0)return e.length;let n=o+1;for(let r=o+1;r<e.length;r++)e[r].frameId===t&&(n=r+1);return n}async function mG(e){let{info:t,targetWidth:o,targetHeight:n,placementX:r,placementY:i,app:a,geminiApiKey:s,openRouterApiKey:l,chatModel:c,agentImageModel:m,customFontMap:p={},onProgress:d,signal:u,debugLabel:h=`${o}\xD7${n}`,existingFrameId:g}=e,E=t.frame,w;if(g)w=g;else{let z=f3({...x3,x:r,y:i,width:o,height:n,opacity:100,locked:!1,name:`${o}\xD7${n}`}),V=[...a.getSceneElements(),z];yu(V,wu([z])),a.updateScene({elements:V}),w=z.id}let x=null;if(t.background.type==="image"){let z=t.background.dataUrl,$=nG(E.width,E.height,o,n);if(fo(`[AutoResize] ${h} \u2014 background: needsRegen=${$}`),$){d?.("Regenerating background image\u2026");let V=rG(o,n);fo(`[AutoResize] ${h} \u2014 calling Gemini for background regen (ar=${V})`),x=await ua(`You are given an input background image. Preserve the original scene identity, composition, color palette, and style. Outpaint only beyond the existing edges so the final image fits aspect ratio ${V}. Keep the center subject and key content unchanged. Ensure all surfaces extend with natural, seamless continuity \u2014 no visible seams, repeated patterns, or tiling artifacts. For areas far from the center, gradually soften into ambient bokeh rather than extending sharp textures. Do not add text, logos, watermarks, UI, symbols, or new unrelated objects. Avoid altering brand-relevant details.`,m||jH,V,"1K",!1,!1,s,z,u)}else x=z}if(x){d?.("Placing background\u2026");let{width:z,height:$}=await iG(x),{relX:V,relY:Q,width:ee,height:ie}=aG(z,$,o,n),Ee=p3(),Le=g3({type:"image",x:r+V,y:i+Q,width:ee,height:ie,fileId:Ee,status:"pending",scale:[1,1],customData:{autoResizeBg:!0}}),De=a.getSceneElements(),We=dG(De,w),lt=[...De.slice(0,We),{...Le,frameId:w},...De.slice(We)];yu(lt,wu([Le])),a.updateScene({elements:lt}),a.addFiles([{id:Ee,dataURL:x,mimeType:Bo(x),created:Date.now(),lastRetrieved:Date.now()}])}d?.("Generating layout\u2026"),fo(`[AutoResize] ${h} \u2014 calling OpenRouter for HTML layout (model=${c})`);let{prompt:y,imagePlaceholders:v}=lG(t,o,n),I=await cG(y,l,c,u);if(!I||I.length<20)throw new Error("LLM returned empty HTML");fo(`[AutoResize] ${h} \u2014 HTML received (${I.length} chars), substituting ${v.size} image placeholder(s)\u2026`);for(let[z,$]of v)I=I.split(`url(${z})`).join(`url(${$})`);d?.("Parsing layout\u2026");let k;try{k=await xu(I,r,i,o,n,p)}catch(z){throw new Error(`HTML parse failed: ${z instanceof Error?z.message:String(z)}`)}if(!k||k.length===0)throw new Error("HTML parser produced no elements");d?.("Inserting elements\u2026");let L=[],S=[];for(let z of k)if(z.kind==="rectangle"){let $=u3({type:"rectangle",x:z.x,y:z.y,width:z.width,height:z.height,backgroundColor:z.backgroundColor,fillStyle:"solid",strokeColor:z.strokeColor,strokeWidth:z.strokeWidth,opacity:z.opacity,roughness:0,...z.borderRadius>0?{roundness:{type:3,value:z.borderRadius}}:{},customData:{generatedByHtml:!0}});L.push({...$,frameId:w})}else if(z.kind==="ellipse"){let $=u3({type:"ellipse",x:z.x,y:z.y,width:z.width,height:z.height,backgroundColor:z.backgroundColor,fillStyle:"solid",strokeColor:z.strokeColor,strokeWidth:z.strokeWidth,opacity:z.opacity,roughness:0,customData:{generatedByHtml:!0}});L.push({...$,frameId:w})}else if(z.kind==="text"){let $=XH({x:z.x,y:z.y,text:z.text,fontSize:z.fontSize,fontFamily:z.fontFamily,strokeColor:z.color,textAlign:z.textAlign,width:z.width,opacity:z.opacity,roughness:0,customData:{generatedByHtml:!0}});L.push({...$,frameId:w})}else if(z.kind==="image"){let $=p3(),V=g3({type:"image",x:z.x,y:z.y,width:z.width,height:z.height,fileId:$,status:"pending",scale:[1,1],customData:{generatedByHtml:!0}});L.push({...V,frameId:w}),S.push({id:$,dataURL:z.dataUrl,mimeType:Bo(z.dataUrl),created:Date.now(),lastRetrieved:Date.now()})}let _=o*n,P=[],T=[];for(let z of L)z.type==="rectangle"&&z.width*z.height>=_*.25?P.push(z):T.push(z);let M=a.getSceneElements(),N=M.findIndex(z=>z.id===w),O=b3(M,w),B=O.length>0?M.findIndex(z=>z.id===O[0].id):N+1,U=O.length>0?M.findIndex(z=>z.id===O[O.length-1].id)+1:N+1,D=[...M.slice(0,B),...P,...M.slice(B,U),...T,...M.slice(U)],F=[...P,...T];return yu(D,wu(F)),a.updateScene({elements:D}),S.length>0&&a.addFiles(S),fo(`[AutoResize] ${h} \u2014 inserted ${L.length} elements (${P.length} bg, ${T.length} fg)`),{frameId:w}}function E3(e,t,o){let n=t.x+t.width+80,r=e.map((l,c)=>{let m=e.slice(0,c).reduce((d,u)=>d+u.height+40,t.y);return{frame:f3({...x3,x:n,y:m,width:l.width,height:l.height,opacity:100,locked:!1,name:l.label??`${l.width}\xD7${l.height}`}),x:n,y:m,width:l.width,height:l.height}}),i=o.getSceneElements(),a=r.map(l=>l.frame),s=[...i,...a];return yu(s,wu(a)),o.updateScene({elements:s}),r.map(l=>({frameId:l.frame.id,x:l.x,y:l.y,width:l.width,height:l.height}))}async function y3(e){let{sourceFrameId:t,targetDimensions:o,app:n,geminiApiKey:r,openRouterApiKey:i,chatModel:a="google/gemini-3.1-flash-lite-preview",agentImageModel:s,customFontMap:l={},onBeforeAutoResize:c,onAfterAutoResize:m,onProgress:p,signal:d,preCreatedFrameInfos:u}=e,h=new Array(o.length),g=n.getSceneElements(),E=g.find(k=>k.id===t);if(!E)return o.map(()=>({status:"error",error:"Source frame not found"}));let w=tG(g,E,n.files),x=E.x+E.width+80,y=u??o.map((k,L)=>({x,y:o.slice(0,L).reduce((S,_)=>S+_.height+40,E.y)})),v=3,I=o.length;fo(`[AutoResize] Starting ${I} dimension(s), batch size ${v}`);for(let k=0;k<I;k+=v){let L=Math.min(k+v,I),S=Math.floor(k/v)+1;fo(`[AutoResize] Batch ${S}: dimensions ${k+1}\u2013${L} of ${I}`),await Promise.allSettled(o.slice(k,L).map(async(_,P)=>{let T=k+P,M=_.label??`${_.width}\xD7${_.height}`,N=`[${T+1}/${I}] ${M}`;if(c){fo(`[AutoResize] ${N} \u2014 checking credits`);let{allowed:O,error:B}=await c();if(!O){h[T]={status:"error",error:B??"Not allowed"},p?.(T,I,"error",M),fo(`[AutoResize] ${N} \u2014 credits denied: ${B}`);return}fo(`[AutoResize] ${N} \u2014 credits OK`)}p?.(T,I,"bg-regen",M),fo(`[AutoResize] ${N} \u2014 starting at (${y[T].x}, ${y[T].y})`);try{let{frameId:O}=await mG({info:w,targetWidth:_.width,targetHeight:_.height,placementX:y[T].x,placementY:y[T].y,existingFrameId:u?.[T]?.frameId,app:n,geminiApiKey:r,openRouterApiKey:i,chatModel:a,agentImageModel:s,customFontMap:l,debugLabel:N,onProgress:B=>{p?.(T,I,"layout",`${M}: ${B}`)},signal:d});h[T]={status:"ok",frameId:O},p?.(T,I,"done",M),m?.(),fo(`[AutoResize] ${N} \u2014 DONE`)}catch(O){let B=O instanceof Error?O.message:String(O);h[T]={status:"error",error:B},p?.(T,I,"error",`${M}: ${B}`),fo(`[AutoResize] ${N} \u2014 ERROR: ${B}`)}})),fo(`[AutoResize] Batch ${S} complete`)}return h}import{Fragment as T3,jsx as pe,jsxs as bo}from"react/jsx-runtime";var w3=[{label:"1200\xD7628",width:1200,height:628,desc:"Facebook / OG"},{label:"1080\xD71080",width:1080,height:1080,desc:"Square"},{label:"1080\xD71920",width:1080,height:1920,desc:"Story 9:16"},{label:"728\xD790",width:728,height:90,desc:"Leaderboard"},{label:"320\xD750",width:320,height:50,desc:"Mobile Banner"},{label:"300\xD7600",width:300,height:600,desc:"Half Page"},{label:"300\xD7250",width:300,height:250,desc:"Medium Rect"},{label:"160\xD7600",width:160,height:600,desc:"Wide Skyscraper"}],gG=()=>bo("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:[pe("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1",stroke:"currentColor",strokeWidth:"1.4"}),pe("rect",{x:"7.5",y:"7.5",width:"7",height:"7",rx:"1",stroke:"currentColor",strokeWidth:"1.4",strokeDasharray:"2 1",opacity:"0.6"}),pe("path",{d:"M9.5 6.5L13.5 6.5M13.5 6.5L13.5 2.5M13.5 2.5L9.5 2.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),hG=()=>pe("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:pe("path",{d:"M1.5 1.5L10.5 10.5M10.5 1.5L1.5 10.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})}),N0=()=>pe("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",children:pe("path",{d:"M2 6.5L4.5 9L10 3",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})}),v3=()=>pe("svg",{className:"arp-spinner",width:"13",height:"13",viewBox:"0 0 14 14",fill:"none",children:pe("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:"20 14"})}),I3=()=>bo("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",children:[pe("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.3"}),pe("path",{d:"M6 3.5V6.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"}),pe("circle",{cx:"6",cy:"8.5",r:"0.65",fill:"currentColor"})]}),fG=({onAdd:e})=>{let[t,o]=ga(""),[n,r]=ga("");return bo("div",{className:"arp-custom-row",children:[pe("input",{className:"arp-custom-input",type:"number",placeholder:"W",value:t,min:1,onChange:a=>o(a.target.value),onPointerDown:a=>a.stopPropagation()}),pe("span",{className:"arp-custom-x",children:"\xD7"}),pe("input",{className:"arp-custom-input",type:"number",placeholder:"H",value:n,min:1,onChange:a=>r(a.target.value),onPointerDown:a=>a.stopPropagation()}),pe("button",{className:"arp-custom-add",onClick:()=>{let a=parseInt(t,10),s=parseInt(n,10);a>0&&s>0&&(e({width:a,height:s,label:`${a}\xD7${s}`}),o(""),r(""))},disabled:!t||!n,title:"Add custom dimension",children:"+ Add"})]})},C3=({element:e,app:t,onClose:o,onBeforeAutoResize:n,onAfterAutoResize:r,onRunningChange:i,openRouterApiKey:a,chatModel:s,agentImageModel:l})=>{let[c,m]=ga(new Set),[p,d]=ga([]),[u,h]=ga(!1),[g,E]=ga({}),[w,x]=ga(null),y=uG(null),v=[...w3.filter(B=>c.has(B.label)).map(B=>({width:B.width,height:B.height,label:B.label})),...p],I=B=>{m(U=>{let D=new Set(U);return D.has(B)?D.delete(B):D.add(B),D})},k=B=>{let U=B.label;c.has(U)||(d(D=>[...D,B]),m(D=>new Set([...D,U])))},L=B=>{d(U=>U.filter(D=>D.label!==B)),m(U=>{let D=new Set(U);return D.delete(B),D})},S=R0((B,U)=>{E(D=>({...D,[B]:{...D[B],...U}}))},[]),_=R0(()=>{vr.clear()},[]);pG(()=>()=>{y.current?.abort(),vr.clear()},[]);let P=R0(async()=>{if(v.length===0)return;h(!0),i?.(!0),x(null);let B={};v.forEach(ee=>{B[ee.label]={status:"waiting"}}),E(B);let U=new AbortController;y.current=U;let D=ol(t.props.geminiApiKey),F={},z=t.state.brandContext;if(z?.typography){let{headline:ee,body:ie}=z.typography;ee?.family&&ee?.fontFamilyId&&(F[ee.family.toLowerCase().trim()]=ee.fontFamilyId),ie?.family&&ie?.fontFamilyId&&(F[ie.family.toLowerCase().trim()]=ie.fontFamilyId)}let V=t.getSceneElements().find(ee=>ee.id===e.id),Q=[];V&&(Q=E3(v,V,t)),Q.length>0&&vr.setLoadingFrames(Q);try{await y3({sourceFrameId:e.id,targetDimensions:v,preCreatedFrameInfos:Q.length>0?Q:void 0,app:t,geminiApiKey:D,openRouterApiKey:a,chatModel:s,agentImageModel:l,customFontMap:F,onBeforeAutoResize:n,onAfterAutoResize:r,onProgress:(ee,ie,Ee,Le)=>{let De=v[ee]?.label??Le;Ee==="done"?(S(De,{status:"done"}),Q[ee]&&vr.markComplete(Q[ee].frameId)):Ee==="error"?(S(De,{status:"error",error:Le}),Q[ee]&&vr.markComplete(Q[ee].frameId)):Ee==="bg-regen"?S(De,{status:"bg-regen"}):S(De,{status:"layout"})},signal:U.signal})}catch(ee){ee instanceof DOMException&&ee.name==="AbortError"||U.signal.aborted||x(ee instanceof Error?ee.message:"An unexpected error occurred")}finally{h(!1),i?.(!1),y.current=null,_()}},[v,t,e.id,S,_,n,r,a,s,l]),T=()=>{y.current?.abort(),h(!1),i?.(!1),_()},M=Object.values(g).filter(B=>B.status==="done").length,N=v.length,O=M>0;return bo("div",{className:"arp",onPointerDown:B=>B.stopPropagation(),onClick:B=>B.stopPropagation(),children:[bo("div",{className:"arp-header",children:[bo("span",{className:"arp-header__title",children:[pe(gG,{}),"Auto Resize"]}),pe("button",{className:"arp-header__close",onClick:()=>{u?window.confirm("This will cancel the generation. Are you sure?")&&(T(),o()):o()},title:"Close",children:pe(hG,{})})]}),bo("div",{className:"arp-source",children:["Source: ",Math.round(e.width),"\xD7",Math.round(e.height)]}),pe("div",{className:"arp-section-label",children:"Target dimensions"}),pe("div",{className:"arp-presets",children:w3.map(B=>{let U=c.has(B.label),D=g[B.label];return bo("button",{className:`arp-preset ${U?"arp-preset--selected":""} ${u?"arp-preset--disabled":""}`,onClick:()=>!u&&I(B.label),title:B.desc,children:[pe("span",{className:"arp-preset__check",children:U&&pe(N0,{})}),pe("span",{className:"arp-preset__label",children:B.label}),pe("span",{className:"arp-preset__desc",children:B.desc}),D&&bo("span",{className:"arp-preset__status",children:[D.status==="waiting"&&pe("span",{className:"arp-status arp-status--waiting",children:"\u2026"}),(D.status==="bg-regen"||D.status==="layout"||D.status==="inserting")&&pe("span",{className:"arp-status arp-status--running",children:pe(v3,{})}),D.status==="done"&&pe("span",{className:"arp-status arp-status--done",children:pe(N0,{})}),D.status==="error"&&pe("span",{className:"arp-status arp-status--error",title:D.error,children:pe(I3,{})})]})]},B.label)})}),p.length>0&&pe("div",{className:"arp-extras",children:p.map(B=>{let U=g[B.label];return bo("div",{className:"arp-extra-tag",children:[pe("span",{children:B.label}),U?.status==="done"&&pe("span",{className:"arp-status arp-status--done",children:pe(N0,{})}),U?.status==="error"&&pe("span",{className:"arp-status arp-status--error",title:U.error,children:pe(I3,{})}),(U?.status==="bg-regen"||U?.status==="layout")&&pe("span",{className:"arp-status arp-status--running",children:pe(v3,{})}),!u&&pe("button",{className:"arp-extra-tag__remove",onClick:()=>L(B.label),children:"\xD7"})]},B.label)})}),!u&&bo(T3,{children:[pe("div",{className:"arp-section-label",children:"Custom size"}),pe(fG,{onAdd:k})]}),w&&pe("div",{className:"arp-error",children:w}),u&&N>0&&bo("div",{className:"arp-progress",children:[pe("div",{className:"arp-progress__bar-bg",children:pe("div",{className:"arp-progress__bar-fill",style:{width:`${M/N*100}%`}})}),bo("span",{className:"arp-progress__text",children:[M,"/",N," done"]})]}),pe("div",{className:"arp-actions",children:u?pe("button",{className:"arp-btn arp-btn--cancel",onClick:T,children:"Cancel"}):O?bo(T3,{children:[pe("button",{className:"arp-btn arp-btn--primary",onClick:P,disabled:v.length===0,children:"Generate more"}),pe("button",{className:"arp-btn arp-btn--ghost",onClick:o,children:"Done"})]}):pe("button",{className:"arp-btn arp-btn--primary",onClick:P,disabled:v.length===0,children:v.length===0?"Select sizes above":`Generate ${v.length} size${v.length!==1?"s":""}`})})]})};function nd(e){let t=e?.trim();return(t||void 0)??(typeof import.meta<"u"&&C?.VITE_APP_OPENROUTER_API_KEY?C.VITE_APP_OPENROUTER_API_KEY:"")??""}import{jsx as S3}from"react/jsx-runtime";var M3=({app:e})=>{let[t,o]=xG(bn.getState()),n=bG(null);if(k3(()=>bn.subscribe(o),[]),k3(()=>{if(!t.isOpen)return;let d=u=>{t.isRunning||n.current&&!n.current.contains(u.target)&&bn.close()};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[t.isOpen,t.isRunning]),!t.isOpen||!t.element)return null;let r=t.element,i=e.state,[a,s]=yG(r,e.scene.getNonDeletedElementsMap()),{x:l,y:c}=EG({sceneX:a+r.width/2,sceneY:s},i),m=l-i.offsetLeft,p=Math.max(c-i.offsetTop-82,8);return S3("div",{ref:n,style:{position:"absolute",left:`${m}px`,top:`${p}px`,transform:"translateX(-50%)",zIndex:"var(--zIndex-canvasButtons)",pointerEvents:"all"},children:S3(C3,{element:r,app:e,onClose:()=>bn.close(),onRunningChange:d=>bn.setRunning(d),onBeforeAutoResize:e.props.onBeforeAutoResize,onAfterAutoResize:e.props.onAfterAutoResize,openRouterApiKey:nd(e.props.openRouterApiKey),chatModel:e.props.chatModel??"google/gemini-3.1-flash-lite-preview",agentImageModel:e.props.agentImageModel})})};import{useCallback as Tu,useState as z0}from"react";import{sceneCoordsToViewportCoords as PG}from"@orangecatai/common";import{getElementAbsoluteCoords as AG}from"@orangecatai/element";function P3(e){let t=e?.trim();return(t||void 0)??(typeof import.meta<"u"&&C?.VITE_APP_LEONARDO_API_KEY?C.VITE_APP_LEONARDO_API_KEY:"")??""}function A3(e){let t=e?.trim();return(t||void 0)??(typeof import.meta<"u"&&C?.VITE_APP_REMOVE_BG_API_KEY?C.VITE_APP_REMOVE_BG_API_KEY:"")??""}import{useCallback as vu,useEffect as B0,useRef as Iu,useState as Vn}from"react";import{sceneCoordsToViewportCoords as L3}from"@orangecatai/common";import{getElementAbsoluteCoords as wG}from"@orangecatai/element";import{ArrowUp as vG}from"lucide-react";import{Fragment as MG,jsx as xe,jsxs as Bt}from"react/jsx-runtime";var F0=()=>xe("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:xe("path",{d:"M2.5 3.75L5 6.25L7.5 3.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),O0=()=>xe("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:xe("path",{d:"M2.5 7.5L5.5 10.5L11.5 3.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),IG=()=>xe("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:xe("path",{d:"M8 2L10.5 5.5H13.5L11.5 8L13 11.5L8 9.5L3 11.5L4.5 8L2.5 5.5H5.5L8 2Z",stroke:"currentColor",strokeWidth:"1.3",strokeLinejoin:"round"})}),TG=()=>Bt("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:[xe("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.2"}),xe("path",{d:"M7 6.5V10",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),xe("circle",{cx:"7",cy:"4.5",r:"0.75",fill:"currentColor"})]}),CG=()=>xe("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",className:"igp-spinner",children:xe("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:"20 14"})}),kG=()=>xe("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:xe("path",{d:"M7 1.5L8.5 5.5H12.5L9.5 8L10.5 12L7 9.5L3.5 12L4.5 8L1.5 5.5H5.5L7 1.5Z",fill:"currentColor"})}),SG=({label:e})=>{let t={border:"1.5px solid currentColor",borderRadius:2,boxSizing:"border-box",display:"inline-block",flexShrink:0},n={"21:9":{width:21,height:9},"16:9":{width:18,height:10},"4:3":{width:16,height:12},"3:2":{width:15,height:10},"1:1":{width:13,height:13},"9:16":{width:10,height:18},"3:4":{width:12,height:16},"2:3":{width:10,height:15},"5:4":{width:15,height:12},"4:5":{width:12,height:15},"4:1":{width:24,height:6},"1:4":{width:6,height:24},"8:1":{width:24,height:3},"1:8":{width:3,height:24}}[e]??{width:13,height:13};return xe("div",{style:{...t,...n}})},_3=({element:e,app:t,onBeforeImageGen:o,onAfterImageGen:n,forceOpen:r,onClose:i})=>{let a=t.state,s=ol(t.props.geminiApiKey),[l,c]=Vn(()=>r||ca(e.id)),m=vu(()=>{c(!1),i?.()},[i]),[p,d]=Vn(()=>gu(e.id)),[u,h]=Vn(()=>si(e.id)?.model??"Gemini 3.1 Flash"),g=ci[u],E=g.supportedRatios,w=g.supportedResolutions,x=E.includes("1:1")?"1:1":E[0],y=w.includes("2K")?"2K":w[w.length-1],[v,I]=Vn(()=>si(e.id)?.ratio??x),[k,L]=Vn(()=>si(e.id)?.resolution??y);B0(()=>{let Y=ci[u],te=Y.supportedRatios;te.includes(v)||I(te.includes("1:1")?"1:1":te[0]);let ft=Y.supportedResolutions;ft.includes(k)||L(ft.includes("2K")?"2K":ft[ft.length-1])},[u]);let[S,_]=Vn(()=>ca(e.id)),[P,T]=Vn(null),[M,N]=Vn(!1),[O,B]=Vn(!1),[U,D]=Vn(!1),F=Iu(null),z=Iu(null),$=Iu(null),V=Iu(null),Q=vu(Y=>{I(Y),N(!1)},[]);B0(()=>{let Y=te=>{_(!1),te?te!=="aborted"&&T(te):(m(),d(""))};return du(e.id,Y),()=>mu(e.id,Y)},[e.id]),B0(()=>{let Y=te=>{F.current&&!F.current.contains(te.target)&&N(!1),z.current&&!z.current.contains(te.target)&&B(!1),$.current&&!$.current.contains(te.target)&&D(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[]);let ee=vu(()=>{uu(e.id)},[e.id]),ie=vu(async()=>{if(!p.trim()){T("Please enter a prompt.");return}if(!s){T("No Gemini API key found. Set VITE_APP_GEMINI_API_KEY in .env or pass geminiApiKey as a prop.");return}if(o)try{let{allowed:Fe,error:ft}=await o();if(!Fe){T(ft||"Insufficient credits for image generation");return}}catch{T("Credit check failed");return}let Y=new AbortController;V.current=Y,lu(e.id,p,{model:u,ratio:v,resolution:k},Y),_(!0),T(null);let te=null;try{let Fe=ci[u],ft=e.fileId?t.files[e.fileId]?.dataURL:void 0,Co=await ua(p,Fe.geminiModelId,v,k,Fe.supportsImageSize,Fe.supportsThinking,s,ft,Y.signal),Dr=pa(u,v,k);await t.insertGeneratedImageNearElement(Co,e,Dr.width,Dr.height),n?.()}catch(Fe){Fe instanceof Error&&(Fe.name==="AbortError"?te="aborted":te=Fe.message)}finally{V.current=null,cu(e.id,te),_(!1),te===null?(pu(e.id),m(),d(""),T(null)):te!=="aborted"&&T(te)}},[p,s,u,v,k,t,e,o,n]);if(a.contextMenu||a.newElement||a.resizingElement||a.isRotating||a.openMenu||a.viewModeEnabled||a.selectedElementsAreBeingDragged)return null;let Ee=t.scene.getNonDeletedElementsMap(),[Le,De,,We]=wG(e,Ee),{x:lt,y:qt}=L3({sceneX:Le+e.width/2,sceneY:De},a),rr=lt-a.offsetLeft,In=Math.max(qt-a.offsetTop-44,8),{x:lo,y:Ct}=L3({sceneX:Le+e.width/2,sceneY:We},a),xt=lo-a.offsetLeft,To=Ct-a.offsetTop+16;return Bt(MG,{children:[!r&&xe("div",{className:"iqep__trigger-bar",style:{left:`${rr}px`,top:`${In}px`},onPointerDown:Y=>Y.stopPropagation(),onClick:Y=>Y.stopPropagation(),children:Bt("button",{className:"iqep__trigger-btn",onClick:()=>c(Y=>!Y),title:"Quick AI edit",children:[xe(kG,{}),xe("span",{children:"AI Edit"})]})}),l&&xe("div",{className:"igp iqep__panel",style:{left:`${xt}px`,top:`${To}px`},onPointerDown:Y=>Y.stopPropagation(),onClick:Y=>Y.stopPropagation(),children:Bt(nl,{isLoading:S,value:p,onValueChange:d,onSubmit:ie,className:"igp-container",children:[xe(rl,{placeholder:"Describe your edit\u2026",className:"igp-textarea",disableAutosize:!1}),P&&xe("div",{className:"igp-error",children:P}),Bt(il,{className:"igp-actions",children:[xe("div",{className:"igp-actions-left",children:Bt("div",{className:"igp-dropdown-root",ref:$,children:[xe(Tr,{tooltip:"Select model",side:"top",children:Bt("button",{className:"igp-btn",onClick:()=>{D(Y=>!Y),N(!1),B(!1)},disabled:S,children:[xe(IG,{}),xe("span",{children:u}),xe(F0,{})]})}),U&&xe("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--left",children:D0.map(Y=>Bt("button",{className:"igp-dropdown-item",onClick:()=>{h(Y),D(!1)},children:[xe("span",{style:{flex:1},children:Y}),Y===u&&xe("span",{className:"igp-check",children:xe(O0,{})})]},Y))})]})}),Bt("div",{className:"igp-actions-right",children:[Bt("div",{className:"igp-dropdown-root",ref:z,children:[Bt("button",{className:"igp-btn igp-btn--compact",onClick:()=>{w.length<=1||(B(Y=>!Y),N(!1),D(!1))},disabled:S||w.length<=1,title:w.length<=1?"Fixed resolution for this model":void 0,children:[xe("span",{children:k}),w.length>1&&xe(F0,{})]}),O&&w.length>1&&xe("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--right",children:w.map(Y=>Bt("button",{className:"igp-dropdown-item",onClick:()=>{L(Y),B(!1)},children:[xe("span",{style:{flex:1},children:Y}),Y===k&&xe("span",{className:"igp-check",children:xe(O0,{})})]},Y))})]}),Bt("div",{className:"igp-dropdown-root",ref:F,children:[Bt("button",{className:"igp-btn igp-btn--compact",onClick:()=>{N(Y=>!Y),B(!1),D(!1)},disabled:S,children:[xe("span",{children:v}),xe(F0,{})]}),M&&Bt("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--right igp-dropdown--ratio",children:[Bt("div",{className:"igp-dropdown-header",children:[xe("span",{children:"Output format"}),xe(TG,{})]}),E.map(Y=>{let te=pa(u,Y,k);return Bt("button",{className:"igp-dropdown-item",onClick:()=>Q(Y),children:[xe(SG,{label:Y}),xe("span",{style:{flex:1},children:Y}),Bt("span",{className:"igp-dims",children:[te.width,"\xD7",te.height]}),Y===v&&xe("span",{className:"igp-check",children:xe(O0,{})})]},Y)})]})]}),xe("button",{className:"igp-generate",onClick:S?ee:ie,disabled:!S&&!p.trim(),title:S?"Stop generation":"Generate edit",children:S?xe(CG,{}):xe(vG,{size:16})})]})]})]})})]})};import{Fragment as $G,jsx as it,jsxs as Cr}from"react/jsx-runtime";var H0="https://cloud.leonardo.ai/api/rest/v1",LG=1500,D3=40,N3=e=>({Authorization:`Bearer ${e}`,"Content-Type":"application/json"}),B3=e=>{switch(e){case"image/jpeg":return"jpeg";case"image/jpg":return"jpg";case"image/webp":return"webp";default:return"png"}},_G=e=>e==="upscale"?"Upscale":"Remove background",DG=e=>e==="upscale"?"Upscaling image...":"Removing background...",RG=e=>new Promise(t=>{window.setTimeout(t,e)}),Cu=async(e,t)=>{try{let o=await e.json(),n=o?.error?.message??o?.message??o?.detail??o?.errors?.[0]?.message;if(typeof n=="string"&&n.trim())return n}catch{}try{let o=await e.text();if(o.trim())return o.trim()}catch{}return`${t} (${e.status})`},R3=async(e,t)=>{let o=e.crop;return o?new Promise((n,r)=>{let i=new Image;i.onload=()=>{let a=document.createElement("canvas");a.width=o.width,a.height=o.height;let s=a.getContext("2d");if(!s){r(new Error("Could not prepare the cropped image for editing."));return}s.drawImage(i,o.x,o.y,o.width,o.height,0,0,o.width,o.height),n(a.toDataURL("image/png"))},i.onerror=()=>r(new Error("Could not read the selected image for editing.")),i.src=t}):t},NG=async(e,t)=>{let o=B3(Bo(e)),n=await fetch(`${H0}/init-image`,{method:"POST",headers:N3(t),body:JSON.stringify({extension:o})});if(!n.ok)throw new Error(await Cu(n,"Leonardo init image request failed"));let i=(await n.json()).uploadInitImage;if(!i?.id||!i.url)throw new Error("Leonardo init image response was incomplete.");let a=i.fields??{},s=typeof a=="string"?JSON.parse(a):a,l=new FormData;return Object.entries(s).forEach(([c,m])=>{l.append(c,m)}),l.append("file",th(e,`image.${o}`)),await fetch(i.url,{method:"POST",body:l,mode:"no-cors"}),i.id},BG=async(e,t)=>{let o=Bo(e),n=B3(o),r=th(e,`image.${n}`),i=new FormData;i.append("size","auto"),i.append("image_file",r);let a=await fetch("https://api.remove.bg/v1.0/removebg",{method:"POST",headers:{"X-Api-Key":t},body:i});if(!a.ok){let l=`Remove background failed (${a.status})`;try{let m=(await a.json())?.errors?.[0]?.title;m&&(l=m)}catch{}throw new Error(l)}let s=await a.arrayBuffer();return await za(new Blob([s],{type:"image/png"}))},FG=async(e,t)=>{let o=await fetch(`${H0}/variations/universal-upscaler`,{method:"POST",headers:N3(t),body:JSON.stringify({ultraUpscaleStyle:"ARTISTIC",creativityStrength:1,detailContrast:5,similarity:10,upscaleMultiplier:1.5,initImageId:e})});if(!o.ok)throw new Error(await Cu(o,"Leonardo upscale request failed"));let r=(await o.json()).universalUpscaler?.id;if(!r)throw new Error("Leonardo variation job id was missing from the response.");return r},OG=async(e,t)=>{for(let o=0;o<D3;o++){let n=await fetch(`${H0}/variations/${e}`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw new Error(await Cu(n,"Leonardo variation status check failed"));let r=await n.json(),i=Array.isArray(r.generated_image_variation_generic)?r.generated_image_variation_generic[0]:r.generated_image_variation_generic;if(!i)throw new Error("Leonardo variation details were missing from the response.");if(i.status==="COMPLETE"){if(!i.url)throw new Error("Leonardo variation completed without an image URL.");return i.url}if(i.status==="FAILED")throw new Error("Leonardo variation failed.");o<D3-1&&await RG(LG)}throw new Error("Leonardo variation timed out.")},zG=async e=>{let t=await fetch(e);if(!t.ok)throw new Error(await Cu(t,"Leonardo result image download failed"));return za(await t.blob())},HG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("path",{d:"M12 20h9"}),it("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"})]}),GG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),it("path",{d:"M9 3v18"}),it("path",{d:"M14 9l3-3 3 3"}),it("path",{d:"M17 6v6"})]}),UG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),it("path",{d:"M9 3v18M3 9h18M3 15h18M15 3v18",strokeDasharray:"2 2",opacity:"0.5"}),it("circle",{cx:"12",cy:"12",r:"4"})]}),WG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),it("polyline",{points:"7 10 12 15 17 10"}),it("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),YG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("path",{d:"M6.13 1L6 16a2 2 0 0 0 2 2h15"}),it("path",{d:"M1 6.13L16 6a2 2 0 0 1 2 2v15"})]}),VG=[{id:"quick-edit",label:"Quick Edit",icon:it(HG,{})},{id:"upscale",label:"Upscale",icon:it(GG,{})},{id:"remove-bg",label:"Remove BG",icon:it(UG,{})},{id:"crop",label:"Crop",icon:it(YG,{})}],F3=({element:e,app:t,callbacks:o})=>{let n=t.state,r=P3(t.props.leonardoApiKey),i=A3(t.props.removeBgApiKey),[a,s]=z0(()=>ca(e.id)),[l,c]=z0(null),[m,p]=z0(null),d=l!==null,u=Tu(async S=>{if(!r){p("No Leonardo API key found. Set VITE_APP_LEONARDO_API_KEY in .env or pass leonardoApiKey as a prop.");return}let _=e.fileId;if(!_){p("The selected image is missing its file reference.");return}let P=t.files[_]?.dataURL;if(!P){p("The selected image file could not be found.");return}let T=t.props.onBeforeUpscale,M=t.props.onAfterUpscale;if(T)try{let{allowed:N,error:O}=await T();if(!N){p(O||"Insufficient credits for upscale");return}}catch{p("Credit check failed");return}c(S),p(null);try{let N=await R3(e,P),O=await NG(N,r),B=await FG(O,r),U=await OG(B,r),D=await zG(U);await t.insertGeneratedImageNearElement(D,e,e.width,e.height),M?.()}catch(N){p(N instanceof Error?N.message:`${_G(S)} failed.`)}finally{c(null)}},[t,e,r]),h=Tu(async()=>{if(!i){p("No remove.bg API key found. Set VITE_APP_REMOVE_BG_API_KEY in .env or pass removeBgApiKey as a prop.");return}let S=e.fileId;if(!S){p("The selected image is missing its file reference.");return}let _=t.files[S]?.dataURL;if(!_){p("The selected image file could not be found.");return}let P=t.props.onBeforeRemoveBg,T=t.props.onAfterRemoveBg;if(P)try{let{allowed:M,error:N}=await P();if(!M){p(N||"Insufficient credits for remove background");return}}catch{p("Credit check failed");return}c("remove-bg"),p(null);try{let M=await R3(e,_),N=await BG(M,i);await t.insertGeneratedImageNearElement(N,e,e.width,e.height),T?.()}catch(M){p(M instanceof Error?M.message:"Remove background failed.")}finally{c(null)}},[t,e,i]),g=Tu(S=>{if(p(null),S==="quick-edit"){o?.onQuickEdit?o.onQuickEdit():s(P=>!P);return}if(S==="crop"){o?.onCrop?o.onCrop():t.actionManager.executeAction(Kc);return}let _={upscale:o?.onUpscale,"remove-bg":o?.onRemoveBG};if(_[S]){_[S]?.();return}S==="upscale"?u(S):S==="remove-bg"&&h()},[o,t.actionManager,u,h]),E=Tu(()=>{if(o?.onDownload){o.onDownload();return}let S=e.fileId;if(!S)return;let _=t.files[S];if(!_?.dataURL)return;let P=N=>{let O=document.createElement("a");O.href=N,O.download=`image-${S}.png`,document.body.appendChild(O),O.click(),document.body.removeChild(O)},T=e.crop;if(!T){P(_.dataURL);return}let M=new Image;M.onload=()=>{let N=document.createElement("canvas");N.width=T.width,N.height=T.height;let O=N.getContext("2d");if(!O){P(_.dataURL);return}O.drawImage(M,T.x,T.y,T.width,T.height,0,0,T.width,T.height),P(N.toDataURL("image/png"))},M.onerror=()=>P(_.dataURL),M.src=_.dataURL},[e.fileId,e.crop,t.files,o]);if(n.contextMenu||n.newElement||n.resizingElement||n.isRotating||n.openMenu||n.viewModeEnabled||n.selectedElementsAreBeingDragged)return null;let w=t.scene.getNonDeletedElementsMap(),[x,y]=AG(e,w),{x:v,y:I}=PG({sceneX:x+e.width/2,sceneY:y},n),k=v-n.offsetLeft,L=Math.max(I-n.offsetTop-52,8);return Cr($G,{children:[a&&!o?.onQuickEdit&&it(_3,{element:e,app:t,onBeforeImageGen:t.props.onBeforeImageGen,onAfterImageGen:t.props.onAfterImageGen,forceOpen:!0,onClose:()=>s(!1)}),Cr("div",{className:"iet",style:{left:`${k}px`,top:`${L}px`},onPointerDown:S=>S.stopPropagation(),onClick:S=>S.stopPropagation(),children:[Cr("div",{className:"iet__bar",children:[VG.map(S=>Cr("button",{type:"button",className:"iet__tool-btn",onClick:()=>g(S.id),title:S.label,disabled:d,"aria-busy":l===S.id,children:[S.icon,it("span",{className:"iet__tool-label",children:S.label}),S.badge&&it("span",{className:"iet__tool-badge",children:S.badge})]},S.id)),it("div",{className:"iet__divider"}),it("button",{type:"button",className:"iet__tool-btn iet__download-btn",onClick:E,title:"Download",disabled:d,children:it(WG,{})})]}),(l||m)&&it("div",{className:`iet__status${m?" iet__status--error":""}`,children:m??(l?DG(l):null)})]})]})};import{DEFAULT_LASER_COLOR as jG,easeOut as z3}from"@orangecatai/common";import{LaserPointer as KG}from"@excalidraw/laser-pointer";import{SVG_NS as O3,getSvgPathFromStroke as XG,sceneCoordsToViewportCoords as ZG}from"@orangecatai/common";var kr=class{constructor(t,o,n){this.animationFrameHandler=t;this.app=o;this.options=n;A(this,"currentTrail");A(this,"pastTrails",[]);A(this,"container");A(this,"trailElement");A(this,"trailAnimation");this.animationFrameHandler.register(this,this.onFrame.bind(this)),this.trailElement=document.createElementNS(O3,"path"),this.options.animateTrail&&(this.trailAnimation=document.createElementNS(O3,"animate"),this.trailAnimation.setAttribute("attributeName","stroke-dashoffset"),this.trailElement.setAttribute("stroke-dasharray","7 7"),this.trailElement.setAttribute("stroke-dashoffset","10"),this.trailAnimation.setAttribute("from","0"),this.trailAnimation.setAttribute("to","-14"),this.trailAnimation.setAttribute("dur","0.3s"),this.trailElement.appendChild(this.trailAnimation))}get hasCurrentTrail(){return!!this.currentTrail}hasLastPoint(t,o){if(this.currentTrail){let n=this.currentTrail.originalPoints.length;return this.currentTrail.originalPoints[n-1][0]===t&&this.currentTrail.originalPoints[n-1][1]===o}return!1}start(t){t&&(this.container=t),this.trailElement.parentNode!==this.container&&this.container&&this.container.appendChild(this.trailElement),this.animationFrameHandler.start(this)}stop(){this.animationFrameHandler.stop(this),this.trailElement.parentNode===this.container&&this.container?.removeChild(this.trailElement)}startPath(t,o){this.currentTrail=new KG(this.options),this.currentTrail.addPoint([t,o,performance.now()]),this.update()}addPointToPath(t,o){this.currentTrail&&(this.currentTrail.addPoint([t,o,performance.now()]),this.update())}endPath(){this.currentTrail&&(this.currentTrail.close(),this.currentTrail.options.keepHead=!1,this.pastTrails.push(this.currentTrail),this.currentTrail=void 0,this.update())}getCurrentTrail(){return this.currentTrail}clearTrails(){this.pastTrails=[],this.currentTrail=void 0,this.update()}update(){this.start(),this.trailAnimation&&(this.trailAnimation.setAttribute("begin","indefinite"),this.trailAnimation.setAttribute("repeatCount","indefinite"))}onFrame(){let t=[];for(let n of this.pastTrails)t.push(this.drawTrail(n,this.app.state));if(this.currentTrail){let n=this.drawTrail(this.currentTrail,this.app.state);t.push(n)}this.pastTrails=this.pastTrails.filter(n=>n.getStrokeOutline().length!==0),t.length===0&&this.stop();let o=t.join(" ").trim();this.trailElement.setAttribute("d",o),this.trailAnimation?(this.trailElement.setAttribute("fill",(this.options.fill??(()=>"black"))(this)),this.trailElement.setAttribute("stroke",(this.options.stroke??(()=>"black"))(this))):this.trailElement.setAttribute("fill",(this.options.fill??(()=>"black"))(this))}drawTrail(t,o){let n=t.getStrokeOutline(t.options.size/o.zoom.value).map(([i,a])=>{let s=ZG({sceneX:i,sceneY:a},o);return[s.x,s.y]}),r=this.trailAnimation?n.slice(0,n.length/2):n;return XG(r,!0)}};var ku=class{constructor(t,o){this.animationFrameHandler=t;this.app=o;A(this,"localTrail");A(this,"collabTrails",new Map);A(this,"container");this.animationFrameHandler.register(this,this.onFrame.bind(this)),this.localTrail=new kr(t,o,{...this.getTrailOptions(),fill:()=>jG})}getTrailOptions(){return{simplify:0,streamline:.4,sizeMapping:t=>{let r=Math.max(0,1-(performance.now()-t.pressure)/1e3),i=(50-Math.min(50,t.totalLength-t.currentIndex))/50;return Math.min(z3(i),z3(r))}}}startPath(t,o){this.localTrail.startPath(t,o)}addPointToPath(t,o){this.localTrail.addPointToPath(t,o)}endPath(){this.localTrail.endPath()}start(t){this.container=t,this.animationFrameHandler.start(this),this.localTrail.start(t)}stop(){this.animationFrameHandler.stop(this),this.localTrail.stop()}onFrame(){this.updateCollabTrails()}updateCollabTrails(){if(!(!this.container||this.app.state.collaborators.size===0)){for(let[t,o]of this.app.state.collaborators.entries()){let n;this.collabTrails.has(t)?n=this.collabTrails.get(t):(n=new kr(this.animationFrameHandler,this.app,{...this.getTrailOptions(),fill:()=>o.pointer?.laserColor||qi(t,o)}),n.start(this.container),this.collabTrails.set(t,n)),o.pointer&&o.pointer.tool==="laser"&&(o.button==="down"&&!n.hasCurrentTrail&&n.startPath(o.pointer.x,o.pointer.y),o.button==="down"&&n.hasCurrentTrail&&!n.hasLastPoint(o.pointer.x,o.pointer.y)&&n.addPointToPath(o.pointer.x,o.pointer.y),o.button==="up"&&n.hasCurrentTrail&&(n.addPointToPath(o.pointer.x,o.pointer.y),n.endPath()))}for(let t of this.collabTrails.keys())this.app.state.collaborators.has(t)||(this.collabTrails.get(t).stop(),this.collabTrails.delete(t))}}};import{version as qG}from"react";import{unstable_batchedUpdates as H3}from"react-dom";import{throttleRAF as JG}from"@orangecatai/common";var mt=e=>t=>{H3(e,t)},Su=e=>JG(t=>{H3(e,t)}),ha=(()=>{let e;try{let o=qG.split(".");e=Number(o[0])>17}catch{e=!1}let t=!1;return()=>window.EXCALIDRAW_THROTTLE_RENDER===!0?e?!0:(t||(t=!0,console.warn("Excalidraw: render throttling is disabled on React versions < 18.")),!1):!1})();import{CODES as G0,KEYS as rd,CLASSES as U0,POINTER_BUTTON as QG,THEME as eU,isWritableElement as tU,getFontString as G3,getFontFamilyString as U3,isTestEnv as W3,MIME_TYPES as W0,applyDarkModeFilter as oU}from"@orangecatai/common";import{getTextFromElements as nU,originalContainerCache as rU,updateBoundElements as Y3,updateOriginalContainerCache as V3}from"@orangecatai/element";import{LinearElementEditor as iU}from"@orangecatai/element";import{bumpVersion as aU}from"@orangecatai/element";import{getBoundTextElementId as sU,getContainerElement as Y0,getTextElementAngle as lU,redrawTextBoundingBox as cU,getBoundTextMaxHeight as dU,getBoundTextMaxWidth as $3,computeContainerDimensionForBoundText as K3,computeBoundTextPosition as mU,getBoundTextElement as pU}from"@orangecatai/element";import{getTextWidth as uU}from"@orangecatai/element";import{normalizeText as X3}from"@orangecatai/element";import{wrapText as gU}from"@orangecatai/element";import{isArrowElement as Mu,isBoundToContainer as hU,isTextElement as Z3}from"@orangecatai/element";var fU=(e,t,o,n,r,i)=>{let{zoom:a}=n,s=180*o/Math.PI,l=e*(a.value-1)/2,c=t*(a.value-1)/2;return e>r&&a.value!==1&&(l=r*(a.value-1)/2),t>i&&a.value!==1&&(c=i*(a.value-1)/2),`translate(${l}px, ${c}px) scale(${a.value}) rotate(${s}deg)`},j3=({id:e,onChange:t,onSubmit:o,getViewportCoords:n,element:r,canvas:i,excalidrawContainer:a,app:s,autoSelect:l=!0})=>{let c=(D,F)=>{if(!F.style.fontFamily||!F.style.fontSize)return!1;let z=F.style.fontFamily.replace(/"/g,"");return U3({fontFamily:D.fontFamily})!==z||`${D.fontSize}px`!==F.style.fontSize},m=s.state.theme,p=()=>{m=s.state.theme;let D=s.state,F=s.scene.getElement(e);if(!F)return;let{textAlign:z,verticalAlign:$}=F,V=s.scene.getNonDeletedElementsMap();if(F&&Z3(F)){let Q=F.x,ee=F.y,ie=Y0(F,s.scene.getNonDeletedElementsMap()),Ee=F.width,Le=F.height,De=F.width,We=F.height;if(ie&&F.containerId){if(Mu(ie)){let xt=iU.getBoundTextElementPosition(ie,F,V);Q=xt.x,ee=xt.y}let lo=c(F,d),Ct;if(lo?Ct=V3(ie.id,ie.height):(Ct=rU[ie.id],Ct||(Ct=V3(ie.id,ie.height))),De=$3(ie,F),We=dU(ie,F),!Mu(ie)&&Le>We){let xt=K3(Le,ie.type);s.scene.mutateElement(ie,{height:xt}),Y3(ie,s.scene);return}else if(!Mu(ie)&&ie.height>Ct.height&&Le<We){let xt=K3(Le,ie.type);s.scene.mutateElement(ie,{height:xt}),Y3(ie,s.scene)}else{let{x:xt,y:To}=mU(ie,F,V);Q=xt,ee=To}}let[lt,qt]=n(Q,ee);ie?Ee+=.5:(De=(D.width-8-lt)/D.zoom.value,Ee=Math.min(Ee,De)),Le*=1.05;let rr=G3(F),In=(D.height-qt)/D.zoom.value;Object.assign(d.style,{font:rr,lineHeight:F.lineHeight,width:`${Ee}px`,height:`${Le}px`,left:`${lt}px`,top:`${qt}px`,transform:fU(Ee,Le,lU(F,ie),D,De,In),textAlign:z,verticalAlign:$,color:D.theme===eU.DARK?oU(F.strokeColor):F.strokeColor,opacity:F.opacity/100,maxHeight:`${In}px`}),d.scrollTop=0,W3()&&(d.style.fontFamily=U3(F)),s.scene.mutateElement(F,{x:Q,y:ee})}},d=document.createElement("textarea");d.dir="auto",d.tabIndex=0,d.dataset.type="wysiwyg",d.wrap="off",d.classList.add("excalidraw-wysiwyg");let u="pre",h="normal";(hU(r)||!r.autoResize)&&(u="pre-wrap",h="break-word"),Object.assign(d.style,{position:"absolute",display:"inline-block",minHeight:"1em",backfaceVisibility:"hidden",margin:0,padding:0,border:0,outline:0,resize:"none",background:"transparent",overflow:"hidden",zIndex:"var(--zIndex-wysiwyg)",wordBreak:h,whiteSpace:u,overflowWrap:"break-word",boxSizing:"content-box"}),d.value=r.originalText,p(),t&&(d.onpaste=async D=>{let F=K2(D),z=null;if(F.has(W0.excalidrawClipboard)||F.has(W0.excalidraw)){D.preventDefault(),z=await Is(D);try{let ie=await Qm(z);if(ie.elements){let Ee=nU(ie.elements);if(Ee){let{selectionStart:Le,selectionEnd:De,value:We}=d;d.value=We.slice(0,Le)+Ee+We.slice(De);let lt=Le+Ee.length;d.selectionStart=d.selectionEnd=lt,d.dispatchEvent(new Event("input"))}}return}catch{console.warn("failed to parse excalidraw clipboard data")}}z=z||await Is(D);let $=z.findByType(W0.text);if(!$)return;let V=X3($.value);if(!V)return;let Q=Y0(r,s.scene.getNonDeletedElementsMap()),ee=G3({fontSize:s.state.currentItemFontSize,fontFamily:s.state.currentItemFontFamily});if(Q){let ie=pU(Q,s.scene.getNonDeletedElementsMap()),Ee=gU(`${d.value}${V}`,ee,$3(Q,ie)),Le=uU(Ee,ee);d.style.width=`${Le}px`}},d.oninput=()=>{let D=X3(d.value);if(d.value!==D){let F=d.selectionStart;d.value=D,d.selectionStart=F,d.selectionEnd=F}t(d.value)}),d.onkeydown=D=>{if(!D.shiftKey&&Wm.keyTest(D))D.preventDefault(),s.actionManager.executeAction(Wm),p();else if(!D.shiftKey&&Ym.keyTest(D))D.preventDefault(),s.actionManager.executeAction(Ym),p();else if(!D.shiftKey&&Vm.keyTest(D))D.preventDefault(),s.actionManager.executeAction(Vm),p();else if(uf.keyTest(D))s.actionManager.executeAction(uf);else if(gf.keyTest(D))s.actionManager.executeAction(gf);else if(D.key===rd.ESCAPE)D.preventDefault(),k=!0,L();else if(Zi.keyTest(D))D.preventDefault(),L(),s.actionManager.executeAction(Zi);else if(D.key===rd.ENTER&&D[rd.CTRL_OR_CMD]){if(D.preventDefault(),D.isComposing||D.keyCode===229)return;k=!0,L()}else if(D.key===rd.TAB||D[rd.CTRL_OR_CMD]&&(D.code===G0.BRACKET_LEFT||D.code===G0.BRACKET_RIGHT)){if(D.preventDefault(),D.isComposing)return;D.shiftKey||D.code===G0.BRACKET_LEFT?y():x(),d.dispatchEvent(new Event("input"))}};let g=4,E=" ".repeat(g),w=new RegExp(`^ {1,${g}}`),x=()=>{let{selectionStart:D,selectionEnd:F}=d,z=v(),$=d.value;z.forEach(V=>{let Q=$.slice(0,V),ee=$.slice(V);$=`${Q}${E}${ee}`}),d.value=$,d.selectionStart=D+g,d.selectionEnd=F+g*z.length},y=()=>{let{selectionStart:D,selectionEnd:F}=d,z=v(),$=[],V=d.value;z.forEach(Q=>{let ee=V.slice(Q,Q+g).match(w);if(ee){let ie=V.slice(0,Q),Ee=V.slice(Q+ee[0].length);V=`${ie}${Ee}`,$.push(Q)}}),d.value=V,$.length&&(D>$[$.length-1]?d.selectionStart=Math.max(D-g,$[$.length-1]):d.selectionStart=D,d.selectionEnd=Math.max(d.selectionStart,F-g*$.length))},v=()=>{let{selectionStart:D,selectionEnd:F,value:z}=d,$=z.slice(0,D).match(/[^\n]*$/)[0].length;return D=D-$,z.slice(D,F).split(`
105
- `).reduce((Q,ee,ie,Ee)=>Q.concat(ie?Q[ie-1]+Ee[ie-1].length+1:D),[]).reverse()},I=D=>{D.target instanceof HTMLCanvasElement&&(D.preventDefault(),D.stopPropagation())},k=!1,L=()=>{if(B)return;B=!0,S();let D=s.scene.getElement(r.id);if(!D)return;let F=Y0(D,s.scene.getNonDeletedElementsMap());if(F){if(d.value.trim()){let z=sU(F);!z||z!==r.id?s.scene.mutateElement(F,{boundElements:(F.boundElements||[]).concat({type:"text",id:r.id})}):Mu(F)&&aU(F)}else s.scene.mutateElement(F,{boundElements:F.boundElements?.filter(z=>!Z3(z))});cU(D,F,s.scene)}o({viaKeyboard:k,nextOriginalText:d.value})},S=()=>{d.onblur=null,d.oninput=null,d.onkeydown=null,U&&U.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("wheel",I,!0),window.removeEventListener("pointerdown",T),window.removeEventListener("pointerup",_),window.removeEventListener("blur",L),window.removeEventListener("beforeunload",L),N(),M(),O(),d.remove()},_=D=>{window.removeEventListener("pointerup",_);let F=D?.target,z=F instanceof HTMLElement&&F.classList.contains("properties-trigger"),$=(F instanceof HTMLElement||F instanceof SVGElement)&&!!F.closest(".properties-content"),V=(F instanceof HTMLElement||F instanceof SVGElement)&&(!!F.closest(`.${U0.SHAPE_ACTIONS_MENU}`)||!!F.closest(".compact-shape-actions-island"));setTimeout(()=>{V||z||$||(d.onblur=L,d.focus())})},P=()=>{d.onblur=null,window.addEventListener("pointerup",_),window.addEventListener("blur",L)},T=D=>{let F=D?.target;if(D.button===QG.WHEEL){F instanceof HTMLTextAreaElement&&(D.preventDefault(),s.handleCanvasPanUsingWheelOrSpaceDrag(D)),P();return}let z=F instanceof HTMLElement&&F.classList.contains("properties-trigger"),$=(F instanceof HTMLElement||F instanceof SVGElement)&&!!F.closest(".properties-content");(D.target instanceof HTMLElement||D.target instanceof SVGElement)&&(D.target.closest(`.${U0.SHAPE_ACTIONS_MENU}, .${U0.ZOOM_ACTIONS}`)||D.target.closest(".compact-shape-actions-island"))&&!tU(D.target)||z||$?P():D.target instanceof HTMLCanvasElement&&!W3()&&requestAnimationFrame(()=>{L()})},M=s.onChangeEmitter.on(D=>{s.state.theme!==m&&p()}),N=s.scene.onUpdate(()=>{p(),!!document.activeElement?.closest(".properties-content")||d.focus()}),O=s.onScrollChangeEmitter.on(()=>{p()}),B=!1;l&&d.select(),_();let U=null;return i&&"ResizeObserver"in window?(U=new window.ResizeObserver(()=>{p()}),U.observe(i)):window.addEventListener("resize",p),d.onpointerdown=D=>D.stopPropagation(),requestAnimationFrame(()=>{window.addEventListener("pointerdown",T,{capture:!0})}),window.addEventListener("beforeunload",L),a?.querySelector(".excalidraw-textEditorContainer").appendChild(d),L};import{getGlobalCSSVariable as Pu}from"@orangecatai/common";import{getCommonBounds as bU}from"@orangecatai/element";var Sr=4,Ko=6,q3="rgba(0,0,0,0.3)",J3=(e,t,o,n)=>{if(!e.size)return{horizontal:null,vertical:null};let[r,i,a,s]=bU(e),l=t/n.zoom.value,c=o/n.zoom.value,m={top:parseInt(Pu("sat"))||0,bottom:parseInt(Pu("sab"))||0,left:parseInt(Pu("sal"))||0,right:parseInt(Pu("sar"))||0},p=lr().rtl,d=-n.scrollX+m.left,u=-n.scrollY+m.top,h=d+l-m.right,g=u+c-m.bottom,E=Math.min(r,d),w=Math.min(i,u),x=Math.max(a,h),y=Math.max(s,g),v=a-r,I=s-i,k=x-E,L=y-w,S=Math.max(Sr*2,m.left+m.right)+Ko*2,_=t*(l/k)-S,P=Math.max(Sr*2,m.top+m.bottom)+Ko*2,T=o*(c/L)-P,M=k>v?k*n.zoom.value/(_+S):t/(_+S),N=L>I?L*n.zoom.value/(T+P):o/(T+P);return{horizontal:d===E&&h===x?null:{x:Math.max(m.left,Sr)+Ko+(d-E)/k*t,y:o-Ko-Math.max(Sr,m.bottom),width:_,height:Ko,deltaMultiplier:M},vertical:u===w&&g===y?null:{x:p?Math.max(m.left,Sr):t-Ko-Math.max(m.right,Sr),y:Math.max(m.top,Sr)+Ko+(u-w)/L*o,width:Ko,height:T,deltaMultiplier:N}}},V0=(e,t,o)=>{let[n,r]=[e.horizontal,e.vertical].map(a=>a!=null&&a.x<=t&&t<=a.x+a.width&&a.y<=o&&o<=a.y+a.height);return{isOverEither:n||r,isOverHorizontal:n,isOverVertical:r}};var Q3=e=>{let t=["flowchart","graph","sequenceDiagram","classDiagram","stateDiagram","stateDiagram-v2","erDiagram","journey","gantt","pie","quadrantChart","requirementDiagram","gitGraph","C4Context","mindmap","timeline","zenuml","sankey","xychart","block"];return new RegExp(`^(?:%%{.*?}%%[\\s\\n]*)?\\b(?:${t.map(n=>`\\s*${n}(-beta)?`).join("|")})\\b`).test(e.trim())};import{pointFrom as SU}from"@orangecatai/math";import{getElementLineSegments as MU}from"@orangecatai/element";import{LinearElementEditor as PU}from"@orangecatai/element";import{isFrameLikeElement as AU,isLinearElement as LU,isTextElement as _U}from"@orangecatai/element";import{getFrameChildren as DU}from"@orangecatai/element";import{selectGroupsForSelectedElements as RU}from"@orangecatai/element";import{getContainerElement as NU}from"@orangecatai/element";import{arrayToMap as BU,easeOut as nk,isShallowEqual as FU}from"@orangecatai/common";import{simplify as xU}from"points-on-curve";import{polygonFromPoints as EU,lineSegment as ek,polygonIncludesPointNonZero as yU}from"@orangecatai/math";import{computeBoundTextPosition as wU,doBoundsIntersect as vU,getBoundTextElement as IU,getElementBounds as TU,intersectElementWithLineSegment as tk}from"@orangecatai/element";var ok=e=>{let{lassoPath:t,elements:o,elementsMap:n,elementsSegments:r,intersectedElements:i,enclosedElements:a,simplifyDistance:s}=e,l=t;s&&(l=xU(t,s));let c=o.filter(d=>!d.locked);a.clear(),i.clear();let m=t.reduce((d,u)=>[Math.min(d[0],u[0]),Math.min(d[1],u[1]),Math.max(d[2],u[0]),Math.max(d[3],u[1])],[1/0,1/0,-1/0,-1/0]);for(let d of c){let u=TU(d,n);vU(m,u)&&!i.has(d.id)&&!a.has(d.id)&&(CU(l,d,r)?a.add(d.id):kU(l,d,n)&&i.add(d.id))}return{selectedElementIds:[...i,...a]}},CU=(e,t,o)=>{let n=EU(e),r=o.get(t.id);return r?r.some(i=>i.some(a=>yU(a,n))):!1},kU=(e,t,o)=>{let n=e.slice(1).map((i,a)=>ek(e[a],i)).concat([ek(e[e.length-1],e[0])]),r=IU(t,o);return n.some(i=>tk(t,o,i,0,!0).length>0||!!r&&tk({...r,...wU(t,r,o)},o,i,0,!0).length>0)};var Au=class extends kr{constructor(o,n){super(o,n,{animateTrail:!0,streamline:.4,sizeMapping:r=>{let s=Math.max(0,1-(performance.now()-r.pressure)/(1/0)),l=(5e3-Math.min(5e3,r.totalLength-r.currentIndex))/5e3;return Math.min(nk(l),nk(s))},fill:()=>"rgba(105,101,219,0.05)",stroke:()=>"rgba(105,101,219)"});A(this,"intersectedElements",new Set);A(this,"enclosedElements",new Set);A(this,"elementsSegments",null);A(this,"canvasTranslate",null);A(this,"keepPreviousSelection",!1);A(this,"selectElementsFromIds",o=>{this.app.setState(n=>{let r=o.reduce((l,c)=>(l[c]=!0,l),{});if(this.keepPreviousSelection)for(let l of Object.keys(n.selectedElementIds))r[l]=!0;for(let[l]of Object.entries(r)){let c=this.app.scene.getNonDeletedElement(l);if(c&&_U(c)){let m=NU(c,this.app.scene.getNonDeletedElementsMap());m&&(r[m.id]=!0,delete r[c.id])}}for(let[l]of Object.entries(r)){let c=this.app.scene.getNonDeletedElement(l);if(c&&AU(c)){let m=DU(this.app.scene.getNonDeletedElementsMap(),c.id);for(let p of m)delete r[p.id]}}let i=RU({editingGroupId:n.editingGroupId,selectedElementIds:r},this.app.scene.getNonDeletedElements(),n,this.app),a=[...Object.keys(i.selectedElementIds)],s=[...Object.keys(i.selectedGroupIds)];return{selectedElementIds:i.selectedElementIds,selectedGroupIds:i.selectedGroupIds,selectedLinearElement:a.length===1&&!s.length&&LU(this.app.scene.getNonDeletedElement(a[0]))?new PU(this.app.scene.getNonDeletedElement(a[0]),this.app.scene.getNonDeletedElementsMap()):null}})});A(this,"addPointToPath",(o,n,r=!1)=>{super.addPointToPath(o,n),this.keepPreviousSelection=r,this.updateSelection()});A(this,"updateSelection",()=>{let o=super.getCurrentTrail()?.originalPoints?.map(r=>SU(r[0],r[1])),n={scrollX:this.app.state.scrollX,scrollY:this.app.state.scrollY,zoom:this.app.state.zoom.value};if(!this.elementsSegments||!FU(n,this.canvasTranslate??{})){this.canvasTranslate=n,this.elementsSegments=new Map;let r=BU(this.app.visibleElements);for(let i of this.app.visibleElements){let a=MU(i,r);this.elementsSegments.set(i.id,a)}}if(o){let{selectedElementIds:r}=ok({lassoPath:o,elements:this.app.visibleElements,elementsMap:this.app.scene.getNonDeletedElementsMap(),elementsSegments:this.elementsSegments,intersectedElements:this.intersectedElements,enclosedElements:this.enclosedElements,simplifyDistance:5/this.app.state.zoom.value});this.selectElementsFromIds(r)}})}startPath(o,n,r=!1){this.endPath(),super.startPath(o,n),this.intersectedElements.clear(),this.enclosedElements.clear(),this.keepPreviousSelection=r,this.keepPreviousSelection||this.app.setState({selectedElementIds:{},selectedGroupIds:{},selectedLinearElement:null})}endPath(){super.endPath(),super.clearTrails(),this.intersectedElements.clear(),this.enclosedElements.clear(),this.elementsSegments=null}};import{arrayToMap as OU,easeOut as rk,THEME as zU}from"@orangecatai/common";import{computeBoundTextPosition as HU,doBoundsIntersect as GU,getBoundTextElement as UU,getElementBounds as WU,getElementLineSegments as YU,getFreedrawOutlineAsSegments as VU,getFreedrawOutlinePoints as $U,intersectElementWithLineSegment as ik,isArrowElement as KU,isFreeDrawElement as ak,isLineElement as XU,isPointInElement as ZU}from"@orangecatai/element";import{lineSegment as jU,lineSegmentsDistance as sk,pointFrom as uk,polygon as qU,polygonIncludesPointNonZero as JU}from"@orangecatai/math";import{getElementsInGroup as lk}from"@orangecatai/element";import{shouldTestInside as QU}from"@orangecatai/element";import{hasBoundTextElement as ck,isBoundToContainer as dk}from"@orangecatai/element";import{getBoundTextElementId as mk}from"@orangecatai/element";var Lu=class extends kr{constructor(o,n){super(o,n,{streamline:.2,size:5,keepHead:!0,sizeMapping:r=>{let s=Math.max(0,1-(performance.now()-r.pressure)/200),l=(10-Math.min(10,r.totalLength-r.currentIndex))/10;return Math.min(rk(l),rk(s))},fill:()=>n.state.theme===zU.LIGHT?"rgba(0, 0, 0, 0.2)":"rgba(255, 255, 255, 0.2)"});A(this,"elementsToErase",new Set);A(this,"groupsToErase",new Set)}startPath(o,n){this.endPath(),super.startPath(o,n),this.elementsToErase.clear()}addPointToPath(o,n,r=!1){return super.addPointToPath(o,n),this.updateElementsToBeErased(r)}updateElementsToBeErased(o){let n=super.getCurrentTrail()?.originalPoints?.map(s=>uk(s[0],s[1]))||[];if(n.length<2)return[];let r=jU(n[n.length-1],n[n.length-2]),i=this.app.visibleElements.filter(s=>!s.locked),a=OU(i);for(let s of i)if(o&&this.elementsToErase.has(s.id)){if(pk(r,s,a,this.app.state.zoom.value)){let c=s.groupIds.at(-1);if(this.groupsToErase.has(c)){let m=lk(this.app.scene.getNonDeletedElementsMap(),c);for(let p of m)this.elementsToErase.delete(p.id);this.groupsToErase.delete(c)}if(dk(s)&&this.elementsToErase.delete(s.containerId),ck(s)){let m=mk(s);m&&this.elementsToErase.delete(m)}this.elementsToErase.delete(s.id)}}else if(!o&&!this.elementsToErase.has(s.id)&&pk(r,s,a,this.app.state.zoom.value)){let c=s.groupIds.at(-1);if(!this.groupsToErase.has(c)){let m=lk(this.app.scene.getNonDeletedElementsMap(),c);for(let p of m)this.elementsToErase.add(p.id);this.groupsToErase.add(c)}if(ck(s)){let m=mk(s);m&&this.elementsToErase.add(m)}dk(s)&&this.elementsToErase.add(s.containerId),this.elementsToErase.add(s.id)}return Array.from(this.elementsToErase)}endPath(){super.endPath(),super.clearTrails(),this.elementsToErase.clear(),this.groupsToErase.clear()}},pk=(e,t,o,n)=>{let r=e[1],i=ak(t)?15:t.strokeWidth/2,a=[Math.min(e[0][0],e[1][0])-i,Math.min(e[0][1],e[1][1])-i,Math.max(e[0][0],e[1][0])+i,Math.max(e[0][1],e[1][1])+i],s=WU(t,o),l=[s[0]-i,s[1]-i,s[2]+i,s[3]+i];if(!GU(a,l))return!1;if(QU(t)&&ZU(r,t,o))return!0;if(ak(t)){let m=$U(t),p=VU(t,m,o),d=Math.max(2.25,5/n);for(let h of p)if(sk(h,e)<=d)return!0;let u=qU(...m.map(([h,g])=>uk(t.x+h,t.y+g)));return!!JU(e[0],u)}let c=UU(t,o);if(KU(t)||XU(t)&&!t.polygon){let m=Math.max(t.strokeWidth,t.strokeWidth*2/n),p=YU(t,o);for(let d of p)if(sk(d,e)<=m)return!0;return!1}return ik(t,o,e,0,!0).length>0||!!c&&ik({...c,...HU(t,c,o)},o,e,0,!0).length>0};import{jsx as Xo,jsxs as gk}from"react/jsx-runtime";var eW=()=>gk("div",{"data-testid":"brave-measure-text-error",children:[Xo("p",{children:Xo(no,{i18nKey:"errors.brave_measure_text_error.line1",bold:e=>Xo("span",{style:{fontWeight:600},children:e})})}),Xo("p",{children:Xo(no,{i18nKey:"errors.brave_measure_text_error.line2",bold:e=>Xo("span",{style:{fontWeight:600},children:e})})}),Xo("p",{children:Xo(no,{i18nKey:"errors.brave_measure_text_error.line3",link:e=>Xo("a",{href:"http://docs.excalidraw.com/docs/@orangecatai/adgen-canvas/faq#turning-off-aggresive-block-fingerprinting-in-brave-browser",children:e})})}),Xo("p",{children:Xo(no,{i18nKey:"errors.brave_measure_text_error.line4",issueLink:e=>Xo("a",{href:"https://github.com/excalidraw/excalidraw/issues/new",children:e}),discordLink:e=>gk("a",{href:"https://discord.gg/UexuTaE",children:[e,"."]})})})]}),hk=eW;import sW from"clsx";import lW from"react";import{useLayoutEffect as tW,useRef as fk,useEffect as bk}from"react";import{unstable_batchedUpdates as oW}from"react-dom";import{KEYS as nW,queryFocusableElements as rW}from"@orangecatai/common";import iW from"clsx";import{jsx as aW}from"react/jsx-runtime";var xk=({children:e,left:t,top:o,onCloseRequest:n,fitInViewport:r=!1,offsetLeft:i=0,offsetTop:a=0,viewportWidth:s=window.innerWidth,viewportHeight:l=window.innerHeight,className:c})=>{let m=fk(null);bk(()=>{let d=m.current;if(!d)return;d.contains(document.activeElement)||d.focus();let u=h=>{if(h.key===nW.TAB){let g=rW(d),{activeElement:E}=document,w=g.findIndex(x=>x===E);E===d?(h.shiftKey?g[g.length-1]?.focus():g[0].focus(),h.preventDefault(),h.stopImmediatePropagation()):w===0&&h.shiftKey?(g[g.length-1]?.focus(),h.preventDefault(),h.stopImmediatePropagation()):w===g.length-1&&!h.shiftKey&&(g[0]?.focus(),h.preventDefault(),h.stopImmediatePropagation())}};return d.addEventListener("keydown",u),()=>d.removeEventListener("keydown",u)},[]);let p=fk(null);return tW(()=>{if(r&&m.current&&o!=null&&t!=null){let d=m.current,{width:u,height:h}=d.getBoundingClientRect();if(p.current?.top===o&&p.current?.left===t)return;p.current={top:o,left:t},u>=s?(d.style.width=`${s}px`,d.style.left="0px",d.style.overflowX="scroll"):t+u-i>s?d.style.left=`${s-u-10}px`:d.style.left=`${t}px`,h>=l?(d.style.height=`${l-20}px`,d.style.top="10px",d.style.overflowY="scroll"):o+h-a>l?d.style.top=`${l-h}px`:d.style.top=`${o}px`}},[o,t,r,s,l,i,a]),bk(()=>{if(n){let d=u=>{m.current?.contains(u.target)||oW(()=>n(u))};return document.addEventListener("pointerdown",d,!1),()=>document.removeEventListener("pointerdown",d,!1)}},[n]),aW("div",{className:iW("popover",c),ref:m,tabIndex:-1,children:e})};import{jsx as al,jsxs as cW}from"react/jsx-runtime";var yt="separator",Ek=lW.memo(({actionManager:e,items:t,top:o,left:n,onClose:r})=>{let i=Go(),a=Hr(),s=t.reduce((l,c)=>(c&&(c===yt||!c.predicate||c.predicate(a,i,e.app.props,e.app))&&l.push(c),l),[]);return al(xk,{onCloseRequest:()=>{r()},top:o,left:n,fitInViewport:!0,offsetLeft:i.offsetLeft,offsetTop:i.offsetTop,viewportWidth:i.width,viewportHeight:i.height,className:"context-menu-popover",children:al("ul",{className:"context-menu",onContextMenu:l=>l.preventDefault(),children:s.map((l,c)=>{if(l===yt)return!s[c-1]||s[c-1]===yt?null:al("hr",{className:"context-menu-item-separator"},c);let m=l.name,p="";return l.label&&(typeof l.label=="function"?p=f(l.label(a,i,e.app)):p=f(l.label)),al("li",{"data-testid":m,onClick:()=>{r(()=>{e.executeAction(l,"contextMenu")})},children:cW("button",{type:"button",className:sW("context-menu-item",{dangerous:m==="deleteSelectedElements",checkmark:l.checked?.(i)}),children:[al("div",{className:"context-menu-item__label",children:p}),al("kbd",{className:"context-menu-item__shortcut",children:m?Ke(m):""})]})},c)})})})});import{jsx as $0,jsxs as yk}from"react/jsx-runtime";var dW=({height:e,width:t,userToFollow:o,onDisconnect:n})=>$0("div",{className:"follow-mode",style:{width:t,height:e},children:yk("div",{className:"follow-mode__badge",children:[yk("div",{className:"follow-mode__badge__label",children:["Following"," ",$0("span",{className:"follow-mode__badge__username",title:o.username,children:o.username})]}),$0("button",{type:"button",onClick:n,className:"follow-mode__disconnect-btn",children:Fo})]})}),wk=dW;import Ia from"clsx";import xX from"react";import{CLASSES as EX,DEFAULT_SIDEBAR as sx,TOOL_TYPE as C4,arrayToMap as yX,capitalizeString as wX,isShallowEqual as bg}from"@orangecatai/common";import{mutateElement as vX}from"@orangecatai/element";import{showSelectedShapeActions as IX}from"@orangecatai/element";import{ShapeCache as TX}from"@orangecatai/element";import mW from"clsx";import{useState as pW,useEffect as uW}from"react";import{THEME as gW}from"@orangecatai/common";import{jsx as K0,jsxs as hW}from"react/jsx-runtime";var _u=({delay:e,theme:t})=>{let[o,n]=pW(!!e);return uW(()=>{if(!e)return;let r=setTimeout(()=>{n(!1)},e);return()=>clearTimeout(r)},[e]),o?null:hW("div",{className:mW("LoadingMessage",{"LoadingMessage--dark":t===gW.DARK}),children:[K0("div",{children:K0(Gt,{})}),K0("div",{className:"LoadingMessage-text",children:f("labels.loadingScene")})]})};import fW from"clsx";import{jsx as Ik,jsxs as xW}from"react/jsx-runtime";var bW="medium",vk={CHECKED:Wa,UNCHECKED:Fi},Tk=e=>xW("label",{className:fW("ToolIcon ToolIcon__lock",`ToolIcon_size_${bW}`,{"is-mobile":e.isMobile}),title:`${e.title} \u2014 Q`,children:[Ik("input",{className:"ToolIcon_type_checkbox",type:"checkbox",name:e.name,onChange:e.onChange,checked:e.checked,"aria-label":e.title,"data-testid":"toolbar-lock"}),Ik("div",{className:"ToolIcon__icon",children:e.checked?vk.CHECKED:vk.UNCHECKED})]});import{useState as Du,useEffect as Sk}from"react";import sl from"clsx";import{KEYS as X0,capitalizeString as vt}from"@orangecatai/common";import EW from"clsx";import{KEYS as Ck}from"@orangecatai/common";import{jsx as yW}from"react/jsx-runtime";var kk=e=>yW(ne,{className:EW("Shape",{fillable:!1,active:e.checked}),type:"radio",icon:Ja,name:"editor-current-shape",checked:e.checked,title:`${e.title} \u2014 H`,keyBindingLabel:e.isMobile?void 0:Ck.H.toLocaleUpperCase(),"aria-label":`${e.title} \u2014 H`,"aria-keyshortcuts":Ck.H,"data-testid":"toolbar-hand",onChange:()=>e.onChange?.()});import{Fragment as wW,jsx as wt,jsxs as Ru}from"react/jsx-runtime";var Z0=[{type:"rectangle",icon:Ya,title:vt(f("toolBar.rectangle"))},{type:"diamond",icon:Va,title:vt(f("toolBar.diamond"))},{type:"ellipse",icon:$a,title:vt(f("toolBar.ellipse"))}],j0=[{type:"selection",icon:Oi,title:vt(f("toolBar.selection"))},{type:"lasso",icon:Nr,title:vt(f("toolBar.lasso"))}],q0=[{type:"arrow",icon:am,title:vt(f("toolBar.arrow"))},{type:"line",icon:Ka,title:vt(f("toolBar.line"))}],Mk=({app:e,onHandToolToggle:t,setAppState:o})=>{let n=e.state.activeTool,[r,i]=Du(!1),[a,s]=Du("rectangle"),[l,c]=Du("arrow");Sk(()=>{(n.type==="rectangle"||n.type==="diamond"||n.type==="ellipse")&&s(n.type)},[n.type]),Sk(()=>{(n.type==="arrow"||n.type==="line")&&c(n.type)},[n.type]);let m=n.type==="frame",p=n.type==="laser",d=n.type==="embeddable",{TTDDialogTriggerTunnel:u}=Xe(),h=(M,N)=>{e.state.activeTool.type!==M&&ge("toolbar",M,"ui"),M==="selection"?e.state.activeTool.type==="selection"||e.setActiveTool({type:"selection"}):e.setActiveTool({type:M})},[g,E]=Du(0),w=36,x=4,y=7,v=y*w+(y-1)*x,I=w+x,k=g>=v+1*I,L=g>=v+2*I,S=g>=v+3*I,P=["text","frame","embeddable","laser","magicframe"].filter(M=>!(k&&M==="text"||L&&M==="image"||S&&M==="frame")).includes(n.type),T=P?n.type==="text"?_n:n.type==="image"?Xa:n.type==="frame"?Dn:n.type==="embeddable"?Za:n.type==="laser"?Rn:n.type==="magicframe"?Gi:Ql:Ql;return Ru("div",{className:"mobile-toolbar",ref:M=>{M&&E(M.getBoundingClientRect().width)},children:[wt(kk,{checked:sr(e.state),onChange:t,title:f("toolBar.hand"),isMobile:!0}),wt($s,{app:e,options:j0,activeTool:n,defaultOption:e.state.preferredSelectionTool.type,namePrefix:"selectionType",title:vt(f("toolBar.selection")),"data-testid":"toolbar-selection",onToolChange:M=>{(M==="selection"||M==="lasso")&&(e.setActiveTool({type:M}),o({preferredSelectionTool:{type:M,initialized:!0}}))},displayedOption:j0.find(M=>M.type===e.state.preferredSelectionTool.type)||j0[0]}),wt(ne,{className:sl({active:n.type==="freedraw"}),type:"radio",icon:Ln,checked:n.type==="freedraw",name:"editor-current-shape",title:`${vt(f("toolBar.freedraw"))}`,"aria-label":vt(f("toolBar.freedraw")),"data-testid":"toolbar-freedraw",onChange:()=>h("freedraw")}),wt(ne,{className:sl({active:n.type==="eraser"}),type:"radio",icon:sm,checked:n.type==="eraser",name:"editor-current-shape",title:`${vt(f("toolBar.eraser"))}`,"aria-label":vt(f("toolBar.eraser")),"data-testid":"toolbar-eraser",onChange:()=>h("eraser")}),wt($s,{app:e,options:Z0,activeTool:n,defaultOption:a,namePrefix:"shapeType",title:vt(f(a==="rectangle"?"toolBar.rectangle":a==="diamond"?"toolBar.diamond":a==="ellipse"?"toolBar.ellipse":"toolBar.rectangle")),"data-testid":"toolbar-rectangle",onToolChange:M=>{(M==="rectangle"||M==="diamond"||M==="ellipse")&&(s(M),e.setActiveTool({type:M}))},displayedOption:Z0.find(M=>M.type===a)||Z0[0]}),wt($s,{app:e,options:q0,activeTool:n,defaultOption:l,namePrefix:"linearElementType",title:vt(f(l==="arrow"?"toolBar.arrow":"toolBar.line")),"data-testid":"toolbar-arrow",fillable:!0,onToolChange:M=>{(M==="arrow"||M==="line")&&(c(M),e.setActiveTool({type:M}))},displayedOption:q0.find(M=>M.type===l)||q0[0]}),k&&wt(ne,{className:sl({active:n.type==="text"}),type:"radio",icon:_n,checked:n.type==="text",name:"editor-current-shape",title:`${vt(f("toolBar.text"))}`,"aria-label":vt(f("toolBar.text")),"data-testid":"toolbar-text",onChange:()=>h("text")}),L&&wt(ne,{className:sl({active:n.type==="image"}),type:"radio",icon:Xa,checked:n.type==="image",name:"editor-current-shape",title:`${vt(f("toolBar.image"))}`,"aria-label":vt(f("toolBar.image")),"data-testid":"toolbar-image",onChange:()=>h("image")}),S&&wt(ne,{className:sl({active:m}),type:"radio",icon:Dn,checked:m,name:"editor-current-shape",title:`${vt(f("toolBar.frame"))}`,"aria-label":vt(f("toolBar.frame")),"data-testid":"toolbar-frame",onChange:()=>h("frame")}),Ru(he,{open:r,children:[wt(he.Trigger,{className:sl("App-toolbar__extra-tools-trigger App-toolbar__extra-tools-trigger--mobile",{"App-toolbar__extra-tools-trigger--selected":P||r}),onToggle:()=>{i(!r),o({openMenu:null,openPopup:null})},title:f("toolBar.extraTools"),style:{width:w,height:w,display:"flex",alignItems:"center",justifyContent:"center"},children:T}),Ru(he.Content,{onClickOutside:()=>i(!1),onSelect:()=>i(!1),className:"App-toolbar__extra-tools-dropdown",align:"start",children:[!k&&wt(he.Item,{onSelect:()=>e.setActiveTool({type:"text"}),icon:_n,shortcut:X0.T.toLocaleUpperCase(),"data-testid":"toolbar-text",selected:n.type==="text",children:f("toolBar.text")}),!L&&wt(he.Item,{onSelect:()=>e.setActiveTool({type:"image"}),icon:Xa,"data-testid":"toolbar-image",selected:n.type==="image",children:f("toolBar.image")}),!S&&wt(he.Item,{onSelect:()=>e.setActiveTool({type:"frame"}),icon:Dn,shortcut:X0.F.toLocaleUpperCase(),"data-testid":"toolbar-frame",selected:m,children:f("toolBar.frame")}),wt(he.Item,{onSelect:()=>e.setActiveTool({type:"embeddable"}),icon:Za,"data-testid":"toolbar-embeddable",selected:d,children:f("toolBar.embeddable")}),wt(he.Item,{onSelect:()=>e.setActiveTool({type:"laser"}),icon:Rn,"data-testid":"toolbar-laser",selected:p,shortcut:X0.K.toLocaleUpperCase(),children:f("toolBar.laser")}),wt("div",{style:{margin:"6px 0",fontSize:14,fontWeight:600},children:"Generate"}),e.props.aiEnabled!==!1&&wt(u.Out,{}),wt(he.Item,{onSelect:()=>e.setOpenDialog({name:"ttd",tab:"mermaid"}),icon:es,"data-testid":"toolbar-embeddable",children:f("toolBar.mermaidToExcalidraw")}),e.props.aiEnabled!==!1&&e.plugins.diagramToCode&&wt(wW,{children:Ru(he.Item,{onSelect:()=>e.onMagicframeToolSelect(),icon:Gi,"data-testid":"toolbar-magicframe",children:[f("toolBar.magicframe"),wt(he.Item.Badge,{children:"AI"})]})})]})]})]})};import vW from"clsx";import{jsx as IW}from"react/jsx-runtime";var Nu=({children:e,side:t,className:o})=>IW("div",{className:vW("FixedSideContainer",`FixedSideContainer_side_${t}`,o),children:e});import TW from"clsx";import{jsx as Pk,jsxs as kW}from"react/jsx-runtime";var CW="medium",Bu=e=>e.penDetected?kW("label",{className:TW("ToolIcon ToolIcon__penMode",`ToolIcon_size_${CW}`,{"is-mobile":e.isMobile}),title:`${e.title}`,children:[Pk("input",{className:"ToolIcon_type_checkbox",type:"checkbox",name:e.name,onChange:e.onChange,checked:e.checked,"aria-label":e.title}),Pk("div",{className:"ToolIcon__icon",children:by})]}):null;import{Fragment as Ak,jsx as $n,jsxs as fa}from"react/jsx-runtime";var Lk=({appState:e,elements:t,actionManager:o,setAppState:n,onHandToolToggle:r,renderTopLeftUI:i,renderTopRightUI:a,renderSidebars:s,renderWelcomeScreen:l,UIOptions:c,app:m,onPenModeToggle:p})=>{let{WelcomeScreenCenterTunnel:d,MainMenuTunnel:u,DefaultSidebarTriggerTunnel:h}=Xe(),g=()=>{if(e.openDialog?.name==="elementLinkSelector")return null;let w=fa("div",{className:"excalidraw-ui-top-right",children:[a?.(!0,e)??(!e.viewModeEnabled&&fa(Ak,{children:[$n(Bu,{checked:e.penMode,onChange:()=>p(null),title:f("toolBar.penMode"),isMobile:!0,penDetected:e.penDetected}),$n(h.Out,{})]})),e.viewModeEnabled&&$n(UC,{actionManager:o})]}),x=fa("div",{className:"excalidraw-ui-top-left",children:[i?.(!0,e),$n(u.Out,{})]});return fa("div",{className:"App-toolbar-content",style:{display:"flex",flexDirection:"row",justifyContent:"space-between"},children:[x,w]})},E=()=>$n(Mk,{app:m,onHandToolToggle:r,setAppState:n});return fa(Ak,{children:[s(),$n("div",{className:"App-welcome-screen",children:l&&$n(d.Out,{})}),!e.viewModeEnabled&&fa("div",{className:"App-bottom-bar",style:{marginBottom:Ko+Sr},children:[$n(BC,{appState:e,elementsMap:m.scene.getNonDeletedElementsMap(),renderAction:o.renderAction,app:m,setAppState:n}),fa(ut,{className:"App-toolbar",children:[!e.viewModeEnabled&&e.openDialog?.name!=="elementLinkSelector"&&E(),e.scrolledOutside&&!e.openMenu&&!e.openSidebar&&$n("button",{type:"button",className:"scroll-back-to-content",onClick:()=>{n(w=>({...Ri(t,w)}))},children:f("buttons.scrollBackToContent")})]})]}),$n(Nu,{side:"top",className:"App-top-bar",children:g()})]})};import SW,{useLayoutEffect as MW,useRef as PW,useState as AW}from"react";import{jsx as id,jsxs as LW}from"react/jsx-runtime";var _k=e=>{let t=PW(null),[o,n]=AW(null);return MW(()=>{if(!e.spreadsheet)return;let r=U2(e.chartType,e.spreadsheet,0,0);n(r);let i,a=t.current;return(async()=>(i=await Fa(r,{exportBackground:!1,viewBackgroundColor:"#fff"},null,{skipInliningFonts:!0}),i.querySelector(".style-fonts")?.remove(),a.replaceChildren(),a.appendChild(i),e.selected&&a.parentNode.focus()))(),()=>{a.replaceChildren()}},[e.spreadsheet,e.chartType,e.selected]),id("button",{type:"button",className:"ChartPreview",onClick:()=>{o&&e.onClick(e.chartType,o)},children:id("div",{ref:t})})},Dk=({setAppState:e,appState:t,onClose:o})=>{let{onInsertElements:n}=Qe(),r=SW.useCallback(()=>{o&&o()},[o]),i=(a,s)=>{n(s),ge("paste","chart",a),e({currentChartType:a,pasteDialog:{shown:!1,data:null}})};return id(ht,{size:"small",onCloseRequest:r,title:f("labels.pasteCharts"),className:"PasteChartDialog",autofocus:!1,children:LW("div",{className:"container",children:[id(_k,{chartType:"bar",spreadsheet:t.pasteDialog.data,selected:t.currentChartType==="bar",onClick:i}),id(_k,{chartType:"line",spreadsheet:t.pasteDialog.data,selected:t.currentChartType==="line",onClick:i})]})})};import{Fragment as _W,jsx as Rk,jsxs as DW}from"react/jsx-runtime";var ad=({heading:e,children:t,...o})=>{let{id:n}=qe(),r=Rk("h2",{className:"visually-hidden",id:`${n}-${e}-title`,children:f(`headings.${e}`)});return Rk("section",{...o,"aria-labelledby":`${n}-${e}-title`,children:typeof t=="function"?t(r):DW(_W,{children:[r,t]})})};import{Popover as Fu}from"radix-ui";import Nk from"clsx";import Ou,{useLayoutEffect as RW}from"react";import{supportsResizeObserver as NW,isShallowEqual as BW}from"@orangecatai/common";import{Fragment as GW,jsx as Kn,jsxs as zu}from"react/jsx-runtime";var FW=4,OW=8,zW=({shouldWrap:e,children:t,username:o})=>e?Kn(Vt,{label:o||"Unknown user",children:t}):Kn(GW,{children:t}),J0=({actionManager:e,collaborator:t,socketId:o,withName:n=!1,shouldWrapWithTooltip:r=!1,isBeingFollowed:i})=>{let a={socketId:o,collaborator:t,withName:n,isBeingFollowed:i},s=e.renderAction("goToCollaborator",a);return Kn(zW,{username:t.username,shouldWrap:r,children:s},o)},HW=["avatarUrl","id","socketId","username","isInCall","isSpeaking","isMuted"],Hu=Ou.memo(({className:e,mobile:t,collaborators:o,userToFollow:n})=>{let r=nt(),i=new Map;o.forEach((g,E)=>{let w=g.id||E;i.set(w,{...g,socketId:E})});let a=Array.from(i.values()).filter(g=>g.username?.trim()),[s,l]=Ou.useState(""),c=a.filter(g=>g.username?.toLowerCase().includes(s)),m=Ou.useRef(null);RW(()=>{if(m.current){let g=w=>{let x=Math.max(1,Math.min(8,Math.floor(w/38)));d(x)};if(g(m.current.clientWidth),!NW)return;let E=new ResizeObserver(w=>{for(let x of w){let{width:y}=x.contentRect;g(y)}});return E.observe(m.current),()=>{E.disconnect()}}},[]);let[p,d]=Ou.useState(FW),h=a.slice(0,p-1).map(g=>J0({actionManager:r,collaborator:g,socketId:g.socketId,shouldWrapWithTooltip:!0,isBeingFollowed:g.socketId===n}));return t?Kn("div",{className:Nk("UserList UserList_mobile",e),children:a.map(g=>J0({actionManager:r,collaborator:g,socketId:g.socketId,shouldWrapWithTooltip:!0,isBeingFollowed:g.socketId===n}))}):Kn("div",{className:"UserList__wrapper",ref:m,children:zu("div",{className:Nk("UserList",e),style:{"--max-avatars":p},children:[h,a.length>p-1&&zu(Fu.Root,{children:[zu(Fu.Trigger,{className:"UserList__more",children:["+",a.length-p+1]}),Kn(Fu.Content,{style:{zIndex:2,width:"15rem",textAlign:"left"},align:"end",sideOffset:10,children:zu(ut,{padding:2,children:[a.length>=OW&&Kn(Dm,{placeholder:f("quickSearch.placeholder"),onChange:l}),Kn(Rm,{className:"dropdown-menu UserList__collaborators",placeholder:f("userList.empty"),children:c.length>0?[Kn("div",{className:"hint",children:f("userList.hint.text")}),c.map(g=>J0({actionManager:r,collaborator:g,socketId:g.socketId,withName:!0,isBeingFollowed:g.socketId===n}))]:[]}),Kn(Fu.Arrow,{width:20,height:10,style:{fill:"var(--popup-bg-color)",filter:"drop-shadow(rgba(0, 0, 0, 0.05) 0px 3px 2px)"}})]})})]})]})})},(e,t)=>{if(e.collaborators.size!==t.collaborators.size||e.mobile!==t.mobile||e.className!==t.className||e.userToFollow!==t.userToFollow)return!1;let o=t.collaborators.keys();for(let[n,r]of e.collaborators){let i=t.collaborators.get(n);if(!i||n!==o.next().value||!BW(r,i,HW))return!1}return!0});import n1 from"clsx";import{useState as qW,useRef as Fk,useEffect as JW,useCallback as QW}from"react";import{useCallback as xo,useEffect as VW,useRef as ld,useState as e1}from"react";var Q0=({h:e,s:t,v:o,a:n})=>{e=e/360,t=t/100,o=o/100;let r=0,i=0,a=0,s=Math.floor(e*6),l=e*6-s,c=o*(1-t),m=o*(1-l*t),p=o*(1-(1-l)*t);switch(s%6){case 0:r=o,i=p,a=c;break;case 1:r=m,i=o,a=c;break;case 2:r=c,i=o,a=p;break;case 3:r=c,i=m,a=o;break;case 4:r=p,i=c,a=o;break;case 5:r=o,i=c,a=m;break}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(a*255),a:n}},UW=({r:e,g:t,b:o,a:n})=>{e/=255,t/=255,o/=255;let r=Math.max(e,t,o),i=Math.min(e,t,o),a=r-i,s=0,l=r===0?0:a/r*100,c=r*100;if(a!==0)switch(r){case e:s=((t-o)/a+(t<o?6:0))*60;break;case t:s=((o-e)/a+2)*60;break;case o:s=((e-t)/a+4)*60;break}return{h:s,s:l,v:c,a:n}},WW=({r:e,g:t,b:o,a:n})=>{let r=a=>a.toString(16).padStart(2,"0"),i=`#${r(e)}${r(t)}${r(o)}`;return n<1?`${i}${r(Math.round(n*255))}`:i},YW=e=>{let t=e.replace(/^#/,"");t.length===3?t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]:t.length===4&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]+t[3]+t[3]);let o=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),i=t.length===8?parseInt(t.slice(6,8),16)/255:1;return{r:isNaN(o)?0:o,g:isNaN(n)?0:n,b:isNaN(r)?0:r,a:isNaN(i)?1:i}},Gu=e=>WW(Q0(e)),sd=e=>UW(YW(e));var ll=(e,t,o)=>Math.max(t,Math.min(o,e));import{jsx as Pt,jsxs as cl}from"react/jsx-runtime";var $W=["transparent","#000000","#ffffff","#00e639","#a855f4","#d4b0ff"],t1=(e,t)=>{let o=ld(null),n=ld(!1),r=ld(null),i=ld(null),a=xo((p,d)=>{if(!o.current||!n.current)return;let u=o.current.getBoundingClientRect();e(p,d,u)},[e]),s=xo(()=>{n.current=!1,t?.(),r.current&&(window.removeEventListener("mousemove",r.current),r.current=null),i.current&&(window.removeEventListener("touchmove",i.current),i.current=null),window.removeEventListener("mouseup",s),window.removeEventListener("touchend",s)},[t]),l=xo(p=>a(p.clientX,p.clientY),[a]),c=xo(p=>{p.preventDefault(),a(p.touches[0].clientX,p.touches[0].clientY)},[a]),m=xo(p=>{p.preventDefault(),p.stopPropagation(),n.current=!0;let d="touches"in p?p.touches[0].clientX:p.clientX,u="touches"in p?p.touches[0].clientY:p.clientY;if(o.current){let h=o.current.getBoundingClientRect();e(d,u,h)}r.current=l,i.current=c,window.addEventListener("mousemove",l),window.addEventListener("mouseup",s),window.addEventListener("touchmove",c,{passive:!1}),window.addEventListener("touchend",s)},[e,l,c,s]);return{ref:o,handleDown:m}},KW=({hsva:e,onChange:t})=>{let{ref:o,handleDown:n}=t1((s,l,c)=>{let m=ll(s-c.left,0,c.width),p=ll(l-c.top,0,c.height),d=m/c.width*100,u=100-p/c.height*100;t(d,u)}),r=`hsl(${e.h}, 100%, 50%)`,i=`${e.s}%`,a=`${100-e.v}%`;return cl("div",{ref:o,className:"adv-cp__saturation",style:{backgroundColor:r},onMouseDown:n,onTouchStart:n,children:[Pt("div",{className:"adv-cp__saturation-white"}),Pt("div",{className:"adv-cp__saturation-black"}),Pt("div",{className:"adv-cp__handle",style:{left:i,top:a}})]})},XW=({hue:e,onChange:t})=>{let{ref:o,handleDown:n}=t1((r,i,a)=>{let s=ll(r-a.left,0,a.width);t(s/a.width*360)});return Pt("div",{ref:o,className:"adv-cp__slider adv-cp__hue-slider",onMouseDown:n,onTouchStart:n,children:Pt("div",{className:"adv-cp__slider-handle",style:{left:`${e/360*100}%`}})})},ZW=({hsva:e,onChange:t})=>{let{r:o,g:n,b:r}=Q0({...e,a:1}),i=`rgba(${o}, ${n}, ${r}, 1)`,{ref:a,handleDown:s}=t1((l,c,m)=>{let p=ll(l-m.left,0,m.width);t(p/m.width)});return cl("div",{ref:a,className:"adv-cp__slider adv-cp__alpha-slider",onMouseDown:s,onTouchStart:s,children:[Pt("div",{className:"adv-cp__alpha-checker"}),Pt("div",{className:"adv-cp__alpha-gradient",style:{background:`linear-gradient(to right, transparent 0%, ${i} 100%)`}}),Pt("div",{className:"adv-cp__slider-handle",style:{left:`${e.a*100}%`}})]})},jW=({activeColor:e,onChange:t})=>Pt("div",{className:"adv-cp__presets",children:$W.map(o=>Pt("button",{type:"button",className:`adv-cp__preset-btn${o===e?" active":""}${o==="transparent"?" is-transparent":""}`,style:o!=="transparent"?{backgroundColor:o}:void 0,title:o,onClick:()=>t(o),children:o==="transparent"&&Pt("div",{className:"adv-cp__preset-slash"})},o))}),Bk=({color:e,onChange:t,showAlpha:o=!0})=>{let[n,r]=e1(()=>!e||e==="transparent"?{h:0,s:0,v:100,a:e==="transparent"?0:1}:sd(e)),[i,a]=e1(()=>e==="transparent"?"000000":(e||"#ffffff").replace(/^#/,"").toUpperCase()),[s,l]=e1(()=>Math.round(n.a*100).toString()),c=ld(e);VW(()=>{if(e!==c.current)if(c.current=e,!e||e==="transparent")r({h:0,s:0,v:100,a:0}),a("000000"),l("0");else{let y=sd(e);r(y),a(e.replace(/^#/,"").substring(0,6).toUpperCase()),l(Math.round(y.a*100).toString())}},[e]);let m=xo(y=>{r(y);let v=Gu(y);c.current=v,a(v.replace(/^#/,"").substring(0,6).toUpperCase()),l(Math.round(y.a*100).toString()),y.a===0?t("transparent"):t(v)},[t]),p=xo((y,v)=>{m({...n,s:y,v})},[n,m]),d=xo(y=>{m({...n,h:y})},[n,m]),u=xo(y=>{m({...n,a:y})},[n,m]),h=xo(y=>{if(y==="transparent")m({h:0,s:0,v:100,a:0});else{let v=sd(y);v.a=1,m(v)}},[m]),g=xo(()=>{let y=i.trim().replace(/^#/,"");if(/^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$|^[0-9a-fA-F]{8}$/.test(y)){let v=sd(`#${y}`);m(v)}else{let v=Gu(n);a(v.replace(/^#/,"").substring(0,6).toUpperCase())}},[i,n,m]),E=xo(y=>{y.key==="Enter"&&g(),y.stopPropagation()},[g]),w=xo(()=>{let y=parseInt(s,10);if(isNaN(y))l(Math.round(n.a*100).toString());else{let v=ll(y,0,100)/100;m({...n,a:v})}},[s,n,m]),x=xo(y=>{y.key==="Enter"&&w(),y.stopPropagation()},[w]);return cl("div",{className:"adv-cp",children:[Pt(KW,{hsva:n,onChange:p}),Pt(XW,{hue:n.h,onChange:d}),o&&Pt(ZW,{hsva:n,onChange:u}),Pt(jW,{activeColor:n.a===0?"transparent":Gu({...n,a:1}).toLowerCase(),onChange:h}),cl("div",{className:"adv-cp__inputs",children:[cl("div",{className:"adv-cp__hex-input",children:[Pt("span",{className:"adv-cp__hash",children:"#"}),Pt("input",{type:"text",style:{border:0,padding:0,margin:0,outline:"none"},spellCheck:!1,value:i,onChange:y=>a(y.target.value.toUpperCase()),onBlur:g,onKeyDown:E,maxLength:8,"aria-label":"Hex color"})]}),o&&cl("div",{className:"adv-cp__alpha-input",children:[Pt("input",{type:"text",style:{border:0,padding:0,margin:0,outline:"none"},value:s,onChange:y=>l(y.target.value),onBlur:w,onKeyDown:x,maxLength:3,"aria-label":"Opacity percentage"}),Pt("span",{className:"adv-cp__percent",children:"%"})]})]})]})};import{jsx as mi,jsxs as o1}from"react/jsx-runtime";var Ok=({actionManager:e,appState:t})=>{let[o,n]=qW(!1),r=Fk(null),i=Fk(null);JW(()=>{if(!o)return;let c=m=>{r.current&&!r.current.contains(m.target)&&i.current&&!i.current.contains(m.target)&&n(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[o]);let a=t.viewBackgroundColor||"#ffffff",s=a==="transparent",l=QW(c=>{e.executeAction(e.actions.changeViewBackgroundColor,"ui",{viewBackgroundColor:c})},[e]);return o1("div",{className:"canvas-bg-swatch-wrapper",children:[mi(Vt,{label:f("labels.canvasBackground"),children:mi("button",{ref:i,type:"button",className:"canvas-bg-swatch",onClick:()=>n(c=>!c),title:f("labels.canvasBackground"),children:mi("div",{className:"canvas-bg-swatch__color",style:{backgroundColor:s?void 0:a},children:s&&mi("div",{className:"canvas-bg-swatch__transparent"})})})}),o&&o1("div",{ref:r,className:"canvas-bg-swatch__popover",children:[o1("div",{className:"canvas-bg-swatch__popover-header",children:[mi("span",{children:f("labels.canvasBackground")}),mi("button",{type:"button",className:"canvas-bg-swatch__close",onClick:()=>n(!1),children:"\u2715"})]}),mi("div",{className:"canvas-bg-swatch__picker-content",children:mi(Bk,{color:a,onChange:l,showAlpha:!0})})]})]})};import{jsx as eY}from"react/jsx-runtime";var zk=e=>eY("button",{className:"help-icon",onClick:e.onClick,type:"button",title:`${f("helpDialog.title")} \u2014 ?`,"aria-label":f("helpDialog.title"),children:ja});import{jsx as Zo,jsxs as cd}from"react/jsx-runtime";var Hk=({appState:e,actionManager:t,showExitZenModeBtn:o,renderWelcomeScreen:n})=>{let{FooterCenterTunnel:r,WelcomeScreenHelpHintTunnel:i}=Xe();return cd("footer",{role:"contentinfo",className:"layer-ui__wrapper__footer App-menu App-menu_bottom",children:[Zo("div",{className:n1("layer-ui__wrapper__footer-left zen-mode-transition",{"layer-ui__wrapper__footer-left--transition-left":e.zenModeEnabled}),children:Zo(Dt.Col,{gap:2,children:Zo(ad,{heading:"canvasActions",children:cd(Dt.Col,{gap:1,className:"footer-canvas-actions",children:[cd(Dt.Row,{align:"center",gap:1,children:[Zo(OC,{renderAction:t.renderAction}),!e.viewModeEnabled&&Zo(Ok,{actionManager:t,appState:e})]}),cd(Dt.Row,{align:"center",gap:1,className:"footer-canvas-actions-row",children:[Zo(zC,{renderAction:t.renderAction,zoom:e.zoom}),!e.viewModeEnabled&&Zo(HC,{renderAction:t.renderAction,className:n1("zen-mode-transition",{"layer-ui__wrapper__footer-left--transition-bottom":e.zenModeEnabled})})]})]})})})}),Zo(r.Out,{}),Zo("div",{className:n1("layer-ui__wrapper__footer-right zen-mode-transition",{"transition-right":e.zenModeEnabled}),children:cd("div",{style:{position:"relative"},children:[n&&Zo(i.Out,{}),Zo(zk,{onClick:()=>t.executeAction(ji)})]})}),Zo(GC,{actionManager:t,showExitZenModeBtn:o})]})},Gk=Hk;Hk.displayName="Footer";import pY from"clsx";import{useEffect as Xk,useLayoutEffect as Zk,useRef as p1,useState as uY,forwardRef as jk,useImperativeHandle as gY,useCallback as Vk}from"react";import{CLASSES as hY,EVENT as $k,isDevEnv as fY,KEYS as bY,updateObject as xY}from"@orangecatai/common";import oY from"clsx";import{useContext as nY}from"react";import tY from"react";var Uu=tY.createContext({});import{jsx as r1,jsxs as Uk}from"react/jsx-runtime";var i1=({children:e,className:t})=>{let o=we(),n=nY(Uu),r=!!(o.canFitSidebar&&n.shouldRenderDockButton);return Uk("div",{className:oY("sidebar__header",t),"data-testid":"sidebar-header",children:[e,Uk("div",{className:"sidebar__header__buttons",children:[r&&r1(Vt,{label:f("labels.sidebarLock"),children:r1(ro,{onSelect:()=>n.onDock?.(!n.docked),selected:!!n.docked,className:"sidebar__dock","data-testid":"sidebar-dock","aria-label":f("labels.sidebarLock"),children:py})}),r1(ro,{"data-testid":"sidebar-close",className:"sidebar__close",onSelect:n.onCloseRequest,"aria-label":f("buttons.close"),children:Fo})]})]})};i1.displayName="SidebarHeader";import{Tabs as rY}from"radix-ui";import{jsx as Wk}from"react/jsx-runtime";var a1=({children:e,tab:t,onSelect:o,...n})=>Wk(rY.Trigger,{value:t,asChild:!0,onSelect:o,children:Wk("button",{type:"button",className:"excalidraw-button sidebar-tab-trigger",...n,children:e})});a1.displayName="SidebarTabTrigger";import{Tabs as iY}from"radix-ui";import{jsx as aY}from"react/jsx-runtime";var s1=({children:e,...t})=>aY(iY.List,{className:"sidebar-triggers",...t,children:e});s1.displayName="SidebarTabTriggers";import sY from"clsx";import{jsx as l1,jsxs as Yk}from"react/jsx-runtime";var c1=({name:e,tab:t,icon:o,title:n,children:r,onToggle:i,className:a,style:s})=>{let l=ve(),c=ye();return Yk("label",{title:n,className:"sidebar-trigger__label-element",children:[l1("input",{className:"ToolIcon_type_checkbox",type:"checkbox",onChange:m=>{document.querySelector(".layer-ui__wrapper")?.classList.remove("animate");let p=m.target.checked;l({openSidebar:p?{name:e,tab:t}:null,openMenu:null,openPopup:null}),i?.(p)},checked:c.openSidebar?.name===e,"aria-label":n,"aria-keyshortcuts":"0"}),Yk("div",{className:sY("sidebar-trigger",a),style:s,children:[o&&l1("div",{children:o}),r&&l1("div",{className:"sidebar-trigger__label",children:r})]})]})};c1.displayName="SidebarTrigger";import{Tabs as lY}from"radix-ui";import{jsx as cY}from"react/jsx-runtime";var d1=({children:e,...t})=>{let o=ye(),n=ve();if(!o.openSidebar)return null;let{name:r}=o.openSidebar;return cY(lY.Root,{className:"sidebar-tabs-root",value:o.openSidebar.tab,onValueChange:i=>n(a=>({...a,openSidebar:{...a.openSidebar,name:r,tab:i}})),...t,children:e})};d1.displayName="SidebarTabs";import{Tabs as dY}from"radix-ui";import{jsx as mY}from"react/jsx-runtime";var m1=({tab:e,children:t,...o})=>mY(dY.Content,{...o,value:e,"data-testid":e,children:t});m1.displayName="SidebarTab";import{jsx as Kk}from"react/jsx-runtime";import{createElement as EY}from"react";var dd=Ce(!1),qk=jk(({name:e,children:t,onDock:o,docked:n,className:r,...i},a)=>{fY()&&o&&n==null&&console.warn("Sidebar: `docked` must be set when `onDock` is supplied for the sidebar to be user-dockable. To hide this message, either pass `docked` or remove `onDock`");let s=ve(),l=Pn(dd);Zk(()=>(l(!!n),()=>{l(!1)}),[l,n]);let c=p1({});c.current.onCloseRequest=()=>{s({openSidebar:null})},c.current.onDock=u=>o?.(u),c.current=xY(c.current,{docked:n,shouldRenderDockButton:!!o&&n!=null});let m=p1(null);gY(a,()=>m.current);let p=we(),d=Vk(()=>{document.querySelector(".Dialog")||s({openSidebar:null})},[s]);return cs(m,Vk(u=>{u.target.closest(".sidebar-trigger")||(!n||!p.canFitSidebar)&&d()},[d,n,p.canFitSidebar])),Xk(()=>{let u=h=>{h.key===bY.ESCAPE&&(!n||!p.canFitSidebar)&&d()};return document.addEventListener($k.KEYDOWN,u),()=>{document.removeEventListener($k.KEYDOWN,u)}},[d,n,p.canFitSidebar]),Kk(ut,{...i,className:pY(hY.SIDEBAR,{"sidebar--docked":n},r),ref:m,children:Kk(Uu.Provider,{value:c.current,children:t})})});qk.displayName="SidebarInner";var jo=Object.assign(jk((e,t)=>{let o=ye()??{openSidebar:null},{onStateChange:n}=e,r=p1(o.openSidebar);Xk(()=>{(!o.openSidebar&&r?.current?.name===e.name||o.openSidebar?.name===e.name&&r?.current?.name!==e.name||r.current?.name===e.name)&&o.openSidebar!==r.current&&n?.(o.openSidebar?.name!==e.name?null:o.openSidebar),r.current=o.openSidebar},[o.openSidebar,n,e.name]);let[i,a]=uY(!1);return Zk(()=>(a(!0),()=>a(!1)),[]),i&&o.openSidebar?.name===e.name?EY(qk,{...e,ref:t,key:e.name}):null}),{Header:i1,TabTriggers:s1,TabTrigger:a1,Tabs:d1,Tab:m1,Trigger:c1});jo.displayName="Sidebar";import{composeEventHandlers as SY}from"@orangecatai/common";import{useLayoutEffect as yY,useRef as wY}from"react";import{jsx as vY}from"react/jsx-runtime";var Mr=(e,t)=>{let o=Ce(0),n=r=>{let{tunnelsJotai:{useAtom:i}}=Xe(),[,a]=i(o),s=wY({preferHost:!1,counter:0});return yY(()=>{let l=s.current;return a(c=>{let m=c+1;return l.counter=m,m}),()=>{a(c=>{let m=c-1;return l.counter=m,m||(l.preferHost=!1),m})}},[a]),r.__fallback||(s.current.preferHost=!0),!s.current.counter&&r.__fallback&&s.current.preferHost||s.current.counter>1&&r.__fallback?null:vY(t,{...r})};return n.displayName=e,n};var b1={};NE(b1,{ChangeCanvasBackground:()=>mS,ClearCanvas:()=>cS,CommandPalette:()=>aS,Export:()=>pS,Help:()=>lS,LiveCollaborationTrigger:()=>gS,LoadScene:()=>nS,Preferences:()=>ui,PreferencesToggleGridModeItem:()=>h1,PreferencesToggleZenModeItem:()=>f1,SaveAsImage:()=>iS,SaveToActiveFile:()=>rS,SearchMenu:()=>sS,Socials:()=>uS,ToggleTheme:()=>dS});import kY from"clsx";import{THEME as pi}from"@orangecatai/common";var u1=Ce({active:!1});async function Jk({title:e,description:t,actionLabel:o,color:n}){return new Promise(r=>{Et.set(u1,{active:!0,onConfirm:()=>r(!0),onClose:()=>r(!1),onReject:()=>r(!1),title:e,description:t,actionLabel:o,color:n})})}import IY from"clsx";import{jsx as Qk,jsxs as TY}from"react/jsx-runtime";var Wu=function({onChange:e,value:t,choices:o,name:n}){return Qk("div",{className:"RadioGroup",children:o.map(r=>TY("div",{className:IY("RadioGroup__choice",{active:r.value===t}),title:r.ariaLabel,children:[Qk("input",{name:n,type:"radio",checked:r.value===t,onChange:()=>e(r.value),"aria-label":r.ariaLabel}),r.label]},String(r.value)))})};import{Fragment as CY,jsx as g1,jsxs as eS}from"react/jsx-runtime";var tS=({value:e,shortcut:t,onChange:o,choices:n,children:r,name:i})=>{let a=we();return eS(CY,{children:[eS("div",{className:"dropdown-menu-item-base dropdown-menu-item-bare",children:[g1("label",{className:"dropdown-menu-item__text",children:r}),g1(Wu,{name:i,value:e,onChange:o,choices:n})]}),t&&a.formFactor!=="phone"&&g1("div",{className:"dropdown-menu-item__shortcut dropdown-menu-item__shortcut--orphaned",children:t})]})};tS.displayName="DropdownMenuItemContentRadio";var oS=tS;import{Fragment as ES,jsx as Ne,jsxs as md}from"react/jsx-runtime";var nS=()=>{let{t:e}=Ge(),t=nt(),o=Hr();return t.isActionEnabled(Cs)?Ne(Jt,{icon:qa,onSelect:async()=>{(!o.length||await Jk({title:e("overwriteConfirm.modal.loadFromFile.title"),actionLabel:e("overwriteConfirm.modal.loadFromFile.button"),color:"warning",description:Ne(no,{i18nKey:"overwriteConfirm.modal.loadFromFile.description",bold:r=>Ne("strong",{children:r}),br:()=>Ne("br",{})})}))&&t.executeAction(Cs)},"data-testid":"load-button",shortcut:Ke("loadScene"),"aria-label":e("buttons.load"),children:e("buttons.load")}):null};nS.displayName="LoadScene";var rS=()=>{let{t:e}=Ge(),t=nt();return t.isActionEnabled(Zi)?Ne(Jt,{shortcut:Ke("saveScene"),"data-testid":"save-button",onSelect:()=>t.executeAction(Zi),icon:Ty,"aria-label":`${e("buttons.save")}`,children:`${e("buttons.save")}`}):null};rS.displayName="SaveToActiveFile";var iS=()=>{let e=ve(),{t}=Ge();return Ne(Jt,{icon:mm,"data-testid":"image-export-button",onSelect:()=>e({openDialog:{name:"imageExport"}}),shortcut:Ke("imageExport"),"aria-label":t("buttons.exportImage"),children:t("buttons.exportImage")})};iS.displayName="SaveAsImage";var aS=e=>{let t=ve(),{t:o}=Ge();return Ne(Jt,{icon:ec,"data-testid":"command-palette-button",onSelect:()=>{ge("command_palette","open","menu"),t({openDialog:{name:"commandPalette"}})},shortcut:Ke("commandPalette"),"aria-label":o("commandPalette.title"),className:e?.className,children:o("commandPalette.title")})};aS.displayName="CommandPalette";var sS=e=>{let{t}=Ge(),o=nt();return Ne(Jt,{icon:ko,"data-testid":"search-menu-button",onSelect:()=>{o.executeAction(Uc)},shortcut:Ke("searchMenu"),"aria-label":t("search.title"),className:e?.className,children:t("search.title")})};sS.displayName="SearchMenu";var lS=()=>{let{t:e}=Ge(),t=nt();return Ne(Jt,{"data-testid":"help-menu-item",icon:ja,onSelect:()=>t.executeAction(ji),shortcut:"?","aria-label":e("helpDialog.title"),children:e("helpDialog.title")})};lS.displayName="Help";var cS=()=>{let{t:e}=Ge(),t=Pn(ta);return nt().isActionEnabled(gr)?Ne(Jt,{icon:Ht,onSelect:()=>t("clearCanvas"),"data-testid":"clear-canvas-button","aria-label":e("buttons.clearReset"),children:e("buttons.clearReset")}):null};cS.displayName="ClearCanvas";var dS=e=>{let{t}=Ge(),o=ye(),n=nt(),r=Ke("toggleTheme");return n.isActionEnabled(Vi)?e?.allowSystemTheme?Ne(oS,{name:"theme",value:e.theme,onChange:i=>e.onSelect(i),choices:[{value:pi.LIGHT,label:jl,ariaLabel:`${t("buttons.lightMode")} - ${r}`},{value:pi.DARK,label:Zl,ariaLabel:`${t("buttons.darkMode")} - ${r}`},{value:"system",label:Uw,ariaLabel:t("buttons.systemMode")}],children:t("labels.theme")}):Ne(Jt,{onSelect:i=>{if(i.preventDefault(),e?.onSelect)e.onSelect(o.theme===pi.DARK?pi.LIGHT:pi.DARK);else return n.executeAction(Vi)},icon:o.theme===pi.DARK?jl:Zl,"data-testid":"toggle-dark-mode",shortcut:r,"aria-label":o.theme===pi.DARK?t("buttons.lightMode"):t("buttons.darkMode"),children:o.theme===pi.DARK?t("buttons.lightMode"):t("buttons.darkMode")}):null};dS.displayName="ToggleTheme";var mS=()=>{let{t:e}=Ge(),t=ye(),o=nt(),n=Nn();return t.viewModeEnabled||!n.UIOptions.canvasActions.changeViewBackgroundColor?null:md("div",{style:{marginTop:"0.75rem"},children:[Ne("div",{"data-testid":"canvas-background-label",style:{fontSize:"0.875rem",marginBottom:"0.25rem",marginLeft:"0.5rem"},children:e("labels.canvasBackground")}),Ne("div",{style:{padding:"0 0.625rem"},children:o.renderAction("changeViewBackgroundColor")})]})};mS.displayName="ChangeCanvasBackground";var pS=()=>{let{t:e}=Ge(),t=ve();return Ne(Jt,{icon:zi,onSelect:()=>{t({openDialog:{name:"jsonExport"}})},"data-testid":"json-export-button","aria-label":e("buttons.export"),children:e("buttons.export")})};pS.displayName="Export";var uS=()=>{let{t:e}=Ge();return md(ES,{children:[Ne(Ys,{icon:lm,href:"https://github.com/excalidraw/excalidraw","aria-label":"GitHub",children:"GitHub"}),Ne(Ys,{icon:Iy,href:"https://x.com/excalidraw","aria-label":"X",children:e("labels.followUs")}),Ne(Ys,{icon:vy,href:"https://discord.gg/UexuTaE","aria-label":"Discord",children:e("labels.discordChat")})]})};uS.displayName="Socials";var gS=({onSelect:e,isCollaborating:t})=>{let{t:o}=Ge();return Ne(Jt,{"data-testid":"collab-button",icon:pm,className:kY({"active-collab":t}),onSelect:e,children:o("labels.liveCollaboration")})};gS.displayName="LiveCollaborationTrigger";var hS=()=>{let{t:e}=Ge(),t=Qe(),o=ye();return Ne(xr,{checked:o.activeTool.locked,shortcut:Ke("toolLock"),onSelect:n=>{t.toggleLock(),n.preventDefault()},children:e("labels.preferences_toolLock")})},fS=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Ne(xr,{checked:o.objectsSnapModeEnabled,shortcut:Ke("objectsSnapMode"),onSelect:n=>{t.executeAction(Cc),n.preventDefault()},children:e("buttons.objectsSnapMode")})},h1=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Ne(xr,{checked:o.gridModeEnabled,shortcut:Ke("gridMode"),onSelect:n=>{t.executeAction(_s),n.preventDefault()},children:e("labels.toggleGrid")})},f1=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Ne(xr,{checked:o.zenModeEnabled,shortcut:Ke("zenMode"),onSelect:n=>{t.executeAction(jr),n.preventDefault()},children:e("buttons.zenMode")})},bS=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Ne(xr,{checked:o.viewModeEnabled,shortcut:Ke("viewMode"),onSelect:n=>{t.executeAction(ea),n.preventDefault()},children:e("labels.viewMode")})},xS=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Ne(xr,{checked:o.stats.open,shortcut:Ke("stats"),onSelect:n=>{t.executeAction(qr),n.preventDefault()},children:e("stats.fullTitle")})},ui=({children:e,additionalItems:t})=>{let{t:o}=Ge();return md(ei,{children:[Ne(ei.Trigger,{icon:ev,children:o("labels.preferences")}),md(ei.Content,{className:"excalidraw-main-menu-preferences-submenu",children:[e||md(ES,{children:[Ne(hS,{}),Ne(fS,{}),Ne(h1,{}),Ne(f1,{}),Ne(bS,{}),Ne(xS,{})]}),t]})]})};ui.ToggleToolLock=hS;ui.ToggleSnapMode=fS;ui.ToggleGridMode=h1;ui.ToggleZenMode=f1;ui.ToggleViewMode=bS;ui.ToggleElementProperties=xS;ui.displayName="Preferences";import{jsx as Yu,jsxs as x1}from"react/jsx-runtime";var MY=Object.assign(Mr("MainMenu",({children:e,onSelect:t})=>{let{MainMenuTunnel:o}=Xe(),n=we(),r=ye(),i=ve();return Yu(o.In,{children:x1(he,{open:r.openMenu==="canvas",children:[Yu(he.Trigger,{onToggle:()=>{i({openMenu:r.openMenu==="canvas"?null:"canvas",openPopup:null,openDialog:null})},"data-testid":"main-menu-trigger",className:"main-menu-trigger",children:yy}),x1(he.Content,{onClickOutside:()=>i({openMenu:null}),onSelect:SY(t,()=>{i({openMenu:null})}),className:"main-menu",align:"start",children:[e,n.formFactor==="phone"&&r.collaborators.size>0&&x1("fieldset",{className:"UserList-Wrapper",children:[Yu("legend",{children:f("labels.collaborators")}),Yu(Hu,{mobile:!0,collaborators:r.collaborators,userToFollow:r.userToFollow?.socketId||null})]})]})]})})}),{Trigger:he.Trigger,Item:he.Item,ItemLink:he.ItemLink,ItemCustom:he.ItemCustom,Group:he.Group,Separator:he.Separator,Sub:ei,DefaultItems:b1}),Kt=MY;import PY from"clsx";import{forwardRef as AY,useState as LY}from"react";import{isPromiseLike as _Y}from"@orangecatai/common";import{jsx as Vu,jsxs as DY}from"react/jsx-runtime";var qo=AY(({children:e,icon:t,onClick:o,label:n,variant:r="filled",color:i="primary",size:a="medium",fullWidth:s,className:l,status:c,disabled:m},p)=>{let[d,u]=LY(!1),h=async E=>{let w=o?.(E);if(_Y(w)){let x=window.setTimeout(()=>{u(!0)},50);try{await w}catch(y){if(y instanceof Ra)console.warn(y);else throw y}finally{clearTimeout(x),u(!1)}}},g=d?"loading":c;return i=g==="success"?"success":i,Vu("button",{className:PY("ExcButton",`ExcButton--color-${i}`,`ExcButton--variant-${r}`,`ExcButton--size-${a}`,`ExcButton--status-${g}`,{"ExcButton--fullWidth":s},l),onClick:h,type:"button","aria-label":n,ref:p,disabled:m||g==="loading"||g==="success",children:DY("div",{className:"ExcButton__contents",children:[g==="loading"?Vu(Gt,{className:"ExcButton__statusIcon"}):g==="success"&&Vu("div",{className:"ExcButton__statusIcon",children:ww}),t&&Vu("div",{className:"ExcButton__icon","aria-hidden":!0,children:t}),r!=="icon"&&(e??n)]})})});import{jsx as dl,jsxs as BY}from"react/jsx-runtime";var $u=({title:e,children:t,actionLabel:o,onClick:n})=>BY("div",{className:"OverwriteConfirm__Actions__Action",children:[dl("h4",{children:e}),dl("div",{className:"OverwriteConfirm__Actions__Action__content",children:t}),dl(qo,{variant:"outlined",color:"muted",label:o,size:"large",fullWidth:!0,onClick:n})]}),RY=()=>{let{t:e}=Ge(),t=nt(),o=ve();return dl($u,{title:e("overwriteConfirm.action.exportToImage.title"),actionLabel:e("overwriteConfirm.action.exportToImage.button"),onClick:()=>{t.executeAction(tp,"ui",!0),o({openDialog:{name:"imageExport"}})},children:e("overwriteConfirm.action.exportToImage.description")})},NY=()=>{let{t:e}=Ge(),t=nt();return dl($u,{title:e("overwriteConfirm.action.saveToDisk.title"),actionLabel:e("overwriteConfirm.action.saveToDisk.button"),onClick:()=>{t.executeAction(Ic,"ui")},children:e("overwriteConfirm.action.saveToDisk.description")})},E1=Object.assign(({children:e})=>dl("div",{className:"OverwriteConfirm__Actions",children:e}),{ExportToImage:RY,SaveToDisk:NY});import{jsx as gi,jsxs as yS}from"react/jsx-runtime";var Ku=Object.assign(Mr("OverwriteConfirmDialog",({children:e})=>{let{OverwriteConfirmDialogTunnel:t}=Xe(),[o,n]=ae(u1);if(!o.active)return null;let r=()=>{o.onClose(),n(a=>({...a,active:!1}))},i=()=>{o.onConfirm(),n(a=>({...a,active:!1}))};return gi(t.In,{children:gi(ht,{onCloseRequest:r,title:!1,size:916,children:yS("div",{className:"OverwriteConfirm",children:[gi("h3",{children:o.title}),yS("div",{className:`OverwriteConfirm__Description OverwriteConfirm__Description--color-${o.color}`,children:[gi("div",{className:"OverwriteConfirm__Description__icon",children:hm}),gi("div",{children:o.description}),gi("div",{className:"OverwriteConfirm__Description__spacer"}),gi(qo,{color:o.color,size:"large",label:o.actionLabel,onClick:i})]}),gi(E1,{children:e})]})})})}),{Actions:E1,Action:$u});import rV from"clsx";import{CANVAS_SEARCH_TAB as T1,DEFAULT_SIDEBAR as iV,LIBRARY_SIDEBAR_TAB as AS,composeEventHandlers as aV}from"@orangecatai/common";import{round as FY}from"@orangecatai/math";import OY from"clsx";import zY from"lodash.debounce";import{Fragment as HY,memo as GY,useEffect as pd,useMemo as wS,useRef as y1,useState as vS}from"react";import{CLASSES as UY,EVENT as WY,FONT_FAMILY as w1,FRAME_STYLE as v1,getLineHeight as YY}from"@orangecatai/common";import{isElementCompletelyInViewport as VY}from"@orangecatai/element";import{measureText as ud}from"@orangecatai/element";import{KEYS as ml,randomInteger as IS,addEventListener as $Y,getFontString as Xu}from"@orangecatai/common";import{newTextElement as KY}from"@orangecatai/element";import{isTextElement as SS,isFrameLikeElement as Zu}from"@orangecatai/element";import{getDefaultFrameName as MS}from"@orangecatai/element/frame";import{Fragment as nV,jsx as Ft,jsxs as Xn}from"react/jsx-runtime";var XY=Ce(""),I1=Ce(null),ZY=350,PS=()=>{let e=Qe(),t=ve(),o=y1(null),[n,r]=ae(XY),i=n.trim(),[a,s]=vS(!1),[l,c]=vS({nonce:null,items:[]}),m=y1(null),p=y1(void 0),[d,u]=ae(I1),h=e.scene.getNonDeletedElementsMap();pd(()=>{a||(i!==m.current||e.scene.getSceneNonce()!==p.current)&&(m.current=null,kS(i,e,(y,v)=>{c({nonce:IS(),items:y}),m.current=i,p.current=e.scene.getSceneNonce(),t({searchMatches:y.length?{focusedId:null,matches:y.map(I=>({id:I.element.id,focus:!1,matchedLines:I.matchedLines}))}:null})}))},[a,i,h,e,t,u,p]);let g=()=>{l.items.length>0&&u(y=>y===null?0:(y+1)%l.items.length)},E=()=>{l.items.length>0&&u(y=>y===null?0:y-1<0?l.items.length-1:y-1)};pd(()=>{t(y=>y.searchMatches?{searchMatches:{focusedId:d!==null&&y.searchMatches?.matches[d]?.id||null,matches:y.searchMatches.matches.map((I,k)=>k===d?{...I,focus:!0}:{...I,focus:!1})}}:null)},[d,t]),pd(()=>{if(l.items.length>0&&d!==null){let y=l.items[d];if(y){let v=e.state.zoom.value,I=KY({text:y.searchQuery,x:y.element.x+(y.matchedLines[0]?.offsetX??0),y:y.element.y+(y.matchedLines[0]?.offsetY??0),width:y.matchedLines[0]?.width,height:y.matchedLines[0]?.height,fontSize:Zu(y.element)?v1.nameFontSize:y.element.fontSize,fontFamily:Zu(y.element)?w1.Assistant:y.element.fontFamily}),k=14,L=I.fontSize,S=L*v<k;if(!VY([I],e.canvas.width/window.devicePixelRatio,e.canvas.height/window.devicePixelRatio,{offsetLeft:e.state.offsetLeft,offsetTop:e.state.offsetTop,scrollX:e.state.scrollX,scrollY:e.state.scrollY,zoom:e.state.zoom},e.scene.getNonDeletedElementsMap(),e.getEditorUIOffsets())||S){let _;S?L>=k?_={fitToContent:!0}:_={fitToViewport:!0,maxZoom:FY(k/L,1)}:_={fitToContent:!0},e.scrollToContent(I,{animate:!0,duration:300,..._,canvasOffsets:e.getEditorUIOffsets()})}}}},[d,l,e]),pd(()=>()=>{u(null),m.current=null,p.current=void 0,t({searchMatches:null}),s(!1)},[t,u]);let w=Fr({goToNextItem:g,goToPreviousItem:E,searchMatches:l});pd(()=>{let y=v=>{if(v.key===ml.ESCAPE&&!e.state.openDialog&&!e.state.openPopup){v.preventDefault(),v.stopPropagation(),t({openSidebar:null});return}if(v[ml.CTRL_OR_CMD]&&v.key===ml.F){if(v.preventDefault(),v.stopPropagation(),e.state.openDialog)return;o.current?.matches(":focus")||(e.state.openDialog&&t({openDialog:null}),o.current?.focus(),o.current?.select())}v.target instanceof HTMLElement&&v.target.closest(".layer-ui__search")&&w.searchMatches.items.length&&(v.key===ml.ENTER&&(v.stopPropagation(),w.goToNextItem()),v.key===ml.ARROW_UP?(v.stopPropagation(),w.goToPreviousItem()):v.key===ml.ARROW_DOWN&&(v.stopPropagation(),w.goToNextItem()))};return $Y(window,WY.KEYDOWN,y,{capture:!0,passive:!1})},[t,w,e]);let x=`${l.items.length} ${l.items.length===1?f("search.singleResult"):f("search.multipleResults")}`;return Xn("div",{className:"layer-ui__search",children:[Ft("div",{className:"layer-ui__search-header",children:Ft(ti,{className:UY.SEARCH_MENU_INPUT_WRAPPER,value:n,ref:o,placeholder:f("search.placeholder"),icon:ko,onChange:y=>{r(y),s(!0);let v=y.trim();kS(v,e,(I,k)=>{c({nonce:IS(),items:I}),u(k),m.current=v,p.current=e.scene.getSceneNonce(),t({searchMatches:I.length?{focusedId:null,matches:I.map(L=>({id:L.element.id,focus:!1,matchedLines:L.matchedLines}))}:null}),s(!1)})},selectOnRender:!0})}),Xn("div",{className:"layer-ui__search-count",children:[l.items.length>0&&Xn(nV,{children:[d!==null&&d>-1?Xn("div",{children:[d+1," / ",x]}):Ft("div",{children:x}),Xn("div",{className:"result-nav",children:[Ft(ro,{onSelect:()=>{g()},className:"result-nav-btn",children:fm}),Ft(ro,{onSelect:()=>{E()},className:"result-nav-btn",children:Kw})]})]}),l.items.length===0&&i&&m.current&&Ft("div",{style:{margin:"1rem auto"},children:f("search.noMatch")})]}),Ft(JY,{matches:l,onItemClick:u,focusIndex:d,searchQuery:i})]})},TS=e=>{let t=[e.preview.moreBefore?"...":"",e.preview.previewText.slice(0,e.preview.indexInSearchQuery),e.preview.previewText.slice(e.preview.indexInSearchQuery,e.preview.indexInSearchQuery+e.searchQuery.length),e.preview.previewText.slice(e.preview.indexInSearchQuery+e.searchQuery.length),e.preview.moreAfter?"...":""];return Ft("div",{tabIndex:-1,className:OY("layer-ui__result-item",{active:e.highlighted}),onClick:e.onClick,ref:o=>{e.highlighted&&o?.scrollIntoView({behavior:"auto",block:"nearest"})},children:Ft("div",{className:"preview-text",children:t.flatMap((o,n)=>Ft(HY,{children:n===2?Ft("b",{children:o}):o},n))})})},jY=e=>{let t=wS(()=>e.matches.items.filter(n=>Zu(n.element)),[e.matches]),o=wS(()=>e.matches.items.filter(n=>SS(n.element)),[e.matches]);return Xn("div",{children:[t.length>0&&Xn("div",{className:"layer-ui__search-result-container",children:[Xn("div",{className:"layer-ui__search-result-title",children:[Ft("div",{className:"title-icon",children:Dn}),Ft("div",{children:f("search.frames")})]}),t.map((n,r)=>Ft(TS,{searchQuery:e.searchQuery,preview:n.preview,highlighted:r===e.focusIndex,onClick:()=>e.onItemClick(r)},n.element.id+n.index)),o.length>0&&Ft("div",{className:"layer-ui__divider"})]}),o.length>0&&Xn("div",{className:"layer-ui__search-result-container",children:[Xn("div",{className:"layer-ui__search-result-title",children:[Ft("div",{className:"title-icon",children:_n}),Ft("div",{children:f("search.texts")})]}),o.map((n,r)=>Ft(TS,{searchQuery:e.searchQuery,preview:n.preview,highlighted:r+t.length===e.focusIndex,onClick:()=>e.onItemClick(r+t.length)},n.element.id+n.index))]})]})},qY=(e,t)=>e.matches.nonce===t.matches.nonce&&e.focusIndex===t.focusIndex,JY=GY(jY,qY),CS=(e,t,o)=>{let i=e.slice(0,t),a=i.split(/\s+/),s=i.endsWith(" "),l=a.length-2-1-(s?0:1),c=a.slice(l<=0?0:l).join(" ")+(s?" ":""),m=20;c=c.length>m?c.slice(-m):c;let p=e.slice(t+o.length),d=p.split(/\s+/),u=!p.startsWith(" "),h=u?6:5,g=(u?"":" ")+d.slice(0,h).join(" ");return{indexInSearchQuery:c.length,previewText:c+o+g,moreBefore:l>0,moreAfter:d.length>h}},QY=(e,t)=>{let o=e.split(`
104
+ Return ONLY the raw HTML. No markdown, no code fences, no explanation.`,imagePlaceholders:l}}async function cG(e,t,o,n){let r=await fetch("https://openrouter.ai/api/v1/chat/completions",{method:"POST",signal:n,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify({model:o,messages:[{role:"user",content:e}],stream:!1,temperature:.3})});if(!r.ok){let l=`OpenRouter API error ${r.status}`;try{let c=await r.json();c?.error?.message&&(l=c.error.message)}catch{}throw new Error(l)}return((await r.json())?.choices?.[0]?.message?.content??"").replace(/^```(?:html)?\s*/i,"").replace(/\s*```\s*$/i,"").trim()}function dG(e,t){let o=e.findIndex(r=>r.id===t);if(o<0)return e.length;let n=o+1;for(let r=o+1;r<e.length;r++)e[r].frameId===t&&(n=r+1);return n}async function mG(e){let{info:t,targetWidth:o,targetHeight:n,placementX:r,placementY:i,app:a,geminiApiKey:s,openRouterApiKey:l,chatModel:c,agentImageModel:m,customFontMap:p={},onProgress:d,signal:u,debugLabel:h=`${o}\xD7${n}`,existingFrameId:g}=e,E=t.frame,w;if(g)w=g;else{let z=f3({...x3,x:r,y:i,width:o,height:n,opacity:100,locked:!1,name:`${o}\xD7${n}`}),V=[...a.getSceneElements(),z];yu(V,wu([z])),a.updateScene({elements:V}),w=z.id}let x=null;if(t.background.type==="image"){let z=t.background.dataUrl,$=nG(E.width,E.height,o,n);if(fo(`[AutoResize] ${h} \u2014 background: needsRegen=${$}`),$){d?.("Regenerating background image\u2026");let V=rG(o,n);fo(`[AutoResize] ${h} \u2014 calling Gemini for background regen (ar=${V})`),x=await ua(`You are given an input background image. Preserve the original scene identity, composition, color palette, and style. Outpaint only beyond the existing edges so the final image fits aspect ratio ${V}. Keep the center subject and key content unchanged. Ensure all surfaces extend with natural, seamless continuity \u2014 no visible seams, repeated patterns, or tiling artifacts. For areas far from the center, gradually soften into ambient bokeh rather than extending sharp textures. Do not add text, logos, watermarks, UI, symbols, or new unrelated objects. Avoid altering brand-relevant details.`,m||jH,V,"1K",!1,!1,s,z,u)}else x=z}if(x){d?.("Placing background\u2026");let{width:z,height:$}=await iG(x),{relX:V,relY:Q,width:ee,height:ie}=aG(z,$,o,n),Ee=p3(),_e=g3({type:"image",x:r+V,y:i+Q,width:ee,height:ie,fileId:Ee,status:"pending",scale:[1,1],customData:{autoResizeBg:!0}}),Re=a.getSceneElements(),We=dG(Re,w),lt=[...Re.slice(0,We),{..._e,frameId:w},...Re.slice(We)];yu(lt,wu([_e])),a.updateScene({elements:lt}),a.addFiles([{id:Ee,dataURL:x,mimeType:Bo(x),created:Date.now(),lastRetrieved:Date.now()}])}d?.("Generating layout\u2026"),fo(`[AutoResize] ${h} \u2014 calling OpenRouter for HTML layout (model=${c})`);let{prompt:y,imagePlaceholders:v}=lG(t,o,n),I=await cG(y,l,c,u);if(!I||I.length<20)throw new Error("LLM returned empty HTML");fo(`[AutoResize] ${h} \u2014 HTML received (${I.length} chars), substituting ${v.size} image placeholder(s)\u2026`);for(let[z,$]of v)I=I.split(`url(${z})`).join(`url(${$})`);d?.("Parsing layout\u2026");let k;try{k=await xu(I,r,i,o,n,p)}catch(z){throw new Error(`HTML parse failed: ${z instanceof Error?z.message:String(z)}`)}if(!k||k.length===0)throw new Error("HTML parser produced no elements");d?.("Inserting elements\u2026");let L=[],S=[];for(let z of k)if(z.kind==="rectangle"){let $=u3({type:"rectangle",x:z.x,y:z.y,width:z.width,height:z.height,backgroundColor:z.backgroundColor,fillStyle:"solid",strokeColor:z.strokeColor,strokeWidth:z.strokeWidth,opacity:z.opacity,roughness:0,...z.borderRadius>0?{roundness:{type:3,value:z.borderRadius}}:{},customData:{generatedByHtml:!0}});L.push({...$,frameId:w})}else if(z.kind==="ellipse"){let $=u3({type:"ellipse",x:z.x,y:z.y,width:z.width,height:z.height,backgroundColor:z.backgroundColor,fillStyle:"solid",strokeColor:z.strokeColor,strokeWidth:z.strokeWidth,opacity:z.opacity,roughness:0,customData:{generatedByHtml:!0}});L.push({...$,frameId:w})}else if(z.kind==="text"){let $=XH({x:z.x,y:z.y,text:z.text,fontSize:z.fontSize,fontFamily:z.fontFamily,strokeColor:z.color,textAlign:z.textAlign,width:z.width,opacity:z.opacity,roughness:0,customData:{generatedByHtml:!0}});L.push({...$,frameId:w})}else if(z.kind==="image"){let $=p3(),V=g3({type:"image",x:z.x,y:z.y,width:z.width,height:z.height,fileId:$,status:"pending",scale:[1,1],customData:{generatedByHtml:!0}});L.push({...V,frameId:w}),S.push({id:$,dataURL:z.dataUrl,mimeType:Bo(z.dataUrl),created:Date.now(),lastRetrieved:Date.now()})}let _=o*n,P=[],T=[];for(let z of L)z.type==="rectangle"&&z.width*z.height>=_*.25?P.push(z):T.push(z);let M=a.getSceneElements(),N=M.findIndex(z=>z.id===w),O=b3(M,w),B=O.length>0?M.findIndex(z=>z.id===O[0].id):N+1,U=O.length>0?M.findIndex(z=>z.id===O[O.length-1].id)+1:N+1,D=[...M.slice(0,B),...P,...M.slice(B,U),...T,...M.slice(U)],F=[...P,...T];return yu(D,wu(F)),a.updateScene({elements:D}),S.length>0&&a.addFiles(S),fo(`[AutoResize] ${h} \u2014 inserted ${L.length} elements (${P.length} bg, ${T.length} fg)`),{frameId:w}}function E3(e,t,o){let n=t.x+t.width+80,r=e.map((l,c)=>{let m=e.slice(0,c).reduce((d,u)=>d+u.height+40,t.y);return{frame:f3({...x3,x:n,y:m,width:l.width,height:l.height,opacity:100,locked:!1,name:l.label??`${l.width}\xD7${l.height}`}),x:n,y:m,width:l.width,height:l.height}}),i=o.getSceneElements(),a=r.map(l=>l.frame),s=[...i,...a];return yu(s,wu(a)),o.updateScene({elements:s}),r.map(l=>({frameId:l.frame.id,x:l.x,y:l.y,width:l.width,height:l.height}))}async function y3(e){let{sourceFrameId:t,targetDimensions:o,app:n,geminiApiKey:r,openRouterApiKey:i,chatModel:a="google/gemini-3.1-flash-lite-preview",agentImageModel:s,customFontMap:l={},onBeforeAutoResize:c,onAfterAutoResize:m,onProgress:p,signal:d,preCreatedFrameInfos:u}=e,h=new Array(o.length),g=n.getSceneElements(),E=g.find(k=>k.id===t);if(!E)return o.map(()=>({status:"error",error:"Source frame not found"}));let w=tG(g,E,n.files),x=E.x+E.width+80,y=u??o.map((k,L)=>({x,y:o.slice(0,L).reduce((S,_)=>S+_.height+40,E.y)})),v=3,I=o.length;fo(`[AutoResize] Starting ${I} dimension(s), batch size ${v}`);for(let k=0;k<I;k+=v){let L=Math.min(k+v,I),S=Math.floor(k/v)+1;fo(`[AutoResize] Batch ${S}: dimensions ${k+1}\u2013${L} of ${I}`),await Promise.allSettled(o.slice(k,L).map(async(_,P)=>{let T=k+P,M=_.label??`${_.width}\xD7${_.height}`,N=`[${T+1}/${I}] ${M}`;if(c){fo(`[AutoResize] ${N} \u2014 checking credits`);let{allowed:O,error:B}=await c();if(!O){h[T]={status:"error",error:B??"Not allowed"},p?.(T,I,"error",M),fo(`[AutoResize] ${N} \u2014 credits denied: ${B}`);return}fo(`[AutoResize] ${N} \u2014 credits OK`)}p?.(T,I,"bg-regen",M),fo(`[AutoResize] ${N} \u2014 starting at (${y[T].x}, ${y[T].y})`);try{let{frameId:O}=await mG({info:w,targetWidth:_.width,targetHeight:_.height,placementX:y[T].x,placementY:y[T].y,existingFrameId:u?.[T]?.frameId,app:n,geminiApiKey:r,openRouterApiKey:i,chatModel:a,agentImageModel:s,customFontMap:l,debugLabel:N,onProgress:B=>{p?.(T,I,"layout",`${M}: ${B}`)},signal:d});h[T]={status:"ok",frameId:O},p?.(T,I,"done",M),m?.(),fo(`[AutoResize] ${N} \u2014 DONE`)}catch(O){let B=O instanceof Error?O.message:String(O);h[T]={status:"error",error:B},p?.(T,I,"error",`${M}: ${B}`),fo(`[AutoResize] ${N} \u2014 ERROR: ${B}`)}})),fo(`[AutoResize] Batch ${S} complete`)}return h}import{Fragment as T3,jsx as pe,jsxs as bo}from"react/jsx-runtime";var w3=[{label:"1200\xD7628",width:1200,height:628,desc:"Facebook / OG"},{label:"1080\xD71080",width:1080,height:1080,desc:"Square"},{label:"1080\xD71920",width:1080,height:1920,desc:"Story 9:16"},{label:"728\xD790",width:728,height:90,desc:"Leaderboard"},{label:"320\xD750",width:320,height:50,desc:"Mobile Banner"},{label:"300\xD7600",width:300,height:600,desc:"Half Page"},{label:"300\xD7250",width:300,height:250,desc:"Medium Rect"},{label:"160\xD7600",width:160,height:600,desc:"Wide Skyscraper"}],gG=()=>bo("svg",{width:"14",height:"14",viewBox:"0 0 16 16",fill:"none",children:[pe("rect",{x:"1.5",y:"1.5",width:"7",height:"7",rx:"1",stroke:"currentColor",strokeWidth:"1.4"}),pe("rect",{x:"7.5",y:"7.5",width:"7",height:"7",rx:"1",stroke:"currentColor",strokeWidth:"1.4",strokeDasharray:"2 1",opacity:"0.6"}),pe("path",{d:"M9.5 6.5L13.5 6.5M13.5 6.5L13.5 2.5M13.5 2.5L9.5 2.5",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round",strokeLinejoin:"round"})]}),hG=()=>pe("svg",{width:"12",height:"12",viewBox:"0 0 12 12",fill:"none",children:pe("path",{d:"M1.5 1.5L10.5 10.5M10.5 1.5L1.5 10.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round"})}),N0=()=>pe("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",children:pe("path",{d:"M2 6.5L4.5 9L10 3",stroke:"currentColor",strokeWidth:"1.6",strokeLinecap:"round",strokeLinejoin:"round"})}),v3=()=>pe("svg",{className:"arp-spinner",width:"13",height:"13",viewBox:"0 0 14 14",fill:"none",children:pe("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:"20 14"})}),I3=()=>bo("svg",{width:"11",height:"11",viewBox:"0 0 12 12",fill:"none",children:[pe("circle",{cx:"6",cy:"6",r:"4.5",stroke:"currentColor",strokeWidth:"1.3"}),pe("path",{d:"M6 3.5V6.5",stroke:"currentColor",strokeWidth:"1.4",strokeLinecap:"round"}),pe("circle",{cx:"6",cy:"8.5",r:"0.65",fill:"currentColor"})]}),fG=({onAdd:e})=>{let[t,o]=ga(""),[n,r]=ga("");return bo("div",{className:"arp-custom-row",children:[pe("input",{className:"arp-custom-input",type:"number",placeholder:"W",value:t,min:1,onChange:a=>o(a.target.value),onPointerDown:a=>a.stopPropagation()}),pe("span",{className:"arp-custom-x",children:"\xD7"}),pe("input",{className:"arp-custom-input",type:"number",placeholder:"H",value:n,min:1,onChange:a=>r(a.target.value),onPointerDown:a=>a.stopPropagation()}),pe("button",{className:"arp-custom-add",onClick:()=>{let a=parseInt(t,10),s=parseInt(n,10);a>0&&s>0&&(e({width:a,height:s,label:`${a}\xD7${s}`}),o(""),r(""))},disabled:!t||!n,title:"Add custom dimension",children:"+ Add"})]})},C3=({element:e,app:t,onClose:o,onBeforeAutoResize:n,onAfterAutoResize:r,onRunningChange:i,openRouterApiKey:a,chatModel:s,agentImageModel:l})=>{let[c,m]=ga(new Set),[p,d]=ga([]),[u,h]=ga(!1),[g,E]=ga({}),[w,x]=ga(null),y=uG(null),v=[...w3.filter(B=>c.has(B.label)).map(B=>({width:B.width,height:B.height,label:B.label})),...p],I=B=>{m(U=>{let D=new Set(U);return D.has(B)?D.delete(B):D.add(B),D})},k=B=>{let U=B.label;c.has(U)||(d(D=>[...D,B]),m(D=>new Set([...D,U])))},L=B=>{d(U=>U.filter(D=>D.label!==B)),m(U=>{let D=new Set(U);return D.delete(B),D})},S=R0((B,U)=>{E(D=>({...D,[B]:{...D[B],...U}}))},[]),_=R0(()=>{vr.clear()},[]);pG(()=>()=>{y.current?.abort(),vr.clear()},[]);let P=R0(async()=>{if(v.length===0)return;h(!0),i?.(!0),x(null);let B={};v.forEach(ee=>{B[ee.label]={status:"waiting"}}),E(B);let U=new AbortController;y.current=U;let D=ol(t.props.geminiApiKey),F={},z=t.state.brandContext;if(z?.typography){let{headline:ee,body:ie}=z.typography;ee?.family&&ee?.fontFamilyId&&(F[ee.family.toLowerCase().trim()]=ee.fontFamilyId),ie?.family&&ie?.fontFamilyId&&(F[ie.family.toLowerCase().trim()]=ie.fontFamilyId)}let V=t.getSceneElements().find(ee=>ee.id===e.id),Q=[];V&&(Q=E3(v,V,t)),Q.length>0&&vr.setLoadingFrames(Q);try{await y3({sourceFrameId:e.id,targetDimensions:v,preCreatedFrameInfos:Q.length>0?Q:void 0,app:t,geminiApiKey:D,openRouterApiKey:a,chatModel:s,agentImageModel:l,customFontMap:F,onBeforeAutoResize:n,onAfterAutoResize:r,onProgress:(ee,ie,Ee,_e)=>{let Re=v[ee]?.label??_e;Ee==="done"?(S(Re,{status:"done"}),Q[ee]&&vr.markComplete(Q[ee].frameId)):Ee==="error"?(S(Re,{status:"error",error:_e}),Q[ee]&&vr.markComplete(Q[ee].frameId)):Ee==="bg-regen"?S(Re,{status:"bg-regen"}):S(Re,{status:"layout"})},signal:U.signal})}catch(ee){ee instanceof DOMException&&ee.name==="AbortError"||U.signal.aborted||x(ee instanceof Error?ee.message:"An unexpected error occurred")}finally{h(!1),i?.(!1),y.current=null,_()}},[v,t,e.id,S,_,n,r,a,s,l]),T=()=>{y.current?.abort(),h(!1),i?.(!1),_()},M=Object.values(g).filter(B=>B.status==="done").length,N=v.length,O=M>0;return bo("div",{className:"arp",onPointerDown:B=>B.stopPropagation(),onClick:B=>B.stopPropagation(),children:[bo("div",{className:"arp-header",children:[bo("span",{className:"arp-header__title",children:[pe(gG,{}),"Auto Resize"]}),pe("button",{className:"arp-header__close",onClick:()=>{u?window.confirm("This will cancel the generation. Are you sure?")&&(T(),o()):o()},title:"Close",children:pe(hG,{})})]}),bo("div",{className:"arp-source",children:["Source: ",Math.round(e.width),"\xD7",Math.round(e.height)]}),pe("div",{className:"arp-section-label",children:"Target dimensions"}),pe("div",{className:"arp-presets",children:w3.map(B=>{let U=c.has(B.label),D=g[B.label];return bo("button",{className:`arp-preset ${U?"arp-preset--selected":""} ${u?"arp-preset--disabled":""}`,onClick:()=>!u&&I(B.label),title:B.desc,children:[pe("span",{className:"arp-preset__check",children:U&&pe(N0,{})}),pe("span",{className:"arp-preset__label",children:B.label}),pe("span",{className:"arp-preset__desc",children:B.desc}),D&&bo("span",{className:"arp-preset__status",children:[D.status==="waiting"&&pe("span",{className:"arp-status arp-status--waiting",children:"\u2026"}),(D.status==="bg-regen"||D.status==="layout"||D.status==="inserting")&&pe("span",{className:"arp-status arp-status--running",children:pe(v3,{})}),D.status==="done"&&pe("span",{className:"arp-status arp-status--done",children:pe(N0,{})}),D.status==="error"&&pe("span",{className:"arp-status arp-status--error",title:D.error,children:pe(I3,{})})]})]},B.label)})}),p.length>0&&pe("div",{className:"arp-extras",children:p.map(B=>{let U=g[B.label];return bo("div",{className:"arp-extra-tag",children:[pe("span",{children:B.label}),U?.status==="done"&&pe("span",{className:"arp-status arp-status--done",children:pe(N0,{})}),U?.status==="error"&&pe("span",{className:"arp-status arp-status--error",title:U.error,children:pe(I3,{})}),(U?.status==="bg-regen"||U?.status==="layout")&&pe("span",{className:"arp-status arp-status--running",children:pe(v3,{})}),!u&&pe("button",{className:"arp-extra-tag__remove",onClick:()=>L(B.label),children:"\xD7"})]},B.label)})}),!u&&bo(T3,{children:[pe("div",{className:"arp-section-label",children:"Custom size"}),pe(fG,{onAdd:k})]}),w&&pe("div",{className:"arp-error",children:w}),u&&N>0&&bo("div",{className:"arp-progress",children:[pe("div",{className:"arp-progress__bar-bg",children:pe("div",{className:"arp-progress__bar-fill",style:{width:`${M/N*100}%`}})}),bo("span",{className:"arp-progress__text",children:[M,"/",N," done"]})]}),pe("div",{className:"arp-actions",children:u?pe("button",{className:"arp-btn arp-btn--cancel",onClick:T,children:"Cancel"}):O?bo(T3,{children:[pe("button",{className:"arp-btn arp-btn--primary",onClick:P,disabled:v.length===0,children:"Generate more"}),pe("button",{className:"arp-btn arp-btn--ghost",onClick:o,children:"Done"})]}):pe("button",{className:"arp-btn arp-btn--primary",onClick:P,disabled:v.length===0,children:v.length===0?"Select sizes above":`Generate ${v.length} size${v.length!==1?"s":""}`})})]})};function nd(e){let t=e?.trim();return(t||void 0)??(typeof import.meta<"u"&&C?.VITE_APP_OPENROUTER_API_KEY?C.VITE_APP_OPENROUTER_API_KEY:"")??""}import{jsx as S3}from"react/jsx-runtime";var M3=({app:e})=>{let[t,o]=xG(bn.getState()),n=bG(null);if(k3(()=>bn.subscribe(o),[]),k3(()=>{if(!t.isOpen)return;let d=u=>{t.isRunning||n.current&&!n.current.contains(u.target)&&bn.close()};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[t.isOpen,t.isRunning]),!t.isOpen||!t.element)return null;let r=t.element,i=e.state,[a,s]=yG(r,e.scene.getNonDeletedElementsMap()),{x:l,y:c}=EG({sceneX:a+r.width/2,sceneY:s},i),m=l-i.offsetLeft,p=Math.max(c-i.offsetTop-82,8);return S3("div",{ref:n,style:{position:"absolute",left:`${m}px`,top:`${p}px`,transform:"translateX(-50%)",zIndex:"var(--zIndex-canvasButtons)",pointerEvents:"all"},children:S3(C3,{element:r,app:e,onClose:()=>bn.close(),onRunningChange:d=>bn.setRunning(d),onBeforeAutoResize:e.props.onBeforeAutoResize,onAfterAutoResize:e.props.onAfterAutoResize,openRouterApiKey:nd(e.props.openRouterApiKey),chatModel:e.props.chatModel??"google/gemini-3.1-flash-lite-preview",agentImageModel:e.props.agentImageModel})})};import{useCallback as Tu,useState as z0}from"react";import{sceneCoordsToViewportCoords as PG}from"@orangecatai/common";import{getElementAbsoluteCoords as AG}from"@orangecatai/element";function P3(e){let t=e?.trim();return(t||void 0)??(typeof import.meta<"u"&&C?.VITE_APP_LEONARDO_API_KEY?C.VITE_APP_LEONARDO_API_KEY:"")??""}function A3(e){let t=e?.trim();return(t||void 0)??(typeof import.meta<"u"&&C?.VITE_APP_REMOVE_BG_API_KEY?C.VITE_APP_REMOVE_BG_API_KEY:"")??""}import{useCallback as vu,useEffect as B0,useRef as Iu,useState as Vn}from"react";import{sceneCoordsToViewportCoords as L3}from"@orangecatai/common";import{getElementAbsoluteCoords as wG}from"@orangecatai/element";import{ArrowUp as vG}from"lucide-react";import{Fragment as MG,jsx as xe,jsxs as Bt}from"react/jsx-runtime";var F0=()=>xe("svg",{width:"10",height:"10",viewBox:"0 0 10 10",fill:"none",children:xe("path",{d:"M2.5 3.75L5 6.25L7.5 3.75",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),O0=()=>xe("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:xe("path",{d:"M2.5 7.5L5.5 10.5L11.5 3.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeLinejoin:"round"})}),IG=()=>xe("svg",{width:"16",height:"16",viewBox:"0 0 16 16",fill:"none",children:xe("path",{d:"M8 2L10.5 5.5H13.5L11.5 8L13 11.5L8 9.5L3 11.5L4.5 8L2.5 5.5H5.5L8 2Z",stroke:"currentColor",strokeWidth:"1.3",strokeLinejoin:"round"})}),TG=()=>Bt("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:[xe("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.2"}),xe("path",{d:"M7 6.5V10",stroke:"currentColor",strokeWidth:"1.3",strokeLinecap:"round"}),xe("circle",{cx:"7",cy:"4.5",r:"0.75",fill:"currentColor"})]}),CG=()=>xe("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",className:"igp-spinner",children:xe("circle",{cx:"7",cy:"7",r:"5.5",stroke:"currentColor",strokeWidth:"1.5",strokeLinecap:"round",strokeDasharray:"20 14"})}),kG=()=>xe("svg",{width:"14",height:"14",viewBox:"0 0 14 14",fill:"none",children:xe("path",{d:"M7 1.5L8.5 5.5H12.5L9.5 8L10.5 12L7 9.5L3.5 12L4.5 8L1.5 5.5H5.5L7 1.5Z",fill:"currentColor"})}),SG=({label:e})=>{let t={border:"1.5px solid currentColor",borderRadius:2,boxSizing:"border-box",display:"inline-block",flexShrink:0},n={"21:9":{width:21,height:9},"16:9":{width:18,height:10},"4:3":{width:16,height:12},"3:2":{width:15,height:10},"1:1":{width:13,height:13},"9:16":{width:10,height:18},"3:4":{width:12,height:16},"2:3":{width:10,height:15},"5:4":{width:15,height:12},"4:5":{width:12,height:15},"4:1":{width:24,height:6},"1:4":{width:6,height:24},"8:1":{width:24,height:3},"1:8":{width:3,height:24}}[e]??{width:13,height:13};return xe("div",{style:{...t,...n}})},_3=({element:e,app:t,onBeforeImageGen:o,onAfterImageGen:n,forceOpen:r,onClose:i})=>{let a=t.state,s=ol(t.props.geminiApiKey),[l,c]=Vn(()=>r||ca(e.id)),m=vu(()=>{c(!1),i?.()},[i]),[p,d]=Vn(()=>gu(e.id)),[u,h]=Vn(()=>si(e.id)?.model??"Gemini 3.1 Flash"),g=ci[u],E=g.supportedRatios,w=g.supportedResolutions,x=E.includes("1:1")?"1:1":E[0],y=w.includes("2K")?"2K":w[w.length-1],[v,I]=Vn(()=>si(e.id)?.ratio??x),[k,L]=Vn(()=>si(e.id)?.resolution??y);B0(()=>{let Y=ci[u],te=Y.supportedRatios;te.includes(v)||I(te.includes("1:1")?"1:1":te[0]);let ft=Y.supportedResolutions;ft.includes(k)||L(ft.includes("2K")?"2K":ft[ft.length-1])},[u]);let[S,_]=Vn(()=>ca(e.id)),[P,T]=Vn(null),[M,N]=Vn(!1),[O,B]=Vn(!1),[U,D]=Vn(!1),F=Iu(null),z=Iu(null),$=Iu(null),V=Iu(null),Q=vu(Y=>{I(Y),N(!1)},[]);B0(()=>{let Y=te=>{_(!1),te?te!=="aborted"&&T(te):(m(),d(""))};return du(e.id,Y),()=>mu(e.id,Y)},[e.id]),B0(()=>{let Y=te=>{F.current&&!F.current.contains(te.target)&&N(!1),z.current&&!z.current.contains(te.target)&&B(!1),$.current&&!$.current.contains(te.target)&&D(!1)};return document.addEventListener("mousedown",Y),()=>document.removeEventListener("mousedown",Y)},[]);let ee=vu(()=>{uu(e.id)},[e.id]),ie=vu(async()=>{if(!p.trim()){T("Please enter a prompt.");return}if(!s){T("No Gemini API key found. Set VITE_APP_GEMINI_API_KEY in .env or pass geminiApiKey as a prop.");return}if(o)try{let{allowed:Pe,error:ft}=await o();if(!Pe){T(ft||"Insufficient credits for image generation");return}}catch{T("Credit check failed");return}let Y=new AbortController;V.current=Y,lu(e.id,p,{model:u,ratio:v,resolution:k},Y),_(!0),T(null);let te=null;try{let Pe=ci[u],ft=e.fileId?t.files[e.fileId]?.dataURL:void 0,To=await ua(p,Pe.geminiModelId,v,k,Pe.supportsImageSize,Pe.supportsThinking,s,ft,Y.signal),Dr=pa(u,v,k);await t.insertGeneratedImageNearElement(To,e,Dr.width,Dr.height),n?.()}catch(Pe){Pe instanceof Error&&(Pe.name==="AbortError"?te="aborted":te=Pe.message)}finally{V.current=null,cu(e.id,te),_(!1),te===null?(pu(e.id),m(),d(""),T(null)):te!=="aborted"&&T(te)}},[p,s,u,v,k,t,e,o,n]);if(a.contextMenu||a.newElement||a.resizingElement||a.isRotating||a.openMenu||a.viewModeEnabled||a.selectedElementsAreBeingDragged)return null;let Ee=t.scene.getNonDeletedElementsMap(),[_e,Re,,We]=wG(e,Ee),{x:lt,y:qt}=L3({sceneX:_e+e.width/2,sceneY:Re},a),rr=lt-a.offsetLeft,In=Math.max(qt-a.offsetTop-44,8),{x:Ro,y:Tt}=L3({sceneX:_e+e.width/2,sceneY:We},a),Ct=Ro-a.offsetLeft,Jt=Tt-a.offsetTop+16;return Bt(MG,{children:[!r&&xe("div",{className:"iqep__trigger-bar",style:{left:`${rr}px`,top:`${In}px`},onPointerDown:Y=>Y.stopPropagation(),onClick:Y=>Y.stopPropagation(),children:Bt("button",{className:"iqep__trigger-btn",onClick:()=>c(Y=>!Y),title:"Quick AI edit",children:[xe(kG,{}),xe("span",{children:"AI Edit"})]})}),l&&xe("div",{className:"igp iqep__panel",style:{left:`${Ct}px`,top:`${Jt}px`},onPointerDown:Y=>Y.stopPropagation(),onClick:Y=>Y.stopPropagation(),children:Bt(nl,{isLoading:S,value:p,onValueChange:d,onSubmit:ie,className:"igp-container",children:[xe(rl,{placeholder:"Describe your edit\u2026",className:"igp-textarea",disableAutosize:!1}),P&&xe("div",{className:"igp-error",children:P}),Bt(il,{className:"igp-actions",children:[xe("div",{className:"igp-actions-left",children:Bt("div",{className:"igp-dropdown-root",ref:$,children:[xe(Tr,{tooltip:"Select model",side:"top",children:Bt("button",{className:"igp-btn",onClick:()=>{D(Y=>!Y),N(!1),B(!1)},disabled:S,children:[xe(IG,{}),xe("span",{children:u}),xe(F0,{})]})}),U&&xe("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--left",children:D0.map(Y=>Bt("button",{className:"igp-dropdown-item",onClick:()=>{h(Y),D(!1)},children:[xe("span",{style:{flex:1},children:Y}),Y===u&&xe("span",{className:"igp-check",children:xe(O0,{})})]},Y))})]})}),Bt("div",{className:"igp-actions-right",children:[Bt("div",{className:"igp-dropdown-root",ref:z,children:[Bt("button",{className:"igp-btn igp-btn--compact",onClick:()=>{w.length<=1||(B(Y=>!Y),N(!1),D(!1))},disabled:S||w.length<=1,title:w.length<=1?"Fixed resolution for this model":void 0,children:[xe("span",{children:k}),w.length>1&&xe(F0,{})]}),O&&w.length>1&&xe("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--right",children:w.map(Y=>Bt("button",{className:"igp-dropdown-item",onClick:()=>{L(Y),B(!1)},children:[xe("span",{style:{flex:1},children:Y}),Y===k&&xe("span",{className:"igp-check",children:xe(O0,{})})]},Y))})]}),Bt("div",{className:"igp-dropdown-root",ref:F,children:[Bt("button",{className:"igp-btn igp-btn--compact",onClick:()=>{N(Y=>!Y),B(!1),D(!1)},disabled:S,children:[xe("span",{children:v}),xe(F0,{})]}),M&&Bt("div",{className:"igp-dropdown igp-dropdown--up igp-dropdown--right igp-dropdown--ratio",children:[Bt("div",{className:"igp-dropdown-header",children:[xe("span",{children:"Output format"}),xe(TG,{})]}),E.map(Y=>{let te=pa(u,Y,k);return Bt("button",{className:"igp-dropdown-item",onClick:()=>Q(Y),children:[xe(SG,{label:Y}),xe("span",{style:{flex:1},children:Y}),Bt("span",{className:"igp-dims",children:[te.width,"\xD7",te.height]}),Y===v&&xe("span",{className:"igp-check",children:xe(O0,{})})]},Y)})]})]}),xe("button",{className:"igp-generate",onClick:S?ee:ie,disabled:!S&&!p.trim(),title:S?"Stop generation":"Generate edit",children:S?xe(CG,{}):xe(vG,{size:16})})]})]})]})})]})};import{Fragment as $G,jsx as it,jsxs as Cr}from"react/jsx-runtime";var H0="https://cloud.leonardo.ai/api/rest/v1",LG=1500,D3=40,N3=e=>({Authorization:`Bearer ${e}`,"Content-Type":"application/json"}),B3=e=>{switch(e){case"image/jpeg":return"jpeg";case"image/jpg":return"jpg";case"image/webp":return"webp";default:return"png"}},_G=e=>e==="upscale"?"Upscale":"Remove background",DG=e=>e==="upscale"?"Upscaling image...":"Removing background...",RG=e=>new Promise(t=>{window.setTimeout(t,e)}),Cu=async(e,t)=>{try{let o=await e.json(),n=o?.error?.message??o?.message??o?.detail??o?.errors?.[0]?.message;if(typeof n=="string"&&n.trim())return n}catch{}try{let o=await e.text();if(o.trim())return o.trim()}catch{}return`${t} (${e.status})`},R3=async(e,t)=>{let o=e.crop;return o?new Promise((n,r)=>{let i=new Image;i.onload=()=>{let a=document.createElement("canvas");a.width=o.width,a.height=o.height;let s=a.getContext("2d");if(!s){r(new Error("Could not prepare the cropped image for editing."));return}s.drawImage(i,o.x,o.y,o.width,o.height,0,0,o.width,o.height),n(a.toDataURL("image/png"))},i.onerror=()=>r(new Error("Could not read the selected image for editing.")),i.src=t}):t},NG=async(e,t)=>{let o=B3(Bo(e)),n=await fetch(`${H0}/init-image`,{method:"POST",headers:N3(t),body:JSON.stringify({extension:o})});if(!n.ok)throw new Error(await Cu(n,"Leonardo init image request failed"));let i=(await n.json()).uploadInitImage;if(!i?.id||!i.url)throw new Error("Leonardo init image response was incomplete.");let a=i.fields??{},s=typeof a=="string"?JSON.parse(a):a,l=new FormData;return Object.entries(s).forEach(([c,m])=>{l.append(c,m)}),l.append("file",th(e,`image.${o}`)),await fetch(i.url,{method:"POST",body:l,mode:"no-cors"}),i.id},BG=async(e,t)=>{let o=Bo(e),n=B3(o),r=th(e,`image.${n}`),i=new FormData;i.append("size","auto"),i.append("image_file",r);let a=await fetch("https://api.remove.bg/v1.0/removebg",{method:"POST",headers:{"X-Api-Key":t},body:i});if(!a.ok){let l=`Remove background failed (${a.status})`;try{let m=(await a.json())?.errors?.[0]?.title;m&&(l=m)}catch{}throw new Error(l)}let s=await a.arrayBuffer();return await za(new Blob([s],{type:"image/png"}))},FG=async(e,t)=>{let o=await fetch(`${H0}/variations/universal-upscaler`,{method:"POST",headers:N3(t),body:JSON.stringify({ultraUpscaleStyle:"ARTISTIC",creativityStrength:1,detailContrast:5,similarity:10,upscaleMultiplier:1.5,initImageId:e})});if(!o.ok)throw new Error(await Cu(o,"Leonardo upscale request failed"));let r=(await o.json()).universalUpscaler?.id;if(!r)throw new Error("Leonardo variation job id was missing from the response.");return r},OG=async(e,t)=>{for(let o=0;o<D3;o++){let n=await fetch(`${H0}/variations/${e}`,{method:"GET",headers:{Authorization:`Bearer ${t}`}});if(!n.ok)throw new Error(await Cu(n,"Leonardo variation status check failed"));let r=await n.json(),i=Array.isArray(r.generated_image_variation_generic)?r.generated_image_variation_generic[0]:r.generated_image_variation_generic;if(!i)throw new Error("Leonardo variation details were missing from the response.");if(i.status==="COMPLETE"){if(!i.url)throw new Error("Leonardo variation completed without an image URL.");return i.url}if(i.status==="FAILED")throw new Error("Leonardo variation failed.");o<D3-1&&await RG(LG)}throw new Error("Leonardo variation timed out.")},zG=async e=>{let t=await fetch(e);if(!t.ok)throw new Error(await Cu(t,"Leonardo result image download failed"));return za(await t.blob())},HG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("path",{d:"M12 20h9"}),it("path",{d:"M16.5 3.5a2.121 2.121 0 0 1 3 3L7 19l-4 1 1-4L16.5 3.5z"})]}),GG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),it("path",{d:"M9 3v18"}),it("path",{d:"M14 9l3-3 3 3"}),it("path",{d:"M17 6v6"})]}),UG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("rect",{x:"3",y:"3",width:"18",height:"18",rx:"2"}),it("path",{d:"M9 3v18M3 9h18M3 15h18M15 3v18",strokeDasharray:"2 2",opacity:"0.5"}),it("circle",{cx:"12",cy:"12",r:"4"})]}),WG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("path",{d:"M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"}),it("polyline",{points:"7 10 12 15 17 10"}),it("line",{x1:"12",y1:"15",x2:"12",y2:"3"})]}),YG=()=>Cr("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",children:[it("path",{d:"M6.13 1L6 16a2 2 0 0 0 2 2h15"}),it("path",{d:"M1 6.13L16 6a2 2 0 0 1 2 2v15"})]}),VG=[{id:"quick-edit",label:"Quick Edit",icon:it(HG,{})},{id:"upscale",label:"Upscale",icon:it(GG,{})},{id:"remove-bg",label:"Remove BG",icon:it(UG,{})},{id:"crop",label:"Crop",icon:it(YG,{})}],F3=({element:e,app:t,callbacks:o})=>{let n=t.state,r=P3(t.props.leonardoApiKey),i=A3(t.props.removeBgApiKey),[a,s]=z0(()=>ca(e.id)),[l,c]=z0(null),[m,p]=z0(null),d=l!==null,u=Tu(async S=>{if(!r){p("No Leonardo API key found. Set VITE_APP_LEONARDO_API_KEY in .env or pass leonardoApiKey as a prop.");return}let _=e.fileId;if(!_){p("The selected image is missing its file reference.");return}let P=t.files[_]?.dataURL;if(!P){p("The selected image file could not be found.");return}let T=t.props.onBeforeUpscale,M=t.props.onAfterUpscale;if(T)try{let{allowed:N,error:O}=await T();if(!N){p(O||"Insufficient credits for upscale");return}}catch{p("Credit check failed");return}c(S),p(null);try{let N=await R3(e,P),O=await NG(N,r),B=await FG(O,r),U=await OG(B,r),D=await zG(U);await t.insertGeneratedImageNearElement(D,e,e.width,e.height),M?.()}catch(N){p(N instanceof Error?N.message:`${_G(S)} failed.`)}finally{c(null)}},[t,e,r]),h=Tu(async()=>{if(!i){p("No remove.bg API key found. Set VITE_APP_REMOVE_BG_API_KEY in .env or pass removeBgApiKey as a prop.");return}let S=e.fileId;if(!S){p("The selected image is missing its file reference.");return}let _=t.files[S]?.dataURL;if(!_){p("The selected image file could not be found.");return}let P=t.props.onBeforeRemoveBg,T=t.props.onAfterRemoveBg;if(P)try{let{allowed:M,error:N}=await P();if(!M){p(N||"Insufficient credits for remove background");return}}catch{p("Credit check failed");return}c("remove-bg"),p(null);try{let M=await R3(e,_),N=await BG(M,i);await t.insertGeneratedImageNearElement(N,e,e.width,e.height),T?.()}catch(M){p(M instanceof Error?M.message:"Remove background failed.")}finally{c(null)}},[t,e,i]),g=Tu(S=>{if(p(null),S==="quick-edit"){o?.onQuickEdit?o.onQuickEdit():s(P=>!P);return}if(S==="crop"){o?.onCrop?o.onCrop():t.actionManager.executeAction(Kc);return}let _={upscale:o?.onUpscale,"remove-bg":o?.onRemoveBG};if(_[S]){_[S]?.();return}S==="upscale"?u(S):S==="remove-bg"&&h()},[o,t.actionManager,u,h]),E=Tu(()=>{if(o?.onDownload){o.onDownload();return}let S=e.fileId;if(!S)return;let _=t.files[S];if(!_?.dataURL)return;let P=N=>{let O=document.createElement("a");O.href=N,O.download=`image-${S}.png`,document.body.appendChild(O),O.click(),document.body.removeChild(O)},T=e.crop;if(!T){P(_.dataURL);return}let M=new Image;M.onload=()=>{let N=document.createElement("canvas");N.width=T.width,N.height=T.height;let O=N.getContext("2d");if(!O){P(_.dataURL);return}O.drawImage(M,T.x,T.y,T.width,T.height,0,0,T.width,T.height),P(N.toDataURL("image/png"))},M.onerror=()=>P(_.dataURL),M.src=_.dataURL},[e.fileId,e.crop,t.files,o]);if(n.contextMenu||n.newElement||n.resizingElement||n.isRotating||n.openMenu||n.viewModeEnabled||n.selectedElementsAreBeingDragged)return null;let w=t.scene.getNonDeletedElementsMap(),[x,y]=AG(e,w),{x:v,y:I}=PG({sceneX:x+e.width/2,sceneY:y},n),k=v-n.offsetLeft,L=Math.max(I-n.offsetTop-52,8);return Cr($G,{children:[a&&!o?.onQuickEdit&&it(_3,{element:e,app:t,onBeforeImageGen:t.props.onBeforeImageGen,onAfterImageGen:t.props.onAfterImageGen,forceOpen:!0,onClose:()=>s(!1)}),Cr("div",{className:"iet",style:{left:`${k}px`,top:`${L}px`},onPointerDown:S=>S.stopPropagation(),onClick:S=>S.stopPropagation(),children:[Cr("div",{className:"iet__bar",children:[VG.map(S=>Cr("button",{type:"button",className:"iet__tool-btn",onClick:()=>g(S.id),title:S.label,disabled:d,"aria-busy":l===S.id,children:[S.icon,it("span",{className:"iet__tool-label",children:S.label}),S.badge&&it("span",{className:"iet__tool-badge",children:S.badge})]},S.id)),it("div",{className:"iet__divider"}),it("button",{type:"button",className:"iet__tool-btn iet__download-btn",onClick:E,title:"Download",disabled:d,children:it(WG,{})})]}),(l||m)&&it("div",{className:`iet__status${m?" iet__status--error":""}`,children:m??(l?DG(l):null)})]})]})};import{DEFAULT_LASER_COLOR as jG,easeOut as z3}from"@orangecatai/common";import{LaserPointer as KG}from"@excalidraw/laser-pointer";import{SVG_NS as O3,getSvgPathFromStroke as XG,sceneCoordsToViewportCoords as ZG}from"@orangecatai/common";var kr=class{constructor(t,o,n){this.animationFrameHandler=t;this.app=o;this.options=n;A(this,"currentTrail");A(this,"pastTrails",[]);A(this,"container");A(this,"trailElement");A(this,"trailAnimation");this.animationFrameHandler.register(this,this.onFrame.bind(this)),this.trailElement=document.createElementNS(O3,"path"),this.options.animateTrail&&(this.trailAnimation=document.createElementNS(O3,"animate"),this.trailAnimation.setAttribute("attributeName","stroke-dashoffset"),this.trailElement.setAttribute("stroke-dasharray","7 7"),this.trailElement.setAttribute("stroke-dashoffset","10"),this.trailAnimation.setAttribute("from","0"),this.trailAnimation.setAttribute("to","-14"),this.trailAnimation.setAttribute("dur","0.3s"),this.trailElement.appendChild(this.trailAnimation))}get hasCurrentTrail(){return!!this.currentTrail}hasLastPoint(t,o){if(this.currentTrail){let n=this.currentTrail.originalPoints.length;return this.currentTrail.originalPoints[n-1][0]===t&&this.currentTrail.originalPoints[n-1][1]===o}return!1}start(t){t&&(this.container=t),this.trailElement.parentNode!==this.container&&this.container&&this.container.appendChild(this.trailElement),this.animationFrameHandler.start(this)}stop(){this.animationFrameHandler.stop(this),this.trailElement.parentNode===this.container&&this.container?.removeChild(this.trailElement)}startPath(t,o){this.currentTrail=new KG(this.options),this.currentTrail.addPoint([t,o,performance.now()]),this.update()}addPointToPath(t,o){this.currentTrail&&(this.currentTrail.addPoint([t,o,performance.now()]),this.update())}endPath(){this.currentTrail&&(this.currentTrail.close(),this.currentTrail.options.keepHead=!1,this.pastTrails.push(this.currentTrail),this.currentTrail=void 0,this.update())}getCurrentTrail(){return this.currentTrail}clearTrails(){this.pastTrails=[],this.currentTrail=void 0,this.update()}update(){this.start(),this.trailAnimation&&(this.trailAnimation.setAttribute("begin","indefinite"),this.trailAnimation.setAttribute("repeatCount","indefinite"))}onFrame(){let t=[];for(let n of this.pastTrails)t.push(this.drawTrail(n,this.app.state));if(this.currentTrail){let n=this.drawTrail(this.currentTrail,this.app.state);t.push(n)}this.pastTrails=this.pastTrails.filter(n=>n.getStrokeOutline().length!==0),t.length===0&&this.stop();let o=t.join(" ").trim();this.trailElement.setAttribute("d",o),this.trailAnimation?(this.trailElement.setAttribute("fill",(this.options.fill??(()=>"black"))(this)),this.trailElement.setAttribute("stroke",(this.options.stroke??(()=>"black"))(this))):this.trailElement.setAttribute("fill",(this.options.fill??(()=>"black"))(this))}drawTrail(t,o){let n=t.getStrokeOutline(t.options.size/o.zoom.value).map(([i,a])=>{let s=ZG({sceneX:i,sceneY:a},o);return[s.x,s.y]}),r=this.trailAnimation?n.slice(0,n.length/2):n;return XG(r,!0)}};var ku=class{constructor(t,o){this.animationFrameHandler=t;this.app=o;A(this,"localTrail");A(this,"collabTrails",new Map);A(this,"container");this.animationFrameHandler.register(this,this.onFrame.bind(this)),this.localTrail=new kr(t,o,{...this.getTrailOptions(),fill:()=>jG})}getTrailOptions(){return{simplify:0,streamline:.4,sizeMapping:t=>{let r=Math.max(0,1-(performance.now()-t.pressure)/1e3),i=(50-Math.min(50,t.totalLength-t.currentIndex))/50;return Math.min(z3(i),z3(r))}}}startPath(t,o){this.localTrail.startPath(t,o)}addPointToPath(t,o){this.localTrail.addPointToPath(t,o)}endPath(){this.localTrail.endPath()}start(t){this.container=t,this.animationFrameHandler.start(this),this.localTrail.start(t)}stop(){this.animationFrameHandler.stop(this),this.localTrail.stop()}onFrame(){this.updateCollabTrails()}updateCollabTrails(){if(!(!this.container||this.app.state.collaborators.size===0)){for(let[t,o]of this.app.state.collaborators.entries()){let n;this.collabTrails.has(t)?n=this.collabTrails.get(t):(n=new kr(this.animationFrameHandler,this.app,{...this.getTrailOptions(),fill:()=>o.pointer?.laserColor||qi(t,o)}),n.start(this.container),this.collabTrails.set(t,n)),o.pointer&&o.pointer.tool==="laser"&&(o.button==="down"&&!n.hasCurrentTrail&&n.startPath(o.pointer.x,o.pointer.y),o.button==="down"&&n.hasCurrentTrail&&!n.hasLastPoint(o.pointer.x,o.pointer.y)&&n.addPointToPath(o.pointer.x,o.pointer.y),o.button==="up"&&n.hasCurrentTrail&&(n.addPointToPath(o.pointer.x,o.pointer.y),n.endPath()))}for(let t of this.collabTrails.keys())this.app.state.collaborators.has(t)||(this.collabTrails.get(t).stop(),this.collabTrails.delete(t))}}};import{version as qG}from"react";import{unstable_batchedUpdates as H3}from"react-dom";import{throttleRAF as JG}from"@orangecatai/common";var mt=e=>t=>{H3(e,t)},Su=e=>JG(t=>{H3(e,t)}),ha=(()=>{let e;try{let o=qG.split(".");e=Number(o[0])>17}catch{e=!1}let t=!1;return()=>window.EXCALIDRAW_THROTTLE_RENDER===!0?e?!0:(t||(t=!0,console.warn("Excalidraw: render throttling is disabled on React versions < 18.")),!1):!1})();import{CODES as G0,KEYS as rd,CLASSES as U0,POINTER_BUTTON as QG,THEME as eU,isWritableElement as tU,getFontString as G3,getFontFamilyString as U3,isTestEnv as W3,MIME_TYPES as W0,applyDarkModeFilter as oU}from"@orangecatai/common";import{getTextFromElements as nU,originalContainerCache as rU,updateBoundElements as Y3,updateOriginalContainerCache as V3}from"@orangecatai/element";import{LinearElementEditor as iU}from"@orangecatai/element";import{bumpVersion as aU}from"@orangecatai/element";import{getBoundTextElementId as sU,getContainerElement as Y0,getTextElementAngle as lU,redrawTextBoundingBox as cU,getBoundTextMaxHeight as dU,getBoundTextMaxWidth as $3,computeContainerDimensionForBoundText as K3,computeBoundTextPosition as mU,getBoundTextElement as pU}from"@orangecatai/element";import{getTextWidth as uU}from"@orangecatai/element";import{normalizeText as X3}from"@orangecatai/element";import{wrapText as gU}from"@orangecatai/element";import{isArrowElement as Mu,isBoundToContainer as hU,isTextElement as Z3}from"@orangecatai/element";var fU=(e,t,o,n,r,i)=>{let{zoom:a}=n,s=180*o/Math.PI,l=e*(a.value-1)/2,c=t*(a.value-1)/2;return e>r&&a.value!==1&&(l=r*(a.value-1)/2),t>i&&a.value!==1&&(c=i*(a.value-1)/2),`translate(${l}px, ${c}px) scale(${a.value}) rotate(${s}deg)`},j3=({id:e,onChange:t,onSubmit:o,getViewportCoords:n,element:r,canvas:i,excalidrawContainer:a,app:s,autoSelect:l=!0})=>{let c=(D,F)=>{if(!F.style.fontFamily||!F.style.fontSize)return!1;let z=F.style.fontFamily.replace(/"/g,"");return U3({fontFamily:D.fontFamily})!==z||`${D.fontSize}px`!==F.style.fontSize},m=s.state.theme,p=()=>{m=s.state.theme;let D=s.state,F=s.scene.getElement(e);if(!F)return;let{textAlign:z,verticalAlign:$}=F,V=s.scene.getNonDeletedElementsMap();if(F&&Z3(F)){let Q=F.x,ee=F.y,ie=Y0(F,s.scene.getNonDeletedElementsMap()),Ee=F.width,_e=F.height,Re=F.width,We=F.height;if(ie&&F.containerId){if(Mu(ie)){let Ct=iU.getBoundTextElementPosition(ie,F,V);Q=Ct.x,ee=Ct.y}let Ro=c(F,d),Tt;if(Ro?Tt=V3(ie.id,ie.height):(Tt=rU[ie.id],Tt||(Tt=V3(ie.id,ie.height))),Re=$3(ie,F),We=dU(ie,F),!Mu(ie)&&_e>We){let Ct=K3(_e,ie.type);s.scene.mutateElement(ie,{height:Ct}),Y3(ie,s.scene);return}else if(!Mu(ie)&&ie.height>Tt.height&&_e<We){let Ct=K3(_e,ie.type);s.scene.mutateElement(ie,{height:Ct}),Y3(ie,s.scene)}else{let{x:Ct,y:Jt}=mU(ie,F,V);Q=Ct,ee=Jt}}let[lt,qt]=n(Q,ee);ie?Ee+=.5:(Re=(D.width-8-lt)/D.zoom.value,Ee=Math.min(Ee,Re)),_e*=1.05;let rr=G3(F),In=(D.height-qt)/D.zoom.value;Object.assign(d.style,{font:rr,lineHeight:F.lineHeight,width:`${Ee}px`,height:`${_e}px`,left:`${lt}px`,top:`${qt}px`,transform:fU(Ee,_e,lU(F,ie),D,Re,In),textAlign:z,verticalAlign:$,color:D.theme===eU.DARK?oU(F.strokeColor):F.strokeColor,opacity:F.opacity/100,maxHeight:`${In}px`}),d.scrollTop=0,W3()&&(d.style.fontFamily=U3(F)),s.scene.mutateElement(F,{x:Q,y:ee})}},d=document.createElement("textarea");d.dir="auto",d.tabIndex=0,d.dataset.type="wysiwyg",d.wrap="off",d.classList.add("excalidraw-wysiwyg");let u="pre",h="normal";(hU(r)||!r.autoResize)&&(u="pre-wrap",h="break-word"),Object.assign(d.style,{position:"absolute",display:"inline-block",minHeight:"1em",backfaceVisibility:"hidden",margin:0,padding:0,border:0,outline:0,resize:"none",background:"transparent",overflow:"hidden",zIndex:"var(--zIndex-wysiwyg)",wordBreak:h,whiteSpace:u,overflowWrap:"break-word",boxSizing:"content-box"}),d.value=r.originalText,p(),t&&(d.onpaste=async D=>{let F=K2(D),z=null;if(F.has(W0.excalidrawClipboard)||F.has(W0.excalidraw)){D.preventDefault(),z=await Is(D);try{let ie=await Qm(z);if(ie.elements){let Ee=nU(ie.elements);if(Ee){let{selectionStart:_e,selectionEnd:Re,value:We}=d;d.value=We.slice(0,_e)+Ee+We.slice(Re);let lt=_e+Ee.length;d.selectionStart=d.selectionEnd=lt,d.dispatchEvent(new Event("input"))}}return}catch{console.warn("failed to parse excalidraw clipboard data")}}z=z||await Is(D);let $=z.findByType(W0.text);if(!$)return;let V=X3($.value);if(!V)return;let Q=Y0(r,s.scene.getNonDeletedElementsMap()),ee=G3({fontSize:s.state.currentItemFontSize,fontFamily:s.state.currentItemFontFamily});if(Q){let ie=pU(Q,s.scene.getNonDeletedElementsMap()),Ee=gU(`${d.value}${V}`,ee,$3(Q,ie)),_e=uU(Ee,ee);d.style.width=`${_e}px`}},d.oninput=()=>{let D=X3(d.value);if(d.value!==D){let F=d.selectionStart;d.value=D,d.selectionStart=F,d.selectionEnd=F}t(d.value)}),d.onkeydown=D=>{if(!D.shiftKey&&Wm.keyTest(D))D.preventDefault(),s.actionManager.executeAction(Wm),p();else if(!D.shiftKey&&Ym.keyTest(D))D.preventDefault(),s.actionManager.executeAction(Ym),p();else if(!D.shiftKey&&Vm.keyTest(D))D.preventDefault(),s.actionManager.executeAction(Vm),p();else if(uf.keyTest(D))s.actionManager.executeAction(uf);else if(gf.keyTest(D))s.actionManager.executeAction(gf);else if(D.key===rd.ESCAPE)D.preventDefault(),k=!0,L();else if(Zi.keyTest(D))D.preventDefault(),L(),s.actionManager.executeAction(Zi);else if(D.key===rd.ENTER&&D[rd.CTRL_OR_CMD]){if(D.preventDefault(),D.isComposing||D.keyCode===229)return;k=!0,L()}else if(D.key===rd.TAB||D[rd.CTRL_OR_CMD]&&(D.code===G0.BRACKET_LEFT||D.code===G0.BRACKET_RIGHT)){if(D.preventDefault(),D.isComposing)return;D.shiftKey||D.code===G0.BRACKET_LEFT?y():x(),d.dispatchEvent(new Event("input"))}};let g=4,E=" ".repeat(g),w=new RegExp(`^ {1,${g}}`),x=()=>{let{selectionStart:D,selectionEnd:F}=d,z=v(),$=d.value;z.forEach(V=>{let Q=$.slice(0,V),ee=$.slice(V);$=`${Q}${E}${ee}`}),d.value=$,d.selectionStart=D+g,d.selectionEnd=F+g*z.length},y=()=>{let{selectionStart:D,selectionEnd:F}=d,z=v(),$=[],V=d.value;z.forEach(Q=>{let ee=V.slice(Q,Q+g).match(w);if(ee){let ie=V.slice(0,Q),Ee=V.slice(Q+ee[0].length);V=`${ie}${Ee}`,$.push(Q)}}),d.value=V,$.length&&(D>$[$.length-1]?d.selectionStart=Math.max(D-g,$[$.length-1]):d.selectionStart=D,d.selectionEnd=Math.max(d.selectionStart,F-g*$.length))},v=()=>{let{selectionStart:D,selectionEnd:F,value:z}=d,$=z.slice(0,D).match(/[^\n]*$/)[0].length;return D=D-$,z.slice(D,F).split(`
105
+ `).reduce((Q,ee,ie,Ee)=>Q.concat(ie?Q[ie-1]+Ee[ie-1].length+1:D),[]).reverse()},I=D=>{D.target instanceof HTMLCanvasElement&&(D.preventDefault(),D.stopPropagation())},k=!1,L=()=>{if(B)return;B=!0,S();let D=s.scene.getElement(r.id);if(!D)return;let F=Y0(D,s.scene.getNonDeletedElementsMap());if(F){if(d.value.trim()){let z=sU(F);!z||z!==r.id?s.scene.mutateElement(F,{boundElements:(F.boundElements||[]).concat({type:"text",id:r.id})}):Mu(F)&&aU(F)}else s.scene.mutateElement(F,{boundElements:F.boundElements?.filter(z=>!Z3(z))});cU(D,F,s.scene)}o({viaKeyboard:k,nextOriginalText:d.value})},S=()=>{d.onblur=null,d.oninput=null,d.onkeydown=null,U&&U.disconnect(),window.removeEventListener("resize",p),window.removeEventListener("wheel",I,!0),window.removeEventListener("pointerdown",T),window.removeEventListener("pointerup",_),window.removeEventListener("blur",L),window.removeEventListener("beforeunload",L),N(),M(),O(),d.remove()},_=D=>{window.removeEventListener("pointerup",_);let F=D?.target,z=F instanceof HTMLElement&&F.classList.contains("properties-trigger"),$=(F instanceof HTMLElement||F instanceof SVGElement)&&!!F.closest(".properties-content"),V=(F instanceof HTMLElement||F instanceof SVGElement)&&(!!F.closest(`.${U0.SHAPE_ACTIONS_MENU}`)||!!F.closest(".compact-shape-actions-island"));setTimeout(()=>{V||z||$||(d.onblur=L,d.focus())})},P=()=>{d.onblur=null,window.addEventListener("pointerup",_),window.addEventListener("blur",L)},T=D=>{let F=D?.target;if(D.button===QG.WHEEL){F instanceof HTMLTextAreaElement&&(D.preventDefault(),s.handleCanvasPanUsingWheelOrSpaceDrag(D)),P();return}let z=F instanceof HTMLElement&&F.classList.contains("properties-trigger"),$=(F instanceof HTMLElement||F instanceof SVGElement)&&!!F.closest(".properties-content");(D.target instanceof HTMLElement||D.target instanceof SVGElement)&&(D.target.closest(`.${U0.SHAPE_ACTIONS_MENU}, .${U0.ZOOM_ACTIONS}`)||D.target.closest(".compact-shape-actions-island"))&&!tU(D.target)||z||$?P():D.target instanceof HTMLCanvasElement&&!W3()&&requestAnimationFrame(()=>{L()})},M=s.onChangeEmitter.on(D=>{s.state.theme!==m&&p()}),N=s.scene.onUpdate(()=>{p(),!!document.activeElement?.closest(".properties-content")||d.focus()}),O=s.onScrollChangeEmitter.on(()=>{p()}),B=!1;l&&d.select(),_();let U=null;return i&&"ResizeObserver"in window?(U=new window.ResizeObserver(()=>{p()}),U.observe(i)):window.addEventListener("resize",p),d.onpointerdown=D=>D.stopPropagation(),requestAnimationFrame(()=>{window.addEventListener("pointerdown",T,{capture:!0})}),window.addEventListener("beforeunload",L),a?.querySelector(".excalidraw-textEditorContainer").appendChild(d),L};import{getGlobalCSSVariable as Pu}from"@orangecatai/common";import{getCommonBounds as bU}from"@orangecatai/element";var Sr=4,Ko=6,q3="rgba(0,0,0,0.3)",J3=(e,t,o,n)=>{if(!e.size)return{horizontal:null,vertical:null};let[r,i,a,s]=bU(e),l=t/n.zoom.value,c=o/n.zoom.value,m={top:parseInt(Pu("sat"))||0,bottom:parseInt(Pu("sab"))||0,left:parseInt(Pu("sal"))||0,right:parseInt(Pu("sar"))||0},p=lr().rtl,d=-n.scrollX+m.left,u=-n.scrollY+m.top,h=d+l-m.right,g=u+c-m.bottom,E=Math.min(r,d),w=Math.min(i,u),x=Math.max(a,h),y=Math.max(s,g),v=a-r,I=s-i,k=x-E,L=y-w,S=Math.max(Sr*2,m.left+m.right)+Ko*2,_=t*(l/k)-S,P=Math.max(Sr*2,m.top+m.bottom)+Ko*2,T=o*(c/L)-P,M=k>v?k*n.zoom.value/(_+S):t/(_+S),N=L>I?L*n.zoom.value/(T+P):o/(T+P);return{horizontal:d===E&&h===x?null:{x:Math.max(m.left,Sr)+Ko+(d-E)/k*t,y:o-Ko-Math.max(Sr,m.bottom),width:_,height:Ko,deltaMultiplier:M},vertical:u===w&&g===y?null:{x:p?Math.max(m.left,Sr):t-Ko-Math.max(m.right,Sr),y:Math.max(m.top,Sr)+Ko+(u-w)/L*o,width:Ko,height:T,deltaMultiplier:N}}},V0=(e,t,o)=>{let[n,r]=[e.horizontal,e.vertical].map(a=>a!=null&&a.x<=t&&t<=a.x+a.width&&a.y<=o&&o<=a.y+a.height);return{isOverEither:n||r,isOverHorizontal:n,isOverVertical:r}};var Q3=e=>{let t=["flowchart","graph","sequenceDiagram","classDiagram","stateDiagram","stateDiagram-v2","erDiagram","journey","gantt","pie","quadrantChart","requirementDiagram","gitGraph","C4Context","mindmap","timeline","zenuml","sankey","xychart","block"];return new RegExp(`^(?:%%{.*?}%%[\\s\\n]*)?\\b(?:${t.map(n=>`\\s*${n}(-beta)?`).join("|")})\\b`).test(e.trim())};import{pointFrom as SU}from"@orangecatai/math";import{getElementLineSegments as MU}from"@orangecatai/element";import{LinearElementEditor as PU}from"@orangecatai/element";import{isFrameLikeElement as AU,isLinearElement as LU,isTextElement as _U}from"@orangecatai/element";import{getFrameChildren as DU}from"@orangecatai/element";import{selectGroupsForSelectedElements as RU}from"@orangecatai/element";import{getContainerElement as NU}from"@orangecatai/element";import{arrayToMap as BU,easeOut as nk,isShallowEqual as FU}from"@orangecatai/common";import{simplify as xU}from"points-on-curve";import{polygonFromPoints as EU,lineSegment as ek,polygonIncludesPointNonZero as yU}from"@orangecatai/math";import{computeBoundTextPosition as wU,doBoundsIntersect as vU,getBoundTextElement as IU,getElementBounds as TU,intersectElementWithLineSegment as tk}from"@orangecatai/element";var ok=e=>{let{lassoPath:t,elements:o,elementsMap:n,elementsSegments:r,intersectedElements:i,enclosedElements:a,simplifyDistance:s}=e,l=t;s&&(l=xU(t,s));let c=o.filter(d=>!d.locked);a.clear(),i.clear();let m=t.reduce((d,u)=>[Math.min(d[0],u[0]),Math.min(d[1],u[1]),Math.max(d[2],u[0]),Math.max(d[3],u[1])],[1/0,1/0,-1/0,-1/0]);for(let d of c){let u=TU(d,n);vU(m,u)&&!i.has(d.id)&&!a.has(d.id)&&(CU(l,d,r)?a.add(d.id):kU(l,d,n)&&i.add(d.id))}return{selectedElementIds:[...i,...a]}},CU=(e,t,o)=>{let n=EU(e),r=o.get(t.id);return r?r.some(i=>i.some(a=>yU(a,n))):!1},kU=(e,t,o)=>{let n=e.slice(1).map((i,a)=>ek(e[a],i)).concat([ek(e[e.length-1],e[0])]),r=IU(t,o);return n.some(i=>tk(t,o,i,0,!0).length>0||!!r&&tk({...r,...wU(t,r,o)},o,i,0,!0).length>0)};var Au=class extends kr{constructor(o,n){super(o,n,{animateTrail:!0,streamline:.4,sizeMapping:r=>{let s=Math.max(0,1-(performance.now()-r.pressure)/(1/0)),l=(5e3-Math.min(5e3,r.totalLength-r.currentIndex))/5e3;return Math.min(nk(l),nk(s))},fill:()=>"rgba(105,101,219,0.05)",stroke:()=>"rgba(105,101,219)"});A(this,"intersectedElements",new Set);A(this,"enclosedElements",new Set);A(this,"elementsSegments",null);A(this,"canvasTranslate",null);A(this,"keepPreviousSelection",!1);A(this,"selectElementsFromIds",o=>{this.app.setState(n=>{let r=o.reduce((l,c)=>(l[c]=!0,l),{});if(this.keepPreviousSelection)for(let l of Object.keys(n.selectedElementIds))r[l]=!0;for(let[l]of Object.entries(r)){let c=this.app.scene.getNonDeletedElement(l);if(c&&_U(c)){let m=NU(c,this.app.scene.getNonDeletedElementsMap());m&&(r[m.id]=!0,delete r[c.id])}}for(let[l]of Object.entries(r)){let c=this.app.scene.getNonDeletedElement(l);if(c&&AU(c)){let m=DU(this.app.scene.getNonDeletedElementsMap(),c.id);for(let p of m)delete r[p.id]}}let i=RU({editingGroupId:n.editingGroupId,selectedElementIds:r},this.app.scene.getNonDeletedElements(),n,this.app),a=[...Object.keys(i.selectedElementIds)],s=[...Object.keys(i.selectedGroupIds)];return{selectedElementIds:i.selectedElementIds,selectedGroupIds:i.selectedGroupIds,selectedLinearElement:a.length===1&&!s.length&&LU(this.app.scene.getNonDeletedElement(a[0]))?new PU(this.app.scene.getNonDeletedElement(a[0]),this.app.scene.getNonDeletedElementsMap()):null}})});A(this,"addPointToPath",(o,n,r=!1)=>{super.addPointToPath(o,n),this.keepPreviousSelection=r,this.updateSelection()});A(this,"updateSelection",()=>{let o=super.getCurrentTrail()?.originalPoints?.map(r=>SU(r[0],r[1])),n={scrollX:this.app.state.scrollX,scrollY:this.app.state.scrollY,zoom:this.app.state.zoom.value};if(!this.elementsSegments||!FU(n,this.canvasTranslate??{})){this.canvasTranslate=n,this.elementsSegments=new Map;let r=BU(this.app.visibleElements);for(let i of this.app.visibleElements){let a=MU(i,r);this.elementsSegments.set(i.id,a)}}if(o){let{selectedElementIds:r}=ok({lassoPath:o,elements:this.app.visibleElements,elementsMap:this.app.scene.getNonDeletedElementsMap(),elementsSegments:this.elementsSegments,intersectedElements:this.intersectedElements,enclosedElements:this.enclosedElements,simplifyDistance:5/this.app.state.zoom.value});this.selectElementsFromIds(r)}})}startPath(o,n,r=!1){this.endPath(),super.startPath(o,n),this.intersectedElements.clear(),this.enclosedElements.clear(),this.keepPreviousSelection=r,this.keepPreviousSelection||this.app.setState({selectedElementIds:{},selectedGroupIds:{},selectedLinearElement:null})}endPath(){super.endPath(),super.clearTrails(),this.intersectedElements.clear(),this.enclosedElements.clear(),this.elementsSegments=null}};import{arrayToMap as OU,easeOut as rk,THEME as zU}from"@orangecatai/common";import{computeBoundTextPosition as HU,doBoundsIntersect as GU,getBoundTextElement as UU,getElementBounds as WU,getElementLineSegments as YU,getFreedrawOutlineAsSegments as VU,getFreedrawOutlinePoints as $U,intersectElementWithLineSegment as ik,isArrowElement as KU,isFreeDrawElement as ak,isLineElement as XU,isPointInElement as ZU}from"@orangecatai/element";import{lineSegment as jU,lineSegmentsDistance as sk,pointFrom as uk,polygon as qU,polygonIncludesPointNonZero as JU}from"@orangecatai/math";import{getElementsInGroup as lk}from"@orangecatai/element";import{shouldTestInside as QU}from"@orangecatai/element";import{hasBoundTextElement as ck,isBoundToContainer as dk}from"@orangecatai/element";import{getBoundTextElementId as mk}from"@orangecatai/element";var Lu=class extends kr{constructor(o,n){super(o,n,{streamline:.2,size:5,keepHead:!0,sizeMapping:r=>{let s=Math.max(0,1-(performance.now()-r.pressure)/200),l=(10-Math.min(10,r.totalLength-r.currentIndex))/10;return Math.min(rk(l),rk(s))},fill:()=>n.state.theme===zU.LIGHT?"rgba(0, 0, 0, 0.2)":"rgba(255, 255, 255, 0.2)"});A(this,"elementsToErase",new Set);A(this,"groupsToErase",new Set)}startPath(o,n){this.endPath(),super.startPath(o,n),this.elementsToErase.clear()}addPointToPath(o,n,r=!1){return super.addPointToPath(o,n),this.updateElementsToBeErased(r)}updateElementsToBeErased(o){let n=super.getCurrentTrail()?.originalPoints?.map(s=>uk(s[0],s[1]))||[];if(n.length<2)return[];let r=jU(n[n.length-1],n[n.length-2]),i=this.app.visibleElements.filter(s=>!s.locked),a=OU(i);for(let s of i)if(o&&this.elementsToErase.has(s.id)){if(pk(r,s,a,this.app.state.zoom.value)){let c=s.groupIds.at(-1);if(this.groupsToErase.has(c)){let m=lk(this.app.scene.getNonDeletedElementsMap(),c);for(let p of m)this.elementsToErase.delete(p.id);this.groupsToErase.delete(c)}if(dk(s)&&this.elementsToErase.delete(s.containerId),ck(s)){let m=mk(s);m&&this.elementsToErase.delete(m)}this.elementsToErase.delete(s.id)}}else if(!o&&!this.elementsToErase.has(s.id)&&pk(r,s,a,this.app.state.zoom.value)){let c=s.groupIds.at(-1);if(!this.groupsToErase.has(c)){let m=lk(this.app.scene.getNonDeletedElementsMap(),c);for(let p of m)this.elementsToErase.add(p.id);this.groupsToErase.add(c)}if(ck(s)){let m=mk(s);m&&this.elementsToErase.add(m)}dk(s)&&this.elementsToErase.add(s.containerId),this.elementsToErase.add(s.id)}return Array.from(this.elementsToErase)}endPath(){super.endPath(),super.clearTrails(),this.elementsToErase.clear(),this.groupsToErase.clear()}},pk=(e,t,o,n)=>{let r=e[1],i=ak(t)?15:t.strokeWidth/2,a=[Math.min(e[0][0],e[1][0])-i,Math.min(e[0][1],e[1][1])-i,Math.max(e[0][0],e[1][0])+i,Math.max(e[0][1],e[1][1])+i],s=WU(t,o),l=[s[0]-i,s[1]-i,s[2]+i,s[3]+i];if(!GU(a,l))return!1;if(QU(t)&&ZU(r,t,o))return!0;if(ak(t)){let m=$U(t),p=VU(t,m,o),d=Math.max(2.25,5/n);for(let h of p)if(sk(h,e)<=d)return!0;let u=qU(...m.map(([h,g])=>uk(t.x+h,t.y+g)));return!!JU(e[0],u)}let c=UU(t,o);if(KU(t)||XU(t)&&!t.polygon){let m=Math.max(t.strokeWidth,t.strokeWidth*2/n),p=YU(t,o);for(let d of p)if(sk(d,e)<=m)return!0;return!1}return ik(t,o,e,0,!0).length>0||!!c&&ik({...c,...HU(t,c,o)},o,e,0,!0).length>0};import{jsx as Xo,jsxs as gk}from"react/jsx-runtime";var eW=()=>gk("div",{"data-testid":"brave-measure-text-error",children:[Xo("p",{children:Xo(ro,{i18nKey:"errors.brave_measure_text_error.line1",bold:e=>Xo("span",{style:{fontWeight:600},children:e})})}),Xo("p",{children:Xo(ro,{i18nKey:"errors.brave_measure_text_error.line2",bold:e=>Xo("span",{style:{fontWeight:600},children:e})})}),Xo("p",{children:Xo(ro,{i18nKey:"errors.brave_measure_text_error.line3",link:e=>Xo("a",{href:"http://docs.excalidraw.com/docs/@orangecatai/adgen-canvas/faq#turning-off-aggresive-block-fingerprinting-in-brave-browser",children:e})})}),Xo("p",{children:Xo(ro,{i18nKey:"errors.brave_measure_text_error.line4",issueLink:e=>Xo("a",{href:"https://github.com/excalidraw/excalidraw/issues/new",children:e}),discordLink:e=>gk("a",{href:"https://discord.gg/UexuTaE",children:[e,"."]})})})]}),hk=eW;import sW from"clsx";import lW from"react";import{useLayoutEffect as tW,useRef as fk,useEffect as bk}from"react";import{unstable_batchedUpdates as oW}from"react-dom";import{KEYS as nW,queryFocusableElements as rW}from"@orangecatai/common";import iW from"clsx";import{jsx as aW}from"react/jsx-runtime";var xk=({children:e,left:t,top:o,onCloseRequest:n,fitInViewport:r=!1,offsetLeft:i=0,offsetTop:a=0,viewportWidth:s=window.innerWidth,viewportHeight:l=window.innerHeight,className:c})=>{let m=fk(null);bk(()=>{let d=m.current;if(!d)return;d.contains(document.activeElement)||d.focus();let u=h=>{if(h.key===nW.TAB){let g=rW(d),{activeElement:E}=document,w=g.findIndex(x=>x===E);E===d?(h.shiftKey?g[g.length-1]?.focus():g[0].focus(),h.preventDefault(),h.stopImmediatePropagation()):w===0&&h.shiftKey?(g[g.length-1]?.focus(),h.preventDefault(),h.stopImmediatePropagation()):w===g.length-1&&!h.shiftKey&&(g[0]?.focus(),h.preventDefault(),h.stopImmediatePropagation())}};return d.addEventListener("keydown",u),()=>d.removeEventListener("keydown",u)},[]);let p=fk(null);return tW(()=>{if(r&&m.current&&o!=null&&t!=null){let d=m.current,{width:u,height:h}=d.getBoundingClientRect();if(p.current?.top===o&&p.current?.left===t)return;p.current={top:o,left:t},u>=s?(d.style.width=`${s}px`,d.style.left="0px",d.style.overflowX="scroll"):t+u-i>s?d.style.left=`${s-u-10}px`:d.style.left=`${t}px`,h>=l?(d.style.height=`${l-20}px`,d.style.top="10px",d.style.overflowY="scroll"):o+h-a>l?d.style.top=`${l-h}px`:d.style.top=`${o}px`}},[o,t,r,s,l,i,a]),bk(()=>{if(n){let d=u=>{m.current?.contains(u.target)||oW(()=>n(u))};return document.addEventListener("pointerdown",d,!1),()=>document.removeEventListener("pointerdown",d,!1)}},[n]),aW("div",{className:iW("popover",c),ref:m,tabIndex:-1,children:e})};import{jsx as al,jsxs as cW}from"react/jsx-runtime";var Et="separator",Ek=lW.memo(({actionManager:e,items:t,top:o,left:n,onClose:r})=>{let i=Go(),a=Hr(),s=t.reduce((l,c)=>(c&&(c===Et||!c.predicate||c.predicate(a,i,e.app.props,e.app))&&l.push(c),l),[]);return al(xk,{onCloseRequest:()=>{r()},top:o,left:n,fitInViewport:!0,offsetLeft:i.offsetLeft,offsetTop:i.offsetTop,viewportWidth:i.width,viewportHeight:i.height,className:"context-menu-popover",children:al("ul",{className:"context-menu",onContextMenu:l=>l.preventDefault(),children:s.map((l,c)=>{if(l===Et)return!s[c-1]||s[c-1]===Et?null:al("hr",{className:"context-menu-item-separator"},c);let m=l.name,p="";return l.label&&(typeof l.label=="function"?p=f(l.label(a,i,e.app)):p=f(l.label)),al("li",{"data-testid":m,onClick:()=>{r(()=>{e.executeAction(l,"contextMenu")})},children:cW("button",{type:"button",className:sW("context-menu-item",{dangerous:m==="deleteSelectedElements",checkmark:l.checked?.(i)}),children:[al("div",{className:"context-menu-item__label",children:p}),al("kbd",{className:"context-menu-item__shortcut",children:m?Ke(m):""})]})},c)})})})});import{jsx as $0,jsxs as yk}from"react/jsx-runtime";var dW=({height:e,width:t,userToFollow:o,onDisconnect:n})=>$0("div",{className:"follow-mode",style:{width:t,height:e},children:yk("div",{className:"follow-mode__badge",children:[yk("div",{className:"follow-mode__badge__label",children:["Following"," ",$0("span",{className:"follow-mode__badge__username",title:o.username,children:o.username})]}),$0("button",{type:"button",onClick:n,className:"follow-mode__disconnect-btn",children:Fo})]})}),wk=dW;import Ia from"clsx";import xX from"react";import{CLASSES as EX,DEFAULT_SIDEBAR as sx,TOOL_TYPE as C4,arrayToMap as yX,capitalizeString as wX,isShallowEqual as bg}from"@orangecatai/common";import{mutateElement as vX}from"@orangecatai/element";import{showSelectedShapeActions as IX}from"@orangecatai/element";import{ShapeCache as TX}from"@orangecatai/element";import mW from"clsx";import{useState as pW,useEffect as uW}from"react";import{THEME as gW}from"@orangecatai/common";import{jsx as K0,jsxs as hW}from"react/jsx-runtime";var _u=({delay:e,theme:t})=>{let[o,n]=pW(!!e);return uW(()=>{if(!e)return;let r=setTimeout(()=>{n(!1)},e);return()=>clearTimeout(r)},[e]),o?null:hW("div",{className:mW("LoadingMessage",{"LoadingMessage--dark":t===gW.DARK}),children:[K0("div",{children:K0(Gt,{})}),K0("div",{className:"LoadingMessage-text",children:f("labels.loadingScene")})]})};import fW from"clsx";import{jsx as Ik,jsxs as xW}from"react/jsx-runtime";var bW="medium",vk={CHECKED:Wa,UNCHECKED:Fi},Tk=e=>xW("label",{className:fW("ToolIcon ToolIcon__lock",`ToolIcon_size_${bW}`,{"is-mobile":e.isMobile}),title:`${e.title} \u2014 Q`,children:[Ik("input",{className:"ToolIcon_type_checkbox",type:"checkbox",name:e.name,onChange:e.onChange,checked:e.checked,"aria-label":e.title,"data-testid":"toolbar-lock"}),Ik("div",{className:"ToolIcon__icon",children:e.checked?vk.CHECKED:vk.UNCHECKED})]});import{useState as Du,useEffect as Sk}from"react";import sl from"clsx";import{KEYS as X0,capitalizeString as wt}from"@orangecatai/common";import EW from"clsx";import{KEYS as Ck}from"@orangecatai/common";import{jsx as yW}from"react/jsx-runtime";var kk=e=>yW(ne,{className:EW("Shape",{fillable:!1,active:e.checked}),type:"radio",icon:Ja,name:"editor-current-shape",checked:e.checked,title:`${e.title} \u2014 H`,keyBindingLabel:e.isMobile?void 0:Ck.H.toLocaleUpperCase(),"aria-label":`${e.title} \u2014 H`,"aria-keyshortcuts":Ck.H,"data-testid":"toolbar-hand",onChange:()=>e.onChange?.()});import{Fragment as wW,jsx as yt,jsxs as Ru}from"react/jsx-runtime";var Z0=[{type:"rectangle",icon:Ya,title:wt(f("toolBar.rectangle"))},{type:"diamond",icon:Va,title:wt(f("toolBar.diamond"))},{type:"ellipse",icon:$a,title:wt(f("toolBar.ellipse"))}],j0=[{type:"selection",icon:Oi,title:wt(f("toolBar.selection"))},{type:"lasso",icon:Nr,title:wt(f("toolBar.lasso"))}],q0=[{type:"arrow",icon:am,title:wt(f("toolBar.arrow"))},{type:"line",icon:Ka,title:wt(f("toolBar.line"))}],Mk=({app:e,onHandToolToggle:t,setAppState:o})=>{let n=e.state.activeTool,[r,i]=Du(!1),[a,s]=Du("rectangle"),[l,c]=Du("arrow");Sk(()=>{(n.type==="rectangle"||n.type==="diamond"||n.type==="ellipse")&&s(n.type)},[n.type]),Sk(()=>{(n.type==="arrow"||n.type==="line")&&c(n.type)},[n.type]);let m=n.type==="frame",p=n.type==="laser",d=n.type==="embeddable",{TTDDialogTriggerTunnel:u}=Xe(),h=(M,N)=>{e.state.activeTool.type!==M&&ge("toolbar",M,"ui"),M==="selection"?e.state.activeTool.type==="selection"||e.setActiveTool({type:"selection"}):e.setActiveTool({type:M})},[g,E]=Du(0),w=36,x=4,y=7,v=y*w+(y-1)*x,I=w+x,k=g>=v+1*I,L=g>=v+2*I,S=g>=v+3*I,P=["text","frame","embeddable","laser","magicframe"].filter(M=>!(k&&M==="text"||L&&M==="image"||S&&M==="frame")).includes(n.type),T=P?n.type==="text"?_n:n.type==="image"?Xa:n.type==="frame"?Dn:n.type==="embeddable"?Za:n.type==="laser"?Rn:n.type==="magicframe"?Gi:Ql:Ql;return Ru("div",{className:"mobile-toolbar",ref:M=>{M&&E(M.getBoundingClientRect().width)},children:[yt(kk,{checked:sr(e.state),onChange:t,title:f("toolBar.hand"),isMobile:!0}),yt($s,{app:e,options:j0,activeTool:n,defaultOption:e.state.preferredSelectionTool.type,namePrefix:"selectionType",title:wt(f("toolBar.selection")),"data-testid":"toolbar-selection",onToolChange:M=>{(M==="selection"||M==="lasso")&&(e.setActiveTool({type:M}),o({preferredSelectionTool:{type:M,initialized:!0}}))},displayedOption:j0.find(M=>M.type===e.state.preferredSelectionTool.type)||j0[0]}),yt(ne,{className:sl({active:n.type==="freedraw"}),type:"radio",icon:Ln,checked:n.type==="freedraw",name:"editor-current-shape",title:`${wt(f("toolBar.freedraw"))}`,"aria-label":wt(f("toolBar.freedraw")),"data-testid":"toolbar-freedraw",onChange:()=>h("freedraw")}),yt(ne,{className:sl({active:n.type==="eraser"}),type:"radio",icon:sm,checked:n.type==="eraser",name:"editor-current-shape",title:`${wt(f("toolBar.eraser"))}`,"aria-label":wt(f("toolBar.eraser")),"data-testid":"toolbar-eraser",onChange:()=>h("eraser")}),yt($s,{app:e,options:Z0,activeTool:n,defaultOption:a,namePrefix:"shapeType",title:wt(f(a==="rectangle"?"toolBar.rectangle":a==="diamond"?"toolBar.diamond":a==="ellipse"?"toolBar.ellipse":"toolBar.rectangle")),"data-testid":"toolbar-rectangle",onToolChange:M=>{(M==="rectangle"||M==="diamond"||M==="ellipse")&&(s(M),e.setActiveTool({type:M}))},displayedOption:Z0.find(M=>M.type===a)||Z0[0]}),yt($s,{app:e,options:q0,activeTool:n,defaultOption:l,namePrefix:"linearElementType",title:wt(f(l==="arrow"?"toolBar.arrow":"toolBar.line")),"data-testid":"toolbar-arrow",fillable:!0,onToolChange:M=>{(M==="arrow"||M==="line")&&(c(M),e.setActiveTool({type:M}))},displayedOption:q0.find(M=>M.type===l)||q0[0]}),k&&yt(ne,{className:sl({active:n.type==="text"}),type:"radio",icon:_n,checked:n.type==="text",name:"editor-current-shape",title:`${wt(f("toolBar.text"))}`,"aria-label":wt(f("toolBar.text")),"data-testid":"toolbar-text",onChange:()=>h("text")}),L&&yt(ne,{className:sl({active:n.type==="image"}),type:"radio",icon:Xa,checked:n.type==="image",name:"editor-current-shape",title:`${wt(f("toolBar.image"))}`,"aria-label":wt(f("toolBar.image")),"data-testid":"toolbar-image",onChange:()=>h("image")}),S&&yt(ne,{className:sl({active:m}),type:"radio",icon:Dn,checked:m,name:"editor-current-shape",title:`${wt(f("toolBar.frame"))}`,"aria-label":wt(f("toolBar.frame")),"data-testid":"toolbar-frame",onChange:()=>h("frame")}),Ru(he,{open:r,children:[yt(he.Trigger,{className:sl("App-toolbar__extra-tools-trigger App-toolbar__extra-tools-trigger--mobile",{"App-toolbar__extra-tools-trigger--selected":P||r}),onToggle:()=>{i(!r),o({openMenu:null,openPopup:null})},title:f("toolBar.extraTools"),style:{width:w,height:w,display:"flex",alignItems:"center",justifyContent:"center"},children:T}),Ru(he.Content,{onClickOutside:()=>i(!1),onSelect:()=>i(!1),className:"App-toolbar__extra-tools-dropdown",align:"start",children:[!k&&yt(he.Item,{onSelect:()=>e.setActiveTool({type:"text"}),icon:_n,shortcut:X0.T.toLocaleUpperCase(),"data-testid":"toolbar-text",selected:n.type==="text",children:f("toolBar.text")}),!L&&yt(he.Item,{onSelect:()=>e.setActiveTool({type:"image"}),icon:Xa,"data-testid":"toolbar-image",selected:n.type==="image",children:f("toolBar.image")}),!S&&yt(he.Item,{onSelect:()=>e.setActiveTool({type:"frame"}),icon:Dn,shortcut:X0.F.toLocaleUpperCase(),"data-testid":"toolbar-frame",selected:m,children:f("toolBar.frame")}),yt(he.Item,{onSelect:()=>e.setActiveTool({type:"embeddable"}),icon:Za,"data-testid":"toolbar-embeddable",selected:d,children:f("toolBar.embeddable")}),yt(he.Item,{onSelect:()=>e.setActiveTool({type:"laser"}),icon:Rn,"data-testid":"toolbar-laser",selected:p,shortcut:X0.K.toLocaleUpperCase(),children:f("toolBar.laser")}),yt("div",{style:{margin:"6px 0",fontSize:14,fontWeight:600},children:"Generate"}),e.props.aiEnabled!==!1&&yt(u.Out,{}),yt(he.Item,{onSelect:()=>e.setOpenDialog({name:"ttd",tab:"mermaid"}),icon:es,"data-testid":"toolbar-embeddable",children:f("toolBar.mermaidToExcalidraw")}),e.props.aiEnabled!==!1&&e.plugins.diagramToCode&&yt(wW,{children:Ru(he.Item,{onSelect:()=>e.onMagicframeToolSelect(),icon:Gi,"data-testid":"toolbar-magicframe",children:[f("toolBar.magicframe"),yt(he.Item.Badge,{children:"AI"})]})})]})]})]})};import vW from"clsx";import{jsx as IW}from"react/jsx-runtime";var Nu=({children:e,side:t,className:o})=>IW("div",{className:vW("FixedSideContainer",`FixedSideContainer_side_${t}`,o),children:e});import TW from"clsx";import{jsx as Pk,jsxs as kW}from"react/jsx-runtime";var CW="medium",Bu=e=>e.penDetected?kW("label",{className:TW("ToolIcon ToolIcon__penMode",`ToolIcon_size_${CW}`,{"is-mobile":e.isMobile}),title:`${e.title}`,children:[Pk("input",{className:"ToolIcon_type_checkbox",type:"checkbox",name:e.name,onChange:e.onChange,checked:e.checked,"aria-label":e.title}),Pk("div",{className:"ToolIcon__icon",children:by})]}):null;import{Fragment as Ak,jsx as $n,jsxs as fa}from"react/jsx-runtime";var Lk=({appState:e,elements:t,actionManager:o,setAppState:n,onHandToolToggle:r,renderTopLeftUI:i,renderTopRightUI:a,renderSidebars:s,renderWelcomeScreen:l,UIOptions:c,app:m,onPenModeToggle:p})=>{let{WelcomeScreenCenterTunnel:d,MainMenuTunnel:u,DefaultSidebarTriggerTunnel:h}=Xe(),g=()=>{if(e.openDialog?.name==="elementLinkSelector")return null;let w=fa("div",{className:"excalidraw-ui-top-right",children:[a?.(!0,e)??(!e.viewModeEnabled&&fa(Ak,{children:[$n(Bu,{checked:e.penMode,onChange:()=>p(null),title:f("toolBar.penMode"),isMobile:!0,penDetected:e.penDetected}),$n(h.Out,{})]})),e.viewModeEnabled&&$n(UC,{actionManager:o})]}),x=fa("div",{className:"excalidraw-ui-top-left",children:[i?.(!0,e),$n(u.Out,{})]});return fa("div",{className:"App-toolbar-content",style:{display:"flex",flexDirection:"row",justifyContent:"space-between"},children:[x,w]})},E=()=>$n(Mk,{app:m,onHandToolToggle:r,setAppState:n});return fa(Ak,{children:[s(),$n("div",{className:"App-welcome-screen",children:l&&$n(d.Out,{})}),!e.viewModeEnabled&&fa("div",{className:"App-bottom-bar",style:{marginBottom:Ko+Sr},children:[$n(BC,{appState:e,elementsMap:m.scene.getNonDeletedElementsMap(),renderAction:o.renderAction,app:m,setAppState:n}),fa(ut,{className:"App-toolbar",children:[!e.viewModeEnabled&&e.openDialog?.name!=="elementLinkSelector"&&E(),e.scrolledOutside&&!e.openMenu&&!e.openSidebar&&$n("button",{type:"button",className:"scroll-back-to-content",onClick:()=>{n(w=>({...Ri(t,w)}))},children:f("buttons.scrollBackToContent")})]})]}),$n(Nu,{side:"top",className:"App-top-bar",children:g()})]})};import SW,{useLayoutEffect as MW,useRef as PW,useState as AW}from"react";import{jsx as id,jsxs as LW}from"react/jsx-runtime";var _k=e=>{let t=PW(null),[o,n]=AW(null);return MW(()=>{if(!e.spreadsheet)return;let r=U2(e.chartType,e.spreadsheet,0,0);n(r);let i,a=t.current;return(async()=>(i=await Fa(r,{exportBackground:!1,viewBackgroundColor:"#fff"},null,{skipInliningFonts:!0}),i.querySelector(".style-fonts")?.remove(),a.replaceChildren(),a.appendChild(i),e.selected&&a.parentNode.focus()))(),()=>{a.replaceChildren()}},[e.spreadsheet,e.chartType,e.selected]),id("button",{type:"button",className:"ChartPreview",onClick:()=>{o&&e.onClick(e.chartType,o)},children:id("div",{ref:t})})},Dk=({setAppState:e,appState:t,onClose:o})=>{let{onInsertElements:n}=Qe(),r=SW.useCallback(()=>{o&&o()},[o]),i=(a,s)=>{n(s),ge("paste","chart",a),e({currentChartType:a,pasteDialog:{shown:!1,data:null}})};return id(ht,{size:"small",onCloseRequest:r,title:f("labels.pasteCharts"),className:"PasteChartDialog",autofocus:!1,children:LW("div",{className:"container",children:[id(_k,{chartType:"bar",spreadsheet:t.pasteDialog.data,selected:t.currentChartType==="bar",onClick:i}),id(_k,{chartType:"line",spreadsheet:t.pasteDialog.data,selected:t.currentChartType==="line",onClick:i})]})})};import{Fragment as _W,jsx as Rk,jsxs as DW}from"react/jsx-runtime";var ad=({heading:e,children:t,...o})=>{let{id:n}=qe(),r=Rk("h2",{className:"visually-hidden",id:`${n}-${e}-title`,children:f(`headings.${e}`)});return Rk("section",{...o,"aria-labelledby":`${n}-${e}-title`,children:typeof t=="function"?t(r):DW(_W,{children:[r,t]})})};import{Popover as Fu}from"radix-ui";import Nk from"clsx";import Ou,{useLayoutEffect as RW}from"react";import{supportsResizeObserver as NW,isShallowEqual as BW}from"@orangecatai/common";import{Fragment as GW,jsx as Kn,jsxs as zu}from"react/jsx-runtime";var FW=4,OW=8,zW=({shouldWrap:e,children:t,username:o})=>e?Kn(Vt,{label:o||"Unknown user",children:t}):Kn(GW,{children:t}),J0=({actionManager:e,collaborator:t,socketId:o,withName:n=!1,shouldWrapWithTooltip:r=!1,isBeingFollowed:i})=>{let a={socketId:o,collaborator:t,withName:n,isBeingFollowed:i},s=e.renderAction("goToCollaborator",a);return Kn(zW,{username:t.username,shouldWrap:r,children:s},o)},HW=["avatarUrl","id","socketId","username","isInCall","isSpeaking","isMuted"],Hu=Ou.memo(({className:e,mobile:t,collaborators:o,userToFollow:n})=>{let r=nt(),i=new Map;o.forEach((g,E)=>{let w=g.id||E;i.set(w,{...g,socketId:E})});let a=Array.from(i.values()).filter(g=>g.username?.trim()),[s,l]=Ou.useState(""),c=a.filter(g=>g.username?.toLowerCase().includes(s)),m=Ou.useRef(null);RW(()=>{if(m.current){let g=w=>{let x=Math.max(1,Math.min(8,Math.floor(w/38)));d(x)};if(g(m.current.clientWidth),!NW)return;let E=new ResizeObserver(w=>{for(let x of w){let{width:y}=x.contentRect;g(y)}});return E.observe(m.current),()=>{E.disconnect()}}},[]);let[p,d]=Ou.useState(FW),h=a.slice(0,p-1).map(g=>J0({actionManager:r,collaborator:g,socketId:g.socketId,shouldWrapWithTooltip:!0,isBeingFollowed:g.socketId===n}));return t?Kn("div",{className:Nk("UserList UserList_mobile",e),children:a.map(g=>J0({actionManager:r,collaborator:g,socketId:g.socketId,shouldWrapWithTooltip:!0,isBeingFollowed:g.socketId===n}))}):Kn("div",{className:"UserList__wrapper",ref:m,children:zu("div",{className:Nk("UserList",e),style:{"--max-avatars":p},children:[h,a.length>p-1&&zu(Fu.Root,{children:[zu(Fu.Trigger,{className:"UserList__more",children:["+",a.length-p+1]}),Kn(Fu.Content,{style:{zIndex:2,width:"15rem",textAlign:"left"},align:"end",sideOffset:10,children:zu(ut,{padding:2,children:[a.length>=OW&&Kn(Dm,{placeholder:f("quickSearch.placeholder"),onChange:l}),Kn(Rm,{className:"dropdown-menu UserList__collaborators",placeholder:f("userList.empty"),children:c.length>0?[Kn("div",{className:"hint",children:f("userList.hint.text")}),c.map(g=>J0({actionManager:r,collaborator:g,socketId:g.socketId,withName:!0,isBeingFollowed:g.socketId===n}))]:[]}),Kn(Fu.Arrow,{width:20,height:10,style:{fill:"var(--popup-bg-color)",filter:"drop-shadow(rgba(0, 0, 0, 0.05) 0px 3px 2px)"}})]})})]})]})})},(e,t)=>{if(e.collaborators.size!==t.collaborators.size||e.mobile!==t.mobile||e.className!==t.className||e.userToFollow!==t.userToFollow)return!1;let o=t.collaborators.keys();for(let[n,r]of e.collaborators){let i=t.collaborators.get(n);if(!i||n!==o.next().value||!BW(r,i,HW))return!1}return!0});import n1 from"clsx";import{useState as qW,useRef as Fk,useEffect as JW,useCallback as QW}from"react";import{useCallback as xo,useEffect as VW,useRef as ld,useState as e1}from"react";var Q0=({h:e,s:t,v:o,a:n})=>{e=e/360,t=t/100,o=o/100;let r=0,i=0,a=0,s=Math.floor(e*6),l=e*6-s,c=o*(1-t),m=o*(1-l*t),p=o*(1-(1-l)*t);switch(s%6){case 0:r=o,i=p,a=c;break;case 1:r=m,i=o,a=c;break;case 2:r=c,i=o,a=p;break;case 3:r=c,i=m,a=o;break;case 4:r=p,i=c,a=o;break;case 5:r=o,i=c,a=m;break}return{r:Math.round(r*255),g:Math.round(i*255),b:Math.round(a*255),a:n}},UW=({r:e,g:t,b:o,a:n})=>{e/=255,t/=255,o/=255;let r=Math.max(e,t,o),i=Math.min(e,t,o),a=r-i,s=0,l=r===0?0:a/r*100,c=r*100;if(a!==0)switch(r){case e:s=((t-o)/a+(t<o?6:0))*60;break;case t:s=((o-e)/a+2)*60;break;case o:s=((e-t)/a+4)*60;break}return{h:s,s:l,v:c,a:n}},WW=({r:e,g:t,b:o,a:n})=>{let r=a=>a.toString(16).padStart(2,"0"),i=`#${r(e)}${r(t)}${r(o)}`;return n<1?`${i}${r(Math.round(n*255))}`:i},YW=e=>{let t=e.replace(/^#/,"");t.length===3?t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]:t.length===4&&(t=t[0]+t[0]+t[1]+t[1]+t[2]+t[2]+t[3]+t[3]);let o=parseInt(t.slice(0,2),16),n=parseInt(t.slice(2,4),16),r=parseInt(t.slice(4,6),16),i=t.length===8?parseInt(t.slice(6,8),16)/255:1;return{r:isNaN(o)?0:o,g:isNaN(n)?0:n,b:isNaN(r)?0:r,a:isNaN(i)?1:i}},Gu=e=>WW(Q0(e)),sd=e=>UW(YW(e));var ll=(e,t,o)=>Math.max(t,Math.min(o,e));import{jsx as Pt,jsxs as cl}from"react/jsx-runtime";var $W=["transparent","#000000","#ffffff","#00e639","#a855f4","#d4b0ff"],t1=(e,t)=>{let o=ld(null),n=ld(!1),r=ld(null),i=ld(null),a=xo((p,d)=>{if(!o.current||!n.current)return;let u=o.current.getBoundingClientRect();e(p,d,u)},[e]),s=xo(()=>{n.current=!1,t?.(),r.current&&(window.removeEventListener("mousemove",r.current),r.current=null),i.current&&(window.removeEventListener("touchmove",i.current),i.current=null),window.removeEventListener("mouseup",s),window.removeEventListener("touchend",s)},[t]),l=xo(p=>a(p.clientX,p.clientY),[a]),c=xo(p=>{p.preventDefault(),a(p.touches[0].clientX,p.touches[0].clientY)},[a]),m=xo(p=>{p.preventDefault(),p.stopPropagation(),n.current=!0;let d="touches"in p?p.touches[0].clientX:p.clientX,u="touches"in p?p.touches[0].clientY:p.clientY;if(o.current){let h=o.current.getBoundingClientRect();e(d,u,h)}r.current=l,i.current=c,window.addEventListener("mousemove",l),window.addEventListener("mouseup",s),window.addEventListener("touchmove",c,{passive:!1}),window.addEventListener("touchend",s)},[e,l,c,s]);return{ref:o,handleDown:m}},KW=({hsva:e,onChange:t})=>{let{ref:o,handleDown:n}=t1((s,l,c)=>{let m=ll(s-c.left,0,c.width),p=ll(l-c.top,0,c.height),d=m/c.width*100,u=100-p/c.height*100;t(d,u)}),r=`hsl(${e.h}, 100%, 50%)`,i=`${e.s}%`,a=`${100-e.v}%`;return cl("div",{ref:o,className:"adv-cp__saturation",style:{backgroundColor:r},onMouseDown:n,onTouchStart:n,children:[Pt("div",{className:"adv-cp__saturation-white"}),Pt("div",{className:"adv-cp__saturation-black"}),Pt("div",{className:"adv-cp__handle",style:{left:i,top:a}})]})},XW=({hue:e,onChange:t})=>{let{ref:o,handleDown:n}=t1((r,i,a)=>{let s=ll(r-a.left,0,a.width);t(s/a.width*360)});return Pt("div",{ref:o,className:"adv-cp__slider adv-cp__hue-slider",onMouseDown:n,onTouchStart:n,children:Pt("div",{className:"adv-cp__slider-handle",style:{left:`${e/360*100}%`}})})},ZW=({hsva:e,onChange:t})=>{let{r:o,g:n,b:r}=Q0({...e,a:1}),i=`rgba(${o}, ${n}, ${r}, 1)`,{ref:a,handleDown:s}=t1((l,c,m)=>{let p=ll(l-m.left,0,m.width);t(p/m.width)});return cl("div",{ref:a,className:"adv-cp__slider adv-cp__alpha-slider",onMouseDown:s,onTouchStart:s,children:[Pt("div",{className:"adv-cp__alpha-checker"}),Pt("div",{className:"adv-cp__alpha-gradient",style:{background:`linear-gradient(to right, transparent 0%, ${i} 100%)`}}),Pt("div",{className:"adv-cp__slider-handle",style:{left:`${e.a*100}%`}})]})},jW=({activeColor:e,onChange:t})=>Pt("div",{className:"adv-cp__presets",children:$W.map(o=>Pt("button",{type:"button",className:`adv-cp__preset-btn${o===e?" active":""}${o==="transparent"?" is-transparent":""}`,style:o!=="transparent"?{backgroundColor:o}:void 0,title:o,onClick:()=>t(o),children:o==="transparent"&&Pt("div",{className:"adv-cp__preset-slash"})},o))}),Bk=({color:e,onChange:t,showAlpha:o=!0})=>{let[n,r]=e1(()=>!e||e==="transparent"?{h:0,s:0,v:100,a:e==="transparent"?0:1}:sd(e)),[i,a]=e1(()=>e==="transparent"?"000000":(e||"#ffffff").replace(/^#/,"").toUpperCase()),[s,l]=e1(()=>Math.round(n.a*100).toString()),c=ld(e);VW(()=>{if(e!==c.current)if(c.current=e,!e||e==="transparent")r({h:0,s:0,v:100,a:0}),a("000000"),l("0");else{let y=sd(e);r(y),a(e.replace(/^#/,"").substring(0,6).toUpperCase()),l(Math.round(y.a*100).toString())}},[e]);let m=xo(y=>{r(y);let v=Gu(y);c.current=v,a(v.replace(/^#/,"").substring(0,6).toUpperCase()),l(Math.round(y.a*100).toString()),y.a===0?t("transparent"):t(v)},[t]),p=xo((y,v)=>{m({...n,s:y,v})},[n,m]),d=xo(y=>{m({...n,h:y})},[n,m]),u=xo(y=>{m({...n,a:y})},[n,m]),h=xo(y=>{if(y==="transparent")m({h:0,s:0,v:100,a:0});else{let v=sd(y);v.a=1,m(v)}},[m]),g=xo(()=>{let y=i.trim().replace(/^#/,"");if(/^[0-9a-fA-F]{3}$|^[0-9a-fA-F]{6}$|^[0-9a-fA-F]{8}$/.test(y)){let v=sd(`#${y}`);m(v)}else{let v=Gu(n);a(v.replace(/^#/,"").substring(0,6).toUpperCase())}},[i,n,m]),E=xo(y=>{y.key==="Enter"&&g(),y.stopPropagation()},[g]),w=xo(()=>{let y=parseInt(s,10);if(isNaN(y))l(Math.round(n.a*100).toString());else{let v=ll(y,0,100)/100;m({...n,a:v})}},[s,n,m]),x=xo(y=>{y.key==="Enter"&&w(),y.stopPropagation()},[w]);return cl("div",{className:"adv-cp",children:[Pt(KW,{hsva:n,onChange:p}),Pt(XW,{hue:n.h,onChange:d}),o&&Pt(ZW,{hsva:n,onChange:u}),Pt(jW,{activeColor:n.a===0?"transparent":Gu({...n,a:1}).toLowerCase(),onChange:h}),cl("div",{className:"adv-cp__inputs",children:[cl("div",{className:"adv-cp__hex-input",children:[Pt("span",{className:"adv-cp__hash",children:"#"}),Pt("input",{type:"text",style:{border:0,padding:0,margin:0,outline:"none"},spellCheck:!1,value:i,onChange:y=>a(y.target.value.toUpperCase()),onBlur:g,onKeyDown:E,maxLength:8,"aria-label":"Hex color"})]}),o&&cl("div",{className:"adv-cp__alpha-input",children:[Pt("input",{type:"text",style:{border:0,padding:0,margin:0,outline:"none"},value:s,onChange:y=>l(y.target.value),onBlur:w,onKeyDown:x,maxLength:3,"aria-label":"Opacity percentage"}),Pt("span",{className:"adv-cp__percent",children:"%"})]})]})]})};import{jsx as mi,jsxs as o1}from"react/jsx-runtime";var Ok=({actionManager:e,appState:t})=>{let[o,n]=qW(!1),r=Fk(null),i=Fk(null);JW(()=>{if(!o)return;let c=m=>{r.current&&!r.current.contains(m.target)&&i.current&&!i.current.contains(m.target)&&n(!1)};return document.addEventListener("mousedown",c),()=>document.removeEventListener("mousedown",c)},[o]);let a=t.viewBackgroundColor||"#ffffff",s=a==="transparent",l=QW(c=>{e.executeAction(e.actions.changeViewBackgroundColor,"ui",{viewBackgroundColor:c})},[e]);return o1("div",{className:"canvas-bg-swatch-wrapper",children:[mi(Vt,{label:f("labels.canvasBackground"),children:mi("button",{ref:i,type:"button",className:"canvas-bg-swatch",onClick:()=>n(c=>!c),title:f("labels.canvasBackground"),children:mi("div",{className:"canvas-bg-swatch__color",style:{backgroundColor:s?void 0:a},children:s&&mi("div",{className:"canvas-bg-swatch__transparent"})})})}),o&&o1("div",{ref:r,className:"canvas-bg-swatch__popover",children:[o1("div",{className:"canvas-bg-swatch__popover-header",children:[mi("span",{children:f("labels.canvasBackground")}),mi("button",{type:"button",className:"canvas-bg-swatch__close",onClick:()=>n(!1),children:"\u2715"})]}),mi("div",{className:"canvas-bg-swatch__picker-content",children:mi(Bk,{color:a,onChange:l,showAlpha:!0})})]})]})};import{jsx as eY}from"react/jsx-runtime";var zk=e=>eY("button",{className:"help-icon",onClick:e.onClick,type:"button",title:`${f("helpDialog.title")} \u2014 ?`,"aria-label":f("helpDialog.title"),children:ja});import{jsx as Zo,jsxs as cd}from"react/jsx-runtime";var Hk=({appState:e,actionManager:t,showExitZenModeBtn:o,renderWelcomeScreen:n})=>{let{FooterCenterTunnel:r,WelcomeScreenHelpHintTunnel:i}=Xe();return cd("footer",{role:"contentinfo",className:"layer-ui__wrapper__footer App-menu App-menu_bottom",children:[Zo("div",{className:n1("layer-ui__wrapper__footer-left zen-mode-transition",{"layer-ui__wrapper__footer-left--transition-left":e.zenModeEnabled}),children:Zo(Dt.Col,{gap:2,children:Zo(ad,{heading:"canvasActions",children:cd(Dt.Col,{gap:1,className:"footer-canvas-actions",children:[cd(Dt.Row,{align:"center",gap:1,children:[Zo(OC,{renderAction:t.renderAction}),!e.viewModeEnabled&&Zo(Ok,{actionManager:t,appState:e})]}),cd(Dt.Row,{align:"center",gap:1,className:"footer-canvas-actions-row",children:[Zo(zC,{renderAction:t.renderAction,zoom:e.zoom}),!e.viewModeEnabled&&Zo(HC,{renderAction:t.renderAction,className:n1("zen-mode-transition",{"layer-ui__wrapper__footer-left--transition-bottom":e.zenModeEnabled})})]})]})})})}),Zo(r.Out,{}),Zo("div",{className:n1("layer-ui__wrapper__footer-right zen-mode-transition",{"transition-right":e.zenModeEnabled}),children:cd("div",{style:{position:"relative"},children:[n&&Zo(i.Out,{}),Zo(zk,{onClick:()=>t.executeAction(ji)})]})}),Zo(GC,{actionManager:t,showExitZenModeBtn:o})]})},Gk=Hk;Hk.displayName="Footer";import pY from"clsx";import{useEffect as Xk,useLayoutEffect as Zk,useRef as p1,useState as uY,forwardRef as jk,useImperativeHandle as gY,useCallback as Vk}from"react";import{CLASSES as hY,EVENT as $k,isDevEnv as fY,KEYS as bY,updateObject as xY}from"@orangecatai/common";import oY from"clsx";import{useContext as nY}from"react";import tY from"react";var Uu=tY.createContext({});import{jsx as r1,jsxs as Uk}from"react/jsx-runtime";var i1=({children:e,className:t})=>{let o=we(),n=nY(Uu),r=!!(o.canFitSidebar&&n.shouldRenderDockButton);return Uk("div",{className:oY("sidebar__header",t),"data-testid":"sidebar-header",children:[e,Uk("div",{className:"sidebar__header__buttons",children:[r&&r1(Vt,{label:f("labels.sidebarLock"),children:r1(io,{onSelect:()=>n.onDock?.(!n.docked),selected:!!n.docked,className:"sidebar__dock","data-testid":"sidebar-dock","aria-label":f("labels.sidebarLock"),children:py})}),r1(io,{"data-testid":"sidebar-close",className:"sidebar__close",onSelect:n.onCloseRequest,"aria-label":f("buttons.close"),children:Fo})]})]})};i1.displayName="SidebarHeader";import{Tabs as rY}from"radix-ui";import{jsx as Wk}from"react/jsx-runtime";var a1=({children:e,tab:t,onSelect:o,...n})=>Wk(rY.Trigger,{value:t,asChild:!0,onSelect:o,children:Wk("button",{type:"button",className:"excalidraw-button sidebar-tab-trigger",...n,children:e})});a1.displayName="SidebarTabTrigger";import{Tabs as iY}from"radix-ui";import{jsx as aY}from"react/jsx-runtime";var s1=({children:e,...t})=>aY(iY.List,{className:"sidebar-triggers",...t,children:e});s1.displayName="SidebarTabTriggers";import sY from"clsx";import{jsx as l1,jsxs as Yk}from"react/jsx-runtime";var c1=({name:e,tab:t,icon:o,title:n,children:r,onToggle:i,className:a,style:s})=>{let l=ve(),c=ye();return Yk("label",{title:n,className:"sidebar-trigger__label-element",children:[l1("input",{className:"ToolIcon_type_checkbox",type:"checkbox",onChange:m=>{document.querySelector(".layer-ui__wrapper")?.classList.remove("animate");let p=m.target.checked;l({openSidebar:p?{name:e,tab:t}:null,openMenu:null,openPopup:null}),i?.(p)},checked:c.openSidebar?.name===e,"aria-label":n,"aria-keyshortcuts":"0"}),Yk("div",{className:sY("sidebar-trigger",a),style:s,children:[o&&l1("div",{children:o}),r&&l1("div",{className:"sidebar-trigger__label",children:r})]})]})};c1.displayName="SidebarTrigger";import{Tabs as lY}from"radix-ui";import{jsx as cY}from"react/jsx-runtime";var d1=({children:e,...t})=>{let o=ye(),n=ve();if(!o.openSidebar)return null;let{name:r}=o.openSidebar;return cY(lY.Root,{className:"sidebar-tabs-root",value:o.openSidebar.tab,onValueChange:i=>n(a=>({...a,openSidebar:{...a.openSidebar,name:r,tab:i}})),...t,children:e})};d1.displayName="SidebarTabs";import{Tabs as dY}from"radix-ui";import{jsx as mY}from"react/jsx-runtime";var m1=({tab:e,children:t,...o})=>mY(dY.Content,{...o,value:e,"data-testid":e,children:t});m1.displayName="SidebarTab";import{jsx as Kk}from"react/jsx-runtime";import{createElement as EY}from"react";var dd=Ce(!1),qk=jk(({name:e,children:t,onDock:o,docked:n,className:r,...i},a)=>{fY()&&o&&n==null&&console.warn("Sidebar: `docked` must be set when `onDock` is supplied for the sidebar to be user-dockable. To hide this message, either pass `docked` or remove `onDock`");let s=ve(),l=Pn(dd);Zk(()=>(l(!!n),()=>{l(!1)}),[l,n]);let c=p1({});c.current.onCloseRequest=()=>{s({openSidebar:null})},c.current.onDock=u=>o?.(u),c.current=xY(c.current,{docked:n,shouldRenderDockButton:!!o&&n!=null});let m=p1(null);gY(a,()=>m.current);let p=we(),d=Vk(()=>{document.querySelector(".Dialog")||s({openSidebar:null})},[s]);return cs(m,Vk(u=>{u.target.closest(".sidebar-trigger")||(!n||!p.canFitSidebar)&&d()},[d,n,p.canFitSidebar])),Xk(()=>{let u=h=>{h.key===bY.ESCAPE&&(!n||!p.canFitSidebar)&&d()};return document.addEventListener($k.KEYDOWN,u),()=>{document.removeEventListener($k.KEYDOWN,u)}},[d,n,p.canFitSidebar]),Kk(ut,{...i,className:pY(hY.SIDEBAR,{"sidebar--docked":n},r),ref:m,children:Kk(Uu.Provider,{value:c.current,children:t})})});qk.displayName="SidebarInner";var jo=Object.assign(jk((e,t)=>{let o=ye()??{openSidebar:null},{onStateChange:n}=e,r=p1(o.openSidebar);Xk(()=>{(!o.openSidebar&&r?.current?.name===e.name||o.openSidebar?.name===e.name&&r?.current?.name!==e.name||r.current?.name===e.name)&&o.openSidebar!==r.current&&n?.(o.openSidebar?.name!==e.name?null:o.openSidebar),r.current=o.openSidebar},[o.openSidebar,n,e.name]);let[i,a]=uY(!1);return Zk(()=>(a(!0),()=>a(!1)),[]),i&&o.openSidebar?.name===e.name?EY(qk,{...e,ref:t,key:e.name}):null}),{Header:i1,TabTriggers:s1,TabTrigger:a1,Tabs:d1,Tab:m1,Trigger:c1});jo.displayName="Sidebar";import{composeEventHandlers as SY}from"@orangecatai/common";import{useLayoutEffect as yY,useRef as wY}from"react";import{jsx as vY}from"react/jsx-runtime";var Mr=(e,t)=>{let o=Ce(0),n=r=>{let{tunnelsJotai:{useAtom:i}}=Xe(),[,a]=i(o),s=wY({preferHost:!1,counter:0});return yY(()=>{let l=s.current;return a(c=>{let m=c+1;return l.counter=m,m}),()=>{a(c=>{let m=c-1;return l.counter=m,m||(l.preferHost=!1),m})}},[a]),r.__fallback||(s.current.preferHost=!0),!s.current.counter&&r.__fallback&&s.current.preferHost||s.current.counter>1&&r.__fallback?null:vY(t,{...r})};return n.displayName=e,n};var b1={};NE(b1,{ChangeCanvasBackground:()=>mS,ClearCanvas:()=>cS,CommandPalette:()=>aS,Export:()=>pS,Help:()=>lS,LiveCollaborationTrigger:()=>gS,LoadScene:()=>nS,Preferences:()=>ui,PreferencesToggleGridModeItem:()=>h1,PreferencesToggleZenModeItem:()=>f1,SaveAsImage:()=>iS,SaveToActiveFile:()=>rS,SearchMenu:()=>sS,Socials:()=>uS,ToggleTheme:()=>dS});import kY from"clsx";import{THEME as pi}from"@orangecatai/common";var u1=Ce({active:!1});async function Jk({title:e,description:t,actionLabel:o,color:n}){return new Promise(r=>{xt.set(u1,{active:!0,onConfirm:()=>r(!0),onClose:()=>r(!1),onReject:()=>r(!1),title:e,description:t,actionLabel:o,color:n})})}import IY from"clsx";import{jsx as Qk,jsxs as TY}from"react/jsx-runtime";var Wu=function({onChange:e,value:t,choices:o,name:n}){return Qk("div",{className:"RadioGroup",children:o.map(r=>TY("div",{className:IY("RadioGroup__choice",{active:r.value===t}),title:r.ariaLabel,children:[Qk("input",{name:n,type:"radio",checked:r.value===t,onChange:()=>e(r.value),"aria-label":r.ariaLabel}),r.label]},String(r.value)))})};import{Fragment as CY,jsx as g1,jsxs as eS}from"react/jsx-runtime";var tS=({value:e,shortcut:t,onChange:o,choices:n,children:r,name:i})=>{let a=we();return eS(CY,{children:[eS("div",{className:"dropdown-menu-item-base dropdown-menu-item-bare",children:[g1("label",{className:"dropdown-menu-item__text",children:r}),g1(Wu,{name:i,value:e,onChange:o,choices:n})]}),t&&a.formFactor!=="phone"&&g1("div",{className:"dropdown-menu-item__shortcut dropdown-menu-item__shortcut--orphaned",children:t})]})};tS.displayName="DropdownMenuItemContentRadio";var oS=tS;import{Fragment as ES,jsx as Be,jsxs as md}from"react/jsx-runtime";var nS=()=>{let{t:e}=Ge(),t=nt(),o=Hr();return t.isActionEnabled(Cs)?Be(Qt,{icon:qa,onSelect:async()=>{(!o.length||await Jk({title:e("overwriteConfirm.modal.loadFromFile.title"),actionLabel:e("overwriteConfirm.modal.loadFromFile.button"),color:"warning",description:Be(ro,{i18nKey:"overwriteConfirm.modal.loadFromFile.description",bold:r=>Be("strong",{children:r}),br:()=>Be("br",{})})}))&&t.executeAction(Cs)},"data-testid":"load-button",shortcut:Ke("loadScene"),"aria-label":e("buttons.load"),children:e("buttons.load")}):null};nS.displayName="LoadScene";var rS=()=>{let{t:e}=Ge(),t=nt();return t.isActionEnabled(Zi)?Be(Qt,{shortcut:Ke("saveScene"),"data-testid":"save-button",onSelect:()=>t.executeAction(Zi),icon:Ty,"aria-label":`${e("buttons.save")}`,children:`${e("buttons.save")}`}):null};rS.displayName="SaveToActiveFile";var iS=()=>{let e=ve(),{t}=Ge();return Be(Qt,{icon:mm,"data-testid":"image-export-button",onSelect:()=>e({openDialog:{name:"imageExport"}}),shortcut:Ke("imageExport"),"aria-label":t("buttons.exportImage"),children:t("buttons.exportImage")})};iS.displayName="SaveAsImage";var aS=e=>{let t=ve(),{t:o}=Ge();return Be(Qt,{icon:ec,"data-testid":"command-palette-button",onSelect:()=>{ge("command_palette","open","menu"),t({openDialog:{name:"commandPalette"}})},shortcut:Ke("commandPalette"),"aria-label":o("commandPalette.title"),className:e?.className,children:o("commandPalette.title")})};aS.displayName="CommandPalette";var sS=e=>{let{t}=Ge(),o=nt();return Be(Qt,{icon:Co,"data-testid":"search-menu-button",onSelect:()=>{o.executeAction(Uc)},shortcut:Ke("searchMenu"),"aria-label":t("search.title"),className:e?.className,children:t("search.title")})};sS.displayName="SearchMenu";var lS=()=>{let{t:e}=Ge(),t=nt();return Be(Qt,{"data-testid":"help-menu-item",icon:ja,onSelect:()=>t.executeAction(ji),shortcut:"?","aria-label":e("helpDialog.title"),children:e("helpDialog.title")})};lS.displayName="Help";var cS=()=>{let{t:e}=Ge(),t=Pn(ta);return nt().isActionEnabled(gr)?Be(Qt,{icon:Ht,onSelect:()=>t("clearCanvas"),"data-testid":"clear-canvas-button","aria-label":e("buttons.clearReset"),children:e("buttons.clearReset")}):null};cS.displayName="ClearCanvas";var dS=e=>{let{t}=Ge(),o=ye(),n=nt(),r=Ke("toggleTheme");return n.isActionEnabled(Vi)?e?.allowSystemTheme?Be(oS,{name:"theme",value:e.theme,onChange:i=>e.onSelect(i),choices:[{value:pi.LIGHT,label:jl,ariaLabel:`${t("buttons.lightMode")} - ${r}`},{value:pi.DARK,label:Zl,ariaLabel:`${t("buttons.darkMode")} - ${r}`},{value:"system",label:Uw,ariaLabel:t("buttons.systemMode")}],children:t("labels.theme")}):Be(Qt,{onSelect:i=>{if(i.preventDefault(),e?.onSelect)e.onSelect(o.theme===pi.DARK?pi.LIGHT:pi.DARK);else return n.executeAction(Vi)},icon:o.theme===pi.DARK?jl:Zl,"data-testid":"toggle-dark-mode",shortcut:r,"aria-label":o.theme===pi.DARK?t("buttons.lightMode"):t("buttons.darkMode"),children:o.theme===pi.DARK?t("buttons.lightMode"):t("buttons.darkMode")}):null};dS.displayName="ToggleTheme";var mS=()=>{let{t:e}=Ge(),t=ye(),o=nt(),n=Nn();return t.viewModeEnabled||!n.UIOptions.canvasActions.changeViewBackgroundColor?null:md("div",{style:{marginTop:"0.75rem"},children:[Be("div",{"data-testid":"canvas-background-label",style:{fontSize:"0.875rem",marginBottom:"0.25rem",marginLeft:"0.5rem"},children:e("labels.canvasBackground")}),Be("div",{style:{padding:"0 0.625rem"},children:o.renderAction("changeViewBackgroundColor")})]})};mS.displayName="ChangeCanvasBackground";var pS=()=>{let{t:e}=Ge(),t=ve();return Be(Qt,{icon:zi,onSelect:()=>{t({openDialog:{name:"jsonExport"}})},"data-testid":"json-export-button","aria-label":e("buttons.export"),children:e("buttons.export")})};pS.displayName="Export";var uS=()=>{let{t:e}=Ge();return md(ES,{children:[Be(Ys,{icon:lm,href:"https://github.com/excalidraw/excalidraw","aria-label":"GitHub",children:"GitHub"}),Be(Ys,{icon:Iy,href:"https://x.com/excalidraw","aria-label":"X",children:e("labels.followUs")}),Be(Ys,{icon:vy,href:"https://discord.gg/UexuTaE","aria-label":"Discord",children:e("labels.discordChat")})]})};uS.displayName="Socials";var gS=({onSelect:e,isCollaborating:t})=>{let{t:o}=Ge();return Be(Qt,{"data-testid":"collab-button",icon:pm,className:kY({"active-collab":t}),onSelect:e,children:o("labels.liveCollaboration")})};gS.displayName="LiveCollaborationTrigger";var hS=()=>{let{t:e}=Ge(),t=Qe(),o=ye();return Be(xr,{checked:o.activeTool.locked,shortcut:Ke("toolLock"),onSelect:n=>{t.toggleLock(),n.preventDefault()},children:e("labels.preferences_toolLock")})},fS=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Be(xr,{checked:o.objectsSnapModeEnabled,shortcut:Ke("objectsSnapMode"),onSelect:n=>{t.executeAction(Cc),n.preventDefault()},children:e("buttons.objectsSnapMode")})},h1=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Be(xr,{checked:o.gridModeEnabled,shortcut:Ke("gridMode"),onSelect:n=>{t.executeAction(_s),n.preventDefault()},children:e("labels.toggleGrid")})},f1=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Be(xr,{checked:o.zenModeEnabled,shortcut:Ke("zenMode"),onSelect:n=>{t.executeAction(jr),n.preventDefault()},children:e("buttons.zenMode")})},bS=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Be(xr,{checked:o.viewModeEnabled,shortcut:Ke("viewMode"),onSelect:n=>{t.executeAction(ea),n.preventDefault()},children:e("labels.viewMode")})},xS=()=>{let{t:e}=Ge(),t=nt(),o=ye();return Be(xr,{checked:o.stats.open,shortcut:Ke("stats"),onSelect:n=>{t.executeAction(qr),n.preventDefault()},children:e("stats.fullTitle")})},ui=({children:e,additionalItems:t})=>{let{t:o}=Ge();return md(ei,{children:[Be(ei.Trigger,{icon:ev,children:o("labels.preferences")}),md(ei.Content,{className:"excalidraw-main-menu-preferences-submenu",children:[e||md(ES,{children:[Be(hS,{}),Be(fS,{}),Be(h1,{}),Be(f1,{}),Be(bS,{}),Be(xS,{})]}),t]})]})};ui.ToggleToolLock=hS;ui.ToggleSnapMode=fS;ui.ToggleGridMode=h1;ui.ToggleZenMode=f1;ui.ToggleViewMode=bS;ui.ToggleElementProperties=xS;ui.displayName="Preferences";import{jsx as Yu,jsxs as x1}from"react/jsx-runtime";var MY=Object.assign(Mr("MainMenu",({children:e,onSelect:t})=>{let{MainMenuTunnel:o}=Xe(),n=we(),r=ye(),i=ve();return Yu(o.In,{children:x1(he,{open:r.openMenu==="canvas",children:[Yu(he.Trigger,{onToggle:()=>{i({openMenu:r.openMenu==="canvas"?null:"canvas",openPopup:null,openDialog:null})},"data-testid":"main-menu-trigger",className:"main-menu-trigger",children:yy}),x1(he.Content,{onClickOutside:()=>i({openMenu:null}),onSelect:SY(t,()=>{i({openMenu:null})}),className:"main-menu",align:"start",children:[e,n.formFactor==="phone"&&r.collaborators.size>0&&x1("fieldset",{className:"UserList-Wrapper",children:[Yu("legend",{children:f("labels.collaborators")}),Yu(Hu,{mobile:!0,collaborators:r.collaborators,userToFollow:r.userToFollow?.socketId||null})]})]})]})})}),{Trigger:he.Trigger,Item:he.Item,ItemLink:he.ItemLink,ItemCustom:he.ItemCustom,Group:he.Group,Separator:he.Separator,Sub:ei,DefaultItems:b1}),Kt=MY;import PY from"clsx";import{forwardRef as AY,useState as LY}from"react";import{isPromiseLike as _Y}from"@orangecatai/common";import{jsx as Vu,jsxs as DY}from"react/jsx-runtime";var qo=AY(({children:e,icon:t,onClick:o,label:n,variant:r="filled",color:i="primary",size:a="medium",fullWidth:s,className:l,status:c,disabled:m},p)=>{let[d,u]=LY(!1),h=async E=>{let w=o?.(E);if(_Y(w)){let x=window.setTimeout(()=>{u(!0)},50);try{await w}catch(y){if(y instanceof Ra)console.warn(y);else throw y}finally{clearTimeout(x),u(!1)}}},g=d?"loading":c;return i=g==="success"?"success":i,Vu("button",{className:PY("ExcButton",`ExcButton--color-${i}`,`ExcButton--variant-${r}`,`ExcButton--size-${a}`,`ExcButton--status-${g}`,{"ExcButton--fullWidth":s},l),onClick:h,type:"button","aria-label":n,ref:p,disabled:m||g==="loading"||g==="success",children:DY("div",{className:"ExcButton__contents",children:[g==="loading"?Vu(Gt,{className:"ExcButton__statusIcon"}):g==="success"&&Vu("div",{className:"ExcButton__statusIcon",children:ww}),t&&Vu("div",{className:"ExcButton__icon","aria-hidden":!0,children:t}),r!=="icon"&&(e??n)]})})});import{jsx as dl,jsxs as BY}from"react/jsx-runtime";var $u=({title:e,children:t,actionLabel:o,onClick:n})=>BY("div",{className:"OverwriteConfirm__Actions__Action",children:[dl("h4",{children:e}),dl("div",{className:"OverwriteConfirm__Actions__Action__content",children:t}),dl(qo,{variant:"outlined",color:"muted",label:o,size:"large",fullWidth:!0,onClick:n})]}),RY=()=>{let{t:e}=Ge(),t=nt(),o=ve();return dl($u,{title:e("overwriteConfirm.action.exportToImage.title"),actionLabel:e("overwriteConfirm.action.exportToImage.button"),onClick:()=>{t.executeAction(tp,"ui",!0),o({openDialog:{name:"imageExport"}})},children:e("overwriteConfirm.action.exportToImage.description")})},NY=()=>{let{t:e}=Ge(),t=nt();return dl($u,{title:e("overwriteConfirm.action.saveToDisk.title"),actionLabel:e("overwriteConfirm.action.saveToDisk.button"),onClick:()=>{t.executeAction(Ic,"ui")},children:e("overwriteConfirm.action.saveToDisk.description")})},E1=Object.assign(({children:e})=>dl("div",{className:"OverwriteConfirm__Actions",children:e}),{ExportToImage:RY,SaveToDisk:NY});import{jsx as gi,jsxs as yS}from"react/jsx-runtime";var Ku=Object.assign(Mr("OverwriteConfirmDialog",({children:e})=>{let{OverwriteConfirmDialogTunnel:t}=Xe(),[o,n]=ae(u1);if(!o.active)return null;let r=()=>{o.onClose(),n(a=>({...a,active:!1}))},i=()=>{o.onConfirm(),n(a=>({...a,active:!1}))};return gi(t.In,{children:gi(ht,{onCloseRequest:r,title:!1,size:916,children:yS("div",{className:"OverwriteConfirm",children:[gi("h3",{children:o.title}),yS("div",{className:`OverwriteConfirm__Description OverwriteConfirm__Description--color-${o.color}`,children:[gi("div",{className:"OverwriteConfirm__Description__icon",children:hm}),gi("div",{children:o.description}),gi("div",{className:"OverwriteConfirm__Description__spacer"}),gi(qo,{color:o.color,size:"large",label:o.actionLabel,onClick:i})]}),gi(E1,{children:e})]})})})}),{Actions:E1,Action:$u});import rV from"clsx";import{CANVAS_SEARCH_TAB as T1,DEFAULT_SIDEBAR as iV,LIBRARY_SIDEBAR_TAB as AS,composeEventHandlers as aV}from"@orangecatai/common";import{round as FY}from"@orangecatai/math";import OY from"clsx";import zY from"lodash.debounce";import{Fragment as HY,memo as GY,useEffect as pd,useMemo as wS,useRef as y1,useState as vS}from"react";import{CLASSES as UY,EVENT as WY,FONT_FAMILY as w1,FRAME_STYLE as v1,getLineHeight as YY}from"@orangecatai/common";import{isElementCompletelyInViewport as VY}from"@orangecatai/element";import{measureText as ud}from"@orangecatai/element";import{KEYS as ml,randomInteger as IS,addEventListener as $Y,getFontString as Xu}from"@orangecatai/common";import{newTextElement as KY}from"@orangecatai/element";import{isTextElement as SS,isFrameLikeElement as Zu}from"@orangecatai/element";import{getDefaultFrameName as MS}from"@orangecatai/element/frame";import{Fragment as nV,jsx as Ft,jsxs as Xn}from"react/jsx-runtime";var XY=Ce(""),I1=Ce(null),ZY=350,PS=()=>{let e=Qe(),t=ve(),o=y1(null),[n,r]=ae(XY),i=n.trim(),[a,s]=vS(!1),[l,c]=vS({nonce:null,items:[]}),m=y1(null),p=y1(void 0),[d,u]=ae(I1),h=e.scene.getNonDeletedElementsMap();pd(()=>{a||(i!==m.current||e.scene.getSceneNonce()!==p.current)&&(m.current=null,kS(i,e,(y,v)=>{c({nonce:IS(),items:y}),m.current=i,p.current=e.scene.getSceneNonce(),t({searchMatches:y.length?{focusedId:null,matches:y.map(I=>({id:I.element.id,focus:!1,matchedLines:I.matchedLines}))}:null})}))},[a,i,h,e,t,u,p]);let g=()=>{l.items.length>0&&u(y=>y===null?0:(y+1)%l.items.length)},E=()=>{l.items.length>0&&u(y=>y===null?0:y-1<0?l.items.length-1:y-1)};pd(()=>{t(y=>y.searchMatches?{searchMatches:{focusedId:d!==null&&y.searchMatches?.matches[d]?.id||null,matches:y.searchMatches.matches.map((I,k)=>k===d?{...I,focus:!0}:{...I,focus:!1})}}:null)},[d,t]),pd(()=>{if(l.items.length>0&&d!==null){let y=l.items[d];if(y){let v=e.state.zoom.value,I=KY({text:y.searchQuery,x:y.element.x+(y.matchedLines[0]?.offsetX??0),y:y.element.y+(y.matchedLines[0]?.offsetY??0),width:y.matchedLines[0]?.width,height:y.matchedLines[0]?.height,fontSize:Zu(y.element)?v1.nameFontSize:y.element.fontSize,fontFamily:Zu(y.element)?w1.Assistant:y.element.fontFamily}),k=14,L=I.fontSize,S=L*v<k;if(!VY([I],e.canvas.width/window.devicePixelRatio,e.canvas.height/window.devicePixelRatio,{offsetLeft:e.state.offsetLeft,offsetTop:e.state.offsetTop,scrollX:e.state.scrollX,scrollY:e.state.scrollY,zoom:e.state.zoom},e.scene.getNonDeletedElementsMap(),e.getEditorUIOffsets())||S){let _;S?L>=k?_={fitToContent:!0}:_={fitToViewport:!0,maxZoom:FY(k/L,1)}:_={fitToContent:!0},e.scrollToContent(I,{animate:!0,duration:300,..._,canvasOffsets:e.getEditorUIOffsets()})}}}},[d,l,e]),pd(()=>()=>{u(null),m.current=null,p.current=void 0,t({searchMatches:null}),s(!1)},[t,u]);let w=Fr({goToNextItem:g,goToPreviousItem:E,searchMatches:l});pd(()=>{let y=v=>{if(v.key===ml.ESCAPE&&!e.state.openDialog&&!e.state.openPopup){v.preventDefault(),v.stopPropagation(),t({openSidebar:null});return}if(v[ml.CTRL_OR_CMD]&&v.key===ml.F){if(v.preventDefault(),v.stopPropagation(),e.state.openDialog)return;o.current?.matches(":focus")||(e.state.openDialog&&t({openDialog:null}),o.current?.focus(),o.current?.select())}v.target instanceof HTMLElement&&v.target.closest(".layer-ui__search")&&w.searchMatches.items.length&&(v.key===ml.ENTER&&(v.stopPropagation(),w.goToNextItem()),v.key===ml.ARROW_UP?(v.stopPropagation(),w.goToPreviousItem()):v.key===ml.ARROW_DOWN&&(v.stopPropagation(),w.goToNextItem()))};return $Y(window,WY.KEYDOWN,y,{capture:!0,passive:!1})},[t,w,e]);let x=`${l.items.length} ${l.items.length===1?f("search.singleResult"):f("search.multipleResults")}`;return Xn("div",{className:"layer-ui__search",children:[Ft("div",{className:"layer-ui__search-header",children:Ft(ti,{className:UY.SEARCH_MENU_INPUT_WRAPPER,value:n,ref:o,placeholder:f("search.placeholder"),icon:Co,onChange:y=>{r(y),s(!0);let v=y.trim();kS(v,e,(I,k)=>{c({nonce:IS(),items:I}),u(k),m.current=v,p.current=e.scene.getSceneNonce(),t({searchMatches:I.length?{focusedId:null,matches:I.map(L=>({id:L.element.id,focus:!1,matchedLines:L.matchedLines}))}:null}),s(!1)})},selectOnRender:!0})}),Xn("div",{className:"layer-ui__search-count",children:[l.items.length>0&&Xn(nV,{children:[d!==null&&d>-1?Xn("div",{children:[d+1," / ",x]}):Ft("div",{children:x}),Xn("div",{className:"result-nav",children:[Ft(io,{onSelect:()=>{g()},className:"result-nav-btn",children:fm}),Ft(io,{onSelect:()=>{E()},className:"result-nav-btn",children:Kw})]})]}),l.items.length===0&&i&&m.current&&Ft("div",{style:{margin:"1rem auto"},children:f("search.noMatch")})]}),Ft(JY,{matches:l,onItemClick:u,focusIndex:d,searchQuery:i})]})},TS=e=>{let t=[e.preview.moreBefore?"...":"",e.preview.previewText.slice(0,e.preview.indexInSearchQuery),e.preview.previewText.slice(e.preview.indexInSearchQuery,e.preview.indexInSearchQuery+e.searchQuery.length),e.preview.previewText.slice(e.preview.indexInSearchQuery+e.searchQuery.length),e.preview.moreAfter?"...":""];return Ft("div",{tabIndex:-1,className:OY("layer-ui__result-item",{active:e.highlighted}),onClick:e.onClick,ref:o=>{e.highlighted&&o?.scrollIntoView({behavior:"auto",block:"nearest"})},children:Ft("div",{className:"preview-text",children:t.flatMap((o,n)=>Ft(HY,{children:n===2?Ft("b",{children:o}):o},n))})})},jY=e=>{let t=wS(()=>e.matches.items.filter(n=>Zu(n.element)),[e.matches]),o=wS(()=>e.matches.items.filter(n=>SS(n.element)),[e.matches]);return Xn("div",{children:[t.length>0&&Xn("div",{className:"layer-ui__search-result-container",children:[Xn("div",{className:"layer-ui__search-result-title",children:[Ft("div",{className:"title-icon",children:Dn}),Ft("div",{children:f("search.frames")})]}),t.map((n,r)=>Ft(TS,{searchQuery:e.searchQuery,preview:n.preview,highlighted:r===e.focusIndex,onClick:()=>e.onItemClick(r)},n.element.id+n.index)),o.length>0&&Ft("div",{className:"layer-ui__divider"})]}),o.length>0&&Xn("div",{className:"layer-ui__search-result-container",children:[Xn("div",{className:"layer-ui__search-result-title",children:[Ft("div",{className:"title-icon",children:_n}),Ft("div",{children:f("search.texts")})]}),o.map((n,r)=>Ft(TS,{searchQuery:e.searchQuery,preview:n.preview,highlighted:r+t.length===e.focusIndex,onClick:()=>e.onItemClick(r+t.length)},n.element.id+n.index))]})]})},qY=(e,t)=>e.matches.nonce===t.matches.nonce&&e.focusIndex===t.focusIndex,JY=GY(jY,qY),CS=(e,t,o)=>{let i=e.slice(0,t),a=i.split(/\s+/),s=i.endsWith(" "),l=a.length-2-1-(s?0:1),c=a.slice(l<=0?0:l).join(" ")+(s?" ":""),m=20;c=c.length>m?c.slice(-m):c;let p=e.slice(t+o.length),d=p.split(/\s+/),u=!p.startsWith(" "),h=u?6:5,g=(u?"":" ")+d.slice(0,h).join(" ");return{indexInSearchQuery:c.length,previewText:c+o+g,moreBefore:l>0,moreAfter:d.length>h}},QY=(e,t)=>{let o=e.split(`
106
106
  `),n=[],r=0;for(let i=0;i<o.length;i++){let a=o[i],s=o[i+1];if(s){let l=t.indexOf(s,r);if(l>a.length+r){let c=l-(a.length+r);for(;c>0;)a+=" ",c--}}n.push(a),r=r+a.length}return n.join(`
107
107
  `)},eV=(e,t,o)=>{let r=QY(e.text,e.originalText).split(`
108
- `),i=[],a=0,s=0;for(let p of r){let d=a,u=d+p.length-1;i.push({line:p,startIndex:d,endIndex:u,lineNumber:s}),a=u+1,s++}let l=o,c=e.originalText.slice(o,o+t.length),m=[];for(let p of i){if(c==="")break;if(l>=p.startIndex&&l<=p.endIndex){let d=p.endIndex+1-l,u=p.line.slice(0,l-p.startIndex),h=c.slice(0,d);c=c.slice(d);let g=ud(u,Xu(e),e.lineHeight);if(u===""&&(g.width=0),e.textAlign!=="left"&&p.line.length>0){let v=ud(p.line,Xu(e),e.lineHeight),I=e.textAlign==="center"?(e.width-v.width)/2:e.width-v.width;g.width+=I}let{width:E,height:w}=ud(h,Xu(e),e.lineHeight),x=g.width,y=p.lineNumber*g.height;m.push({offsetX:x,offsetY:y,width:E,height:w,showOnCanvas:!0}),l+=d}}return m},tV=(e,t,o,n)=>{let r=e.name??MS(e),i=r.slice(o,o+t.length),a=r.slice(0,o),s=Xu({fontSize:v1.nameFontSize,fontFamily:w1.Assistant}),l=YY(w1.Assistant),c=ud(a,s,l);a===""&&(c.width=0);let m=ud(i,s,l),p=c.width,d=-c.height-v1.strokeWidth,u=m.width;return[{offsetX:p,offsetY:d,width:u,height:m.height,showOnCanvas:p+u<=e.width*n}]},oV=e=>e.replace(/[.*+?^${}()|[\]\\-]/g,"\\$&"),kS=zY((e,t,o)=>{if(!e||e===""){o([],null);return}let n=t.scene.getNonDeletedElements(),r=n.filter(d=>SS(d)),i=n.filter(d=>Zu(d));r.sort((d,u)=>d.y-u.y),i.sort((d,u)=>d.y-u.y);let a=[],s=new RegExp(oV(e),"gi");for(let d of r){let u=null,h=d.originalText;for(;(u=s.exec(h))!==null;){let g=CS(h,u.index,e),E=eV(d,e,u.index);E.length>0&&a.push({element:d,searchQuery:e,preview:g,index:u.index,matchedLines:E})}}let l=[];for(let d of i){let u=null,h=d.name??MS(d);for(;(u=s.exec(h))!==null;){let g=CS(h,u.index,e),E=tV(d,e,u.index,t.state.zoom.value);E.length>0&&l.push({element:d,searchQuery:e,preview:g,index:u.index,matchedLines:E})}}let c=new Set(t.visibleElements.map(d=>d.id)),m=[...l,...a],p=m.findIndex(d=>c.has(d.element.id))??null;o(m,p)},ZY);import{jsx as En,jsxs as LS}from"react/jsx-runtime";import{createElement as sV}from"react";var _S=Mr("DefaultSidebarTrigger",e=>{let{DefaultSidebarTriggerTunnel:t}=Xe();return En(t.In,{children:En(jo.Trigger,{...e,className:"default-sidebar-trigger",name:iV.name})})});_S.displayName="DefaultSidebarTrigger";var DS=({children:e})=>{let{DefaultSidebarTabTriggersTunnel:t}=Xe();return En(t.In,{children:e})};DS.displayName="DefaultTabTriggers";var ju=Object.assign(Mr("DefaultSidebar",({children:e,className:t,onDock:o,docked:n,...r})=>{let i=ye(),a=ve(),{DefaultSidebarTabTriggersTunnel:s}=Xe(),l=i.openSidebar?.tab===T1;return sV(jo,{...r,name:"default",key:"default",className:rV("default-sidebar",t),docked:l||(n??i.defaultSidebarDockedPreference),onDock:l||o===!1||!o&&n!=null?void 0:aV(o,c=>{a({defaultSidebarDockedPreference:c})})},LS(jo.Tabs,{children:[En(jo.Header,{children:LS(jo.TabTriggers,{children:[En(jo.TabTrigger,{tab:T1,children:ko}),En(jo.TabTrigger,{tab:AS,children:im}),En(s.Out,{})]})}),En(jo.Tab,{tab:AS,children:En(fC,{})}),En(jo.Tab,{tab:T1,children:En(PS,{})}),e]}))}),{Trigger:_S,TabTriggers:DS});import{useEffect as r$,useState as i$}from"react";import{useState as YS,useRef as VS,useEffect as $S,useDeferredValue as fV}from"react";import{EDITOR_LS_KEYS as bV,debounce as xV,isDevEnv as EV}from"@orangecatai/common";import{useEffect as lV,useRef as RS}from"react";import{EVENT as NS,KEYS as BS}from"@orangecatai/common";import{jsx as cV}from"react/jsx-runtime";var FS=({input:e,placeholder:t,onChange:o,onKeyboardSubmit:n})=>{let r=RS(null),i=RS(n);return i.current=n,lV(()=>{if(!i.current)return;let a=r.current;if(a){let s=l=>{l[BS.CTRL_OR_CMD]&&l.key===BS.ENTER&&(l.preventDefault(),i.current?.())};return a.focus(),a.addEventListener(NS.KEYDOWN,s),()=>{a.removeEventListener(NS.KEYDOWN,s)}}},[]),cV("textarea",{className:"ttd-dialog-input",onChange:o,value:e,placeholder:t,ref:r})};import dV from"clsx";import{jsx as ba,jsxs as OS}from"react/jsx-runtime";var qu=({error:e,canvasRef:t,loaded:o,hideErrorDetails:n})=>OS("div",{className:`ttd-dialog-output-wrapper ${e?"ttd-dialog-output-wrapper--error":""}`,children:[e&&ba("div",{"data-testid":"ttd-dialog-output-error",className:"ttd-dialog-output-error",children:OS("div",{className:"ttd-dialog-output-error-content",children:[ba("div",{className:"ttd-dialog-output-error-icon",children:hm}),ba("div",{className:"ttd-dialog-output-error-title",children:f("ttd.error")}),ba("div",{className:"ttd-dialog-output-error-message",children:n?f("chat.errors.mermaidParseError"):e.message})]})},"error"),o?ba("div",{className:dV("ttd-dialog-output-canvas-container",{invisible:!!e}),children:ba("div",{ref:t,className:"ttd-dialog-output-canvas-content"})},"canvas"):ba(Gt,{size:"2rem"})]});import pl from"clsx";import{Fragment as mV}from"react";import{jsx as ul,jsxs as gl}from"react/jsx-runtime";var xa=({label:e,children:t,panelActions:o=[],onTextSubmitInProgess:n,renderTopRight:r,renderSubmitShortcut:i,className:a,panelActionJustifyContent:s="flex-start"})=>{let l=c=>{if(c?.variant==="link")return gl("button",{className:pl("ttd-dialog-panel-action-link",c.className),onClick:c.action,disabled:c?.disabled||n,type:"button",children:[c.label,c.icon&&ul("span",{className:"ttd-dialog-panel-action-link__icon",children:c.icon})]});if(c?.variant==="button")return gl(ro,{className:pl("ttd-dialog-panel-button",c.className),onSelect:c.action?c.action:()=>{},disabled:c?.disabled||n,children:[gl("div",{className:pl({invisible:n}),children:[c?.label,c?.icon&&ul("span",{children:c.icon})]}),n&&ul(Gt,{})]});if(c?.variant==="rateLimit")return ul("div",{className:pl("ttd-dialog-panel__rate-limit",c.className),children:c.label})};return gl("div",{className:pl("ttd-dialog-panel",a),children:[(e||r)&&gl("div",{className:"ttd-dialog-panel__header",children:[typeof e=="string"?ul("label",{children:e}):e,r?.()]}),t,gl("div",{className:pl("ttd-dialog-panel-button-container",{invisible:!o.length}),style:{justifyContent:s},children:[o.filter(Boolean).map(c=>ul(mV,{children:l(c)},c.label)),!n&&i?.()]})]})};import{jsx as pV}from"react/jsx-runtime";var zS=({children:e})=>pV("div",{className:"ttd-dialog-panels",children:e});import{jsx as HS,jsxs as uV}from"react/jsx-runtime";var GS=()=>uV("div",{className:"ttd-dialog-submit-shortcut",children:[HS("div",{className:"ttd-dialog-submit-shortcut__key",children:G("CtrlOrCmd")}),HS("div",{className:"ttd-dialog-submit-shortcut__key",children:G("Enter")})]});import{DEFAULT_EXPORT_PADDING as gV,EDITOR_LS_KEYS as hV}from"@orangecatai/common";var C1=({canvasRef:e,setError:t})=>{let o=e.current;if(!o)return;let n=o.parentElement;n&&(n.style.background="",t(null),o.replaceChildren())},hl=async({canvasRef:e,mermaidToExcalidrawLib:t,mermaidDefinition:o,setError:n,data:r,theme:i})=>{let a=e.current,s=a?.parentElement;if(!a||!s)return{success:!1};if(!o)return C1({canvasRef:e,setError:n}),{success:!1};let l;try{let c=await t.api;try{try{l=await c.parseMermaidToExcalidraw(o)}catch{l=await c.parseMermaidToExcalidraw(o.replace(/"/g,"'"))}}catch(u){return{success:!1,error:u}}let{elements:m,files:p}=l;n(null),r.current={elements:WS(m,{regenerateIds:!0}),files:p};let d=await Jr({elements:r.current.elements,files:r.current.files,exportPadding:gV,maxWidthOrHeight:Math.max(s.offsetWidth,s.offsetHeight)*window.devicePixelRatio,appState:{exportWithDarkMode:i===US.DARK}});return s.style.background="var(--default-bg-color)",a.replaceChildren(d),{success:!0}}catch(c){return s.style.background="var(--default-bg-color)",o&&n(c),{success:!1,error:c}}},fl=e=>{Yo.set(hV.MERMAID_TO_EXCALIDRAW,e)},gd=({app:e,data:t,text:o,shouldSaveMermaidDataToStorage:n})=>{let{elements:r,files:i}=t.current;r.length&&(e.addElementsFromPasteOrLibrary({elements:r,files:i,position:"center",fitToContent:!0}),e.setOpenDialog(null),n&&o&&fl(o))};import{Fragment as vV,jsx as Zn,jsxs as XS}from"react/jsx-runtime";var yV=`flowchart TD
108
+ `),i=[],a=0,s=0;for(let p of r){let d=a,u=d+p.length-1;i.push({line:p,startIndex:d,endIndex:u,lineNumber:s}),a=u+1,s++}let l=o,c=e.originalText.slice(o,o+t.length),m=[];for(let p of i){if(c==="")break;if(l>=p.startIndex&&l<=p.endIndex){let d=p.endIndex+1-l,u=p.line.slice(0,l-p.startIndex),h=c.slice(0,d);c=c.slice(d);let g=ud(u,Xu(e),e.lineHeight);if(u===""&&(g.width=0),e.textAlign!=="left"&&p.line.length>0){let v=ud(p.line,Xu(e),e.lineHeight),I=e.textAlign==="center"?(e.width-v.width)/2:e.width-v.width;g.width+=I}let{width:E,height:w}=ud(h,Xu(e),e.lineHeight),x=g.width,y=p.lineNumber*g.height;m.push({offsetX:x,offsetY:y,width:E,height:w,showOnCanvas:!0}),l+=d}}return m},tV=(e,t,o,n)=>{let r=e.name??MS(e),i=r.slice(o,o+t.length),a=r.slice(0,o),s=Xu({fontSize:v1.nameFontSize,fontFamily:w1.Assistant}),l=YY(w1.Assistant),c=ud(a,s,l);a===""&&(c.width=0);let m=ud(i,s,l),p=c.width,d=-c.height-v1.strokeWidth,u=m.width;return[{offsetX:p,offsetY:d,width:u,height:m.height,showOnCanvas:p+u<=e.width*n}]},oV=e=>e.replace(/[.*+?^${}()|[\]\\-]/g,"\\$&"),kS=zY((e,t,o)=>{if(!e||e===""){o([],null);return}let n=t.scene.getNonDeletedElements(),r=n.filter(d=>SS(d)),i=n.filter(d=>Zu(d));r.sort((d,u)=>d.y-u.y),i.sort((d,u)=>d.y-u.y);let a=[],s=new RegExp(oV(e),"gi");for(let d of r){let u=null,h=d.originalText;for(;(u=s.exec(h))!==null;){let g=CS(h,u.index,e),E=eV(d,e,u.index);E.length>0&&a.push({element:d,searchQuery:e,preview:g,index:u.index,matchedLines:E})}}let l=[];for(let d of i){let u=null,h=d.name??MS(d);for(;(u=s.exec(h))!==null;){let g=CS(h,u.index,e),E=tV(d,e,u.index,t.state.zoom.value);E.length>0&&l.push({element:d,searchQuery:e,preview:g,index:u.index,matchedLines:E})}}let c=new Set(t.visibleElements.map(d=>d.id)),m=[...l,...a],p=m.findIndex(d=>c.has(d.element.id))??null;o(m,p)},ZY);import{jsx as En,jsxs as LS}from"react/jsx-runtime";import{createElement as sV}from"react";var _S=Mr("DefaultSidebarTrigger",e=>{let{DefaultSidebarTriggerTunnel:t}=Xe();return En(t.In,{children:En(jo.Trigger,{...e,className:"default-sidebar-trigger",name:iV.name})})});_S.displayName="DefaultSidebarTrigger";var DS=({children:e})=>{let{DefaultSidebarTabTriggersTunnel:t}=Xe();return En(t.In,{children:e})};DS.displayName="DefaultTabTriggers";var ju=Object.assign(Mr("DefaultSidebar",({children:e,className:t,onDock:o,docked:n,...r})=>{let i=ye(),a=ve(),{DefaultSidebarTabTriggersTunnel:s}=Xe(),l=i.openSidebar?.tab===T1;return sV(jo,{...r,name:"default",key:"default",className:rV("default-sidebar",t),docked:l||(n??i.defaultSidebarDockedPreference),onDock:l||o===!1||!o&&n!=null?void 0:aV(o,c=>{a({defaultSidebarDockedPreference:c})})},LS(jo.Tabs,{children:[En(jo.Header,{children:LS(jo.TabTriggers,{children:[En(jo.TabTrigger,{tab:T1,children:Co}),En(jo.TabTrigger,{tab:AS,children:im}),En(s.Out,{})]})}),En(jo.Tab,{tab:AS,children:En(fC,{})}),En(jo.Tab,{tab:T1,children:En(PS,{})}),e]}))}),{Trigger:_S,TabTriggers:DS});import{useEffect as r$,useState as i$}from"react";import{useState as YS,useRef as VS,useEffect as $S,useDeferredValue as fV}from"react";import{EDITOR_LS_KEYS as bV,debounce as xV,isDevEnv as EV}from"@orangecatai/common";import{useEffect as lV,useRef as RS}from"react";import{EVENT as NS,KEYS as BS}from"@orangecatai/common";import{jsx as cV}from"react/jsx-runtime";var FS=({input:e,placeholder:t,onChange:o,onKeyboardSubmit:n})=>{let r=RS(null),i=RS(n);return i.current=n,lV(()=>{if(!i.current)return;let a=r.current;if(a){let s=l=>{l[BS.CTRL_OR_CMD]&&l.key===BS.ENTER&&(l.preventDefault(),i.current?.())};return a.focus(),a.addEventListener(NS.KEYDOWN,s),()=>{a.removeEventListener(NS.KEYDOWN,s)}}},[]),cV("textarea",{className:"ttd-dialog-input",onChange:o,value:e,placeholder:t,ref:r})};import dV from"clsx";import{jsx as ba,jsxs as OS}from"react/jsx-runtime";var qu=({error:e,canvasRef:t,loaded:o,hideErrorDetails:n})=>OS("div",{className:`ttd-dialog-output-wrapper ${e?"ttd-dialog-output-wrapper--error":""}`,children:[e&&ba("div",{"data-testid":"ttd-dialog-output-error",className:"ttd-dialog-output-error",children:OS("div",{className:"ttd-dialog-output-error-content",children:[ba("div",{className:"ttd-dialog-output-error-icon",children:hm}),ba("div",{className:"ttd-dialog-output-error-title",children:f("ttd.error")}),ba("div",{className:"ttd-dialog-output-error-message",children:n?f("chat.errors.mermaidParseError"):e.message})]})},"error"),o?ba("div",{className:dV("ttd-dialog-output-canvas-container",{invisible:!!e}),children:ba("div",{ref:t,className:"ttd-dialog-output-canvas-content"})},"canvas"):ba(Gt,{size:"2rem"})]});import pl from"clsx";import{Fragment as mV}from"react";import{jsx as ul,jsxs as gl}from"react/jsx-runtime";var xa=({label:e,children:t,panelActions:o=[],onTextSubmitInProgess:n,renderTopRight:r,renderSubmitShortcut:i,className:a,panelActionJustifyContent:s="flex-start"})=>{let l=c=>{if(c?.variant==="link")return gl("button",{className:pl("ttd-dialog-panel-action-link",c.className),onClick:c.action,disabled:c?.disabled||n,type:"button",children:[c.label,c.icon&&ul("span",{className:"ttd-dialog-panel-action-link__icon",children:c.icon})]});if(c?.variant==="button")return gl(io,{className:pl("ttd-dialog-panel-button",c.className),onSelect:c.action?c.action:()=>{},disabled:c?.disabled||n,children:[gl("div",{className:pl({invisible:n}),children:[c?.label,c?.icon&&ul("span",{children:c.icon})]}),n&&ul(Gt,{})]});if(c?.variant==="rateLimit")return ul("div",{className:pl("ttd-dialog-panel__rate-limit",c.className),children:c.label})};return gl("div",{className:pl("ttd-dialog-panel",a),children:[(e||r)&&gl("div",{className:"ttd-dialog-panel__header",children:[typeof e=="string"?ul("label",{children:e}):e,r?.()]}),t,gl("div",{className:pl("ttd-dialog-panel-button-container",{invisible:!o.length}),style:{justifyContent:s},children:[o.filter(Boolean).map(c=>ul(mV,{children:l(c)},c.label)),!n&&i?.()]})]})};import{jsx as pV}from"react/jsx-runtime";var zS=({children:e})=>pV("div",{className:"ttd-dialog-panels",children:e});import{jsx as HS,jsxs as uV}from"react/jsx-runtime";var GS=()=>uV("div",{className:"ttd-dialog-submit-shortcut",children:[HS("div",{className:"ttd-dialog-submit-shortcut__key",children:G("CtrlOrCmd")}),HS("div",{className:"ttd-dialog-submit-shortcut__key",children:G("Enter")})]});import{DEFAULT_EXPORT_PADDING as gV,EDITOR_LS_KEYS as hV}from"@orangecatai/common";var C1=({canvasRef:e,setError:t})=>{let o=e.current;if(!o)return;let n=o.parentElement;n&&(n.style.background="",t(null),o.replaceChildren())},hl=async({canvasRef:e,mermaidToExcalidrawLib:t,mermaidDefinition:o,setError:n,data:r,theme:i})=>{let a=e.current,s=a?.parentElement;if(!a||!s)return{success:!1};if(!o)return C1({canvasRef:e,setError:n}),{success:!1};let l;try{let c=await t.api;try{try{l=await c.parseMermaidToExcalidraw(o)}catch{l=await c.parseMermaidToExcalidraw(o.replace(/"/g,"'"))}}catch(u){return{success:!1,error:u}}let{elements:m,files:p}=l;n(null),r.current={elements:WS(m,{regenerateIds:!0}),files:p};let d=await Jr({elements:r.current.elements,files:r.current.files,exportPadding:gV,maxWidthOrHeight:Math.max(s.offsetWidth,s.offsetHeight)*window.devicePixelRatio,appState:{exportWithDarkMode:i===US.DARK}});return s.style.background="var(--default-bg-color)",a.replaceChildren(d),{success:!0}}catch(c){return s.style.background="var(--default-bg-color)",o&&n(c),{success:!1,error:c}}},fl=e=>{Yo.set(hV.MERMAID_TO_EXCALIDRAW,e)},gd=({app:e,data:t,text:o,shouldSaveMermaidDataToStorage:n})=>{let{elements:r,files:i}=t.current;r.length&&(e.addElementsFromPasteOrLibrary({elements:r,files:i,position:"center",fitToContent:!0}),e.setOpenDialog(null),n&&o&&fl(o))};import{Fragment as vV,jsx as Zn,jsxs as XS}from"react/jsx-runtime";var yV=`flowchart TD
109
109
  A[Christmas] -->|Get money| B(Go shopping)
110
110
  B --> C{Let me think}
111
111
  C -->|One| D[Laptop]
112
112
  C -->|Two| E[iPhone]
113
- C -->|Three| F[Car]`,KS=xV(fl,300),wV=({mermaidToExcalidrawLib:e,isActive:t})=>{let[o,n]=YS(()=>Yo.get(bV.MERMAID_TO_EXCALIDRAW)||yV),r=fV(o.trim()),[i,a]=YS(null),s=VS(null),l=VS({elements:[],files:null}),c=Qe(),{theme:m}=ye();$S(()=>{t&&((async()=>{try{if(!r){C1({canvasRef:s,setError:a});return}let u=await hl({canvasRef:s,data:l,mermaidToExcalidrawLib:e,setError:a,mermaidDefinition:r,theme:m});if(!u.success){let h=u.error??new Error("Invalid mermaid definition");a(h)}}catch(u){EV()&&console.error("Failed to parse mermaid definition",u)}})(),KS(r))},[r,e,t,m]),$S(()=>()=>{KS.flush()},[]);let p=()=>{gd({app:c,data:l,text:o,shouldSaveMermaidDataToStorage:!0})};return XS(vV,{children:[Zn("div",{className:"ttd-dialog-desc",children:Zn(no,{i18nKey:"mermaid.description",flowchartLink:d=>Zn("a",{href:"https://mermaid.js.org/syntax/flowchart.html",children:d}),sequenceLink:d=>Zn("a",{href:"https://mermaid.js.org/syntax/sequenceDiagram.html",children:d}),classLink:d=>Zn("a",{href:"https://mermaid.js.org/syntax/classDiagram.html",children:d})})}),XS(zS,{children:[Zn(xa,{children:Zn(FS,{input:o,placeholder:f("mermaid.inputPlaceholder"),onChange:d=>n(d.target.value),onKeyboardSubmit:()=>{p()}})}),Zn(xa,{panelActions:[{action:()=>{p()},label:f("mermaid.button"),icon:Br,variant:"button"}],renderSubmitShortcut:()=>Zn(GS,{}),children:Zn(qu,{canvasRef:s,loaded:e.loaded,error:i})})]})]})},ZS=wV;import{useRef as $V}from"react";import{useRef as qS,useEffect as SV,useLayoutEffect as MV}from"react";import{KEYS as PV}from"@orangecatai/common";import{jsx as k1,jsxs as IV}from"react/jsx-runtime";var Ju=()=>IV("div",{className:"chat-interface__welcome-screen__welcome-message",children:[k1("h3",{children:f("chat.placeholder.title")}),k1("p",{children:f("chat.placeholder.description")}),k1("p",{children:f("chat.placeholder.hint")})]});import TV from"clsx";import{useState as CV,useEffect as kV}from"react";import{Fragment as jS,jsx as At,jsxs as Jo}from"react/jsx-runtime";var S1=({message:e,onMermaidTabClick:t,onAiRepairClick:o,onDeleteMessage:n,onInsertMessage:r,onRetry:i,rateLimitRemaining:a,isLastMessage:s,renderWarning:l,allowFixingParseError:c})=>{let[m,p]=CV(!1);kV(()=>{if(!e.error||!s)return;if(e.error&&!e.lastAttemptAt){p(!0);return}let u=Date.now()-e.lastAttemptAt,h=Math.max(0,5e3-u);if(h===0){p(!0);return}p(!1);let g=setTimeout(()=>{p(!0)},h);return()=>clearTimeout(g)},[e.error,e.lastAttemptAt,s]);let d=u=>u.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(e.type==="warning"){let u=l?.(e);return At("div",{className:"chat-message chat-message--system",children:Jo("div",{className:"chat-message__content",children:[Jo("div",{className:"chat-message__header",children:[At("span",{className:"chat-message__role",children:f("chat.role.system")}),At("span",{className:"chat-message__timestamp",children:d(e.timestamp)})]}),At("div",{className:"chat-message__body",children:At("div",{className:"chat-message__text",children:u||(e.warningType==="messageLimitExceeded"?Jo(jS,{children:[f("chat.rateLimit.messageLimit"),At("div",{style:{marginTop:"10px"},children:At(qo,{onClick:()=>{window.open(`${C.VITE_APP_PLUS_LP}/plus?utm_source=excalidraw&utm_medium=app&utm_content=ttdChatBanner#excalidraw-redirect`,"_blank","noopener")},children:f("chat.upsellBtnLabel")})})]}):f("chat.rateLimit.generalRateLimit"))})})]})})}return Jo("div",{className:`chat-message chat-message--${e.type}`,children:[Jo("div",{className:"chat-message__content",children:[Jo("div",{className:"chat-message__header",children:[At("span",{className:"chat-message__role",children:e.type==="user"?f("chat.role.user"):f("chat.role.assistant")}),At("span",{className:"chat-message__timestamp",children:d(e.timestamp)})]}),At("div",{className:"chat-message__body",children:e.error?Jo(jS,{children:[At("div",{className:"chat-message__error",children:e.content}),e.errorType!=="parse"&&Jo("div",{className:"chat-message__error_message",children:["Error: ",e.error||f("chat.errors.generationFailed")]}),e.errorType==="parse"&&c&&Jo("div",{className:"chat-message__error_message",children:[At("p",{children:f("chat.errors.invalidDiagram")}),Jo("div",{className:"chat-message__error-actions",children:[t&&At("button",{className:"chat-message__error-link",onClick:()=>t(e),type:"button",children:f("chat.errors.fixInMermaid")}),o&&At("button",{className:"chat-message__error-link",onClick:()=>o(e),disabled:a===0,type:"button",children:f("chat.errors.aiRepair")})]})]})]}):Jo("div",{className:"chat-message__text",children:[e.content,e.isGenerating&&At("span",{className:"chat-message__cursor",children:"\u258B"})]})})]}),e.type==="assistant"&&!e.isGenerating&&Jo("div",{className:"chat-message__actions",children:[!e.error&&r&&At("button",{className:"chat-message__action",onClick:()=>r(e),type:"button","aria-label":f("chat.insert"),title:f("chat.insert"),children:Cw}),t&&e.content&&At("button",{className:"chat-message__action",onClick:()=>t(e),type:"button","aria-label":f("chat.viewAsMermaid"),title:f("chat.viewAsMermaid"),children:vh}),n&&e.errorType!=="network"&&At("button",{className:"chat-message__action chat-message__action--danger",onClick:()=>n(e.id),type:"button","aria-label":f("chat.deleteMessage"),title:f("chat.deleteMessage"),children:Ht}),e.errorType==="network"&&i&&s&&At("button",{className:TV("chat-message__action",{invisible:!m}),onClick:()=>i(e),type:"button","aria-label":f("chat.retry"),title:f("chat.retry"),children:Tw})]})]})};import{jsx as Pr,jsxs as M1}from"react/jsx-runtime";var P1=({chatId:e,messages:t,currentPrompt:o,onPromptChange:n,onGenerate:r,isGenerating:i,rateLimits:a,onAbort:s,onMermaidTabClick:l,onAiRepairClick:c,onDeleteMessage:m,onInsertMessage:p,onRetry:d,renderWelcomeScreen:u,renderWarning:h})=>{let g=qS(null),E=qS(null);MV(()=>{g.current?.scrollIntoView()},[t]),SV(()=>{E.current&&E.current.focus()},[e]);let w=L=>{let S=L.target.value;n(S)},x=()=>{if(i&&s){s();return}let L=o.trim();L&&(r({prompt:L}),n(""))},y=L=>{L.key===PV.ENTER&&!L.shiftKey&&(L.preventDefault(),i||x())},v=o.trim().length>3&&!i&&(a?.rateLimitRemaining??1)>0,I=i&&!!s,k=L=>{let S=L.target;S.style.height="auto",S.style.height=`${Math.min(S.scrollHeight,120)}px`};return M1("div",{className:"chat-interface",children:[M1("div",{className:"chat-interface__messages",children:[t.length===0?Pr("div",{className:"chat-interface__welcome-screen",children:u?u({rateLimits:a??null}):Pr(Ju,{})}):t.map((L,S)=>Pr(S1,{message:L,onMermaidTabClick:l,onAiRepairClick:c,onDeleteMessage:m,onInsertMessage:p,onRetry:d,rateLimitRemaining:a?.rateLimitRemaining,isLastMessage:S===t.length-1,renderWarning:h,allowFixingParseError:L.errorType==="parse"&&S===t.length-1},L.id)),Pr("div",{ref:g,id:"messages-end"})]}),Pr("div",{className:"chat-interface__input-container",children:Pr("div",{className:"chat-interface__input-outer",children:M1("div",{className:"chat-interface__input-wrapper",style:{borderColor:i?"var(--dialog-border-color)":void 0},children:[Pr("textarea",{ref:E,autoFocus:!0,className:"chat-interface__input",value:o,onChange:w,onKeyDown:y,placeholder:i?f("chat.generating"):a?.rateLimitRemaining===0?f("chat.rateLimit.messageLimitInputPlaceholder"):t.length>0?f("chat.inputPlaceholderWithMessages"):f("chat.inputPlaceholder",{shortcut:"Shift + Enter"}),disabled:a?.rateLimitRemaining===0,rows:1,cols:30,onInput:k}),Pr("button",{className:"chat-interface__send-button",onClick:x,disabled:!v&&!I,type:"button",children:Pr(Bn,{size:"1.5em",icon:i?Ny:Br})})]})})})]})};import{randomId as AV}from"@orangecatai/common";var Qu=Ce(null),eg=Ce(!1),hi=Ce(null),Qo=Ce({id:AV(),messages:[],currentPrompt:""});import{findLastIndex as A1,randomId as LV}from"@orangecatai/common";var fi=(e,t)=>{let{messages:o}=e,n=A1(o,a=>a.type==="assistant");if(n===-1)return e;let r=o[n],i=o.slice();return i[n]={...r,...t},{...e,messages:i}},bi=e=>{let{messages:t}=e,o=A1(t,n=>n.type==="assistant");return t[o]},hd=(e,t)=>{let o=t.map(n=>({...n,id:LV(),timestamp:new Date}));return{...e,messages:[...e.messages,...o]}},JS=e=>{let t=A1(e.messages??[],o=>o.type==="assistant");return t!==-1?{...e,messages:e.messages.filter((o,n)=>n!==t)}:e},QS=e=>{let t=[];for(let o of e.messages)o.content&&(o.type==="user"||o.type==="assistant")&&t.push({role:o.type,content:o.content});return t};var fd=()=>{let[e,t]=ae(Qo);return{addUserMessage:a=>{t(s=>hd(s,[{type:"user",content:a}]))},addAssistantMessage:()=>{t(a=>hd(a,[{type:"assistant",content:"",isGenerating:!0}]))},setAssistantError:(a,s="other",l)=>{let c=l?JSON.stringify({name:l instanceof Error?l.name:"Error",message:l instanceof Error?l.message:String(l),stack:l instanceof Error?l.stack:void 0}):void 0;t(m=>fi(m,{isGenerating:!1,error:a,errorType:s,errorDetails:c}))},chatHistory:e,setChatHistory:t,setLastRetryAttempt:()=>{t(a=>fi(a,{lastAttemptAt:Date.now()}))}}};import{useCallback as bd,useEffect as eM,useRef as _V}from"react";import{randomId as DV}from"@orangecatai/common";var RV=e=>{let t=e.trim();return t.length<=50?t:`${t.substring(0,47)}...`},NV=Ce([]),BV=Ce(!1),FV=Ce(!1),tg=({persistenceAdapter:e})=>{let[t]=ae(Qo),[o,n]=ae(NV),[r,i]=ae(BV),[a,s]=ae(FV),l=_V(o);l.current=o;let c=t?.messages[t?.messages.length-1],m=bd(async()=>{if(!(a||r)){i(!0);try{let g=await e.loadChats();n(g),s(!0)}catch(g){console.warn("Failed to load chats:",g),n([]),s(!0)}finally{i(!1)}}},[a,r,n,i,s,e]);eM(()=>{m()},[]);let p=bd(async()=>{if(t.messages.length===0)return;let g=t.messages.find(k=>k.type==="user");if(!g||typeof g.content!="string")return;let E=RV(g.content),w=l.current,x=w.find(k=>k.id===t.id),y=!x||x.messages.length!==t.messages.length||x.messages.some((k,L)=>k.id!==t.messages[L]?.id||k.content!==t.messages[L]?.content),v={id:t.id,title:E,messages:t.messages.filter(k=>k.type==="user"||k.type==="assistant").map(k=>({...k,timestamp:k.timestamp instanceof Date?k.timestamp:new Date(k.timestamp)})),currentPrompt:t.currentPrompt,timestamp:y?Date.now():x?.timestamp??Date.now()},I=[...w.filter(k=>k.id!==t.id),v].sort((k,L)=>L.timestamp-k.timestamp).slice(0,10);n(I);try{await e.saveChats(I)}catch(k){console.warn("Failed to save chats:",k)}},[t,n,e]);eM(()=>{c?.isGenerating||p()},[t.messages?.length,c?.id,c?.isGenerating]);let d=bd(async g=>{let E=l.current.filter(w=>w.id!==g);n(E);try{await e.saveChats(E)}catch(w){console.warn("Failed to save after delete:",w)}return E},[n,e]),u=bd(g=>g,[]),h=bd(async()=>(await p(),DV()),[p]);return{savedChats:o,saveCurrentChat:p,deleteChat:d,restoreChat:u,createNewChatId:h}};import{useCallback as oM,useEffect as og,useMemo as nM,useRef as Ea}from"react";var tM=e=>{let t=e.trim();if(!t)return!1;let o=(t.match(/\[/g)||[]).length,n=(t.match(/\]/g)||[]).length,r=(t.match(/\{/g)||[]).length,i=(t.match(/\}/g)||[]).length,a=(t.match(/\(/g)||[]).length,s=(t.match(/\)/g)||[]).length;if(o!==n||r!==i||a!==s)return!1;let l=t.split(`
113
+ C -->|Three| F[Car]`,KS=xV(fl,300),wV=({mermaidToExcalidrawLib:e,isActive:t})=>{let[o,n]=YS(()=>Yo.get(bV.MERMAID_TO_EXCALIDRAW)||yV),r=fV(o.trim()),[i,a]=YS(null),s=VS(null),l=VS({elements:[],files:null}),c=Qe(),{theme:m}=ye();$S(()=>{t&&((async()=>{try{if(!r){C1({canvasRef:s,setError:a});return}let u=await hl({canvasRef:s,data:l,mermaidToExcalidrawLib:e,setError:a,mermaidDefinition:r,theme:m});if(!u.success){let h=u.error??new Error("Invalid mermaid definition");a(h)}}catch(u){EV()&&console.error("Failed to parse mermaid definition",u)}})(),KS(r))},[r,e,t,m]),$S(()=>()=>{KS.flush()},[]);let p=()=>{gd({app:c,data:l,text:o,shouldSaveMermaidDataToStorage:!0})};return XS(vV,{children:[Zn("div",{className:"ttd-dialog-desc",children:Zn(ro,{i18nKey:"mermaid.description",flowchartLink:d=>Zn("a",{href:"https://mermaid.js.org/syntax/flowchart.html",children:d}),sequenceLink:d=>Zn("a",{href:"https://mermaid.js.org/syntax/sequenceDiagram.html",children:d}),classLink:d=>Zn("a",{href:"https://mermaid.js.org/syntax/classDiagram.html",children:d})})}),XS(zS,{children:[Zn(xa,{children:Zn(FS,{input:o,placeholder:f("mermaid.inputPlaceholder"),onChange:d=>n(d.target.value),onKeyboardSubmit:()=>{p()}})}),Zn(xa,{panelActions:[{action:()=>{p()},label:f("mermaid.button"),icon:Br,variant:"button"}],renderSubmitShortcut:()=>Zn(GS,{}),children:Zn(qu,{canvasRef:s,loaded:e.loaded,error:i})})]})]})},ZS=wV;import{useRef as $V}from"react";import{useRef as qS,useEffect as SV,useLayoutEffect as MV}from"react";import{KEYS as PV}from"@orangecatai/common";import{jsx as k1,jsxs as IV}from"react/jsx-runtime";var Ju=()=>IV("div",{className:"chat-interface__welcome-screen__welcome-message",children:[k1("h3",{children:f("chat.placeholder.title")}),k1("p",{children:f("chat.placeholder.description")}),k1("p",{children:f("chat.placeholder.hint")})]});import TV from"clsx";import{useState as CV,useEffect as kV}from"react";import{Fragment as jS,jsx as At,jsxs as Jo}from"react/jsx-runtime";var S1=({message:e,onMermaidTabClick:t,onAiRepairClick:o,onDeleteMessage:n,onInsertMessage:r,onRetry:i,rateLimitRemaining:a,isLastMessage:s,renderWarning:l,allowFixingParseError:c})=>{let[m,p]=CV(!1);kV(()=>{if(!e.error||!s)return;if(e.error&&!e.lastAttemptAt){p(!0);return}let u=Date.now()-e.lastAttemptAt,h=Math.max(0,5e3-u);if(h===0){p(!0);return}p(!1);let g=setTimeout(()=>{p(!0)},h);return()=>clearTimeout(g)},[e.error,e.lastAttemptAt,s]);let d=u=>u.toLocaleTimeString([],{hour:"2-digit",minute:"2-digit"});if(e.type==="warning"){let u=l?.(e);return At("div",{className:"chat-message chat-message--system",children:Jo("div",{className:"chat-message__content",children:[Jo("div",{className:"chat-message__header",children:[At("span",{className:"chat-message__role",children:f("chat.role.system")}),At("span",{className:"chat-message__timestamp",children:d(e.timestamp)})]}),At("div",{className:"chat-message__body",children:At("div",{className:"chat-message__text",children:u||(e.warningType==="messageLimitExceeded"?Jo(jS,{children:[f("chat.rateLimit.messageLimit"),At("div",{style:{marginTop:"10px"},children:At(qo,{onClick:()=>{window.open(`${C.VITE_APP_PLUS_LP}/plus?utm_source=excalidraw&utm_medium=app&utm_content=ttdChatBanner#excalidraw-redirect`,"_blank","noopener")},children:f("chat.upsellBtnLabel")})})]}):f("chat.rateLimit.generalRateLimit"))})})]})})}return Jo("div",{className:`chat-message chat-message--${e.type}`,children:[Jo("div",{className:"chat-message__content",children:[Jo("div",{className:"chat-message__header",children:[At("span",{className:"chat-message__role",children:e.type==="user"?f("chat.role.user"):f("chat.role.assistant")}),At("span",{className:"chat-message__timestamp",children:d(e.timestamp)})]}),At("div",{className:"chat-message__body",children:e.error?Jo(jS,{children:[At("div",{className:"chat-message__error",children:e.content}),e.errorType!=="parse"&&Jo("div",{className:"chat-message__error_message",children:["Error: ",e.error||f("chat.errors.generationFailed")]}),e.errorType==="parse"&&c&&Jo("div",{className:"chat-message__error_message",children:[At("p",{children:f("chat.errors.invalidDiagram")}),Jo("div",{className:"chat-message__error-actions",children:[t&&At("button",{className:"chat-message__error-link",onClick:()=>t(e),type:"button",children:f("chat.errors.fixInMermaid")}),o&&At("button",{className:"chat-message__error-link",onClick:()=>o(e),disabled:a===0,type:"button",children:f("chat.errors.aiRepair")})]})]})]}):Jo("div",{className:"chat-message__text",children:[e.content,e.isGenerating&&At("span",{className:"chat-message__cursor",children:"\u258B"})]})})]}),e.type==="assistant"&&!e.isGenerating&&Jo("div",{className:"chat-message__actions",children:[!e.error&&r&&At("button",{className:"chat-message__action",onClick:()=>r(e),type:"button","aria-label":f("chat.insert"),title:f("chat.insert"),children:Cw}),t&&e.content&&At("button",{className:"chat-message__action",onClick:()=>t(e),type:"button","aria-label":f("chat.viewAsMermaid"),title:f("chat.viewAsMermaid"),children:vh}),n&&e.errorType!=="network"&&At("button",{className:"chat-message__action chat-message__action--danger",onClick:()=>n(e.id),type:"button","aria-label":f("chat.deleteMessage"),title:f("chat.deleteMessage"),children:Ht}),e.errorType==="network"&&i&&s&&At("button",{className:TV("chat-message__action",{invisible:!m}),onClick:()=>i(e),type:"button","aria-label":f("chat.retry"),title:f("chat.retry"),children:Tw})]})]})};import{jsx as Pr,jsxs as M1}from"react/jsx-runtime";var P1=({chatId:e,messages:t,currentPrompt:o,onPromptChange:n,onGenerate:r,isGenerating:i,rateLimits:a,onAbort:s,onMermaidTabClick:l,onAiRepairClick:c,onDeleteMessage:m,onInsertMessage:p,onRetry:d,renderWelcomeScreen:u,renderWarning:h})=>{let g=qS(null),E=qS(null);MV(()=>{g.current?.scrollIntoView()},[t]),SV(()=>{E.current&&E.current.focus()},[e]);let w=L=>{let S=L.target.value;n(S)},x=()=>{if(i&&s){s();return}let L=o.trim();L&&(r({prompt:L}),n(""))},y=L=>{L.key===PV.ENTER&&!L.shiftKey&&(L.preventDefault(),i||x())},v=o.trim().length>3&&!i&&(a?.rateLimitRemaining??1)>0,I=i&&!!s,k=L=>{let S=L.target;S.style.height="auto",S.style.height=`${Math.min(S.scrollHeight,120)}px`};return M1("div",{className:"chat-interface",children:[M1("div",{className:"chat-interface__messages",children:[t.length===0?Pr("div",{className:"chat-interface__welcome-screen",children:u?u({rateLimits:a??null}):Pr(Ju,{})}):t.map((L,S)=>Pr(S1,{message:L,onMermaidTabClick:l,onAiRepairClick:c,onDeleteMessage:m,onInsertMessage:p,onRetry:d,rateLimitRemaining:a?.rateLimitRemaining,isLastMessage:S===t.length-1,renderWarning:h,allowFixingParseError:L.errorType==="parse"&&S===t.length-1},L.id)),Pr("div",{ref:g,id:"messages-end"})]}),Pr("div",{className:"chat-interface__input-container",children:Pr("div",{className:"chat-interface__input-outer",children:M1("div",{className:"chat-interface__input-wrapper",style:{borderColor:i?"var(--dialog-border-color)":void 0},children:[Pr("textarea",{ref:E,autoFocus:!0,className:"chat-interface__input",value:o,onChange:w,onKeyDown:y,placeholder:i?f("chat.generating"):a?.rateLimitRemaining===0?f("chat.rateLimit.messageLimitInputPlaceholder"):t.length>0?f("chat.inputPlaceholderWithMessages"):f("chat.inputPlaceholder",{shortcut:"Shift + Enter"}),disabled:a?.rateLimitRemaining===0,rows:1,cols:30,onInput:k}),Pr("button",{className:"chat-interface__send-button",onClick:x,disabled:!v&&!I,type:"button",children:Pr(Bn,{size:"1.5em",icon:i?Ny:Br})})]})})})]})};import{randomId as AV}from"@orangecatai/common";var Qu=Ce(null),eg=Ce(!1),hi=Ce(null),Qo=Ce({id:AV(),messages:[],currentPrompt:""});import{findLastIndex as A1,randomId as LV}from"@orangecatai/common";var fi=(e,t)=>{let{messages:o}=e,n=A1(o,a=>a.type==="assistant");if(n===-1)return e;let r=o[n],i=o.slice();return i[n]={...r,...t},{...e,messages:i}},bi=e=>{let{messages:t}=e,o=A1(t,n=>n.type==="assistant");return t[o]},hd=(e,t)=>{let o=t.map(n=>({...n,id:LV(),timestamp:new Date}));return{...e,messages:[...e.messages,...o]}},JS=e=>{let t=A1(e.messages??[],o=>o.type==="assistant");return t!==-1?{...e,messages:e.messages.filter((o,n)=>n!==t)}:e},QS=e=>{let t=[];for(let o of e.messages)o.content&&(o.type==="user"||o.type==="assistant")&&t.push({role:o.type,content:o.content});return t};var fd=()=>{let[e,t]=ae(Qo);return{addUserMessage:a=>{t(s=>hd(s,[{type:"user",content:a}]))},addAssistantMessage:()=>{t(a=>hd(a,[{type:"assistant",content:"",isGenerating:!0}]))},setAssistantError:(a,s="other",l)=>{let c=l?JSON.stringify({name:l instanceof Error?l.name:"Error",message:l instanceof Error?l.message:String(l),stack:l instanceof Error?l.stack:void 0}):void 0;t(m=>fi(m,{isGenerating:!1,error:a,errorType:s,errorDetails:c}))},chatHistory:e,setChatHistory:t,setLastRetryAttempt:()=>{t(a=>fi(a,{lastAttemptAt:Date.now()}))}}};import{useCallback as bd,useEffect as eM,useRef as _V}from"react";import{randomId as DV}from"@orangecatai/common";var RV=e=>{let t=e.trim();return t.length<=50?t:`${t.substring(0,47)}...`},NV=Ce([]),BV=Ce(!1),FV=Ce(!1),tg=({persistenceAdapter:e})=>{let[t]=ae(Qo),[o,n]=ae(NV),[r,i]=ae(BV),[a,s]=ae(FV),l=_V(o);l.current=o;let c=t?.messages[t?.messages.length-1],m=bd(async()=>{if(!(a||r)){i(!0);try{let g=await e.loadChats();n(g),s(!0)}catch(g){console.warn("Failed to load chats:",g),n([]),s(!0)}finally{i(!1)}}},[a,r,n,i,s,e]);eM(()=>{m()},[]);let p=bd(async()=>{if(t.messages.length===0)return;let g=t.messages.find(k=>k.type==="user");if(!g||typeof g.content!="string")return;let E=RV(g.content),w=l.current,x=w.find(k=>k.id===t.id),y=!x||x.messages.length!==t.messages.length||x.messages.some((k,L)=>k.id!==t.messages[L]?.id||k.content!==t.messages[L]?.content),v={id:t.id,title:E,messages:t.messages.filter(k=>k.type==="user"||k.type==="assistant").map(k=>({...k,timestamp:k.timestamp instanceof Date?k.timestamp:new Date(k.timestamp)})),currentPrompt:t.currentPrompt,timestamp:y?Date.now():x?.timestamp??Date.now()},I=[...w.filter(k=>k.id!==t.id),v].sort((k,L)=>L.timestamp-k.timestamp).slice(0,10);n(I);try{await e.saveChats(I)}catch(k){console.warn("Failed to save chats:",k)}},[t,n,e]);eM(()=>{c?.isGenerating||p()},[t.messages?.length,c?.id,c?.isGenerating]);let d=bd(async g=>{let E=l.current.filter(w=>w.id!==g);n(E);try{await e.saveChats(E)}catch(w){console.warn("Failed to save after delete:",w)}return E},[n,e]),u=bd(g=>g,[]),h=bd(async()=>(await p(),DV()),[p]);return{savedChats:o,saveCurrentChat:p,deleteChat:d,restoreChat:u,createNewChatId:h}};import{useCallback as oM,useEffect as og,useMemo as nM,useRef as Ea}from"react";var tM=e=>{let t=e.trim();if(!t)return!1;let o=(t.match(/\[/g)||[]).length,n=(t.match(/\]/g)||[]).length,r=(t.match(/\{/g)||[]).length,i=(t.match(/\}/g)||[]).length,a=(t.match(/\(/g)||[]).length,s=(t.match(/\)/g)||[]).length;if(o!==n||r!==i||a!==s)return!1;let l=t.split(`
114
114
  `).pop()?.trim()||"";return![/-->$/,/--$/,/-\.$/,/==>$/,/==$/,/~~$/,/::$/,/:$/,/\|$/,/&$/].some(m=>m.test(l))};var L1=300,OV=3e3,zV=100,rM=100,iM=({mermaidToExcalidrawLib:e,canvasRef:t})=>{let[o]=ae(Qo),[,n]=ae(hi),[r,i]=ae(eg),a=Ea(!1),s=nM(()=>bi(o),[o]),l=Ea(s);og(()=>{l.current=s},[s]);let c=Ea({elements:[],files:null}),m=Ea(0),p=Ea(null),d=Ea(!1),u=Ea(L1),{theme:h}=ye(),g=oM(async x=>{if(!x.trim()||!e.loaded||a.current)return!1;a.current=!0;let y=performance.now(),v=await hl({canvasRef:t,data:c,mermaidToExcalidrawLib:e,setError:n,mermaidDefinition:x,theme:h});return performance.now()-y<zV?u.current=L1:u.current=OV,a.current=!1,v.success},[t,e,n,h]),E=nM(()=>{let x=async y=>{let v=Date.now(),I=v-m.current,k=u.current;if(!tM(y)){d.current||(m.current=Math.max(m.current,v-k+rM),d.current=!0),p.current=y;return}if(d.current=!1,I<k){p.current=y;return}p.current=null;let L=await g(y);m.current=Date.now(),L||(m.current=m.current-k+rM,d.current=!0)};return x.flush=async()=>{if(p.current){let y=p.current;p.current=null,await g(y),m.current=Date.now()}},x.cancel=()=>{p.current=null},x},[g]),w=oM(()=>{m.current=0,p.current=null,d.current=!1,u.current=L1},[]);return og(()=>{s?.content&&s?.isGenerating?E(s.content):s?.isGenerating||(E.flush(),w(),s?.content&&E(s.content))},[w,E,s?.isGenerating,s?.content]),og(()=>{let x=l.current;!x?.content||x.error||r&&g(x.content)},[o?.id,g,r]),og(()=>{if(o.messages?.filter(x=>x.type==="assistant").length)r||i(!0);else{let x=t.current;if(x){let y=x.parentElement;y&&(y.style.background="",x.replaceChildren())}i(!1)}},[o.messages,i,t,r]),{data:c}};import{useRef as HV}from"react";import{parseMermaidToExcalidraw as GV}from"@excalidraw/mermaid-to-excalidraw";import{isFiniteNumber as aM}from"@orangecatai/math";var _1=3,D1=1e4,sM=({onTextSubmit:e})=>{let[,t]=ae(hi),[o,n]=ae(Qu),[r,i]=ae(Qo),{addUserMessage:a,addAssistantMessage:s,setAssistantError:l}=fd(),c=HV(null),m=u=>u.length>D1||u.length<_1||o?.rateLimitRemaining===0?(u.length<_1&&t(new Error(f("chat.errors.promptTooShort",{min:_1}))),u.length>D1&&t(new Error(f("chat.errors.promptTooLong",{max:D1}))),!1):!0;return{onGenerate:async({prompt:u,isRepairFlow:h=!1})=>{if(!m(u))return;c.current&&c.current.abort(),t(null);let g=new AbortController;c.current=g,h?i(E=>fi(E,{isGenerating:!0,content:"",error:void 0,errorType:void 0,errorDetails:void 0})):(a(u),s());try{ge("ai","generate","ttd");let w=[...QS(r).slice(-3),{role:"user",content:u}],{generatedResponse:x,error:y,rateLimit:v,rateLimitRemaining:I}=await e({messages:w,onStreamCreated:()=>{h&&i(k=>fi(k,{content:"",error:"",isGenerating:!0}))},onChunk:k=>{i(L=>{let S=bi(L);return fi(L,{content:S.content+k})})},signal:g.signal});if(i(k=>fi(k,{isGenerating:!1})),aM(v)&&aM(I)&&n({rateLimit:v,rateLimitRemaining:I}),(y?.status===429||I===0)&&i(k=>(y?.status===429&&(k=JS(k)),k={...k,messages:k.messages.filter(S=>S.type!=="warning"||S.warningType==="rateLimitExceeded"||S.warningType==="messageLimitExceeded")},hd(k,[{type:"warning",warningType:I===0?"messageLimitExceeded":"rateLimitExceeded"}]))),y){if(y.name==="AbortError"||y.message==="Aborted"||g.signal.aborted)return;let L=new Error(y.message||f("chat.errors.requestFailed"));y.status!==429&&l(L.message,"network"),t(L);return}try{await GV(x??""),ge("ai","mermaid parse success","ttd")}catch(k){ge("ai","mermaid parse failed","ttd");let L=new Error(k.message||f("chat.errors.mermaidParseError"));l(L.message,"parse"),t(L)}}catch(E){let w=new Error(E.message||f("chat.errors.generationFailed"));l(w.message,"other"),t(w)}finally{c.current=null}},handleAbort:()=>{c.current&&c.current.abort()}}};import{useCallback as ya,useState as UV}from"react";var lM=({persistenceAdapter:e})=>{let t=Pn(hi),[o,n]=ae(Qo),[r,i]=UV(!1),{restoreChat:a,deleteChat:s,createNewChatId:l}=tg({persistenceAdapter:e}),c=ya(E=>{let w=E.messages.map(v=>({...v,timestamp:v.timestamp instanceof Date?v.timestamp:new Date(v.timestamp)})),x={id:E.id,messages:w,currentPrompt:""},y=bi(x);t(y?.error?new Error(y?.error):null),n(x)},[t,n]),m=ya(async()=>{let E=await l();n({id:E,messages:[],currentPrompt:""}),t(null)},[l,n,t]),p=ya(E=>{let w=a(E);c(w),i(!1)},[a,c]),d=ya(async(E,w)=>{w.stopPropagation();let x=E===o.id,y=await s(E);if(x)if(y.length>0){let v=y[0];c(v)}else await m()},[o.id,s,c,m]),u=ya(async()=>{await m(),i(!1)},[m]),h=ya(()=>{i(E=>!E)},[]),g=ya(()=>{i(!1)},[]);return{isMenuOpen:r,onRestoreChat:p,handleDeleteChat:d,handleNewChat:u,handleMenuToggle:h,handleMenuClose:g}};import WV from"clsx";import{Fragment as YV,jsx as wa,jsxs as R1}from"react/jsx-runtime";var cM=({isOpen:e,onToggle:t,onClose:o,onNewChat:n,onRestoreChat:r,onDeleteChat:i,isNewChatBtnVisible:a,savedChats:s,activeSessionId:l,disabled:c})=>R1("div",{className:"ttd-chat-history-menu",children:[a&&wa(qo,{onClick:n,disabled:c,children:f("chat.newChat")}),s.length>0&&wa("div",{className:"ttd-dialog-panel__menu-wrapper",children:R1(he,{open:e,children:[wa(he.Trigger,{onToggle:t,className:"ttd-dialog-menu-trigger",disabled:c,title:f("chat.menu"),"aria-label":f("chat.menu"),children:Lw}),wa(he.Content,{onClickOutside:o,onSelect:o,children:wa(YV,{children:s.map(m=>R1(he.ItemCustom,{className:WV("ttd-chat-menu-item",{"ttd-chat-menu-item--active":m.id===l}),onClick:()=>{r(m)},children:[wa("span",{className:"ttd-chat-menu-item__title",children:m.title}),wa("button",{className:"ttd-chat-menu-item__delete",onClick:p=>i(m.id,p),title:f("chat.deleteChat"),"aria-label":f("chat.deleteChat"),type:"button",children:Ht})]},m.id))})})]})})]});import{jsx as bl,jsxs as VV}from"react/jsx-runtime";var dM=({chatId:e,messages:t,currentPrompt:o,onPromptChange:n,onGenerate:r,isGenerating:i,generatedResponse:a,isMenuOpen:s,onMenuToggle:l,onMenuClose:c,onNewChat:m,onRestoreChat:p,onDeleteChat:d,savedChats:u,activeSessionId:h,onAbort:g,onMermaidTabClick:E,onAiRepairClick:w,onDeleteMessage:x,onInsertMessage:y,onRetry:v,onViewAsMermaid:I,renderWelcomeScreen:k,renderWarning:L})=>{let[S]=ae(Qu),P=(()=>{let M=[];return S&&M.push({label:f("chat.rateLimitRemaining",{count:S.rateLimitRemaining}),variant:"rateLimit",className:S.rateLimitRemaining<5?"ttd-dialog-panel__rate-limit--danger":""}),a&&M.push({action:I,label:f("chat.viewAsMermaid"),icon:bl(Bn,{icon:Br}),variant:"link"}),M})(),T=()=>P.length===2?"space-between":P.length===1&&P[0].variant==="rateLimit"?"flex-start":"flex-end";return bl(xa,{label:VV("div",{className:"ttd-dialog-panel__label-wrapper",children:[bl("div",{className:"ttd-dialog-panel__label-group"}),bl("div",{className:"ttd-dialog-panel__header-right",children:bl(cM,{isNewChatBtnVisible:!!t.length,isOpen:s,onToggle:l,onClose:c,onNewChat:m,onRestoreChat:p,onDeleteChat:d,savedChats:u,activeSessionId:h,disabled:i})})]}),className:"ttd-dialog-chat-panel",panelActionJustifyContent:T(),panelActions:P,children:bl(P1,{chatId:e,messages:t,currentPrompt:o,onPromptChange:n,onGenerate:r,isGenerating:i,generatedResponse:a,onAbort:g,onMermaidTabClick:E,onAiRepairClick:w,onDeleteMessage:x,onInsertMessage:y,onRetry:v,rateLimits:S,renderWelcomeScreen:k,renderWarning:L})})};import{jsx as mM}from"react/jsx-runtime";var pM=({canvasRef:e,error:t,loaded:o,onInsert:n,hideErrorDetails:r})=>{let i=[{action:n,label:f("chat.insert"),icon:Br,variant:"button"}];return mM(xa,{panelActionJustifyContent:"flex-end",panelActions:i,className:"ttd-dialog-preview-panel",children:mM(qu,{canvasRef:e,error:t,loaded:o,hideErrorDetails:r})})};import{jsx as N1,jsxs as ZV}from"react/jsx-runtime";var KV=({mermaidToExcalidrawLib:e,onTextSubmit:t,renderWelcomeScreen:o,renderWarning:n,persistenceAdapter:r})=>{let i=Qe(),a=ve(),s=$V(null),[l,c]=ae(hi),[m,p]=ae(Qo),d=Ha(eg),{savedChats:u}=tg({persistenceAdapter:r}),h=bi(m),{setLastRetryAttempt:g}=fd(),{data:E}=iM({canvasRef:s,mermaidToExcalidrawLib:e}),{onGenerate:w,handleAbort:x}=sM({onTextSubmit:t}),{isMenuOpen:y,onRestoreChat:v,handleDeleteChat:I,handleNewChat:k,handleMenuToggle:L,handleMenuClose:S}=lM({persistenceAdapter:r}),_=()=>{typeof h?.content=="string"&&(fl(h.content),a({openDialog:{name:"ttd",tab:"mermaid"}}))},P=D=>{let F=D.content||"";F&&(fl(F),a({openDialog:{name:"ttd",tab:"mermaid"}}))},T=async D=>{let F=D.content||"";if(!F.trim()||!e.loaded)return;let z={current:{elements:[],files:null}};(await hl({canvasRef:s,data:z,mermaidToExcalidrawLib:e,setError:c,mermaidDefinition:F,theme:i.state.theme})).success&&gd({app:i,data:z,text:F,shouldSaveMermaidDataToStorage:!0})},M=async D=>{let F=D.content||"",z=D.error||"";if(!F)return;let $=`Fix the error in this Mermaid diagram. The diagram is:
115
115
 
116
116
  \`\`\`mermaid
@@ -119,7 +119,7 @@ ${F}
119
119
 
120
120
  The exception/error is: ${z}
121
121
 
122
- Please fix the Mermaid syntax and regenerate a valid diagram.`;await w({prompt:$,isRepairFlow:!0})},N=async D=>{let F=m.messages.findIndex(z=>z.id===D.id);if(F>0){let z=m.messages[F-1];z.type==="user"&&typeof z.content=="string"&&(g(),await w({prompt:z.content,isRepairFlow:!0}))}},O=()=>{gd({app:i,data:E})},B=D=>{let F=m.messages.findIndex($=>$.id===D&&$.type==="assistant"),z=m.messages.slice(0,F-1);p({...m,messages:z})},U=D=>{p(F=>({...F,currentPrompt:D}))};return ZV("div",{className:`ttd-dialog-layout ${d?"ttd-dialog-layout--split":"ttd-dialog-layout--chat-only"}`,children:[N1(dM,{chatId:m.id,messages:m.messages,currentPrompt:m.currentPrompt,onPromptChange:U,onGenerate:w,isGenerating:h?.isGenerating??!1,generatedResponse:h?.content,isMenuOpen:y,onMenuToggle:L,onMenuClose:S,onNewChat:k,onRestoreChat:v,onDeleteChat:I,savedChats:u,activeSessionId:m.id,onAbort:x,onMermaidTabClick:P,onAiRepairClick:M,onDeleteMessage:B,onInsertMessage:T,onRetry:N,onViewAsMermaid:_,renderWarning:n,renderWelcomeScreen:o}),d&&N1(pM,{canvasRef:s,hideErrorDetails:h?.errorType==="parse",error:l,loaded:e.loaded,onInsert:O})]})},XV=({mermaidToExcalidrawLib:e,onTextSubmit:t,renderWelcomeScreen:o,renderWarning:n,persistenceAdapter:r})=>N1(KV,{mermaidToExcalidrawLib:e,onTextSubmit:t,renderWelcomeScreen:o,renderWarning:n,persistenceAdapter:r}),uM=XV;import{Tabs as jV}from"radix-ui";import{useRef as gM}from"react";import{isMemberOf as qV}from"@orangecatai/common";import{jsx as JV}from"react/jsx-runtime";var hM=e=>{let t=ve(),o=gM(null),n=gM(0);return JV(jV.Root,{ref:o,className:"ttd-dialog-tabs-root",value:e.tab,onValueChange:r=>{if(!r)return;let i=o.current?.closest(".Modal__content");if(i){let a=i.offsetHeight||0;a>n.current&&(n.current=a,i.style.minHeight=`min(${n.current}px, 100%)`)}e.dialog==="ttd"&&qV(["text-to-diagram","mermaid"],r)&&t({openDialog:{name:e.dialog,tab:r}})},children:e.children})};hM.displayName="TTDDialogTabs";var fM=hM;import{Tabs as QV}from"radix-ui";import{jsx as e$}from"react/jsx-runtime";var B1=({children:e,...t})=>e$(QV.List,{className:"ttd-dialog-triggers",...t,children:e});B1.displayName="TTDDialogTabTriggers";import{Tabs as t$}from"radix-ui";import{jsx as bM}from"react/jsx-runtime";var ng=({children:e,tab:t,onSelect:o,...n})=>bM(t$.Trigger,{value:t,asChild:!0,onSelect:o,children:bM("button",{type:"button",className:"ttd-dialog-tab-trigger",...n,children:e})});ng.displayName="TTDDialogTabTrigger";import{Tabs as o$}from"radix-ui";import{jsx as n$}from"react/jsx-runtime";var rg=({tab:e,children:t,...o})=>n$(o$.Content,{...o,value:e,children:t});rg.displayName="TTDDialogTab";import{jsx as jn,jsxs as F1}from"react/jsx-runtime";var ig=e=>{let t=ye();return t.openDialog?.name!=="ttd"?null:jn(a$,{...e,tab:t.openDialog.tab})};ig.WelcomeMessage=Ju;var a$=Mr("TTDDialogBase",({tab:e,...t})=>{let o=Qe(),[n,r]=i$({loaded:!1,api:import("@excalidraw/mermaid-to-excalidraw")});return r$(()=>{(async()=>{await n.api,r(a=>({...a,loaded:!0}))})()},[n.api]),jn(ht,{className:"ttd-dialog",onCloseRequest:()=>{o.setOpenDialog(null)},size:1520,title:!1,...t,autofocus:!1,children:F1(fM,{dialog:"ttd",tab:e,children:["__fallback"in t&&t.__fallback?jn("p",{className:"dialog-mermaid-title",children:f("mermaid.title")}):F1(B1,{children:[jn(ng,{tab:"text-to-diagram",children:F1("div",{className:"ttd-dialog-tab-trigger__content",children:[f("labels.textToDiagram"),jn("div",{className:"ttd-dialog-tab-trigger__badge",children:f("chat.aiBeta")})]})}),jn(ng,{tab:"mermaid",children:f("mermaid.label")})]}),!("__fallback"in t)&&jn(rg,{className:"ttd-dialog-content",tab:"text-to-diagram",children:jn(uM,{mermaidToExcalidrawLib:n,onTextSubmit:t.onTextSubmit,renderWelcomeScreen:t.renderWelcomeScreen,renderWarning:t.renderWarning,persistenceAdapter:t.persistenceAdapter})}),jn(rg,{className:"ttd-dialog-content",tab:"mermaid",children:jn(ZS,{mermaidToExcalidrawLib:n,isActive:e==="mermaid"})})]})})});import{round as r4}from"@orangecatai/math";import yK from"clsx";import wK from"lodash.throttle";import{useEffect as i4,useMemo as q1,useState as vK,memo as IK}from"react";import{STATS_PANELS as ug}from"@orangecatai/common";import{getCommonBounds as TK}from"@orangecatai/element";import{getUncroppedWidthAndHeight as CK}from"@orangecatai/element";import{isImageElement as J1}from"@orangecatai/element";import{frameAndChildrenSelectedTogether as kK}from"@orangecatai/element";import{elementsAreInSameGroup as SK}from"@orangecatai/element";import{degreesToRadians as CM,radiansToDegrees as PM}from"@orangecatai/math";import{getBoundTextElement as kM}from"@orangecatai/element";import{isArrowElement as SM,isElbowArrow as E$}from"@orangecatai/element";import{updateBindings as MM}from"@orangecatai/element";import u$ from"clsx";import{useEffect as IM,useRef as sg,useState as g$}from"react";import{EVENT as yl,KEYS as h$,cloneJSON as O1}from"@orangecatai/common";import{deepCopyElement as f$}from"@orangecatai/element";import{CaptureUpdateAction as TM}from"@orangecatai/element";import{pointFrom as xi,pointRotateRads as ag}from"@orangecatai/math";import{getBoundTextElement as s$,isBindingElement as l$,unbindBindingElement as xM}from"@orangecatai/element";import{isFrameLikeElement as wM}from"@orangecatai/element";import{getSelectedGroupIds as c$,getElementsInGroup as d$,isInGroup as m$}from"@orangecatai/element";import{getFrameChildren as p$}from"@orangecatai/element";import{updateBindings as EM}from"@orangecatai/element";import{DRAGGING_THRESHOLD as yM}from"@orangecatai/common";var vM=.01,xd=10,Eo=(e,t)=>!(t==="angle"&&wM(e)),at=(e,t)=>{let o=e+t/2;return o-o%t},xl=(e,t,o)=>Object.keys(e).map(n=>({original:(o??t).get(n),latest:t.get(n)})).filter(n=>n.original!==void 0&&n.latest!==void 0);var va=(e,t,o,n,r,i,a=!0)=>{if(l$(o)&&(o.startBinding||o.endBinding)){if(Math.abs(e-o.x)<yM&&Math.abs(t-o.y)<yM)return;xM(o,"start",n),xM(o,"end",n)}let s=n.getNonDeletedElementsMap(),l=s.get(o.id);if(!l)return;let[c,m]=[o.x+o.width/2,o.y+o.height/2],[p,d]=ag(xi(o.x,o.y),xi(c,m),o.angle),u=e-p,h=t-d,[g,E]=ag(xi(e,t),xi(c+u,m+h),-o.angle);n.mutateElement(l,{x:g,y:E},{informMutation:a,isDragging:!1}),EM(l,n,r);let w=s$(o,i);if(w){let x=s.get(w.id);x&&n.mutateElement(x,{x:w.x+u,y:w.y+h},{informMutation:a,isDragging:!1})}if(wM(o)){let x=p$(i,o.id);x.forEach(y=>{let v=s.get(y.id);if(!v)return;let[I,k]=[y.x+y.width/2,y.y+y.height/2],[L,S]=ag(xi(y.x,y.y),xi(I,k),y.angle),_=Math.round(L+u),P=Math.round(S+h),[T,M]=ag(xi(_,P),xi(I+u,k+h),-y.angle);n.mutateElement(v,{x:T,y:M},{informMutation:a,isDragging:!1}),EM(v,n,r,{simultaneouslyUpdated:x})})}},El=(e,t)=>{let n=c$(t).map(r=>d$(e,r).reduce((i,a)=>(i[a.id]=!0,i),{}));return e.filter(r=>!m$(r)).forEach(r=>{n.push({[r.id]:!0})}),n};import{jsx as z1,jsxs as x$}from"react/jsx-runtime";var b$=({label:e,icon:t,dragInputCallback:o,value:n,elements:r,editable:i=!0,shouldKeepAspectRatio:a,property:s,scene:l,appState:c,sensitivity:m=1,dragFinishedCallback:p})=>{let d=Qe(),u=ve(),h=sg(null),g=sg(null),[E,w]=g$(n.toString()),x=sg(null);x.current||(x.current={originalAppState:O1(c),originalElements:r,lastUpdatedValue:E,updatePending:!1}),IM(()=>{let I=n.toString();w(I),x.current.lastUpdatedValue=I},[n]);let y=(I,k,L)=>{if(!x.current.updatePending)return!1;x.current.updatePending=!1;let S=Number(I);if(isNaN(S)){w(n.toString());return}let _=Number(S.toFixed(2)),P=Number(n);(isNaN(P)||Math.abs(_-P)>=vM)&&(x.current.lastUpdatedValue=I,o({accumulatedChange:0,instantChange:0,originalElements:k,originalElementsMap:d.scene.getNonDeletedElementsMap(),shouldKeepAspectRatio:a,shouldChangeByStepSize:!1,scene:l,nextValue:_,property:s,originalAppState:L,setInputValue:T=>w(String(T)),app:d,setAppState:u}),d.syncActionResult({captureUpdate:TM.IMMEDIATELY}))},v=sg({});return v.current.handleInputValue=y,IM(()=>{let I=h.current,k=v.current;return()=>{let L=I?.value;L&&k.handleInputValue?.(L,x.current.originalElements,x.current.originalAppState),window.removeEventListener(yl.POINTER_MOVE,k.onPointerMove,!1),window.removeEventListener(yl.POINTER_UP,k.onPointerUp,!1)}},[i]),i?x$("div",{className:u$("drag-input-container",!i&&"disabled"),"data-testid":e,children:[z1("div",{className:"drag-input-label",ref:g,onPointerDown:I=>{if(h.current&&i){document.body.classList.add("excalidraw-cursor-resize");let k=Number(h.current.value);isNaN(k)&&(k=0);let L=null,S=d.scene.getNonDeletedElements().reduce((B,U)=>(B.set(U.id,f$(U)),B),new Map),_=r.map(B=>S.get(B.id)),P=O1(c),T=0,M=0,N=B=>{if(L&&S!==null&&_!==null){let U=B.clientX-L.x;U!==0&&(M+=U,Math.abs(M)>=m&&(M=Math.sign(M)*Math.floor(Math.abs(M)/m),T+=M,o({accumulatedChange:T,instantChange:M,originalElements:_,originalElementsMap:S,shouldKeepAspectRatio:a,shouldChangeByStepSize:B.shiftKey,property:s,scene:l,originalAppState:P,setInputValue:D=>w(String(D)),app:d,setAppState:u}),M=0))}L={x:B.clientX,y:B.clientY}},O=()=>{window.removeEventListener(yl.POINTER_MOVE,N,!1),d.syncActionResult({captureUpdate:TM.IMMEDIATELY}),p?.({app:d,setAppState:u,originalElements:_,originalAppState:P}),L=null,T=0,M=0,_=null,S=null,document.body.classList.remove("excalidraw-cursor-resize"),window.removeEventListener(yl.POINTER_UP,O,!1)};v.current.onPointerMove=N,v.current.onPointerUp=O,window.addEventListener(yl.POINTER_MOVE,N,!1),window.addEventListener(yl.POINTER_UP,O,!1)}},onPointerEnter:()=>{g.current&&(g.current.style.cursor="ew-resize")},children:t?z1(Bn,{icon:t}):e}),z1("input",{className:"drag-input",autoComplete:"off",spellCheck:"false",onKeyDown:I=>{if(i){let k=I.target;k instanceof HTMLInputElement&&I.key===h$.ENTER&&(y(k.value,r,c),d.focusContainer())}},ref:h,value:E,onChange:I=>{x.current.updatePending=!0,w(I.target.value)},onFocus:I=>{I.target.select(),x.current.originalElements=r,x.current.originalAppState=O1(c)},onBlur:I=>{E?i&&y(I.target.value,x.current.originalElements,x.current.originalAppState):w(n.toString())},disabled:!i})]}):null},Ot=b$;import{jsx as I$}from"react/jsx-runtime";var y$=15,w$=({accumulatedChange:e,originalElements:t,shouldChangeByStepSize:o,nextValue:n,scene:r,app:i})=>{let a=r.getNonDeletedElementsMap(),s=t[0];if(s&&!E$(s)){let l=a.get(s.id);if(!l)return;if(n!==void 0){let h=CM(n);r.mutateElement(l,{angle:h}),MM(l,r,i.state);let g=kM(l,a);g&&!SM(l)&&r.mutateElement(g,{angle:h});return}let c=Math.round(PM(s.angle)*100)/100,m=Math.round(e),p=(c+m)%360;o&&(p=at(p,y$)),p=p<0?p+360:p;let d=CM(p);r.mutateElement(l,{angle:d}),MM(l,r,i.state);let u=kM(l,a);u&&!SM(l)&&r.mutateElement(u,{angle:d})}},v$=({element:e,scene:t,appState:o,property:n})=>I$(Ot,{label:"A",icon:gm,value:Math.round(PM(e.angle)%360*100)/100,elements:[e],dragInputCallback:w$,editable:Eo(e,"angle"),scene:t,appState:o,property:n}),AM=v$;import{jsx as C$}from"react/jsx-runtime";var LM=5,T$=({property:e,scene:t,appState:o,setAppState:n})=>C$(Ot,{label:"Grid step",sensitivity:8,elements:[],dragInputCallback:({nextValue:r,instantChange:i,shouldChangeByStepSize:a,setInputValue:s})=>{n(l=>{let c;return r?c=r:i&&(c=a?at(l.gridStep+LM*Math.sign(i),LM):l.gridStep+i),c?(c=OE(c),s(c),{gridStep:c}):(s(l.gridStep),null)})},scene:t,value:o.gridStep,property:e,appState:o}),_M=T$;import{clamp as lg,round as H1}from"@orangecatai/math";import{MIN_WIDTH_OR_HEIGHT as cg}from"@orangecatai/common";import{MINIMAL_CROP_SIZE as DM,getUncroppedWidthAndHeight as BM}from"@orangecatai/element";import{resizeSingleElement as RM}from"@orangecatai/element";import{isImageElement as FM}from"@orangecatai/element";import{isFrameLikeElement as G1}from"@orangecatai/element";import{getElementsInResizingFrame as U1}from"@orangecatai/element";import{replaceAllElementsInFrame as OM}from"@orangecatai/element";import{jsx as A$}from"react/jsx-runtime";var NM=10,k$=e=>e.type==="image",S$=({accumulatedChange:e,originalElements:t,originalElementsMap:o,shouldKeepAspectRatio:n,shouldChangeByStepSize:r,nextValue:i,property:a,originalAppState:s,instantChange:l,scene:c,app:m,setAppState:p})=>{let d=c.getNonDeletedElementsMap(),u=t[0],h=d.get(u.id);if(u&&h){let g=n||k$(u),E=u.width/u.height;if(s.croppingElementId===u.id){let w=d.get(u.id);if(!w||!FM(w)||!w.crop)return;let x=w.crop,y={...x},v=w.scale[0]===-1,I=w.scale[1]===-1,{width:k,height:L}=BM(w),S=x.naturalWidth/k,_=x.naturalHeight/L,P=v?x.width+x.x:x.naturalWidth-x.x,T=I?x.height+x.y:x.naturalHeight-x.y,M=DM*S,N=DM*_;if(i!==void 0){if(a==="width"){let F=i*S,z=lg(F,M,P);y={...y,width:z,x:v?x.x+x.width-z:x.x}}else if(a==="height"){let F=i*_,z=lg(F,N,T);y={...y,height:z,y:I?x.y+x.height-z:x.y}}c.mutateElement(w,{crop:y,width:y.width/(x.naturalWidth/k),height:y.height/(x.naturalHeight/L)});return}let O=a==="width"?l:0,B=a==="height"?l:0,U=lg(x.width+O,M,P),D=lg(x.height+B,M,T);y={...x,x:v?x.x+x.width-U:x.x,y:I?x.y+x.height-D:x.y,width:U,height:D},c.mutateElement(w,{crop:y,width:y.width/(x.naturalWidth/k),height:y.height/(x.naturalHeight/L)});return}if(i!==void 0){let w=Math.max(a==="width"?i:g?i*E:u.width,cg),x=Math.max(a==="height"?i:g?i/E:u.height,cg);if(RM(w,x,h,u,o,c,a==="width"?"e":"s",{shouldMaintainAspectRatio:g}),G1(h)){let y=U1(c.getElementsIncludingDeleted(),h,s,c.getNonDeletedElementsMap()),v=OM(c.getElementsIncludingDeleted(),y,h,m);c.replaceAllElements(v)}return}{let w=a==="width"?e:0,x=a==="height"?e:0,y=Math.max(0,u.width+w);a==="width"&&(r?y=at(y,NM):y=Math.round(y));let v=Math.max(0,u.height+x);if(a==="height"&&(r?v=at(v,NM):v=Math.round(v)),g&&(a==="width"?v=Math.round(y/E*100)/100:y=Math.round(v*E*100)/100),v=Math.max(cg,v),y=Math.max(cg,y),RM(y,v,h,u,o,c,a==="width"?"e":"s",{shouldMaintainAspectRatio:g}),G1(h)){let I=U1(c.getElementsIncludingDeleted(),h,s,c.getNonDeletedElementsMap());p({elementsToHighlight:I})}}}},M$=({setAppState:e,app:t,originalElements:o,originalAppState:n})=>{let r=t.scene.getNonDeletedElementsMap(),i=o?.[0],a=i&&r.get(i.id);if(a&&G1(a)){let s=U1(t.scene.getElementsIncludingDeleted(),a,n,t.scene.getNonDeletedElementsMap()),l=OM(t.scene.getElementsIncludingDeleted(),s,a,t);t.scene.replaceAllElements(l),e({elementsToHighlight:null})}},P$=({property:e,element:t,scene:o,appState:n})=>{let r=H1(e==="width"?t.width:t.height,2);if(n.croppingElementId&&n.croppingElementId===t.id&&FM(t)&&t.crop){let{width:i,height:a}=BM(t);if(e==="width"){let s=i/t.crop.naturalWidth;r=H1(t.crop.width*s,2)}if(e==="height"){let s=a/t.crop.naturalHeight;r=H1(t.crop.height*s,2)}}return A$(Ot,{label:e==="width"?"W":"H",elements:[t],dragInputCallback:S$,value:r,editable:Eo(t,e),scene:o,appState:n,property:e,dragFinishedCallback:M$})},W1=P$;import{getBoundTextElement as L$,redrawTextBoundingBox as _$}from"@orangecatai/element";import{hasBoundTextElement as D$,isTextElement as HM}from"@orangecatai/element";import{jsx as F$}from"react/jsx-runtime";var zM=4,R$=4,N$=({accumulatedChange:e,originalElements:t,shouldChangeByStepSize:o,nextValue:n,scene:r})=>{let i=r.getNonDeletedElementsMap(),a=t[0];if(a){let s=i.get(a.id);if(!s||!HM(s))return;let l;if(n!==void 0)l=Math.max(Math.round(n),zM);else if(a.type==="text"){let c=Math.round(a.fontSize),m=Math.round(e);l=Math.max(c+m,zM),o&&(l=at(l,R$))}l&&(r.mutateElement(s,{fontSize:l}),_$(s,r.getContainerElement(s),r))}},B$=({element:e,scene:t,appState:o,property:n})=>{let r=HM(e)?e:D$(e)?L$(e,t.getNonDeletedElementsMap()):null;return r?F$(Ot,{label:"F",value:Math.round(r.fontSize*10)/10,elements:[r],dragInputCallback:N$,icon:Hi,appState:o,scene:t,property:n}):null},GM=B$;import{degreesToRadians as UM,radiansToDegrees as VM}from"@orangecatai/math";import{getBoundTextElement as WM}from"@orangecatai/element";import{isArrowElement as YM}from"@orangecatai/element";import{isInGroup as Y1}from"@orangecatai/element";import{jsx as G$}from"react/jsx-runtime";var O$=15,z$=({accumulatedChange:e,originalElements:t,shouldChangeByStepSize:o,nextValue:n,property:r,scene:i})=>{let a=i.getNonDeletedElementsMap(),s=t.map(c=>a.get(c.id)).filter(c=>c&&!Y1(c)&&Eo(c,r)),l=t.filter(c=>!Y1(c)&&Eo(c,r));if(n!==void 0){let c=UM(n);for(let m of s){if(!m)continue;i.mutateElement(m,{angle:c});let p=WM(m,a);p&&!YM(m)&&i.mutateElement(p,{angle:c})}i.triggerUpdate();return}for(let c=0;c<s.length;c++){let m=s[c];if(!m)continue;let p=l[c],d=Math.round(VM(p.angle)*100)/100,u=Math.round(e),h=(d+u)%360;o&&(h=at(h,O$)),h=h<0?h+360:h;let g=UM(h);i.mutateElement(m,{angle:g});let E=WM(m,a);E&&!YM(m)&&i.mutateElement(E,{angle:g})}i.triggerUpdate()},H$=({elements:e,scene:t,appState:o,property:n})=>{let r=e.filter(l=>!Y1(l)&&Eo(l,"angle")),i=r.map(l=>Math.round(VM(l.angle)%360*100)/100),a=new Set(i).size===1?i[0]:"Mixed",s=r.some(l=>Eo(l,"angle"));return G$(Ot,{label:"A",icon:gm,value:a,elements:e,dragInputCallback:z$,editable:s,appState:o,scene:t,property:n})},$M=H$;import{pointFrom as KM}from"@orangecatai/math";import{useMemo as U$}from"react";import{MIN_WIDTH_OR_HEIGHT as Ei}from"@orangecatai/common";import{getElementsInResizingFrame as V1,isFrameLikeElement as $1,replaceAllElementsInFrame as jM,updateBoundElements as W$}from"@orangecatai/element";import{rescalePointsInElement as Y$,resizeSingleElement as XM}from"@orangecatai/element";import{getBoundTextElement as V$,handleBindTextResize as $$}from"@orangecatai/element";import{isTextElement as qM}from"@orangecatai/element";import{getCommonBounds as dg}from"@orangecatai/element";import{jsx as J$}from"react/jsx-runtime";var wl=10,K$=(e,t,o,n)=>{let r=n.x-e,i=n.y-t,a=n.width*o,s=n.height*o,l=e+r*o,c=t+i*o;return{width:a,height:s,x:l,y:c,...Y$(n,a,s,!1),...qM(n)?{fontSize:n.fontSize*o}:{}}},X$=(e,t,o,n,r,i,a,s)=>{let l=s.getNonDeletedElementsMap(),c=K$(e,t,n,i);s.mutateElement(r,c);let m=V$(i,a);if(m){let p=m.fontSize*n;W$(r,s);let d=l.get(m.id);d&&qM(d)&&(s.mutateElement(d,{fontSize:p}),$$(r,s,o==="width"?"e":"s",!0))}},ZM=(e,t,o,n,r,i,a,s,l,c)=>{i==="width"?t=Math.round(e/n*100)/100:e=Math.round(t*n*100)/100;let m=t/o;for(let p=0;p<s.length;p++){let d=s[p],u=a[p];X$(r[0],r[1],i,m,u,d,l,c)}},Z$=({accumulatedChange:e,originalElements:t,originalElementsMap:o,originalAppState:n,shouldChangeByStepSize:r,nextValue:i,scene:a,property:s,setAppState:l,app:c})=>{let m=a.getNonDeletedElementsMap(),p=El(t,n);if(i!==void 0){for(let g of p){let E=xl(g,m,o);if(E.length>1){let w=E.map(M=>M.latest),x=E.map(M=>M.original),[y,v,I,k]=dg(x),L=I-y,S=k-v,_=L/S,P=Math.max(Ei,s==="width"?Math.max(0,i):L),T=Math.max(Ei,s==="height"?Math.max(0,i):S);ZM(P,T,S,_,KM(y,v),s,w,x,o,a)}else{let[w]=E,x=w?.latest,y=w?.original;if(x&&y&&Eo(x,s)){let v=s==="width"?Math.max(0,i):x.width;s==="width"&&(r?v=at(v,wl):v=Math.round(v));let I=s==="height"?Math.max(0,i):x.height;if(s==="height"&&(r?I=at(I,wl):I=Math.round(I)),v=Math.max(Ei,v),I=Math.max(Ei,I),XM(v,I,x,y,o,a,s==="width"?"e":"s",{shouldInformMutation:!1}),$1(x)){let k=V1(a.getElementsIncludingDeleted(),x,n,a.getNonDeletedElementsMap()),L=jM(a.getElementsIncludingDeleted(),k,x,c);a.replaceAllElements(L)}}}}a.triggerUpdate();return}let d=s==="width"?e:0,u=s==="height"?e:0,h=[];for(let g of p){let E=xl(g,m,o);if(E.length>1){let w=E.map(M=>M.latest),x=E.map(M=>M.original),[y,v,I,k]=dg(x),L=I-y,S=k-v,_=L/S,P=Math.max(0,L+d);s==="width"&&(r?P=at(P,wl):P=Math.round(P));let T=Math.max(0,S+u);s==="height"&&(r?T=at(T,wl):T=Math.round(T)),P=Math.max(Ei,P),T=Math.max(Ei,T),ZM(P,T,S,_,KM(y,v),s,w,x,o,a)}else{let[w]=E,x=w?.latest,y=w?.original;if(x&&y&&Eo(x,s)){let v=Math.max(0,y.width+d);s==="width"&&(r?v=at(v,wl):v=Math.round(v));let I=Math.max(0,y.height+u);if(s==="height"&&(r?I=at(I,wl):I=Math.round(I)),v=Math.max(Ei,v),I=Math.max(Ei,I),XM(v,I,x,y,o,a,s==="width"?"e":"s",{shouldInformMutation:!1}),$1(x)){let k=V1(a.getElementsIncludingDeleted(),x,n,a.getNonDeletedElementsMap());h.push(...k)}}}}l({elementsToHighlight:h}),a.triggerUpdate()},j$=({setAppState:e,app:t,originalElements:o,originalAppState:n})=>{let r=t.scene.getNonDeletedElementsMap(),i=o?.[0],a=i&&r.get(i.id);if(a&&$1(a)){let s=V1(t.scene.getElementsIncludingDeleted(),a,n,t.scene.getNonDeletedElementsMap()),l=jM(t.scene.getElementsIncludingDeleted(),s,a,t);t.scene.replaceAllElements(l),e({elementsToHighlight:null})}},q$=({property:e,elements:t,elementsMap:o,atomicUnits:n,scene:r,appState:i})=>{let a=U$(()=>n.map(c=>{let m=xl(c,o);if(m.length>1){let[d,u,h,g]=dg(m.map(E=>E.latest));return Math.round((e==="width"?h-d:g-u)*100)/100}let[p]=m;return Math.round((e==="width"?p.latest.width:p.latest.height)*100)/100}),[o,n,e]),s=new Set(a).size===1?Math.round(a[0]*100)/100:"Mixed",l=a.length>0;return J$(Ot,{label:e==="width"?"W":"H",elements:t,dragInputCallback:Z$,value:s,editable:l,appState:i,property:e,scene:r,dragFinishedCallback:j$})},K1=q$;import{getBoundTextElement as Q$,redrawTextBoundingBox as JM}from"@orangecatai/element";import{hasBoundTextElement as eK,isTextElement as tK}from"@orangecatai/element";import{isInGroup as oK}from"@orangecatai/element";import{jsx as sK}from"react/jsx-runtime";var QM=4,nK=4,rK=(e,t)=>e.reduce((o,n)=>{if(!n||oK(n))return o;if(tK(n))return o.push(n),o;if(eK(n)){let r=Q$(n,t);if(r)return o.push(r),o}return o},[]),iK=({accumulatedChange:e,originalElements:t,shouldChangeByStepSize:o,nextValue:n,scene:r})=>{let i=r.getNonDeletedElementsMap(),a=t.map(l=>i.get(l.id)),s;if(n){s=Math.max(Math.round(n),QM);for(let l of a)r.mutateElement(l,{fontSize:s}),JM(l,r.getContainerElement(l),r);r.triggerUpdate()}else{let l=t;for(let c=0;c<a.length;c++){let m=a[c],p=l[c],d=Math.round(p.fontSize),u=Math.round(e),h=Math.max(d+u,QM);o&&(h=at(h,nK)),r.mutateElement(m,{fontSize:h}),JM(m,r.getContainerElement(m),r)}r.triggerUpdate()}},aK=({elements:e,scene:t,appState:o,property:n,elementsMap:r})=>{let i=rK(e,r);if(!i.length)return null;let a=i.map(c=>Math.round(c.fontSize*10)/10),s=new Set(a).size===1?a[0]:"Mixed",l=a.length>0;return sK(Ot,{label:"F",icon:Hi,elements:i,dragInputCallback:iK,value:s,editable:l,scene:t,property:n,appState:o})},e4=aK;import{pointFrom as yi,pointRotateRads as mg}from"@orangecatai/math";import{useMemo as lK}from"react";import{isTextElement as cK}from"@orangecatai/element";import{getCommonBounds as X1}from"@orangecatai/element";import{jsx as gK}from"react/jsx-runtime";var dK=(e,t,o,n,r,i,a)=>{for(let s=0;s<n.length;s++){let l=n[s],[c,m]=[l.x+l.width/2,l.y+l.height/2],[p,d]=mg(yi(l.x,l.y),yi(c,m),l.angle),u=e==="x"?Math.round(p+t):p,h=e==="y"?Math.round(d+o):d;va(u,h,l,i,a,r,!1)}},mK=(e,t,o,n,r,i)=>{let a=r.getNonDeletedElementsMap(),[s,l,,]=X1(o),c=e-s,m=t-l;for(let p=0;p<o.length;p++){let d=o[p],u=a.get(d.id);if(u&&(!cK(u)||!u.containerId)){let[h,g]=[u.x+u.width/2,u.y+u.height/2],[E,w]=mg(yi(u.x,u.y),yi(h,g),u.angle);va(E+c,w+m,d,r,i,n,!1)}}},pK=({accumulatedChange:e,originalElements:t,originalElementsMap:o,shouldChangeByStepSize:n,nextValue:r,property:i,scene:a,originalAppState:s,app:l})=>{let c=a.getNonDeletedElementsMap();if(r!==void 0){for(let u of El(t,s)){let h=xl(u,c,o);if(h.length>1){let[g,E,,]=X1(h.map(y=>y.latest));mK(i==="x"?r:g,i==="y"?r:E,h.map(y=>y.original),o,a,l.state)}else{let g=h[0]?.original,E=h[0]?.latest;if(g&&E&&Eo(E,i)){let[w,x]=[g.x+g.width/2,g.y+g.height/2],[y,v]=mg(yi(g.x,g.y),yi(w,x),g.angle);va(i==="x"?r:y,i==="y"?r:v,g,a,l.state,o,!1)}}}a.triggerUpdate();return}let m=n?at(e,xd):e;dK(i,i==="x"?m:0,i==="y"?m:0,t,o,a,l.state),a.triggerUpdate()},uK=({property:e,elements:t,elementsMap:o,atomicUnits:n,scene:r,appState:i})=>{let a=lK(()=>n.map(l=>{let c=Object.keys(l).map(g=>o.get(g)).filter(g=>g!==void 0);if(c.length>1){let[g,E]=X1(c);return Math.round((e==="x"?g:E)*100)/100}let[m]=c,[p,d]=[m.x+m.width/2,m.y+m.height/2],[u,h]=mg(yi(m.x,m.y),yi(p,d),m.angle);return Math.round((e==="x"?u:h)*100)/100}),[n,o,e]),s=new Set(a).size===1?a[0]:"Mixed";return gK(Ot,{label:e==="x"?"X":"Y",elements:t,dragInputCallback:pK,value:s,property:e,scene:r,appState:i})},Z1=uK;import{clamp as Ed,pointFrom as pg,pointRotateRads as o4,round as t4}from"@orangecatai/math";import{getFlipAdjustedCropPosition as hK,getUncroppedWidthAndHeight as fK}from"@orangecatai/element";import{isImageElement as n4}from"@orangecatai/element";import{jsx as EK}from"react/jsx-runtime";var bK=({accumulatedChange:e,instantChange:t,originalElements:o,originalElementsMap:n,shouldChangeByStepSize:r,nextValue:i,property:a,scene:s,originalAppState:l,app:c})=>{let m=s.getNonDeletedElementsMap(),p=o[0],[d,u]=[p.x+p.width/2,p.y+p.height/2],[h,g]=o4(pg(p.x,p.y),pg(d,u),p.angle);if(l.croppingElementId===p.id){let v=m.get(p.id);if(!v||!n4(v)||!v.crop)return;let I=v.crop,k=I,L=v.scale[0]===-1,S=v.scale[1]===-1,{width:_,height:P}=fK(v);if(i!==void 0){if(a==="x"){let N=i*(I.naturalWidth/_);L?k={...I,x:Ed(I.naturalWidth-N-I.width,0,I.naturalWidth-I.width)}:k={...I,x:Ed(i*(I.naturalWidth/_),0,I.naturalWidth-I.width)}}a==="y"&&(k={...I,y:Ed(i*(I.naturalHeight/P),0,I.naturalHeight-I.height)}),s.mutateElement(v,{crop:k});return}let T=(a==="x"?t:0)*(L?-1:1),M=(a==="y"?t:0)*(S?-1:1);k={...I,x:Ed(I.x+T,0,I.naturalWidth-I.width),y:Ed(I.y+M,0,I.naturalHeight-I.height)},s.mutateElement(v,{crop:k});return}if(i!==void 0){va(a==="x"?i:h,a==="y"?i:g,p,s,c.state,n);return}let E=a==="x"?e:0,w=a==="y"?e:0,x=a==="x"?Math.round(r?at(p.x+E,xd):h+E):h,y=a==="y"?Math.round(r?at(p.y+w,xd):g+w):g;va(x,y,p,s,c.state,n)},xK=({property:e,element:t,elementsMap:o,scene:n,appState:r})=>{let[i,a]=o4(pg(t.x,t.y),pg(t.x+t.width/2,t.y+t.height/2),t.angle),s=t4(e==="x"?i:a,2);if(r.croppingElementId===t.id&&n4(t)&&t.crop){let l=hK(t);l&&(s=t4(e==="x"?l.x:l.y,2))}return EK(Ot,{label:e==="x"?"X":"Y",elements:[t],dragInputCallback:bK,scene:n,value:s,property:e,appState:r})},j1=xK;import{Fragment as Q1,jsx as ce,jsxs as yo}from"react/jsx-runtime";var MK=50,yd=e=>{let t=Go(),o=e.app.scene.getSceneNonce()||1,n=e.app.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!1}),r=ai(e.app);return ce(PK,{...e,appState:t,sceneNonce:o,selectedElements:n,gridModeEnabled:r})},et=({children:e,columns:t=1,heading:o,style:n,...r})=>ce("div",{className:yK("exc-stats__row",{"exc-stats__row--heading":o}),style:{gridTemplateColumns:`repeat(${t}, 1fr)`,...n},...r,children:e});et.displayName="StatsRow";var gg=({children:e,order:t,style:o,...n})=>ce("div",{className:"exc-stats__rows",style:{order:t,...o},...n,children:e});gg.displayName="StatsRows";yd.StatsRow=et;yd.StatsRows=gg;var PK=IK(({app:e,onClose:t,renderCustomStats:o,selectedElements:n,appState:r,sceneNonce:i,gridModeEnabled:a})=>{let s=e.scene,l=s.getNonDeletedElements(),c=s.getNonDeletedElementsMap(),m=ve(),p=n.length===1?n[0]:null,d=n.length>1?n:null,u=r.croppingElementId&&J1(p),h=u?CK(p):null,[g,E]=vK({width:0,height:0}),w=q1(()=>wK(v=>{let I=TK(v);E({width:Math.round(I[2])-Math.round(I[0]),height:Math.round(I[3])-Math.round(I[1])})},MK),[]);i4(()=>{w(l)},[i,l,w]),i4(()=>()=>w.cancel(),[w]);let x=q1(()=>El(n,r),[n,r]),y=q1(()=>kK(n),[n]);return ce("div",{className:"exc-stats",children:yo(ut,{padding:3,children:[yo("div",{className:"title",children:[ce("h2",{children:f("stats.title")}),ce("div",{className:"close",onClick:t,children:Fo})]}),yo(gc,{label:ce("h3",{children:f("stats.generalStats")}),open:!!(r.stats.panels&ug.generalStats),openTrigger:()=>m(v=>({stats:{open:!0,panels:v.stats.panels^ug.generalStats}})),children:[yo(gg,{children:[ce(et,{heading:!0,children:f("stats.scene")}),yo(et,{columns:2,children:[ce("div",{children:f("stats.shapes")}),ce("div",{children:l.length})]}),yo(et,{columns:2,children:[ce("div",{children:f("stats.width")}),ce("div",{children:g.width})]}),yo(et,{columns:2,children:[ce("div",{children:f("stats.height")}),ce("div",{children:g.height})]}),a&&yo(Q1,{children:[ce(et,{heading:!0,children:"Canvas"}),ce(et,{children:ce(_M,{property:"gridStep",scene:s,appState:r,setAppState:m})})]})]}),o?.(l,r)]}),!y&&n.length>0&&ce("div",{id:"elementStats",style:{marginTop:12},children:ce(gc,{label:ce("h3",{children:f("stats.elementProperties")}),open:!!(r.stats.panels&ug.elementProperties),openTrigger:()=>m(v=>({stats:{open:!0,panels:v.stats.panels^ug.elementProperties}})),children:yo(gg,{children:[p&&yo(Q1,{children:[u&&ce(et,{heading:!0,children:f("labels.unCroppedDimension")}),r.croppingElementId&&J1(p)&&h&&yo(et,{columns:2,children:[ce("div",{children:f("stats.width")}),ce("div",{children:r4(h.width,2)})]}),r.croppingElementId&&J1(p)&&h&&yo(et,{columns:2,children:[ce("div",{children:f("stats.height")}),ce("div",{children:r4(h.height,2)})]}),ce(et,{heading:!0,"data-testid":"stats-element-type",style:{margin:"0.3125rem 0"},children:r.croppingElementId?f("labels.imageCropping"):f(`element.${p.type}`)}),ce(et,{children:ce(j1,{element:p,property:"x",elementsMap:c,scene:s,appState:r})}),ce(et,{children:ce(j1,{element:p,property:"y",elementsMap:c,scene:s,appState:r})}),ce(et,{children:ce(W1,{property:"width",element:p,scene:s,appState:r})}),ce(et,{children:ce(W1,{property:"height",element:p,scene:s,appState:r})}),ce(et,{children:ce(AM,{property:"angle",element:p,scene:s,appState:r})}),ce(et,{children:ce(GM,{property:"fontSize",element:p,scene:s,appState:r})})]}),d&&yo(Q1,{children:[SK(d)&&ce(et,{heading:!0,children:f("element.group")}),yo(et,{columns:2,style:{margin:"0.3125rem 0"},children:[ce("div",{children:f("stats.shapes")}),ce("div",{children:n.length})]}),ce(et,{children:ce(Z1,{property:"x",elements:d,elementsMap:c,atomicUnits:x,scene:s,appState:r})}),ce(et,{children:ce(Z1,{property:"y",elements:d,elementsMap:c,atomicUnits:x,scene:s,appState:r})}),ce(et,{children:ce(K1,{property:"width",elements:d,elementsMap:c,atomicUnits:x,scene:s,appState:r})}),ce(et,{children:ce(K1,{property:"height",elements:d,elementsMap:c,atomicUnits:x,scene:s,appState:r})}),ce(et,{children:ce($M,{property:"angle",elements:d,scene:s,appState:r})}),ce(et,{children:ce(e4,{property:"fontSize",elements:d,scene:s,appState:r,elementsMap:c})})]})]})})})]})})},(e,t)=>e.sceneNonce===t.sceneNonce&&e.selectedElements===t.selectedElements&&e.appState.stats.panels===t.appState.stats.panels&&e.gridModeEnabled===t.gridModeEnabled&&e.appState.gridStep===t.appState.gridStep&&e.appState.croppingElementId===t.appState.croppingElementId);import{useCallback as AK,useEffect as a4,useState as s4}from"react";import{normalizeLink as LK,KEYS as ex}from"@orangecatai/common";import{defaultGetElementLinkFromSelection as _K,getLinkIdAndTypeFromSelection as DK}from"@orangecatai/element";import{jsx as vl,jsxs as hg}from"react/jsx-runtime";var RK=({sourceElementId:e,onClose:t,appState:o,scene:n,generateLinkForSelection:r=_K})=>{let i=n.getNonDeletedElementsMap(),a=i.get(e)?.link??null,[s,l]=s4(a),[c,m]=s4(!1);a4(()=>{let d=le(i,o),u=a;if(d.length>0&&r){let h=DK(d,o);h&&(u=LK(r(h.id,h.type)))}l(u)},[i,o,o.selectedElementIds,a,r]);let p=AK(()=>{if(s&&s!==i.get(e)?.link){let d=i.get(e);d&&n.mutateElement(d,{link:s})}if(!s&&c&&e){let d=i.get(e);d&&n.mutateElement(d,{link:null})}t?.()},[e,s,i,c,n,t]);return a4(()=>{let d=u=>{o.openDialog?.name==="elementLinkSelector"&&u.key===ex.ENTER&&p(),o.openDialog?.name==="elementLinkSelector"&&u.key===ex.ESCAPE&&t?.()};return window.addEventListener("keydown",d),()=>{window.removeEventListener("keydown",d)}},[o,t,p]),hg("div",{className:"ElementLinkDialog",children:[hg("div",{className:"ElementLinkDialog__header",children:[vl("h2",{children:f("elementLink.title")}),vl("p",{children:f("elementLink.desc")})]}),hg("div",{className:"ElementLinkDialog__input",children:[vl(ti,{value:s??"",onChange:d=>{c||m(!0),l(d)},onKeyDown:d=>{d.key===ex.ENTER&&p()},className:"ElementLinkDialog__input-field",selectOnRender:!0}),a&&s&&vl(ne,{type:"button",title:f("buttons.remove"),"aria-label":f("buttons.remove"),label:f("buttons.remove"),onClick:()=>{l(null),m(!0)},className:"ElementLinkDialog__remove",icon:Ht})]}),hg("div",{className:"ElementLinkDialog__actions",children:[vl(br,{label:f("buttons.cancel"),onClick:()=>{t?.()},style:{marginRight:10}}),vl(br,{label:f("buttons.confirm"),onClick:p,actionType:"primary"})]})]})},l4=RK;import NK,{useState as BK}from"react";import{Fragment as FK,jsx as tx}from"react/jsx-runtime";var c4=({children:e,onClose:t})=>{let[o,n]=BK(!!e),{container:r}=qe(),i=NK.useCallback(()=>{n(!1),t&&t(),r?.focus()},[t,r]);return tx(FK,{children:o&&tx(ht,{size:"small",onCloseRequest:i,title:f("errorDialog.title"),children:tx("div",{style:{whiteSpace:"pre-wrap"},children:e})})})};import OK from"react";import{isDarwin as d4,isFirefox as m4,isWindows as zK}from"@orangecatai/common";import{KEYS as pt}from"@orangecatai/common";import{Fragment as u4,jsx as Z,jsxs as Do}from"react/jsx-runtime";var HK=()=>Do("div",{className:"HelpDialog__header",children:[Do("a",{className:"HelpDialog__btn",href:"https://docs.excalidraw.com",target:"_blank",rel:"noopener",children:[Z("div",{className:"HelpDialog__link-icon",children:ah}),f("helpDialog.documentation")]}),Do("a",{className:"HelpDialog__btn",href:"https://plus.excalidraw.com/blog",target:"_blank",rel:"noopener",children:[Z("div",{className:"HelpDialog__link-icon",children:ah}),f("helpDialog.blog")]}),Do("a",{className:"HelpDialog__btn",href:"https://github.com/excalidraw/excalidraw/issues",target:"_blank",rel:"noopener noreferrer",children:[Z("div",{className:"HelpDialog__link-icon",children:lm}),f("helpDialog.github")]}),Do("a",{className:"HelpDialog__btn",href:"https://youtube.com/@excalidraw",target:"_blank",rel:"noopener noreferrer",children:[Z("div",{className:"HelpDialog__link-icon",children:Ww}),"YouTube"]})]}),GK=e=>Do(u4,{children:[Z("h3",{children:e.title}),Z("div",{className:"HelpDialog__islands-container",children:e.children})]}),ox=e=>Do("div",{className:`HelpDialog__island ${e.className}`,children:[Z("h4",{className:"HelpDialog__island-title",children:e.caption}),Z("div",{className:"HelpDialog__island-content",children:e.children})]});function*UK(e,t){let o=!0;for(let n of e)o||(yield t),o=!1,yield n}var WK=e=>e.replace(/\b[a-z]\b/,t=>t.toUpperCase()),J=({label:e,shortcuts:t,isOr:o=!0})=>{let n=t.map(r=>(r.endsWith("++")?[...r.slice(0,-2).split("+"),"+"]:r.split("+")).map(a=>Z(YK,{children:WK(a)},a)));return Do("div",{className:"HelpDialog__shortcut",children:[Z("div",{children:e}),Z("div",{className:"HelpDialog__key-container",children:[...UK(n,o?f("helpDialog.or"):null)]})]})},YK=e=>Z("kbd",{className:"HelpDialog__key",...e}),p4=({onClose:e})=>{let t=OK.useCallback(()=>{e&&e()},[e]);return Z(u4,{children:Do(ht,{onCloseRequest:t,title:f("helpDialog.title"),className:"HelpDialog",children:[Z(HK,{}),Do(GK,{title:f("helpDialog.shortcuts"),children:[Do(ox,{className:"HelpDialog__island--tools",caption:f("helpDialog.tools"),children:[Z(J,{label:f("toolBar.hand"),shortcuts:[pt.H]}),Z(J,{label:f("toolBar.selection"),shortcuts:[pt.V,pt[1]]}),Z(J,{label:f("toolBar.rectangle"),shortcuts:[pt.R,pt[2]]}),Z(J,{label:f("toolBar.diamond"),shortcuts:[pt.D,pt[3]]}),Z(J,{label:f("toolBar.ellipse"),shortcuts:[pt.O,pt[4]]}),Z(J,{label:f("toolBar.arrow"),shortcuts:[pt.A,pt[5]]}),Z(J,{label:f("toolBar.line"),shortcuts:[pt.L,pt[6]]}),Z(J,{label:f("toolBar.freedraw"),shortcuts:[pt.P,pt[7]]}),Z(J,{label:f("toolBar.text"),shortcuts:[pt.T,pt[8]]}),Z(J,{label:f("toolBar.image"),shortcuts:[pt[9]]}),Z(J,{label:f("toolBar.eraser"),shortcuts:[pt.E,pt[0]]}),Z(J,{label:f("toolBar.frame"),shortcuts:[pt.F]}),Z(J,{label:f("toolBar.laser"),shortcuts:[pt.K]}),Z(J,{label:f("labels.eyeDropper"),shortcuts:[pt.I,"Shift+S","Shift+G"]}),Z(J,{label:f("helpDialog.editLineArrowPoints"),shortcuts:[G("CtrlOrCmd+Enter")]}),Z(J,{label:f("helpDialog.editText"),shortcuts:[G("Enter")]}),Z(J,{label:f("helpDialog.textNewLine"),shortcuts:[G("Enter"),G("Shift+Enter")]}),Z(J,{label:f("helpDialog.textFinish"),shortcuts:[G("Esc"),G("CtrlOrCmd+Enter")]}),Z(J,{label:f("helpDialog.curvedArrow"),shortcuts:["A",f("helpDialog.click"),f("helpDialog.click"),f("helpDialog.click")],isOr:!1}),Z(J,{label:f("helpDialog.curvedLine"),shortcuts:["L",f("helpDialog.click"),f("helpDialog.click"),f("helpDialog.click")],isOr:!1}),Z(J,{label:f("helpDialog.cropStart"),shortcuts:[f("helpDialog.doubleClick"),G("Enter")],isOr:!0}),Z(J,{label:f("helpDialog.cropFinish"),shortcuts:[G("Enter"),G("Escape")],isOr:!0}),Z(J,{label:f("toolBar.lock"),shortcuts:[pt.Q]}),Z(J,{label:f("helpDialog.preventBinding"),shortcuts:[G("CtrlOrCmd")]}),Z(J,{label:f("toolBar.link"),shortcuts:[G("CtrlOrCmd+K")]}),Z(J,{label:f("toolBar.convertElementType"),shortcuts:["Tab","Shift+Tab"],isOr:!0})]}),Do(ox,{className:"HelpDialog__island--view",caption:f("helpDialog.view"),children:[Z(J,{label:f("buttons.zoomIn"),shortcuts:[G("CtrlOrCmd++")]}),Z(J,{label:f("buttons.zoomOut"),shortcuts:[G("CtrlOrCmd+-")]}),Z(J,{label:f("buttons.resetZoom"),shortcuts:[G("CtrlOrCmd+0")]}),Z(J,{label:f("helpDialog.zoomToFit"),shortcuts:["Shift+1"]}),Z(J,{label:f("helpDialog.zoomToSelection"),shortcuts:["Shift+2"]}),Z(J,{label:f("helpDialog.movePageUpDown"),shortcuts:["PgUp/PgDn"]}),Z(J,{label:f("helpDialog.movePageLeftRight"),shortcuts:["Shift+PgUp/PgDn"]}),Z(J,{label:f("buttons.zenMode"),shortcuts:[G("Alt+Z")]}),Z(J,{label:f("buttons.objectsSnapMode"),shortcuts:[G("Alt+S")]}),Z(J,{label:f("labels.toggleGrid"),shortcuts:[G("CtrlOrCmd+'")]}),Z(J,{label:f("labels.viewMode"),shortcuts:[G("Alt+R")]}),Z(J,{label:f("labels.toggleTheme"),shortcuts:[G("Alt+Shift+D")]}),Z(J,{label:f("stats.fullTitle"),shortcuts:[G("Alt+/")]}),Z(J,{label:f("search.title"),shortcuts:[Ke("searchMenu")]}),Z(J,{label:f("commandPalette.title"),shortcuts:m4?[Ke("commandPalette")]:[Ke("commandPalette"),Ke("commandPalette",1)]})]}),Do(ox,{className:"HelpDialog__island--editor",caption:f("helpDialog.editor"),children:[Z(J,{label:f("helpDialog.createFlowchart"),shortcuts:[G("CtrlOrCmd+Arrow Key")],isOr:!0}),Z(J,{label:f("helpDialog.navigateFlowchart"),shortcuts:[G("Alt+Arrow Key")],isOr:!0}),Z(J,{label:f("labels.moveCanvas"),shortcuts:[G(`Space+${f("helpDialog.drag")}`),G(`Wheel+${f("helpDialog.drag")}`)],isOr:!0}),Z(J,{label:f("buttons.clearReset"),shortcuts:[G("CtrlOrCmd+Delete")]}),Z(J,{label:f("labels.delete"),shortcuts:[G("Delete")]}),Z(J,{label:f("labels.cut"),shortcuts:[G("CtrlOrCmd+X")]}),Z(J,{label:f("labels.copy"),shortcuts:[G("CtrlOrCmd+C")]}),Z(J,{label:f("labels.paste"),shortcuts:[G("CtrlOrCmd+V")]}),Z(J,{label:f("labels.pasteAsPlaintext"),shortcuts:[G("CtrlOrCmd+Shift+V")]}),Z(J,{label:f("labels.selectAll"),shortcuts:[G("CtrlOrCmd+A")]}),Z(J,{label:f("labels.multiSelect"),shortcuts:[G(`Shift+${f("helpDialog.click")}`)]}),Z(J,{label:f("helpDialog.deepSelect"),shortcuts:[G(`CtrlOrCmd+${f("helpDialog.click")}`)]}),Z(J,{label:f("helpDialog.deepBoxSelect"),shortcuts:[G(`CtrlOrCmd+${f("helpDialog.drag")}`)]}),(vs||m4)&&Z(J,{label:f("labels.copyAsPng"),shortcuts:[G("Shift+Alt+C")]}),Z(J,{label:f("labels.copyStyles"),shortcuts:[G("CtrlOrCmd+Alt+C")]}),Z(J,{label:f("labels.pasteStyles"),shortcuts:[G("CtrlOrCmd+Alt+V")]}),Z(J,{label:f("labels.sendToBack"),shortcuts:[d4?G("CtrlOrCmd+Alt+["):G("CtrlOrCmd+Shift+[")]}),Z(J,{label:f("labels.bringToFront"),shortcuts:[d4?G("CtrlOrCmd+Alt+]"):G("CtrlOrCmd+Shift+]")]}),Z(J,{label:f("labels.sendBackward"),shortcuts:[G("CtrlOrCmd+[")]}),Z(J,{label:f("labels.bringForward"),shortcuts:[G("CtrlOrCmd+]")]}),Z(J,{label:f("labels.alignTop"),shortcuts:[G("CtrlOrCmd+Shift+Up")]}),Z(J,{label:f("labels.alignBottom"),shortcuts:[G("CtrlOrCmd+Shift+Down")]}),Z(J,{label:f("labels.alignLeft"),shortcuts:[G("CtrlOrCmd+Shift+Left")]}),Z(J,{label:f("labels.alignRight"),shortcuts:[G("CtrlOrCmd+Shift+Right")]}),Z(J,{label:f("labels.duplicateSelection"),shortcuts:[G("CtrlOrCmd+D"),G(`Alt+${f("helpDialog.drag")}`)]}),Z(J,{label:f("helpDialog.toggleElementLock"),shortcuts:[G("CtrlOrCmd+Shift+L")]}),Z(J,{label:f("buttons.undo"),shortcuts:[G("CtrlOrCmd+Z")]}),Z(J,{label:f("buttons.redo"),shortcuts:zK?[G("CtrlOrCmd+Y"),G("CtrlOrCmd+Shift+Z")]:[G("CtrlOrCmd+Shift+Z")]}),Z(J,{label:f("labels.group"),shortcuts:[G("CtrlOrCmd+G")]}),Z(J,{label:f("labels.ungroup"),shortcuts:[G("CtrlOrCmd+Shift+G")]}),Z(J,{label:f("labels.flipHorizontal"),shortcuts:[G("Shift+H")]}),Z(J,{label:f("labels.flipVertical"),shortcuts:[G("Shift+V")]}),Z(J,{label:f("labels.showStroke"),shortcuts:[G("S")]}),Z(J,{label:f("labels.showBackground"),shortcuts:[G("G")]}),Z(J,{label:f("labels.showFonts"),shortcuts:[G("Shift+F")]}),Z(J,{label:f("labels.decreaseFontSize"),shortcuts:[G("CtrlOrCmd+Shift+<")]}),Z(J,{label:f("labels.increaseFontSize"),shortcuts:[G("CtrlOrCmd+Shift+>")]})]})]})]})})};import{CANVAS_SEARCH_TAB as VK,DEFAULT_SIDEBAR as $K}from"@orangecatai/common";import{isFlowchartNodeElement as KK,isImageElement as g4,isLinearElement as h4,isLineElement as XK,isTextBindableContainer as ZK,isTextElement as jK}from"@orangecatai/element";import{isNodeInFlowchart as qK}from"@orangecatai/element";import{jsx as nx}from"react/jsx-runtime";var Be=e=>Array.isArray(e)?`<kbd>${e.map(G).join(" + ")}</kbd>`:`<kbd>${G(e)}</kbd>`,JK=({appState:e,isMobile:t,editorInterface:o,app:n})=>{let{activeTool:r,isResizing:i,isRotating:a,lastPointerDownWith:s}=e,l=e.multiElement!==null;if(e.openSidebar?.name===$K.name&&e.openSidebar.tab===VK&&e.searchMatches?.matches.length)return f("hints.dismissSearch",{shortcut:Be("Escape")});if(e.openSidebar&&!o.canFitSidebar)return null;if(po(e))return f("hints.eraserRevert",{shortcut:Be("Alt")});let c=n.scene.getSelectedElements(e);if(e.selectedLinearElement?.isDragging&&c[0]?.type==="arrow")return f("hints.arrowBindModifiers",{shortcut_1:Be("Ctrl"),shortcut_2:Be("Alt")});if(r.type==="arrow"||r.type==="line")return l?f("hints.linearElementMulti",{shortcut_1:Be("Escape"),shortcut_2:Be("Enter")}):r.type==="arrow"?f("hints.arrowTool",{shortcut:Be("A")}):f("hints.linearElement");if(r.type==="freedraw")return f("hints.freeDraw");if(r.type==="text")return f("hints.text");if(r.type==="embeddable")return f("hints.embeddable");if(i&&s==="mouse"&&c.length===1){let m=c[0];return h4(m)&&m.points.length===2?f("hints.lockAngle",{shortcut:Be("Shift")}):g4(m)?f("hints.resizeImage",{shortcut_1:Be("Shift"),shortcut_2:Be("Alt")}):f("hints.resize",{shortcut_1:Be("Shift"),shortcut_2:Be("Alt")})}if(a&&s==="mouse")return f("hints.rotate",{shortcut:Be("Shift")});if(c.length===1&&jK(c[0]))return f("hints.text_selected",{shortcut:Be("Enter")});if(e.editingTextElement)return f("hints.text_editing",{shortcut_1:Be("Escape"),shortcut_2:Be(["CtrlOrCmd","Enter"])});if(e.croppingElementId)return f("hints.leaveCropEditor",{shortcut_1:Be("Enter"),shortcut_2:Be("Escape")});if(c.length===1&&g4(c[0]))return f("hints.enterCropEditor",{shortcut:Be("Enter")});if(r.type==="selection"){if(e.selectionElement&&!c.length&&!e.editingTextElement&&!e.selectedLinearElement?.isEditing)return f("hints.deepBoxSelect",{shortcut:Be("CtrlOrCmd")});if(ai(n)&&e.selectedElementsAreBeingDragged)return f("hints.disableSnapping",{shortcut:Be("CtrlOrCmd")});if(!c.length&&!t)return f("hints.canvasPanning",{shortcut_1:Be(f("keys.mmb")),shortcut_2:Be("Space")});if(c.length===1){if(h4(c[0]))return e.selectedLinearElement?.isEditing?e.selectedLinearElement.selectedPointsIndices?f("hints.lineEditor_pointSelected",{shortcut_1:Be("Delete"),shortcut_2:Be(["CtrlOrCmd","D"])}):f("hints.lineEditor_nothingSelected",{shortcut_1:Be("Shift"),shortcut_2:Be("Alt")}):XK(c[0])?f("hints.lineEditor_line_info",{shortcut:Be("Enter")}):f("hints.lineEditor_info",{shortcut_1:Be("CtrlOrCmd"),shortcut_2:Be(["CtrlOrCmd","Enter"])});if(!e.newElement&&!e.selectedElementsAreBeingDragged&&ZK(c[0])){let m=f("hints.bindTextToElement",{shortcut:Be("Enter")}),p=f("hints.createFlowchart",{shortcut:Be(["CtrlOrCmd","\u2191\u2193"])});return KK(c[0])?qK(c[0],n.scene.getNonDeletedElementsMap())?[m,p]:[m,p]:m}}}return null},f4=({appState:e,isMobile:t,editorInterface:o,app:n})=>{let r=JK({appState:e,isMobile:t,editorInterface:o,app:n});if(!r)return null;let a=(Array.isArray(r)?r.map(s=>s.replace(/\. ?$/,"")).join(", "):r).split(/(<kbd>[^<]+<\/kbd>)/g).map((s,l)=>{if(l%2===1){let c=s[0]==="<"&&s.match(/^<kbd>([^<]+)<\/kbd>$/);return nx("kbd",{children:c?c[1]:s},l)}return s});return nx("div",{className:"HintViewer",children:nx("span",{children:a})})};import{useEffect as E4,useRef as rX,useState as wi}from"react";import{DEFAULT_EXPORT_PADDING as iX,EXPORT_IMAGE_TYPES as rx,isFirefox as aX,EXPORT_SCALES as sX,cloneJSON as y4}from"@orangecatai/common";import{useCallback as QK,useRef as eX,useState as tX}from"react";var oX=2e3,b4=()=>{let[e,t]=tX(null),o=eX(0),n=()=>{clearTimeout(o.current),t("success"),o.current=window.setTimeout(()=>{t(null)},oX)},r=QK(()=>{t(null)},[]);return{copyStatus:e,resetCopyStatus:r,onCopy:n}};import nX from"clsx";import{jsx as x4}from"react/jsx-runtime";var wd=({title:e,name:t,checked:o,onChange:n,disabled:r=!1})=>x4("div",{className:nX("Switch",{toggled:o,disabled:r}),children:x4("input",{name:t,id:t,title:e,type:"checkbox",checked:o,disabled:r,onChange:()=>n(!o),onKeyDown:i=>{i.key===" "&&n(!o)}})});import{jsx as tt,jsxs as vi}from"react/jsx-runtime";var lX=()=>vi("div",{children:[tt("h3",{children:f("canvasError.cannotShowPreview")}),tt("p",{children:tt("span",{children:f("canvasError.canvasTooBig")})}),vi("em",{children:["(",f("canvasError.canvasTooBigTip"),")"]})]}),cX=({appStateSnapshot:e,elementsSnapshot:t,files:o,actionManager:n,onExportImage:r,name:i})=>{let a=He(t,e),[s,l]=wi(i),[c,m]=wi(a),[p,d]=wi(e.exportBackground),[u,h]=wi(e.exportWithDarkMode),[g,E]=wi(e.exportEmbedScene),[w,x]=wi(e.exportScale),y=rX(null),[v,I]=wi(null),{onCopy:k,copyStatus:L,resetCopyStatus:S}=b4();E4(()=>{S()},[s,p,u,w,g,S]);let{exportedElements:_,exportingFrame:P}=Ki(t,e,c);return E4(()=>{let T=y.current;if(!T)return;let M=T.offsetWidth,N=T.offsetHeight;M&&Jr({elements:_,appState:{...e,name:s,exportBackground:p,exportWithDarkMode:u,exportScale:w,exportEmbedScene:g},files:o,exportPadding:iX,maxWidthOrHeight:Math.max(M,N),exportingFrame:P}).then(O=>(I(null),Bi(O).then(()=>{T.replaceChildren(O)}).catch(B=>{throw B.name==="CANVAS_POSSIBLY_TOO_BIG"?new Error(f("canvasError.canvasTooBig")):B}))).catch(O=>{console.error(O),I(O)})},[e,o,_,P,s,p,u,w,g]),vi("div",{className:"ImageExportModal",children:[tt("h3",{children:f("imageExportDialog.header")}),vi("div",{className:"ImageExportModal__preview",children:[tt("div",{className:"ImageExportModal__preview__canvas",ref:y,children:v&&tt(lX,{})}),tt("div",{className:"ImageExportModal__preview__filename",children:!Na&&tt("input",{type:"text",className:"TextInput",value:s,style:{width:"30ch"},onChange:T=>{l(T.target.value),n.executeAction(Mf,"ui",T.target.value)}})})]}),vi("div",{className:"ImageExportModal__settings",children:[tt("h3",{children:f("imageExportDialog.header")}),a&&tt(vd,{label:f("imageExportDialog.label.onlySelected"),name:"exportOnlySelected",children:tt(wd,{name:"exportOnlySelected",checked:c,onChange:T=>{m(T)}})}),tt(vd,{label:f("imageExportDialog.label.withBackground"),name:"exportBackgroundSwitch",children:tt(wd,{name:"exportBackgroundSwitch",checked:p,onChange:T=>{d(T),n.executeAction(Pf,"ui",T)}})}),tt(vd,{label:f("imageExportDialog.label.darkMode"),name:"exportDarkModeSwitch",children:tt(wd,{name:"exportDarkModeSwitch",checked:u,onChange:T=>{h(T),n.executeAction(J2,"ui",T)}})}),tt(vd,{label:f("imageExportDialog.label.embedScene"),tooltip:f("imageExportDialog.tooltip.embedScene"),name:"exportEmbedSwitch",children:tt(wd,{name:"exportEmbedSwitch",checked:g,onChange:T=>{E(T),n.executeAction(tp,"ui",T)}})}),tt(vd,{label:f("imageExportDialog.label.scale"),name:"exportScale",children:tt(Wu,{name:"exportScale",value:w,onChange:T=>{x(T),n.executeAction(q2,"ui",T)},choices:sX.map(T=>({value:T,label:`${T}\xD7`}))})}),vi("div",{className:"ImageExportModal__settings__buttons",children:[tt(qo,{className:"ImageExportModal__settings__buttons__button",label:f("imageExportDialog.title.exportToPng"),onClick:()=>r(rx.png,_,{exportingFrame:P}),icon:Ih,children:f("imageExportDialog.button.exportToPng")}),tt(qo,{className:"ImageExportModal__settings__buttons__button",label:f("imageExportDialog.title.exportToSvg"),onClick:()=>r(rx.svg,_,{exportingFrame:P}),icon:Ih,children:f("imageExportDialog.button.exportToSvg")}),(vs||aX)&&tt(qo,{className:"ImageExportModal__settings__buttons__button",label:f("imageExportDialog.title.copyPngToClipboard"),status:L,onClick:async()=>{await r(rx.clipboard,_,{exportingFrame:P}),k()},icon:Qa,children:f("imageExportDialog.button.copyPngToClipboard")})]})]})]})},vd=({label:e,children:t,tooltip:o,name:n})=>vi("div",{className:"ImageExportModal__settings__setting",title:e,children:[vi("label",{htmlFor:n,className:"ImageExportModal__settings__setting__label",children:[e,o&&tt(Vt,{label:o,long:!0,children:yw})]}),tt("div",{className:"ImageExportModal__settings__setting__content",children:t})]}),w4=({elements:e,appState:t,files:o,actionManager:n,onExportImage:r,onCloseRequest:i,name:a})=>{let[{appStateSnapshot:s,elementsSnapshot:l}]=wi(()=>({appStateSnapshot:y4(t),elementsSnapshot:y4(e)}));return tt(ht,{onCloseRequest:i,size:"wide",title:!1,children:tt(cX,{elementsSnapshot:l,appStateSnapshot:s,files:o,actionManager:n,onExportImage:r,name:a})})};import mX from"react";import{getFrame as pX}from"@orangecatai/common";import{jsx as dX}from"react/jsx-runtime";var ix={primary:{base:"var(--color-primary)",darker:"var(--color-primary-darker)",darkest:"var(--color-primary-darkest)"},lime:{base:"#74b816",darker:"#66a80f",darkest:"#5c940d"},pink:{base:"#d6336c",darker:"#c2255c",darkest:"#a61e4d"}},ax=({children:e,color:t})=>dX("div",{className:"Card",style:{"--card-color":ix[t].base,"--card-color-darker":ix[t].darker,"--card-color-darkest":ix[t].darkest},children:e});import{Fragment as gX,jsx as yn,jsxs as fg}from"react/jsx-runtime";var uX=({elements:e,appState:t,setAppState:o,files:n,actionManager:r,exportOpts:i,canvas:a,onCloseRequest:s})=>{let{onExportToBackend:l}=i;return yn("div",{className:"ExportDialog ExportDialog--json",children:fg("div",{className:"ExportDialog-cards",children:[i.saveFileToDisk&&fg(ax,{color:"lime",children:[yn("div",{className:"Card-icon",children:Sy}),yn("h2",{children:f("exportDialog.disk_title")}),fg("div",{className:"Card-details",children:[f("exportDialog.disk_details"),!Na&&r.renderAction("changeProjectName")]}),yn(ne,{className:"Card-button",type:"button",title:f("exportDialog.disk_button"),"aria-label":f("exportDialog.disk_button"),showAriaLabel:!0,onClick:()=>{r.executeAction(Ic,"ui")}})]}),l&&fg(ax,{color:"pink",children:[yn("div",{className:"Card-icon",children:ql}),yn("h2",{children:f("exportDialog.link_title")}),yn("div",{className:"Card-details",children:f("exportDialog.link_details")}),yn(ne,{className:"Card-button",type:"button",title:f("exportDialog.link_button"),"aria-label":f("exportDialog.link_button"),showAriaLabel:!0,onClick:async()=>{try{ge("export","link",`ui (${pX()})`),await l(e,t,n),s()}catch(c){o({errorMessage:c.message})}}})]}),i.renderCustomUI&&i.renderCustomUI(e,t,n,a)]})})},v4=({elements:e,appState:t,files:o,actionManager:n,exportOpts:r,canvas:i,setAppState:a})=>{let s=mX.useCallback(()=>{a({openDialog:null})},[a]);return yn(gX,{children:t.openDialog?.name==="jsonExport"&&yn(ht,{onCloseRequest:s,title:f("buttons.export"),children:yn(uX,{elements:e,appState:t,setAppState:a,files:o,actionManager:n,onCloseRequest:s,exportOpts:r,canvas:i})})})};import hX from"clsx";import{jsx as I4,jsxs as bX}from"react/jsx-runtime";var fX="small",T4=e=>bX("label",{className:hX("ToolIcon ToolIcon__LaserPointer",`ToolIcon_size_${fX}`,{"is-mobile":e.isMobile}),title:`${e.title}`,children:[I4("input",{className:"ToolIcon_type_checkbox",type:"checkbox",name:e.name,onChange:e.onChange,checked:e.checked,"aria-label":e.title,"data-testid":"toolbar-LaserPointer"}),I4("div",{className:"ToolIcon__icon",children:Rn})]});import{Fragment as S4,jsx as se,jsxs as Ro}from"react/jsx-runtime";var CX=({UIOptions:e})=>Ro(Kt,{__fallback:!0,children:[se(Kt.DefaultItems.LoadScene,{}),se(Kt.DefaultItems.SaveToActiveFile,{}),e.canvasActions.export&&se(Kt.DefaultItems.Export,{}),e.canvasActions.saveAsImage&&se(Kt.DefaultItems.SaveAsImage,{}),se(Kt.DefaultItems.SearchMenu,{}),se(Kt.DefaultItems.Help,{}),se(Kt.DefaultItems.ClearCanvas,{}),se(Kt.Separator,{}),se(Kt.Group,{title:"Excalidraw links",children:se(Kt.DefaultItems.Socials,{})}),se(Kt.Separator,{}),se(Kt.DefaultItems.ToggleTheme,{}),se(Kt.DefaultItems.ChangeCanvasBackground,{})]}),kX=()=>Ro(Ku,{__fallback:!0,children:[se(Ku.Actions.SaveToDisk,{}),se(Ku.Actions.ExportToImage,{})]}),SX=({actionManager:e,appState:t,files:o,setAppState:n,elements:r,canvas:i,onLockToggle:a,onHandToolToggle:s,onPenModeToggle:l,showExitZenModeBtn:c,renderTopLeftUI:m,renderTopRightUI:p,renderCustomStats:d,UIOptions:u,onExportImage:h,renderWelcomeScreen:g,children:E,app:w,isCollaborating:x,generateLinkForSelection:y})=>{let v=we(),k=_t()==="compact",L=wC(),S=k?{menuTopGap:4,toolbarColGap:4,toolbarRowGap:1,toolbarInnerRowGap:.5,islandPadding:1,collabMarginLeft:8}:{menuTopGap:6,toolbarColGap:4,toolbarRowGap:1,toolbarInnerRowGap:1,islandPadding:1,collabMarginLeft:8},_=L.tunnelsJotai.Provider,[P,T]=ae(zr),M=()=>u.canvasActions.export?se(v4,{elements:r,appState:t,files:o,actionManager:e,exportOpts:u.canvasActions.export,canvas:i,setAppState:n}):null,N=()=>!u.canvasActions.saveAsImage||t.openDialog?.name!=="imageExport"?null:se(w4,{elements:r,appState:t,files:o,actionManager:e,onExportImage:h,onCloseRequest:()=>n({openDialog:null}),name:w.getName()}),O=()=>Ro("div",{style:{position:"relative"},children:[se(L.MainMenuTunnel.Out,{}),g&&se(L.WelcomeScreenMenuHintTunnel.Out,{})]}),B=()=>{let $=k;return se(ad,{heading:"selectedShapeActions",className:Ia("selected-shape-actions zen-mode-transition",{"transition-left":t.zenModeEnabled}),children:$?se(ut,{className:Ia("compact-shape-actions-island"),padding:0,style:{maxHeight:`${t.height-166}px`},children:se(NC,{appState:t,elementsMap:w.scene.getNonDeletedElementsMap(),renderAction:e.renderAction,app:w,setAppState:n})}):se(ut,{className:EX.SHAPE_ACTIONS_MENU,padding:2,style:{maxHeight:`${t.height-166}px`},children:se(AC,{appState:t,elementsMap:w.scene.getNonDeletedElementsMap(),renderAction:e.renderAction,app:w})})})},U=()=>{let $=IX(t,r),V=t.stats.open&&!t.zenModeEnabled&&!t.viewModeEnabled&&t.openDialog?.name!=="elementLinkSelector";return se(Nu,{side:"top",children:Ro("div",{className:"App-menu App-menu_top",children:[Ro(Dt.Col,{gap:S.menuTopGap,className:Ia("App-menu_top__left"),children:[O(),se("div",{className:Ia("selected-shape-actions-container",{"selected-shape-actions-container--compact":k}),children:$&&B()})]}),!t.viewModeEnabled&&t.openDialog?.name!=="elementLinkSelector"&&se(ad,{heading:"shapes",className:"shapes-section",children:Q=>Ro("div",{style:{position:"relative"},children:[g&&se(L.WelcomeScreenToolbarHintTunnel.Out,{}),se(Dt.Col,{gap:S.toolbarColGap,align:"start",children:Ro(Dt.Row,{gap:S.toolbarRowGap,className:Ia("App-toolbar-container",{"zen-mode":t.zenModeEnabled}),children:[Ro(ut,{padding:S.islandPadding,className:Ia("App-toolbar",{"zen-mode":t.zenModeEnabled,"App-toolbar--compact":k}),children:[se(f4,{appState:t,isMobile:v.formFactor==="phone",editorInterface:v,app:w}),Q,Ro(Dt.Row,{gap:S.toolbarInnerRowGap,children:[se(Bu,{zenModeEnabled:t.zenModeEnabled,checked:t.penMode,onChange:()=>l(null),title:f("toolBar.penMode"),penDetected:t.penDetected}),se(Tk,{checked:t.activeTool.locked,onChange:a,title:f("toolBar.lock")}),se("div",{className:"App-toolbar__divider"}),se(FC,{setAppState:n,activeTool:t.activeTool,UIOptions:u,app:w})]})]}),x&&se(ut,{style:{marginLeft:S.collabMarginLeft,alignSelf:"center",height:"fit-content"},children:se(T4,{title:f("toolBar.laser"),checked:t.activeTool.type===C4.laser,onChange:()=>w.setActiveTool({type:C4.laser}),isMobile:!0})})]})})]})}),Ro("div",{className:Ia("layer-ui__wrapper__top-right zen-mode-transition",{"transition-right":t.zenModeEnabled,"layer-ui__wrapper__top-right--compact":k}),children:[t.collaborators.size>0&&se(Hu,{collaborators:t.collaborators,userToFollow:t.userToFollow?.socketId||null}),p?.(v.formFactor==="phone",t),w.props.showLibraryButton===!0&&!t.viewModeEnabled&&t.openDialog?.name!=="elementLinkSelector"&&(!F||t.openSidebar?.name!==sx.name)&&se(L.DefaultSidebarTriggerTunnel.Out,{}),V&&se(yd,{app:w,onClose:()=>{e.executeAction(qr)},renderCustomStats:d})]})]})})},D=()=>se(ju,{__fallback:!0,onDock:$=>{ge("sidebar",`toggleDock (${$?"dock":"undock"})`,`(${v.formFactor==="phone"?"mobile":"desktop"})`)}}),F=Ha(dd),z=Ro(S4,{children:[E,se(CX,{UIOptions:u}),se(ju.Trigger,{__fallback:!0,icon:qw,title:wX(f("toolBar.library")),onToggle:$=>{$&&ge("sidebar",`${sx.name} (open)`,`button (${v.formFactor==="phone"?"mobile":"desktop"})`)},tab:sx.defaultTab}),se(kX,{}),t.openDialog?.name==="ttd"&&se(ig,{__fallback:!0}),t.isLoading&&se(_u,{delay:250}),t.errorMessage&&se(c4,{onClose:()=>n({errorMessage:null}),children:t.errorMessage}),P&&v.formFactor!=="phone"&&se(hv,{colorPickerType:P.colorPickerType,onCancel:()=>{T(null)},onChange:($,V,Q,{altKey:ee})=>{if(!($!=="elementBackground"&&$!=="elementStroke"))if(Q.length){for(let ie of Q)vX(ie,yX(r),{[ee&&P.swapPreviewOnAlt?$==="elementBackground"?"strokeColor":"backgroundColor":$==="elementBackground"?"backgroundColor":"strokeColor"]:V}),TX.delete(ie);w.scene.triggerUpdate()}else n($==="elementBackground"?{currentItemBackgroundColor:V}:{currentItemStrokeColor:V})},onSelect:($,V)=>{T(Q=>Q?.keepOpenOnAlt&&V.altKey?Q:null),P?.onSelect?.($,V)}}),t.openDialog?.name==="help"&&se(p4,{onClose:()=>{n({openDialog:null})}}),se(WC,{}),t.openDialog?.name==="elementLinkSelector"&&se(l4,{sourceElementId:t.openDialog.sourceElementId,onClose:()=>{n({openDialog:null})},scene:w.scene,appState:t,generateLinkForSelection:y}),se(L.OverwriteConfirmDialogTunnel.Out,{}),N(),M(),t.pasteDialog.shown&&se(Dk,{setAppState:n,appState:t,onClose:()=>n({pasteDialog:{shown:!1,data:null}})}),v.formFactor==="phone"&&se(Lk,{app:w,appState:t,elements:r,actionManager:e,renderJSONExportDialog:M,renderImageExportDialog:N,setAppState:n,onHandToolToggle:s,onPenModeToggle:l,renderTopLeftUI:m,renderTopRightUI:p,renderSidebars:D,renderWelcomeScreen:g,UIOptions:u}),v.formFactor!=="phone"&&Ro(S4,{children:[Ro("div",{className:"layer-ui__wrapper",style:t.openSidebar&&F&&v.canFitSidebar?{width:"calc(100% - var(--right-sidebar-width))"}:{},children:[g&&se(L.WelcomeScreenCenterTunnel.Out,{}),U(),se(Gk,{appState:t,actionManager:e,showExitZenModeBtn:c,renderWelcomeScreen:g}),t.scrolledOutside&&se("button",{type:"button",className:"scroll-back-to-content",onClick:()=>{n($=>({...Ri(r,$)}))},children:f("buttons.scrollBackToContent")})]}),D()]})]});return se(Oh.Provider,{value:t,children:se(_,{children:se(zb.Provider,{value:L,children:z})})})},k4=e=>{let{startBoundElement:t,cursorButton:o,scrollX:n,scrollY:r,...i}=e;return i},MX=(e,t)=>{if(e.children!==t.children)return!1;let{canvas:o,appState:n,...r}=e,{canvas:i,appState:a,...s}=t;return bg(k4(n),k4(a),{selectedElementIds:bg,selectedGroupIds:bg})&&bg(r,s)},M4=xX.memo(SX,MX);import PX from"clsx";import{jsx as P4,jsxs as LX}from"react/jsx-runtime";var AX="small",xg=e=>LX("label",{className:PX("ToolIcon ToolIcon__MagicButton",`ToolIcon_size_${AX}`,{"is-mobile":e.isMobile}),title:`${e.title}`,children:[P4("input",{className:"ToolIcon_type_checkbox",type:"checkbox",name:e.name,onChange:e.onChange,checked:e.checked,"aria-label":e.title}),P4("div",{className:"ToolIcon__icon",children:e.icon})]});import{useEffect as _X,useRef as DX}from"react";import{jsx as A4}from"react/jsx-runtime";var L4=({trails:e})=>{let t=DX(null);return _X(()=>{if(t.current)for(let o of e)o.start(t.current);return()=>{for(let o of e)o.stop()}},e),A4("div",{className:"SVGLayer",children:A4("svg",{ref:t})})};import bZ,{useEffect as xZ,useRef as X4}from"react";import{CURSOR_TYPE as Z4,isShallowEqual as EZ,sceneCoordsToViewportCoords as yZ}from"@orangecatai/common";var zt=class zt{static start(t,o){let n=o({deltaTime:0,state:void 0});n&&(zt.animations.set(t,{animation:o,lastTime:0,state:n}),zt.isRunning||(zt.isRunning=!0,ha()?requestAnimationFrame(zt.tick):setTimeout(zt.tick,0)))}static tick(){if(zt.animations.size>0){for(let[t,o]of zt.animations){let n=performance.now(),r=o.lastTime===0?0:n-o.lastTime,i=o.animation({deltaTime:r,state:o.state});if(i)o.lastTime=n,o.state=i;else if(zt.animations.delete(t),zt.animations.size===0){zt.isRunning=!1;return}}ha()?requestAnimationFrame(zt.tick):setTimeout(zt.tick,0)}}static running(t){return zt.animations.has(t)}static cancel(t){zt.animations.delete(t)}};A(zt,"isRunning",!1),A(zt,"animations",new Map);var Id=zt;import{clamp as mx,pointFrom as Il,pointsEqual as HX,bezierEquation as W4,pointRotateRads as Eg,pointDistance as GX}from"@orangecatai/math";import{arrayToMap as UX,BIND_MODE_TIMEOUT as Td,DEFAULT_TRANSFORM_HANDLE_SPACING as hx,FRAME_STYLE as tn,getFeatureFlag as WX,invariant as B4,THEME as Ii}from"@orangecatai/common";import{deconstructDiamondElement as px,deconstructRectanguloidElement as Y4,elementCenterPoint as Tl,getDiamondBaseCorners as YX,FOCUS_POINT_SIZE as VX,getOmitSidesForEditorInterface as lx,getTransformHandles as $X,getTransformHandlesFromCoords as KX,hasBoundingBox as XX,hitElementItself as ZX,isArrowElement as jX,isBindableElement as V4,isElbowArrow as Cl,isFrameLikeElement as kl,isImageElement as F4,isLinearElement as qX,isLineElement as JX,maxBindingDistance_simple as QX,isTextElement as O4,LinearElementEditor as qn}from"@orangecatai/element";import{renderSelectionElement as eZ}from"@orangecatai/element";import{getElementsInGroup as ux,getSelectedGroupIds as tZ,isSelectedViaGroup as oZ,selectGroupsFromGivenElements as nZ}from"@orangecatai/element";import{getCommonBounds as gx,getElementAbsoluteCoords as yg}from"@orangecatai/element";import{getGlobalFixedPointForBindableElement as z4,isFocusPointVisible as rZ}from"@orangecatai/element";import{pointFrom as Xt}from"@orangecatai/math";import{THEME as RX}from"@orangecatai/common";var NX="#ff6b6b",BX="#ff0000",_4=1,D4=2,R4=(e,t)=>{if(!t.snapLines.length)return;let o=t.theme===RX.LIGHT||t.zenModeEnabled?NX:BX,n=(t.zenModeEnabled?_4*1.5:_4)/t.zoom.value;e.save(),e.translate(t.scrollX,t.scrollY);for(let r of t.snapLines)r.type==="pointer"?(e.lineWidth=n,e.strokeStyle=o,OX(r,e,t)):r.type==="gap"?(e.lineWidth=n,e.strokeStyle=o,zX(r.points[0],r.points[1],r.direction,t,e)):r.type==="points"&&(e.lineWidth=n,e.strokeStyle=o,FX(r,e,t));e.restore()},FX=(e,t,o)=>{if(!o.zenModeEnabled){let n=e.points[0],r=e.points[e.points.length-1];en(n,r,t)}for(let n of e.points)N4(n,o,t)},OX=(e,t,o)=>{N4(e.points[0],o,t),o.zenModeEnabled||en(e.points[0],e.points[1],t)},N4=([e,t],o,n)=>{n.save();let r=(o.zenModeEnabled?D4*1.5:D4)/o.zoom.value;n.beginPath(),n.moveTo(e-r,t-r),n.lineTo(e+r,t+r),n.moveTo(e+r,t-r),n.lineTo(e-r,t+r),n.stroke(),n.restore()},en=(e,t,o)=>{o.beginPath(),o.lineTo(e[0],e[1]),o.lineTo(t[0],t[1]),o.stroke()},zX=(e,t,o,n,r)=>{let i=8/n.zoom.value,a=i/2,s=i/4;if(o==="horizontal"){let l=[(e[0]+t[0])/2,e[1]];n.zenModeEnabled||en(Xt(e[0],e[1]-i),Xt(e[0],e[1]+i),r),en(Xt(l[0]-s,l[1]-a),Xt(l[0]-s,l[1]+a),r),en(Xt(l[0]+s,l[1]-a),Xt(l[0]+s,l[1]+a),r),n.zenModeEnabled||(en(Xt(t[0],t[1]-i),Xt(t[0],t[1]+i),r),en(e,t,r))}else{let l=[e[0],(e[1]+t[1])/2];n.zenModeEnabled||en(Xt(e[0]-i,e[1]),Xt(e[0]+i,e[1]),r),en(Xt(l[0]-a,l[1]-s),Xt(l[0]+a,l[1]-s),r),en(Xt(l[0]-a,l[1]+s),Xt(l[0]+a,l[1]+s),r),n.zenModeEnabled||(en(Xt(t[0]-i,t[1]),Xt(t[0]+i,t[1]),r),en(e,t,r))}};var iZ=(e,t)=>{B4(t.selectedLinearElement,"selectedLinearElement is null");let{segmentMidPointHoveredCoords:o}=t.selectedLinearElement;B4(o,"midPointCoords is null"),e.save(),e.translate(t.scrollX,t.scrollY),fx(o,e,t),e.restore()},aZ=(e,t,o)=>{let{elementId:n,hoverPointIndex:r}=t.selectedLinearElement;if(t.selectedLinearElement?.isEditing&&t.selectedLinearElement?.selectedPointsIndices?.includes(r)||t.selectedLinearElement?.isDragging)return;let i=qn.getElement(n,o);if(!i)return;let a=qn.getPointAtIndexGlobalCoordinates(i,r,o);e.save(),e.translate(t.scrollX,t.scrollY),fx(a,e,t),e.restore()},fx=(e,t,o)=>{t.fillStyle="rgba(105, 101, 219, 0.4)",Yl(t,e[0],e[1],qn.POINT_HANDLE_SIZE/o.zoom.value,!1)},sZ=(e,t,o)=>{e.save(),e.translate(t.scrollX,t.scrollY),fx(o,e,t),e.restore()},cx=(e,t,o,n,r,i,a)=>{e.strokeStyle="#5e5ad8",e.setLineDash([]),e.fillStyle="rgba(255, 255, 255, 0.9)",r?e.fillStyle="rgba(134, 131, 226, 0.9)":i&&(e.fillStyle="rgba(177, 151, 252, 0.7)"),Yl(e,o[0],o[1],(a?n*(t.selectedLinearElement?.isEditing?1.5:2):n)/t.zoom.value,!i,!a||r)},lZ=(e,t,o,n,r)=>{let i=t.element.frameId&&o.get(t.element.frameId);switch(i&&kl(i)&&(e.translate(i.x,i.y),e.beginPath(),tn.radius&&e.roundRect?e.roundRect(-1,-1,i.width+1,i.height+1,tn.radius/n.zoom.value):e.rect(-1,-1,i.width+1,i.height+1),e.clip(),e.translate(-i.x,-i.y)),t.element.type){case"magicframe":case"frame":e.save(),e.translate(t.element.x,t.element.y),e.lineWidth=tn.strokeWidth/n.zoom.value,e.strokeStyle=n.theme===Ii.DARK?"rgba(3, 93, 161, 1)":"rgba(106, 189, 252, 1)",tn.radius&&e.roundRect?(e.beginPath(),e.roundRect(0,0,t.element.width,t.element.height,tn.radius/n.zoom.value),e.stroke(),e.closePath()):e.strokeRect(0,0,t.element.width,t.element.height),e.restore();break;default:e.save();let a=Tl(t.element,o);switch(e.translate(a[0],a[1]),e.rotate(t.element.angle),e.translate(-a[0],-a[1]),e.translate(t.element.x,t.element.y),e.lineWidth=mx(1.75,t.element.strokeWidth,4)/Math.max(.25,n.zoom.value),e.strokeStyle=n.theme===Ii.DARK?"rgba(3, 93, 161, 1)":"rgba(106, 189, 252, 1)",t.element.type){case"ellipse":e.beginPath(),e.ellipse(t.element.width/2,t.element.height/2,t.element.width/2,t.element.height/2,0,0,2*Math.PI),e.closePath(),e.stroke();break;case"diamond":{let[s,l]=px(t.element);s.forEach(c=>{e.beginPath(),e.moveTo(c[0][0]-t.element.x,c[0][1]-t.element.y),e.lineTo(c[1][0]-t.element.x,c[1][1]-t.element.y),e.stroke()}),l.forEach(c=>{let[m,p,d,u]=c;e.beginPath(),e.moveTo(m[0]-t.element.x,m[1]-t.element.y),e.bezierCurveTo(p[0]-t.element.x,p[1]-t.element.y,d[0]-t.element.x,d[1]-t.element.y,u[0]-t.element.x,u[1]-t.element.y),e.stroke()})}break;default:{let[s,l]=Y4(t.element);s.forEach(c=>{e.beginPath(),e.moveTo(c[0][0]-t.element.x,c[0][1]-t.element.y),e.lineTo(c[1][0]-t.element.x,c[1][1]-t.element.y),e.stroke()}),l.forEach(c=>{let[m,p,d,u]=c;e.beginPath(),e.moveTo(m[0]-t.element.x,m[1]-t.element.y),e.bezierCurveTo(p[0]-t.element.x,p[1]-t.element.y,d[0]-t.element.x,d[1]-t.element.y,u[0]-t.element.x,u[1]-t.element.y),e.stroke()})}break}e.restore();break}if(kl(t.element)||V4(t.element)){let a=n.selectedLinearElement,s=a?.elementId&&qn.getElement(a?.elementId,o),l=r&&ZX({point:r,element:t.element,elementsMap:o,threshold:0,overrideShouldTestInside:!0}),c=s&&Cl(s)||n.activeTool.type==="arrow"&&n.currentItemArrowType==="elbow";if(!l||c){e.save();let m=Tl(t.element,o),p;if(t.element.type==="diamond"){let g=Tl(t.element,o);p=YX(t.element).map(E=>{let w=W4(E,.5),x=Eg(w,g,t.element.angle);return Il(x[0],x[1])})}else p=[{x:t.element.width,y:t.element.height/2},{x:t.element.width/2,y:t.element.height},{x:0,y:t.element.height/2},{x:t.element.width/2,y:0}].map(E=>{let w=Il(E.x+t.element.x,E.y+t.element.y),x=Eg(w,m,t.element.angle);return Il(x[0],x[1])});let d=r&&p.reduce((g,E,w)=>{let x=GX(E,r);return w===-1||x<g.distance?{idx:w,distance:x}:g},{idx:-1,distance:1/0}),u=4/n.zoom.value,h=QX(n.zoom)+t.element.strokeWidth/2;p.forEach((g,E)=>{let w=(!l||c)&&d?.idx===E&&d.distance<=h,x=!w&&(c||E===d?.idx&&d.distance<=h*2);w?(e.fillStyle=n.theme===Ii.DARK?"rgba(3, 93, 161, 1)":"rgba(106, 189, 252, 1)",e.beginPath(),e.arc(g[0],g[1],u,0,2*Math.PI),e.fill()):x&&(e.fillStyle=n.theme===Ii.DARK?"rgba(0, 0, 0, 0.8)":"rgba(65, 65, 65, 0.5)",e.beginPath(),e.arc(g[0],g[1],u,0,2*Math.PI),e.fill())}),e.restore()}}},cZ=(e,t,o,n,r,i,a)=>{let s=e.state.bindMode==="orbit"&&e.bindModeHandler!==null,l=Td-(a?.runtime??(s?0:Td)),c=mx(1/Td*l,1e-4,1),m=o.strokeWidth/2,p=o.frameId&&n.get(o.frameId);switch(p&&kl(p)&&(t.translate(p.x,p.y),t.beginPath(),tn.radius&&t.roundRect?t.roundRect(-1,-1,p.width+1,p.height+1,tn.radius/r.zoom.value):t.rect(-1,-1,p.width+1,p.height+1),t.clip(),t.translate(-p.x,-p.y)),o.type){case"magicframe":case"frame":t.save(),t.translate(o.x,o.y),t.lineWidth=tn.strokeWidth/r.zoom.value,t.strokeStyle=r.theme===Ii.DARK?`rgba(3, 93, 161, ${c})`:`rgba(106, 189, 252, ${c})`,tn.radius&&t.roundRect?(t.beginPath(),t.roundRect(0,0,o.width,o.height,tn.radius/r.zoom.value),t.stroke(),t.closePath()):t.strokeRect(0,0,o.width,o.height),t.restore();break;default:t.save();let u=Tl(o,n),h=u[0]+r.scrollX,g=u[1]+r.scrollY;switch(t.translate(h,g),t.rotate(o.angle),t.translate(-h,-g),t.translate(o.x+r.scrollX-m,o.y+r.scrollY-m),t.lineWidth=mx(2.5,o.strokeWidth*1.75,4)/Math.max(.25,r.zoom.value),t.strokeStyle=r.theme===Ii.DARK?`rgba(3, 93, 161, ${c/2})`:`rgba(106, 189, 252, ${c/2})`,o.type){case"ellipse":t.beginPath(),t.ellipse((o.width+m*2)/2,(o.height+m*2)/2,(o.width+m*2)/2,(o.height+m*2)/2,0,0,2*Math.PI),t.closePath(),t.stroke();break;case"diamond":{let[E,w]=px(o,m);E.forEach(x=>{t.beginPath(),t.moveTo(x[0][0]-o.x+m,x[0][1]-o.y+m),t.lineTo(x[1][0]-o.x+m,x[1][1]-o.y+m),t.stroke()}),w.forEach(x=>{let[y,v,I,k]=x;t.beginPath(),t.moveTo(y[0]-o.x+m,y[1]-o.y+m),t.bezierCurveTo(v[0]-o.x+m,v[1]-o.y+m,I[0]-o.x+m,I[1]-o.y+m,k[0]-o.x+m,k[1]-o.y+m),t.stroke()})}break;default:{let[E,w]=Y4(o,m);E.forEach(x=>{t.beginPath(),t.moveTo(x[0][0]-o.x+m,x[0][1]-o.y+m),t.lineTo(x[1][0]-o.x+m,x[1][1]-o.y+m),t.stroke()}),w.forEach(x=>{let[y,v,I,k]=x;t.beginPath(),t.moveTo(y[0]-o.x+m,y[1]-o.y+m),t.bezierCurveTo(v[0]-o.x+m,v[1]-o.y+m,I[0]-o.x+m,I[1]-o.y+m,k[0]-o.x+m,k[1]-o.y+m),t.stroke()})}break}t.restore();break}if(!s||(a?.runtime??0)>Td)return;let d=.5*(Math.min(o.width,o.height)/2);if(!kl(o)){t.save(),t.translate(o.x+r.scrollX,o.y+r.scrollY);let u=1/Td*l;t.strokeStyle="rgba(0, 0, 0, 0.2)",t.lineWidth=1/r.zoom.value,t.setLineDash([4/r.zoom.value,4/r.zoom.value]),t.lineDashOffset=-u*10/r.zoom.value,t.beginPath(),t.ellipse(o.width/2,o.height/2,d,d,0,0,2*Math.PI),t.stroke(),t.fillStyle="rgba(0, 0, 0, 0.04)",t.beginPath(),t.ellipse(o.width/2,o.height/2,d*(1-c),d*(1-c),0,0,2*Math.PI),t.fill(),t.restore(),t.save(),t.translate(o.x+r.scrollX,o.y+r.scrollY);let h=5/r.zoom.value,g=5/r.zoom.value,E=h+g,w;if(o.type==="diamond"){let[,x]=px(o),y=Tl(o,n);w=x.map(v=>{let I=W4(v,.5),k=Eg(I,y,o.angle);return{x:k[0]-o.x,y:k[1]-o.y}})}else{let x=Tl(o,n);w=[{x:o.width/2,y:0},{x:o.width,y:o.height/2},{x:o.width/2,y:o.height},{x:0,y:o.height/2}].map(v=>{let I=Il(v.x+o.x,v.y+o.y),k=Eg(I,x,o.angle);return{x:k[0]-o.x,y:k[1]-o.y}})}w.forEach(x=>{t.clearRect(x.x-E,x.y-E,E*2,E*2)}),t.fillStyle=r.theme===Ii.DARK?`rgba(3, 93, 161, ${c})`:`rgba(106, 189, 252, ${c})`,w.forEach(x=>{t.beginPath(),t.arc(x.x,x.y,h,0,2*Math.PI),t.fill()}),t.restore()}return{runtime:(a?.runtime??0)+i}},dZ=(e,t,o,n,r,i,a)=>{if(o===null)return;if(WX("COMPLEX_BINDINGS"))return cZ(e,t,o.element,n,r,i,a);t.save(),t.translate(r.scrollX,r.scrollY);let s=e.lastPointerMoveCoords?Il(e.lastPointerMoveCoords.x,e.lastPointerMoveCoords.y):null;lZ(t,o,n,r,s),t.restore()},$4=(e,t,o)=>{let{angle:n,x1:r,y1:i,x2:a,y2:s,selectionColors:l,cx:c,cy:m,dashed:p,activeEmbeddable:d}=o,u=a-r,h=s-i,E=(o.padding??hx*2)/t.zoom.value,w=8/t.zoom.value,x=4/t.zoom.value;e.save(),e.translate(t.scrollX,t.scrollY),e.lineWidth=(d?4:1)/t.zoom.value;let y=l.length;for(let v=0;v<y;++v)e.strokeStyle=l[v],p&&e.setLineDash([w,x+(w+x)*(y-1)]),e.lineDashOffset=(w+x)*v,Vl(e,r-E,i-E,u+E*2,h+E*2,c,m,n);e.restore()},mZ=(e,t,o,n)=>{let[r,i,a,s]=yg(o,n),l=a-r,c=s-i;e.strokeStyle="rgb(0,118,255)",e.lineWidth=tn.strokeWidth/t.zoom.value,e.save(),e.translate(t.scrollX,t.scrollY),Vl(e,r,i,l,c,r+l/2,i+c/2,o.angle,!1,tn.radius/t.zoom.value),e.restore()},H4=(e,t,o,n)=>{let{colors:r=["rgb(0,118,255)"],dashed:i=!1}=n||{},a=o.filter(m=>m.groupIds.length===0),s=o.filter(m=>m.groupIds.length>0),l=m=>{let[p,d,u,h]=gx(m);return{angle:0,x1:p,x2:u,y1:d,y2:h,selectionColors:r,dashed:i,cx:p+(u-p)/2,cy:d+(h-d)/2,activeEmbeddable:!1}},c=m=>{let p=ux(o,m);return l(p)};Object.entries(nZ(s,t)).filter(([m,p])=>p).map(([m,p])=>m).map(m=>c(m)).concat(a.map(m=>l([m]))).forEach(m=>$4(e,t,m))},dx=(e,t,o,n)=>{if(!t.selectedLinearElement)return;e.save(),e.translate(t.scrollX,t.scrollY),e.lineWidth=1/t.zoom.value;let r=qn.getPointsGlobalCoordinates(o,n),{POINT_HANDLE_SIZE:i}=qn,a=t.selectedLinearElement?.isEditing?i:i/2,s=Cl(o),l=JX(o);if(r.forEach((c,m)=>{if(s&&m!==0&&m!==r.length-1)return;let p=m>0&&(m!==r.length-1||!l||!o.polygon)&&HX(c,m===r.length-1?r[0]:r[m-1],2/t.zoom.value),d=!!t.selectedLinearElement?.isEditing&&!!t.selectedLinearElement?.selectedPointsIndices?.includes(m);l&&o.polygon&&!d&&m===o.points.length-1&&t.selectedLinearElement?.isEditing&&t.selectedLinearElement?.selectedPointsIndices?.includes(0)&&(d=!0),cx(e,t,c,a,d,!1,p)}),Cl(o)){let c=o.fixedSegments?.map(m=>m.index)||[];r.slice(0,-1).forEach((m,p)=>{qn.isSegmentTooShort(o,r[p+1],r[p],p,t.zoom)||cx(e,t,Il((m[0]+r[p+1][0])/2,(m[1]+r[p+1][1])/2),i/2,!1,!c.includes(p+1),!1)})}else qn.getEditorMidPoints(o,n,t).filter((m,p,d)=>m!==null&&!(Cl(o)&&(p===0||p===d.length-1))).forEach(m=>{(t.selectedLinearElement?.isEditing||r.length===2)&&cx(e,t,m,i/2,!1,!0,!1)});e.restore()},pZ=(e,t,o,n)=>{e.save(),e.translate(t.scrollX,t.scrollY),e.strokeStyle="rgba(134, 131, 226, 0.6)",e.lineWidth=1/t.zoom.value,e.setLineDash([4/t.zoom.value,4/t.zoom.value]),e.beginPath(),e.moveTo(o[0],o[1]),e.lineTo(n[0],n[1]),e.stroke(),e.restore()},uZ=(e,t,o,n,r)=>{e.save(),e.translate(t.scrollX,t.scrollY),e.strokeStyle="rgba(134, 131, 226, 0.6)",e.lineWidth=1/t.zoom.value,e.setLineDash([]),e.fillStyle=r?"rgba(134, 131, 226, 0.9)":"rgba(255, 255, 255, 0.9)",Yl(e,o[0],o[1],n/t.zoom.value,!0,!0),e.restore()},G4=({arrow:e,appState:t,type:o,context:n,elementsMap:r})=>{let i=o==="start"?e.startBinding:e.endBinding,a=i?.elementId&&r.get(i.elementId);if(!a||!V4(a)||a.isDeleted)return;let s=z4(i.fixedPoint,a,r);if(!rZ(s,e,a,r,t,o))return;let l=t.selectedLinearElement,c=!!l?.isDragging,m=o==="start"?0:e.points.length-1,p=!!l?.selectedPointsIndices?.includes(m);if(l?.hoveredFocusPointBinding===o&&!l.draggedFocusPointBinding&&sZ(n,t,s),!(p&&c)){let d=z4(i.fixedPoint,a,r),u=l?.hoveredFocusPointBinding===o,h=qn.getPointAtIndexGlobalCoordinates(e,m,r);pZ(n,t,h,d),uZ(n,t,d,VX/1.5,u)}},U4=(e,t,o,n,r)=>{Object.keys(n).forEach(i=>{let a=n[i];if(a!==void 0){let[s,l,c,m]=a;e.save(),e.lineWidth=1/o.zoom.value,t.selectionColor&&(e.strokeStyle=t.selectionColor),i==="rotation"?Yl(e,s+c/2,l+m/2,c/2,!0):e.roundRect?(e.beginPath(),e.roundRect(s,l,c,m,2/o.zoom.value),e.fill(),e.stroke()):Vl(e,s,l,c,m,s+c/2,l+m/2,r,!0),e.restore()}})},gZ=(e,t,o,n,r)=>{let[i,a,,,s,l]=yg(n,r),c=3,m=20,p=c/o.zoom.value,d=p/2,u=s-i+p,h=l-a+p,g=Math.min(m/o.zoom.value,u),E=Math.min(m/o.zoom.value,h);e.save(),e.fillStyle=t.selectionColor,e.strokeStyle=t.selectionColor,e.lineWidth=p,[[[-u,-h],[0,d],[g,d],[d,0],[d,E]],[[u-d,-h],[d,d],[-g+d,d],[0,0],[0,E]],[[-u,h],[0,-d],[g,-d],[d,0],[d,-E]],[[u-d,h],[d,-d],[-g+d,-d],[0,0],[0,-E]]].forEach(x=>{let[[y,v],[I,k],[L,S],[_,P],[T,M]]=x;e.save(),e.translate(s,l),e.rotate(n.angle),e.beginPath(),e.moveTo(y+I,v+k),e.lineTo(y+L,v+S),e.stroke(),e.beginPath(),e.moveTo(y+_,v+P),e.lineTo(y+T,v+M),e.stroke(),e.restore()}),e.restore()},hZ=(e,t,o,n)=>{t.save();let r=hx*2/o.zoom.value,i=e.width+r*2,a=e.height+r*2,s=e.x+i/2,l=e.y+a/2,c=-(i/2+r),m=-(a/2+r);t.translate(s+o.scrollX,l+o.scrollY),t.rotate(e.angle),t.lineWidth=1/o.zoom.value,t.strokeStyle=n,t.strokeRect(c,m,i,a),t.restore()},fZ=({app:e,canvas:t,elementsMap:o,visibleElements:n,selectedElements:r,allElementsMap:i,scale:a,appState:s,renderConfig:l,editorInterface:c,animationState:m,deltaTime:p})=>{if(t===null)return{atLeastOneVisibleElement:!1,elementsMap:o};let[d,u]=qd(t,a),h=m,g=Jd({canvas:t,scale:a,normalizedWidth:d,normalizedHeight:u});g.save(),g.scale(s.zoom.value,s.zoom.value);let E;if(n.forEach(I=>{s.selectedLinearElement?.isEditing&&s.selectedLinearElement.elementId===I.id&&I&&(E=I)}),E&&dx(g,s,E,o),s.selectionElement&&!s.isCropping)try{eZ(s.selectionElement,g,s,l.selectionColor)}catch(I){console.error(I)}if(s.editingTextElement&&O4(s.editingTextElement)){let I=i.get(s.editingTextElement.id);I&&!I.autoResize&&hZ(I,g,s,l.selectionColor)}if(s.isBindingEnabled&&s.suggestedBinding?h={...m,bindingHighlight:dZ(e,g,s.suggestedBinding,i,s,p,m?.bindingHighlight)}:h={...m,bindingHighlight:void 0},s.frameToHighlight&&mZ(g,s,s.frameToHighlight,o),s.elementsToHighlight&&H4(g,s,s.elementsToHighlight),s.activeLockedId){let I=i.get(s.activeLockedId),k=I?[I]:ux(i,s.activeLockedId);H4(g,s,k,{colors:["#ced4da"],dashed:!0})}let w=r.some(I=>kl(I));r.length===1&&s.selectedLinearElement?.isEditing&&s.selectedLinearElement.elementId===r[0].id&&dx(g,s,r[0],o);let x=s.selectedLinearElement,y=x&&qn.getElement(x.elementId,i);if(y&&(s.selectedLinearElement.isDragging||(x.segmentMidPointHoveredCoords?iZ(g,s):(Cl(y)?x.hoverPointIndex===0||x.hoverPointIndex===y.points.length-1:x.hoverPointIndex>=0)&&aZ(g,s,o)),jX(y)&&(G4({arrow:y,elementsMap:i,appState:s,context:g,type:"start"}),G4({arrow:y,elementsMap:i,appState:s,context:g,type:"end"}))),!s.multiElement&&!s.newElement&&!s.selectedLinearElement?.isEditing){let I=XX(r,s,c),k=r.length===1&&qX(r[0]);k&&s.selectedLinearElement?.elementId===r[0].id&&!r[0].locked&&dx(g,s,r[0],o);let L=l.selectionColor||"#000";if(I){let S=UX(r),_=[];for(let T of o.values()){let M=[],N=l.remoteSelectedElementIds.get(T.id);if(k&&Cl(T)&&(T.startBinding||T.endBinding)||(S.has(T.id)&&!oZ(s,T)&&M.push(L),N&&M.push(...N.map(O=>qi(O,s.collaborators.get(O))))),M.length){let[O,B,U,D,F,z]=yg(T,o,!0);_.push({angle:T.angle,x1:O,y1:B,x2:U,y2:D,selectionColors:T.locked?["#ced4da"]:M,dashed:!!N||T.locked,cx:F,cy:z,activeEmbeddable:s.activeEmbeddable?.element===T&&s.activeEmbeddable.state==="active",padding:T.id===s.croppingElementId||F4(T)?0:void 0})}}let P=T=>{let M=ux(o,T),[N,O,B,U]=gx(M);_.push({angle:0,x1:N,x2:B,y1:O,y2:U,selectionColors:M.some(D=>D.locked)?["#ced4da"]:["#000"],dashed:!0,cx:N+(B-N)/2,cy:O+(U-O)/2,activeEmbeddable:!1})};for(let T of tZ(s))P(T);s.editingGroupId&&P(s.editingGroupId),_.forEach(T=>$4(g,s,T))}if(g.save(),g.translate(s.scrollX,s.scrollY),r.length===1){g.fillStyle="#fff";let S=$X(r[0],s.zoom,o,"mouse",lx(c));if(!s.viewModeEnabled&&I&&!O4(s.editingTextElement)&&!s.croppingElementId&&U4(g,l,s,S,r[0].angle),s.croppingElementId&&!s.isCropping){let _=o.get(s.croppingElementId);_&&F4(_)&&gZ(g,l,s,_,o)}}else if(r.length>1&&!s.isRotating&&!r.some(S=>S.locked)){let S=hx*2/s.zoom.value;g.fillStyle="#fff";let[_,P,T,M]=gx(r,o),N=g.getLineDash();g.setLineDash([2/s.zoom.value]);let O=g.lineWidth;g.lineWidth=1/s.zoom.value,g.strokeStyle=L,Vl(g,_-S,P-S,T-_+S*2,M-P+S*2,(_+T)/2,(P+M)/2,0),g.lineWidth=O,g.setLineDash(N);let B=KX([_,P,T,M,(_+T)/2,(P+M)/2],0,s.zoom,"mouse",w?{...lx(c),rotation:!0}:lx(c));r.some(U=>!U.locked)&&U4(g,l,s,B,0)}g.restore()}s.searchMatches?.matches.forEach(({id:I,focus:k,matchedLines:L})=>{let S=o.get(I);if(S){let[_,P,,,T,M]=yg(S,o,!0);g.save(),s.theme===Ii.LIGHT?k?g.fillStyle="rgba(255, 124, 0, 0.4)":g.fillStyle="rgba(255, 226, 0, 0.4)":k?g.fillStyle="rgba(229, 82, 0, 0.4)":g.fillStyle="rgba(99, 52, 0, 0.4)";let N=kl(S)?s.zoom.value:1;g.translate(s.scrollX,s.scrollY),g.translate(T,M),g.rotate(S.angle),L.forEach(O=>{(O.showOnCanvas||k)&&g.fillRect(_+O.offsetX/N-T,P+O.offsetY/N-M,O.width/N,O.height/N)}),g.restore()}}),R4(g,s),g.restore(),lI({context:g,renderConfig:l,appState:s,normalizedWidth:d,normalizedHeight:u});let v;return l.renderScrollbars&&(v=J3(o,d,u,s),g.save(),g.fillStyle=q3,g.strokeStyle="rgba(255,255,255,0.8)",[v.horizontal,v.vertical].forEach(I=>{I&&ap(g,I.x,I.y,I.width,I.height,Ko/2)}),g.restore()),{scrollBars:v,atLeastOneVisibleElement:n.length>0,elementsMap:o,animationState:h}},K4=e=>{let t=fZ(e);return e.callback(t),t};import{jsx as IZ}from"react/jsx-runtime";var j4="animateInteractiveScene",wZ=e=>{let t=X4(!1),o=X4(null);return xZ(()=>{if(!t.current){t.current=!0;return}let n=new Map,r=new Map,i=new Map,a=new Map,s=new Map;e.appState.collaborators.forEach((c,m)=>{if(c.selectedElementIds)for(let p of Object.keys(c.selectedElementIds))i.has(p)||i.set(p,[]),i.get(p).push(m);!c.pointer||c.pointer.renderCursor===!1||(c.username&&a.set(m,c.username),c.userState&&s.set(m,c.userState),r.set(m,yZ({sceneX:c.pointer.x,sceneY:c.pointer.y},e.appState)),n.set(m,c.button))});let l=e.containerRef?.current&&getComputedStyle(e.containerRef.current).getPropertyValue("--color-selection")||"#6965db";o.current={app:e.app,canvas:e.canvas,elementsMap:e.elementsMap,visibleElements:e.visibleElements,selectedElements:e.selectedElements,allElementsMap:e.allElementsMap,scale:window.devicePixelRatio,appState:e.appState,renderConfig:{remotePointerViewportCoords:r,remotePointerButton:n,remoteSelectedElementIds:i,remotePointerUsernames:a,remotePointerUserStates:s,selectionColor:l,renderScrollbars:e.renderScrollbars,lastViewportPosition:e.app.lastViewportPosition},editorInterface:e.editorInterface,callback:e.renderInteractiveSceneCallback,animationState:{bindingHighlight:void 0},deltaTime:0},Id.running(j4)||Id.start(j4,({deltaTime:c,state:m})=>{let p=K4({...o.current,deltaTime:c,animationState:m}).animationState;if(p){for(let d in p)if(p[d]!==void 0)return p}})}),IZ("canvas",{className:"excalidraw__canvas interactive",style:{width:e.appState.width,height:e.appState.height,cursor:e.appState.viewModeEnabled&&e.appState.activeTool.type!=="laser"?Z4.GRAB:Z4.AUTO},width:e.appState.width*e.scale,height:e.appState.height*e.scale,ref:e.handleCanvasRef,onContextMenu:e.onContextMenu,onPointerMove:e.onPointerMove,onPointerUp:e.onPointerUp,onPointerCancel:e.onPointerCancel,onTouchMove:e.onTouchMove,onPointerDown:e.onPointerDown,onDoubleClick:e.appState.viewModeEnabled?void 0:e.onDoubleClick,children:f("labels.drawingCanvas")})},q4=e=>({zoom:e.zoom,scrollX:e.scrollX,scrollY:e.scrollY,width:e.width,height:e.height,viewModeEnabled:e.viewModeEnabled,activeTool:e.activeTool,openDialog:e.openDialog,editingGroupId:e.editingGroupId,selectedElementIds:e.selectedElementIds,frameToHighlight:e.frameToHighlight,offsetLeft:e.offsetLeft,offsetTop:e.offsetTop,theme:e.theme,selectionElement:e.selectionElement,selectedGroupIds:e.selectedGroupIds,selectedLinearElement:e.selectedLinearElement,multiElement:e.multiElement,newElement:e.newElement,isBindingEnabled:e.isBindingEnabled,suggestedBinding:e.suggestedBinding,isRotating:e.isRotating,elementsToHighlight:e.elementsToHighlight,collaborators:e.collaborators,activeEmbeddable:e.activeEmbeddable,snapLines:e.snapLines,zenModeEnabled:e.zenModeEnabled,editingTextElement:e.editingTextElement,isCropping:e.isCropping,croppingElementId:e.croppingElementId,searchMatches:e.searchMatches,activeLockedId:e.activeLockedId,hoveredElementIds:e.hoveredElementIds,frameRendering:e.frameRendering,shouldCacheIgnoreZoom:e.shouldCacheIgnoreZoom,exportScale:e.exportScale,currentItemArrowType:e.currentItemArrowType}),vZ=(e,t)=>e.selectionNonce!==t.selectionNonce||e.sceneNonce!==t.sceneNonce||e.scale!==t.scale||e.elementsMap!==t.elementsMap||e.visibleElements!==t.visibleElements||e.selectedElements!==t.selectedElements||e.renderScrollbars!==t.renderScrollbars?!1:EZ(q4(e.appState),q4(t.appState)),bx=bZ.memo(wZ,vZ);import TZ,{useEffect as J4,useRef as Q4}from"react";import{isShallowEqual as e6}from"@orangecatai/common";import{jsx as SZ}from"react/jsx-runtime";var CZ=e=>{let t=Q4(null),o=Q4(!1);return J4(()=>{e.canvas.style.width=`${e.appState.width}px`,e.canvas.style.height=`${e.appState.height}px`,e.canvas.width=e.appState.width*e.scale,e.canvas.height=e.appState.height*e.scale},[e.appState.height,e.appState.width,e.canvas,e.scale]),J4(()=>{let n=t.current;if(!n)return;let r=e.canvas;o.current||(o.current=!0,n.replaceChildren(r),r.classList.add("excalidraw__canvas","static")),VE({canvas:r,rc:e.rc,scale:e.scale,elementsMap:e.elementsMap,allElementsMap:e.allElementsMap,visibleElements:e.visibleElements,appState:e.appState,renderConfig:e.renderConfig},ha())}),SZ("div",{className:"excalidraw__canvas-wrapper",ref:t})},t6=e=>({zoom:e.zoom,scrollX:e.scrollX,scrollY:e.scrollY,width:e.width,height:e.height,viewModeEnabled:e.viewModeEnabled,openDialog:e.openDialog,hoveredElementIds:e.hoveredElementIds,offsetLeft:e.offsetLeft,offsetTop:e.offsetTop,theme:e.theme,shouldCacheIgnoreZoom:e.shouldCacheIgnoreZoom,viewBackgroundColor:e.viewBackgroundColor,exportScale:e.exportScale,selectedElementsAreBeingDragged:e.selectedElementsAreBeingDragged,gridSize:e.gridSize,gridStep:e.gridStep,frameRendering:e.frameRendering,selectedElementIds:e.selectedElementIds,frameToHighlight:e.frameToHighlight,editingGroupId:e.editingGroupId,currentHoveredFontFamily:e.currentHoveredFontFamily,croppingElementId:e.croppingElementId,suggestedBinding:e.suggestedBinding}),kZ=(e,t)=>e.sceneNonce!==t.sceneNonce||e.scale!==t.scale||e.elementsMap!==t.elementsMap||e.visibleElements!==t.visibleElements?!1:e6(t6(e.appState),t6(t.appState))&&e6(e.renderConfig,t.renderConfig),xx=TZ.memo(CZ,kZ);import{useEffect as RZ,useRef as NZ}from"react";import{throttleRAF as MZ}from"@orangecatai/common";import{getTargetFrame as PZ,isInvisiblySmallElement as AZ,renderElement as LZ,shouldApplyFrameClip as _Z}from"@orangecatai/element";var o6=({canvas:e,rc:t,newElement:o,elementsMap:n,allElementsMap:r,scale:i,appState:a,renderConfig:s})=>{if(e){let[l,c]=qd(e,i),m=Jd({canvas:e,scale:i,normalizedWidth:l,normalizedHeight:c});if(m.save(),m.scale(a.zoom.value,a.zoom.value),o&&o.type!=="selection"){if(AZ(o))return;if((o.frameId||a.frameToHighlight?.id)&&a.frameRendering.enabled&&a.frameRendering.clip){let d=PZ(o,n,a);d&&_Z(o,d,a,n)&&WE(d,m,s,a)}LZ(o,n,r,t,m,s,a)}else m.clearRect(0,0,l,c);m.restore()}},DZ=MZ(e=>{o6(e)},{trailing:!0}),n6=(e,t)=>{if(t){DZ(e);return}o6(e)};import{jsx as FZ}from"react/jsx-runtime";var BZ=e=>{let t=NZ(null);return RZ(()=>{t.current&&n6({canvas:t.current,scale:e.scale,newElement:e.appState.newElement,elementsMap:e.elementsMap,allElementsMap:e.allElementsMap,rc:e.rc,renderConfig:e.renderConfig,appState:e.appState},ha())}),FZ("canvas",{className:"excalidraw__canvas",style:{width:e.appState.width,height:e.appState.height},width:e.appState.width*e.scale,height:e.appState.height*e.scale,ref:t})},r6=BZ;import{useCallback as OZ,useEffect as zZ,useRef as HZ}from"react";import{jsx as i6,jsxs as UZ}from"react/jsx-runtime";var GZ=5e3,a6=({message:e,onClose:t,closable:o=!1,duration:n=GZ,style:r})=>{let i=HZ(0),a=n!==1/0,s=OZ(()=>{a&&(i.current=window.setTimeout(()=>t(),n))},[t,n,a]);return zZ(()=>{if(a)return s(),()=>clearTimeout(i.current)},[s,e,n,a]),UZ("div",{className:"Toast",onMouseEnter:a?()=>clearTimeout(i?.current):void 0,onMouseLeave:a?s:void 0,style:r,children:[i6("p",{className:"Toast__message",children:e}),o&&i6(ne,{icon:Fo,"aria-label":"close",type:"icon",onClick:t,className:"close"})]})};import{getCommonBounds as WZ,getElementsInGroup as YZ,selectGroupsFromGivenElements as VZ}from"@orangecatai/element";import{sceneCoordsToViewportCoords as $Z}from"@orangecatai/common";import{flushSync as KZ}from"react-dom";import{jsx as ZZ}from"react/jsx-runtime";var XZ=({app:e,activeLockedId:t})=>{let o=e.scene.getElement(t),n=o?[o]:YZ(e.scene.getNonDeletedElementsMap(),t);if(n.length===0)return null;let[r,i]=WZ(n),{x:a,y:s}=$Z({sceneX:r,sceneY:i},e.state);return ZZ("div",{className:"UnlockPopup",style:{bottom:`${e.state.height+12-s+e.state.offsetTop}px`,left:`${a-e.state.offsetLeft}px`},onClick:()=>{KZ(()=>{let l=VZ(n,e.state);e.setState({selectedElementIds:n.reduce((c,m)=>({...c,[m.id]:!0}),{}),selectedGroupIds:l,activeLockedId:null})}),e.actionManager.executeAction(Pc)},title:f("labels.elementLock.unlock"),children:uy})},s6=XZ;import{Fragment as lP,jsx as Se,jsxs as Od}from"react/jsx-runtime";var uP=nr.createContext(null),gP=nr.createContext(null),qx={formFactor:"desktop",desktopUIMode:"full",userAgent:mP(typeof navigator<"u"?navigator.userAgent:""),isTouchScreen:!1,canFitSidebar:!1,isLandscape:!0},Qx=nr.createContext(qx);Qx.displayName="EditorInterfaceContext";var eE=nr.createContext({container:null,id:null});eE.displayName="ExcalidrawContainerContext";var tE=nr.createContext([]);tE.displayName="ExcalidrawElementsContext";var oE=nr.createContext({...Rr(),width:0,height:0,offsetLeft:0,offsetTop:0});oE.displayName="ExcalidrawAppStateContext";var nE=nr.createContext(()=>{console.warn("Uninitialized ExcalidrawSetAppStateContext context!")});nE.displayName="ExcalidrawSetAppStateContext";var rE=nr.createContext(null);rE.displayName="ExcalidrawActionManagerContext";var Qe=()=>Li(uP),Nn=()=>Li(gP),we=()=>Li(Qx),_t=()=>Dg(we()),qe=()=>Li(eE),Hr=()=>Li(tE),Go=()=>Li(oE),ve=()=>Li(nE),nt=()=>Li(rE),_d=!1,Kx=0,Dd=null,Pi=!1,Rd=!1,Xx=!1,Nd={horizontal:null,vertical:null},Ai=0,Bd=!1,Zx=new Map,jx=!1,aP=0,sP=!1,Fd=null,_e={pointers:new Map,lastCenter:null,initialDistance:null,initialScale:null},Jx=class e extends nr.Component{constructor(o){super(o);A(this,"canvas");A(this,"interactiveCanvas",null);A(this,"rc");A(this,"unmounted",!1);A(this,"actionManager");A(this,"editorInterface",qx);A(this,"stylesPanelMode",Dg(qx));A(this,"excalidrawContainerRef",nr.createRef());A(this,"scene");A(this,"fonts");A(this,"renderer");A(this,"visibleElements");A(this,"resizeObserver");A(this,"library");A(this,"libraryItemsFromStorage");A(this,"id");A(this,"store");A(this,"history");A(this,"excalidrawContainerValue");A(this,"files",{});A(this,"imageCache",new Map);A(this,"iFrameRefs",new Map);A(this,"embedsValidationStatus",new Map);A(this,"initializedEmbeds",new Set);A(this,"handleToastClose",()=>{this.setToast(null)});A(this,"elementsPendingErasure",new Set);A(this,"flowChartCreator",new pq);A(this,"flowChartNavigator",new uq);A(this,"bindModeHandler",null);A(this,"hitLinkElement");A(this,"lastPointerDownEvent",null);A(this,"lastPointerUpEvent",null);A(this,"lastPointerMoveEvent",null);A(this,"lastPointerMoveCoords",null);A(this,"previousPointerMoveCoords",null);A(this,"lastViewportPosition",{x:0,y:0});A(this,"animationFrameHandler",new ru);A(this,"laserTrails",new ku(this.animationFrameHandler,this));A(this,"eraserTrail",new Lu(this.animationFrameHandler,this));A(this,"lassoTrail",new Au(this.animationFrameHandler,this));A(this,"onChangeEmitter",new Ta);A(this,"onPointerDownEmitter",new Ta);A(this,"onPointerUpEmitter",new Ta);A(this,"onUserFollowEmitter",new Ta);A(this,"onScrollChangeEmitter",new Ta);A(this,"missingPointerEventCleanupEmitter",new Ta);A(this,"onRemoveEventListenersEmitter",new Ta);A(this,"updateEditorAtom",(o,...n)=>{let r=Et.set(o,...n);return this.triggerRender(),r});A(this,"previousHoveredBindableElement",null);A(this,"getEffectiveGridSize",()=>ai(this)?this.state.gridSize:null);A(this,"handleIframeLikeElementHover",({hitElement:o,scenePointer:n,moveEvent:r})=>o&&Lx(o)&&(this.state.viewModeEnabled||this.state.activeTool.type==="laser"||this.isIframeLikeElementCenter(o,r,n.x,n.y))?(Re(this.interactiveCanvas,st.POINTER),this.setState({activeEmbeddable:{element:o,state:"hover"}}),!0):(this.state.activeEmbeddable?.state==="hover"&&this.setState({activeEmbeddable:null}),!1));A(this,"updateEmbedValidationStatus",(o,n)=>{this.embedsValidationStatus.set(o.id,n),Ld.delete(o)});A(this,"updateEmbeddables",()=>{let o=new Set,n=!1;this.scene.getNonDeletedElements().filter(r=>{if(Lr(r)){if(o.add(r.id),!this.embedsValidationStatus.has(r.id)){n=!0;let i=Nx(r.link,this.props.validateEmbeddable);this.updateEmbedValidationStatus(r,i)}}else Ll(r)&&o.add(r.id);return!1}),n&&this.scene.triggerUpdate(),this.iFrameRefs.forEach((r,i)=>{o.has(i)||this.iFrameRefs.delete(i)})});A(this,"getFrameNameDOMId",o=>`${this.id}-frame-name-${o.id}`);A(this,"frameNameBoundsCache",{get:o=>{let n=this.frameNameBoundsCache._cache.get(o.id);if(!n||n.zoom!==this.state.zoom.value||n.versionNonce!==o.versionNonce){let r=document.getElementById(this.getFrameNameDOMId(o));if(r){let i=r.getBoundingClientRect(),a=ot({clientX:i.x,clientY:i.y},this.state),s=ot({clientX:i.right,clientY:i.bottom},this.state);return n={x:a.x,y:a.y,width:s.x-a.x,height:s.y-a.y,angle:0,zoom:this.state.zoom.value,versionNonce:o.versionNonce},this.frameNameBoundsCache._cache.set(o.id,n),n}return null}return n},_cache:new Map});A(this,"resetEditingFrame",o=>{o&&this.scene.mutateElement(o,{name:o.name?.trim()||null}),this.setState({editingFrame:null})});A(this,"renderFrameNames",()=>{if(!this.state.frameRendering.enabled||!this.state.frameRendering.name)return this.state.editingFrame&&this.resetEditingFrame(null),null;let o=this.state.theme===Ig.DARK,n=this.scene.getNonDeletedFramesLikes(),r=n.length>0&&this.state.searchMatches?.focusedId&&jt(this.scene.getElement(this.state.searchMatches.focusedId))?this.state.searchMatches.matches.find(i=>i.focus):null;return n.map(i=>{if(!B6(i,this.canvas.width/window.devicePixelRatio,this.canvas.height/window.devicePixelRatio,{offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,zoom:this.state.zoom},this.scene.getNonDeletedElementsMap()))return this.state.editingFrame===i.id&&this.resetEditingFrame(i),null;let{x:a,y:s}=Cg({sceneX:i.x,sceneY:i.y},this.state),l=6,c,m=aq(i),p=`${Math.round(i.width)} x ${Math.round(i.height)}`;if(i.id===this.state.editingFrame){let d=m;c=Se("input",{autoFocus:!0,value:d,onChange:u=>{this.scene.mutateElement(i,{name:u.target.value})},onFocus:u=>u.target.select(),onBlur:()=>this.resetEditingFrame(i),onKeyDown:u=>{(u.key===oe.ESCAPE||u.key===oe.ENTER)&&this.resetEditingFrame(i)},style:{background:o?Tj(this.state.viewBackgroundColor):this.state.viewBackgroundColor,zIndex:2,border:"none",display:"block",padding:`${l}px`,borderRadius:4,boxShadow:"inset 0 0 0 1px var(--color-primary)",fontFamily:"Assistant",fontSize:`${on.nameFontSize}px`,transform:`translate(-${l}px, ${l}px)`,color:o?on.nameColorDarkTheme:on.nameColorLightTheme,overflow:"hidden",maxWidth:`${document.body.clientWidth-a-l}px`},size:d.length+1||1,dir:"auto",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off"})}else c=Od(lP,{children:[Se("span",{children:m}),Se("span",{style:{marginLeft:8,opacity:.7,fontSize:on.nameFontSize-1},children:p})]});return Se("div",{id:this.getFrameNameDOMId(i),className:Sx.FRAME_NAME,style:{position:"absolute",bottom:`${this.state.height+on.nameOffsetY-s+this.state.offsetTop}px`,left:`${a-this.state.offsetLeft}px`,zIndex:2,fontSize:on.nameFontSize,color:o?on.nameColorDarkTheme:on.nameColorLightTheme,lineHeight:on.nameLineHeight,width:"max-content",maxWidth:r?.id===i.id&&r?.focus?"none":`${i.width*this.state.zoom.value}px`,overflow:i.id===this.state.editingFrame?"visible":"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",cursor:st.MOVE,pointerEvents:this.state.viewModeEnabled?Sl.disabled:Sl.enabled},onPointerDown:d=>this.handleCanvasPointerDown(d),onWheel:d=>this.handleWheel(d),onContextMenu:this.handleCanvasContextMenu,onDoubleClick:()=>{this.setState({editingFrame:i.id})},children:c},i.id)})});A(this,"focusContainer",()=>{this.excalidrawContainerRef.current?.focus()});A(this,"getSceneElementsIncludingDeleted",()=>this.scene.getElementsIncludingDeleted());A(this,"getSceneElementsMapIncludingDeleted",()=>this.scene.getElementsMapIncludingDeleted());A(this,"getSceneElements",()=>this.scene.getNonDeletedElements());A(this,"onInsertElements",o=>{this.addElementsFromPasteOrLibrary({elements:o,position:"center",files:null})});A(this,"onExportImage",async(o,n,r)=>{ge("export",o,"ui");let i=await Xi(o,n,this.state,this.files,{exportBackground:this.state.exportBackground,name:this.getName(),viewBackgroundColor:this.state.viewBackgroundColor,exportingFrame:r.exportingFrame}).catch(wj).catch(a=>{console.error(a),this.setState({errorMessage:a.message})});this.state.exportEmbedScene&&i&&Qd(i)&&this.setState({fileHandle:i})});A(this,"magicGenerations",new Map);A(this,"updateMagicGeneration",({frameElement:o,data:n})=>{n.status==="pending"?this.scene.mutateElement(o,{customData:{generationData:void 0}},{informMutation:!1,isDragging:!1}):this.scene.mutateElement(o,{customData:{generationData:n}},{informMutation:!1,isDragging:!1}),this.magicGenerations.set(o.id,n),this.triggerRender()});A(this,"plugins",{});A(this,"onMagicframeToolSelect",()=>{let o=this.scene.getSelectedElements({selectedElementIds:this.state.selectedElementIds});if(o.length===0)this.setActiveTool({type:Qn.magicframe}),ge("ai","tool-select (empty-selection)","d2c");else{let n=o.length===1&&_x(o[0])&&o[0];if(!n&&o.some(i=>jt(i)||i.frameId)){this.setActiveTool({type:Qn.magicframe});return}ge("ai","tool-select (existing selection)","d2c");let r;if(n)r=n;else{let[i,a,s,l]=Pl(o),c=50;r=L6({...on,x:i-c,y:a-c,width:s-i+c*2,height:l-a+c*2,opacity:100,locked:!1}),this.scene.insertElement(r);for(let m of o)this.scene.mutateElement(m,{frameId:r.id});this.setState({selectedElementIds:{[r.id]:!0}})}this.onMagicFrameGenerate(r,"upstream")}});A(this,"onImageGeneratorSelect",()=>{let r=(this.canvas.width/window.devicePixelRatio/2-this.state.offsetLeft)/this.state.zoom.value-this.state.scrollX,i=(this.canvas.height/window.devicePixelRatio/2-this.state.offsetTop)/this.state.zoom.value-this.state.scrollY,a=P6({...on,x:r-896/2,y:i-1344/2,width:896,height:1344,opacity:100,locked:!1,backgroundColor:"#cce8f5",fillStyle:"solid",customData:{type:"image-generator",imageGeneratorAutoFitPending:!0}});this.scene.insertElement(a),this.setActiveTool({type:"selection"}),this.setState({selectedElementIds:{[a.id]:!0}})});A(this,"insertGeneratedImageIntoFrame",async(o,n)=>{let r=Ex(),i=Mx({type:"image",x:n.x,y:n.y,width:n.width,height:n.height,fileId:r,status:"pending",scale:[1,1],frameId:null});this.scene.insertElement(i),this.scene.mutateElement(i,{frameId:n.id}),this.addFiles([{id:r,dataURL:o,mimeType:Bo(o),created:Date.now(),lastRetrieved:Date.now()}])});A(this,"insertGeneratedImageNearElement",async(o,n,r,i)=>{let s=this.scene.getNonDeletedElementsMap(),l=this.scene.getNonDeletedElements().filter(x=>x.id!==n.id),[c,m,p,d]=Mg(n,s),u=[{x:p+25,y:m},{x:c,y:d+25},{x:c-r-25,y:m},{x:c,y:m-i-25}],h=(x,y)=>{let v=x+r,I=y+i,k=x-25,L=y-25,S=v+25,_=I+25;return l.some(P=>{let[T,M,N,O]=Mg(P,s);return T<S&&N>k&&M<_&&O>L})},g=u.find(x=>!h(x.x,x.y))??u[0],E=Ex(),w=Mx({type:"image",x:g.x,y:g.y,width:r,height:i,fileId:E,status:"pending",scale:[1,1],frameId:null});this.scene.insertElement(w),this.addFiles([{id:E,dataURL:o,mimeType:Bo(o),created:Date.now(),lastRetrieved:Date.now()}]),this.setState({selectedElementIds:{[w.id]:!0}})});A(this,"openEyeDropper",({type:o})=>{this.updateEditorAtom(zr,{swapPreviewOnAlt:!0,colorPickerType:o==="stroke"?"elementStroke":"elementBackground",onSelect:(n,r)=>{let i=o==="background"&&r.altKey||o==="stroke"&&!r.altKey;!this.scene.getSelectedElements(this.state).length||this.state.activeTool.type!=="selection"?i?this.syncActionResult({appState:{...this.state,currentItemStrokeColor:n},captureUpdate:so.IMMEDIATELY}):this.syncActionResult({appState:{...this.state,currentItemBackgroundColor:n},captureUpdate:so.IMMEDIATELY}):this.updateScene({elements:this.scene.getElementsIncludingDeleted().map(s=>this.state.selectedElementIds[s.id]?Si(s,{[i?"strokeColor":"backgroundColor"]:n}):s),captureUpdate:so.IMMEDIATELY})},keepOpenOnAlt:!1})});A(this,"dismissLinearEditor",()=>{setTimeout(()=>{this.state.selectedLinearElement?.isEditing&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,isEditing:!1}})})});A(this,"syncActionResult",mt(o=>{if(this.unmounted||o===!1)return;this.store.scheduleAction(o.captureUpdate);let n=!1,r=null;if(o.elements&&(this.scene.replaceAllElements(o.elements),n=!0),o.files&&(this.addMissingFiles(o.files,o.replaceFiles),this.addNewImagesToImageCache()),o.appState||r||this.state.contextMenu){let i=o?.appState?.viewModeEnabled||!1,a=o?.appState?.zenModeEnabled||!1,s=o?.appState?.theme||this.props.theme||Ig.LIGHT,l=o?.appState?.name??this.state.name,c=o?.appState?.errorMessage??this.state.errorMessage;typeof this.props.viewModeEnabled<"u"&&(i=this.props.viewModeEnabled),typeof this.props.zenModeEnabled<"u"&&(a=this.props.zenModeEnabled),r=o.appState?.editingTextElement||null,o.elements&&r&&o.elements.forEach(m=>{r?.id===m.id&&r!==m&&Q6(m)&&vn(m)&&(r=m)}),r?.isDeleted&&(r=null),this.setState(m=>{let p=o.appState||{};return{...m,...p,contextMenu:null,editingTextElement:r,viewModeEnabled:i,zenModeEnabled:a,theme:s,name:l,errorMessage:c}}),n=!0}n||this.scene.triggerUpdate()}));A(this,"onBlur",mt(()=>{Pi=!1,this.setState({isBindingEnabled:!0})}));A(this,"onUnload",()=>{this.onBlur()});A(this,"disableEvent",o=>{o.preventDefault()});A(this,"resetHistory",()=>{this.history.clear()});A(this,"resetStore",()=>{this.store.clear()});A(this,"resetScene",mt(o=>{this.scene.replaceAllElements([]),this.setState(n=>({...Rr(),isLoading:o?.resetLoadingState?!1:n.isLoading,theme:this.state.theme})),this.resetStore(),this.resetHistory()}));A(this,"initializeScene",async()=>{"launchQueue"in window&&"LaunchParams"in window&&window.launchQueue.setConsumer(async a=>{if(!a.files.length)return;let s=a.files[0],l=await s.getFile();this.loadFileToCanvas(new File([l],l.name||"",{type:l.type}),s)}),this.props.theme&&this.setState({theme:this.props.theme}),this.state.isLoading||this.setState({isLoading:!0});let o=null;try{typeof this.props.initialData=="function"?o=await this.props.initialData()||null:o=await this.props.initialData||null,o?.libraryItems&&this.library.updateLibrary({libraryItems:o.libraryItems,merge:!0}).catch(a=>{console.error(a)})}catch(a){console.error(a),o={appState:{errorMessage:a.message||"Encountered an error during importing or restoring scene data"}}}let n=Ni(o?.elements,null,{repairBindings:!0,deleteInvisibleElements:!0}),r=Oa(o?.appState,null),i=r.activeTool;r.preferredSelectionTool.initialized||(r.preferredSelectionTool={type:this.editorInterface.formFactor==="phone"?"lasso":"selection",initialized:!0}),r={...r,theme:this.props.theme||r.theme,openSidebar:r?.openSidebar||this.state.openSidebar,activeTool:i.type==="image"||i.type==="lasso"||i.type==="selection"?{...i,type:r.preferredSelectionTool.type}:r.activeTool,isLoading:!1,toast:this.state.toast},o?.scrollToContent&&(r={...r,...Ri(n,{...r,width:this.state.width,height:this.state.height,offsetTop:this.state.offsetTop,offsetLeft:this.state.offsetLeft})}),this.resetStore(),this.resetHistory(),this.syncActionResult({elements:n,appState:r,files:o?.files,captureUpdate:so.NEVER}),this.clearImageShapeCache(),this.fonts.loadSceneFonts().then(a=>{this.fonts.onLoaded(a)}),Ux(window.location.href)&&this.scrollToContent(window.location.href,{animate:!1})});A(this,"getFormFactor",(o,n)=>this.props.UIOptions.getFormFactor?.(o,n)??Pj(o,n));A(this,"refreshEditorInterface",()=>{let o=this.excalidrawContainerRef.current;if(!o)return;let{width:n,height:r}=o.getBoundingClientRect(),i=Dj(),a=mP(typeof navigator<"u"?navigator.userAgent:""),s=this.props.UIOptions.dockedSidebarBreakpoint!=null?this.props.UIOptions.dockedSidebarBreakpoint:rj,l=kx(this.editorInterface,{desktopUIMode:i??this.editorInterface.desktopUIMode,formFactor:this.getFormFactor(n,r),userAgent:a,canFitSidebar:n>s,isLandscape:n>r});this.editorInterface=l,this.reconcileStylesPanelMode(l)});A(this,"reconcileStylesPanelMode",o=>{let n=Dg(o);if(n===this.stylesPanelMode)return;let r=this.stylesPanelMode;this.stylesPanelMode=n,r!=="full"&&n==="full"&&this.setState(i=>({preferredSelectionTool:{type:"selection",initialized:!0}}))});A(this,"setDesktopUIMode",o=>{let n=Rj(o);this.editorInterface=kx(this.editorInterface,{desktopUIMode:n}),this.reconcileStylesPanelMode(this.editorInterface)});A(this,"onResize",mt(()=>{this.scene.getElementsIncludingDeleted().forEach(o=>Ld.delete(o)),this.refreshEditorInterface(),this.updateDOMRect(),this.setState({})}));A(this,"onFullscreenChange",()=>{!document.fullscreenElement&&this.state.activeEmbeddable?.state==="active"&&this.setState({activeEmbeddable:null})});A(this,"renderInteractiveSceneCallback",({atLeastOneVisibleElement:o,scrollBars:n,elementsMap:r})=>{n&&(Nd=n);let i=this.state.editingTextElement?!1:!o&&r.size>0;this.state.scrolledOutside!==i&&this.setState({scrolledOutside:i}),this.scheduleImageRefresh()});A(this,"onScroll",I6(()=>{let{offsetTop:o,offsetLeft:n}=this.getCanvasOffsets();this.setState(r=>r.offsetLeft===n&&r.offsetTop===o?null:{offsetTop:o,offsetLeft:n})},ij));A(this,"onCut",mt(o=>{!this.excalidrawContainerRef.current?.contains(document.activeElement)||kd(o.target)||(this.actionManager.executeAction(cp,"keyboard",o),o.preventDefault(),o.stopPropagation())}));A(this,"onCopy",mt(o=>{!this.excalidrawContainerRef.current?.contains(document.activeElement)||kd(o.target)||(this.actionManager.executeAction(Ls,"keyboard",o),o.preventDefault(),o.stopPropagation())}));A(this,"onTouchStart",o=>{if(Aj&&o.preventDefault(),!_d){_d=!0,o.touches.length===1&&(Dd={x:o.touches[0].clientX,y:o.touches[0].clientY}),clearTimeout(Kx),Kx=window.setTimeout(e.resetTapTwice,aj);return}if(_d&&o.touches.length===1&&Dd){let n=o.touches[0];Ti(de(n.clientX,n.clientY),de(Dd.x,Dd.y))<=Sj&&(this.lassoTrail.endPath(),this.deselectElements(),this.handleCanvasDoubleClick({clientX:n.clientX,clientY:n.clientY})),_d=!1,clearTimeout(Kx)}o.touches.length===2&&this.setState({selectedElementIds:Oe({},this.state),activeEmbeddable:null})});A(this,"onTouchEnd",o=>{this.resetContextMenuTimer(),o.touches.length>0?this.setState({previousSelectedElementIds:{},selectedElementIds:Oe(this.state.previousSelectedElementIds,this.state)}):_e.pointers.clear()});A(this,"pasteFromClipboard",mt(async o=>{let n=!!jx,r=document.activeElement,i=this.excalidrawContainerRef.current?.contains(r);if(o&&!i)return;let a=document.elementFromPoint(this.lastViewportPosition.x,this.lastViewportPosition.y);if(o&&(!(a instanceof HTMLCanvasElement)||kd(r)))return;let s=await Is(o),l=s.getFiles(),c=await Qm(s,n);if(this.props.onPaste)try{if(await this.props.onPaste(c,o)===!1)return}catch(m){console.error(m)}await this.insertClipboardContent(c,l,n),this.setActiveTool({type:this.state.preferredSelectionTool.type},!0),o?.preventDefault()}));A(this,"addElementsFromPasteOrLibrary",o=>{let n=Ni(o.elements,null,{deleteInvisibleElements:!0}),[r,i,a,s]=Pl(n),l=Ml(r,a)/2,c=Ml(i,s)/2,m=typeof o.position=="object"?o.position.clientX:o.position==="cursor"?this.lastViewportPosition.x:this.state.width/2+this.state.offsetLeft,p=typeof o.position=="object"?o.position.clientY:o.position==="cursor"?this.lastViewportPosition.y:this.state.height/2+this.state.offsetTop,{x:d,y:u}=ot({clientX:m,clientY:p},this.state),h=d-l,g=u-c,[E,w]=Zt(h,g,this.getEffectiveGridSize()),{duplicatedElements:x}=Px({type:"everything",elements:n.map(S=>Si(S,{x:S.x+E-r,y:S.y+w-i})),randomizeSeed:!o.retainSeed}),y=this.scene.getElementsIncludingDeleted(),v=[...y,...x];v=this.props.onDuplicate?.(v,y)||v,X6(v,kg(x));let k=this.getTopLayerFrameAtSceneCoords({x:d,y:u});if(k){let S=lq(x,k);zx(v,S,k,this.state)}this.scene.replaceAllElements(v),x.forEach(S=>{if(vn(S)&&Ax(S)){let _=G6(S,this.scene.getElementsMapIncludingDeleted());eq(S,_,this.scene)}}),_j&&Mn.loadElementsFonts(x).then(S=>{this.fonts.onLoaded(S)}),o.files&&this.addMissingFiles(o.files);let L=Mq(x);this.store.scheduleCapture(),this.setState({...this.state,openSidebar:this.state.openSidebar&&this.editorInterface.canFitSidebar&&Et.get(dd)?this.state.openSidebar:null,...nn({editingGroupId:null,selectedElementIds:L.reduce((S,_)=>(Ax(_)||(S[_.id]=!0),S),{})},this.scene.getNonDeletedElements(),this.state,this)},()=>{o.files&&this.addNewImagesToImageCache()}),this.setActiveTool({type:this.state.preferredSelectionTool.type},!0),o.fitToContent&&this.scrollToContent(x,{fitToContent:!0,canvasOffsets:this.getEditorUIOffsets()})});A(this,"setAppState",(o,n)=>{this.setState(o,n)});A(this,"removePointer",o=>{Ai&&this.resetContextMenuTimer(),_e.pointers.delete(o.pointerId)});A(this,"toggleLock",(o="ui")=>{this.state.activeTool.locked||ge("toolbar","toggleLock",`${o} (${this.editorInterface.formFactor==="phone"?"mobile":"desktop"})`),this.setState(n=>({activeTool:{...n.activeTool,...er(this.state,n.activeTool.locked?{type:this.state.preferredSelectionTool.type}:n.activeTool),locked:!n.activeTool.locked}}))});A(this,"updateFrameRendering",o=>{this.setState(n=>{let r=typeof o=="function"?o(n.frameRendering):o;return{frameRendering:{enabled:r?.enabled??n.frameRendering.enabled,clip:r?.clip??n.frameRendering.clip,name:r?.name??n.frameRendering.name,outline:r?.outline??n.frameRendering.outline}}})});A(this,"togglePenMode",o=>{this.setState(n=>({penMode:o??!n.penMode,penDetected:!0}))});A(this,"onHandToolToggle",()=>{this.actionManager.executeAction(x2)});A(this,"zoomCanvas",o=>{this.setState({...pr({viewportX:this.state.width/2+this.state.offsetLeft,viewportY:this.state.height/2+this.state.offsetTop,nextZoom:Cn(o)},this.state)})});A(this,"cancelInProgressAnimation",null);A(this,"scrollToContent",(o=this.scene.getNonDeletedElements(),n)=>{if(typeof o=="string"){let l;if(Ux(o)?l=fq(o):l=o,l){let c=this.scene.getElementsFromId(l);c?.length?this.scrollToContent(c,{fitToContent:n?.fitToContent??!0,animate:n?.animate??!0}):Ux(o)&&this.setState({toast:{message:f("elementLink.notFound"),duration:3e3,closable:!0}})}return}this.cancelInProgressAnimation?.();let r=Array.isArray(o)?o:[o],i=this.state.zoom,a=this.state.scrollX,s=this.state.scrollY;if(n?.fitToContent||n?.fitToViewport){let{appState:l}=ys({canvasOffsets:n.canvasOffsets,targetElements:r,appState:this.state,fitToViewport:!!n?.fitToViewport,viewportZoomFactor:n?.viewportZoomFactor,minZoom:n?.minZoom,maxZoom:n?.maxZoom});i=l.zoom,a=l.scrollX,s=l.scrollY}else{let l=Ri(r,this.state);a=l.scrollX,s=l.scrollY}if(n?.animate){let l=this.state.scrollX,c=this.state.scrollY,m=this.state.zoom.value,p=yj({fromValues:{scrollX:l,scrollY:c,zoom:m},toValues:{scrollX:a,scrollY:s,zoom:i.value},interpolateValue:(d,u,h,g)=>{if(g==="zoom")return d*Math.pow(u/d,vj(h))},onStep:({scrollX:d,scrollY:u,zoom:h})=>{this.setState({scrollX:d,scrollY:u,zoom:{value:h}})},onStart:()=>{this.setState({shouldCacheIgnoreZoom:!0})},onEnd:()=>{this.setState({shouldCacheIgnoreZoom:!1})},onCancel:()=>{this.setState({shouldCacheIgnoreZoom:!1})},duration:n?.duration??500});this.cancelInProgressAnimation=()=>{p(),this.cancelInProgressAnimation=null}}else this.setState({scrollX:a,scrollY:s,zoom:i})});A(this,"maybeUnfollowRemoteUser",()=>{this.state.userToFollow&&this.setState({userToFollow:null})});A(this,"translateCanvas",o=>{this.cancelInProgressAnimation?.(),this.maybeUnfollowRemoteUser(),this.setState(o)});A(this,"setToast",o=>{this.setState({toast:o})});A(this,"restoreFileFromShare",async()=>{try{let o=await caches.open("web-share-target"),n=await o.match("shared-file");if(n){let r=await n.blob(),i=new File([r],r.name||"",{type:r.type});this.loadFileToCanvas(i,null),await o.delete("shared-file"),window.history.replaceState(null,QZ,window.location.pathname)}}catch(o){this.setState({errorMessage:o.message})}});A(this,"addFiles",mt(o=>{let{addedFiles:n}=this.addMissingFiles(o);this.clearImageShapeCache(n),this.scene.triggerUpdate(),this.addNewImagesToImageCache()}));A(this,"addMissingFiles",(o,n=!1)=>{let r=n?{}:{...this.files},i={},a=Array.isArray(o)?o:Object.values(o);for(let s of a)if(!r[s.id]&&(i[s.id]=s,r[s.id]=s,s.mimeType===Jn.svg))try{let l=QE(H6(ey(s.dataURL)),Jn.svg);s.dataURL!==l&&(s.version=(s.version??1)+1,s.dataURL=l)}catch(l){console.error(l)}return this.files=r,{addedFiles:i}});A(this,"updateScene",mt(o=>{let{elements:n,appState:r,collaborators:i,captureUpdate:a}=o;if(a){let s=n||void 0,l=r?Nj({...this.store.snapshot.appState,...r}):void 0;this.store.scheduleMicroAction({action:a,elements:s,appState:l})}r&&this.setState(r),n&&this.scene.replaceAllElements(n),i&&this.setState({collaborators:i})}));A(this,"applyDeltas",(o,n)=>{let r=tP.squash(...o),i={...this.state},a=new Map(this.scene.getElementsMapIncludingDeleted());return tP.applyTo(r,a,i,n)});A(this,"mutateElement",(o,n,r=!0)=>this.scene.mutateElement(o,n,{informMutation:r,isDragging:!1}));A(this,"triggerRender",o=>{o===!0?this.scene.triggerUpdate():this.setState({})});A(this,"toggleSidebar",({name:o,tab:n,force:r})=>{let i;r===void 0?i=this.state.openSidebar?.name===o&&this.state.openSidebar?.tab===n?null:o:i=r?o:null;let a=i?{name:i}:null;return a&&n&&(a.tab=n),this.setState({openSidebar:a}),!!i});A(this,"updateCurrentCursorPosition",mt(o=>{this.lastViewportPosition.x=o.clientX,this.lastViewportPosition.y=o.clientY}));A(this,"getEditorUIOffsets",()=>{let o=this.excalidrawContainerRef?.current?.querySelector(".App-toolbar")?.getBoundingClientRect()?.bottom??0,n=this.excalidrawContainerRef?.current?.querySelector(".sidebar")?.getBoundingClientRect(),r=this.excalidrawContainerRef?.current?.querySelector(".App-menu__left")?.getBoundingClientRect(),i=16;return lr().rtl?{top:o+i,right:Math.max(this.state.width-(r?.left??this.state.width),0)+i,bottom:i,left:Math.max(n?.right??0,0)+i}:{top:o+i,right:Math.max(this.state.width-(n?.left??this.state.width)+i,0),bottom:i,left:Math.max(r?.right??0,0)+i}});A(this,"onKeyDown",mt(o=>{if("Proxy"in window&&(!o.shiftKey&&/^[A-Z]$/.test(o.key)||o.shiftKey&&/^[a-z]$/.test(o.key))&&(o=new Proxy(o,{get(s,l){let c=s[l];return typeof c=="function"?c.bind(s):l==="key"?o.shiftKey?s.key.toUpperCase():s.key.toLowerCase():c}})),!T6(o.target)){if((o.key===oe.ESCAPE||o.key===oe.ENTER)&&this.state.croppingElementId){this.finishImageCropping();return}let s=le(this.scene.getNonDeletedElementsMap(),this.state);if(s.length===1&&Mi(s[0])&&o.key===oe.ENTER){this.startImageCropping(s[0]);return}if(o.key===oe.ESCAPE)this.updateEditorAtom(gn,null);else if(o.key===oe.TAB&&(document.activeElement===this.excalidrawContainerRef?.current||document.activeElement?.classList.contains(Sx.CONVERT_ELEMENT_TYPE_POPUP))){o.preventDefault();let c=Os(s);Et.get(gn)?.type==="panel"&&pb(this,{conversionType:c,direction:o.shiftKey?"left":"right"})&&this.store.scheduleCapture(),c&&this.updateEditorAtom(gn,{type:"panel"})}if(o.key===oe.ESCAPE&&this.flowChartCreator.isCreatingChart){this.flowChartCreator.clear(),this.triggerRender(!0);return}let l=wg(o.key);if(o[oe.CTRL_OR_CMD]&&l&&!o.shiftKey){o.preventDefault();let c=le(this.scene.getNonDeletedElementsMap(),this.state);c.length===1&&Kj(c[0])&&this.flowChartCreator.createNodes(c[0],this.state,V6(o.key),this.scene),this.flowChartCreator.pendingNodes?.length&&!Rx(this.flowChartCreator.pendingNodes,this.canvas.width/window.devicePixelRatio,this.canvas.height/window.devicePixelRatio,{offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,zoom:this.state.zoom},this.scene.getNonDeletedElementsMap(),this.getEditorUIOffsets())&&this.scrollToContent(this.flowChartCreator.pendingNodes,{animate:!0,duration:300,fitToContent:!0,canvasOffsets:this.getEditorUIOffsets()});return}if(o.altKey){let c=le(this.scene.getNonDeletedElementsMap(),this.state);if(c.length===1&&l){o.preventDefault();let m=this.flowChartNavigator.exploreByDirection(c[0],this.scene.getNonDeletedElementsMap(),V6(o.key));if(m){this.setState(d=>({selectedElementIds:Oe({[m]:!0},d)}));let p=this.scene.getNonDeletedElementsMap().get(m);p&&!Rx([p],this.canvas.width/window.devicePixelRatio,this.canvas.height/window.devicePixelRatio,{offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,zoom:this.state.zoom},this.scene.getNonDeletedElementsMap(),this.getEditorUIOffsets())&&this.scrollToContent(p,{animate:!0,duration:300,canvasOffsets:this.getEditorUIOffsets()})}return}}}if(o[oe.CTRL_OR_CMD]&&o.key===oe.P&&!o.shiftKey&&!o.altKey){this.setToast({message:f("commandPalette.shortcutHint",{shortcut:Ke("commandPalette")})}),o.preventDefault();return}if(o[oe.CTRL_OR_CMD]&&o.key.toLowerCase()===oe.V&&(jx=o.shiftKey,clearTimeout(aP),aP=window.setTimeout(()=>{jx=!1},100)),o[oe.CTRL_OR_CMD]&&kd(o.target)&&(o.code===g6.MINUS||o.code===g6.EQUAL)){o.preventDefault();return}if(kd(o.target)&&o.key!==oe.ESCAPE||wg(o.key)&&T6(o.target))return;if(o.key===oe.QUESTION_MARK){this.setState({openDialog:{name:"help"}});return}else if(o.key.toLowerCase()===oe.E&&o.shiftKey&&o[oe.CTRL_OR_CMD]){o.preventDefault(),this.setState({openDialog:{name:"imageExport"}});return}if(o.key===oe.PAGE_UP||o.key===oe.PAGE_DOWN){let s=(o.shiftKey?this.state.width:this.state.height)/this.state.zoom.value;o.key===oe.PAGE_DOWN&&(s=-s),o.shiftKey?this.translateCanvas(l=>({scrollX:l.scrollX+s})):this.translateCanvas(l=>({scrollY:l.scrollY+s}))}if(this.state.openDialog?.name==="elementLinkSelector"||(o.key===oe.ALT&&(Ar("COMPLEX_BINDINGS")?this.handleSkipBindMode():_g({app:this,event:o})),this.actionManager.handleKeyDown(o)))return;let n=this.props.viewModeEnabled===!0;if(!n&&this.state.viewModeEnabled&&o.key===oe.ESCAPE){this.setActiveTool({type:"hand"});return}if(!n&&!o.ctrlKey&&!o.altKey&&!o.metaKey&&!this.state.newElement&&!this.state.selectionElement&&!this.state.selectedElementsAreBeingDragged){let s=yC(o.key,this);if(this.state.viewModeEnabled&&!S6(s,["laser","hand"]))return;if(s){this.state.activeTool.type!==s&&ge("toolbar",s,`keyboard (${this.editorInterface.formFactor==="phone"?"mobile":"desktop"})`),s==="arrow"&&this.state.activeTool.type==="arrow"&&this.setState(l=>({currentItemArrowType:l.currentItemArrowType===ki.sharp?ki.round:l.currentItemArrowType===ki.round?ki.elbow:ki.sharp})),s==="lasso"&&this.state.activeTool.type==="laser"?this.setActiveTool({type:this.state.preferredSelectionTool.type}):this.setActiveTool({type:s}),o.stopPropagation();return}else if(o.key===oe.Q){this.toggleLock("keyboard"),o.stopPropagation();return}}if(this.state.viewModeEnabled)return;if(o[oe.CTRL_OR_CMD]&&this.state.isBindingEnabled&&(Ar("COMPLEX_BINDINGS")&&this.resetDelayedBindMode(),wo(()=>{this.setState({isBindingEnabled:!1})}),_g({app:this,event:o})),wg(o.key)){let s=this.scene.getSelectedElements({selectedElementIds:this.state.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0}),l=new Set;s.filter(d=>or(d)).filter(d=>{let u=d.startBinding&&!s.some(g=>g.id===d.startBinding?.elementId),h=d.endBinding&&!s.some(g=>g.id===d.endBinding?.elementId);return u||h}).forEach(d=>l.add(d.id)),s=s.filter(d=>!l.has(d.id));let c=this.getEffectiveGridSize()&&(o.shiftKey?E6:this.getEffectiveGridSize())||(o.shiftKey?tj:E6),m=0,p=0;o.key===oe.ARROW_LEFT?m=-c:o.key===oe.ARROW_RIGHT?m=c:o.key===oe.ARROW_UP?p=-c:o.key===oe.ARROW_DOWN&&(p=c),s.forEach(d=>{this.scene.mutateElement(d,{x:d.x+m,y:d.y+p},{informMutation:!1,isDragging:!1}),Pg(d,this.scene,{simultaneouslyUpdated:s})}),this.scene.triggerUpdate(),o.preventDefault()}else if(o.key===oe.ENTER){let s=this.scene.getSelectedElements(this.state);if(s.length===1){let l=s[0];if(o[oe.CTRL_OR_CMD]||Wx(l))ao(l)&&(!this.state.selectedLinearElement?.isEditing||this.state.selectedLinearElement.elementId!==l.id)&&(this.store.scheduleCapture(),vo(l)||this.actionManager.executeAction(Qs));else if(vn(l)||Qj(l)){let c;vn(l)||(c=l);let m=Fx(l,this.state,this.scene.getNonDeletedElementsMap()),p=m.x,d=m.y;this.startTextEditing({sceneX:p,sceneY:d,container:c}),o.preventDefault();return}else jt(l)&&this.setState({editingFrame:l.id})}}if(o.key===oe.SPACE&&_e.pointers.size===0&&(Pi=!0,Re(this.interactiveCanvas,st.GRAB),o.preventDefault()),(o.key===oe.G||o.key===oe.S)&&!o.altKey&&!o[oe.CTRL_OR_CMD]){let s=this.scene.getSelectedElements(this.state);if(this.state.activeTool.type==="selection"&&!s.length)return;o.key===oe.G&&(kn(this.state.activeTool.type)||s.some(l=>kn(l.type)))&&(this.setState({openPopup:"elementBackground"}),o.stopPropagation()),o.key===oe.S&&(this.setState({openPopup:"elementStroke"}),o.stopPropagation())}if(!o[oe.CTRL_OR_CMD]&&o.shiftKey&&o.key.toLowerCase()===oe.F){let s=this.scene.getSelectedElements(this.state);if(this.state.activeTool.type==="selection"&&!s.length)return;(this.state.activeTool.type==="text"||s.find(l=>vn(l)||Bx(l,this.scene.getNonDeletedElementsMap())))&&(o.preventDefault(),this.setState({openPopup:"fontFamily"}))}o[oe.CTRL_OR_CMD]&&(o.key===oe.BACKSPACE||o.key===oe.DELETE)&&this.updateEditorAtom(ta,"clearCanvas");let r=o.key.toLocaleLowerCase(),i=r===oe.S&&o.shiftKey,a=o.key===oe.I||r===oe.G&&o.shiftKey;(i||a)&&this.openEyeDropper({type:i?"stroke":"background"})}));A(this,"onKeyUp",mt(o=>{if(o.key===oe.SPACE&&(this.state.viewModeEnabled&&this.state.activeTool.type!=="laser"||this.state.openDialog?.name==="elementLinkSelector"?Re(this.interactiveCanvas,st.GRAB):Sg(this.state.activeTool.type)?So(this.interactiveCanvas):(Mo(this.interactiveCanvas,this.state),this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null})),Pi=!1),o.key===oe.ALT&&_g({app:this,event:o}),(o.key===oe.ALT&&this.state.bindMode==="skip"||!o[oe.CTRL_OR_CMD]&&!Md(this.state))&&(this.setState({bindMode:"orbit"}),this.lastPointerMoveEvent&&Ar("COMPLEX_BINDINGS"))){let n=ot({clientX:this.lastPointerMoveEvent.clientX,clientY:this.lastPointerMoveEvent.clientY},this.state),r=wn(de(n.x,n.y),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap());if(this.state.selectedLinearElement){let i=Me.getElement(this.state.selectedLinearElement.elementId,this.scene.getNonDeletedElementsMap());or(i)&&this.handleDelayedBindModeChange(i,r)}}if(!o[oe.CTRL_OR_CMD]&&!this.state.isBindingEnabled&&(wo(()=>{this.setState({isBindingEnabled:!0})}),_g({app:this,event:o})),wg(o.key)){M6(this.scene.getSelectedElements(this.state).filter(Al),this.scene,this.state);let n=this.scene.getNonDeletedElementsMap();this.scene.getSelectedElements(this.state).filter(Yx).forEach(r=>{r.startBinding&&this.scene.mutateElement(r,{startBinding:{...r.startBinding,...nP(r,n.get(r.startBinding.elementId),"start",n)}}),r.endBinding&&this.scene.mutateElement(r,{endBinding:{...r.endBinding,...nP(r,n.get(r.endBinding.elementId),"end",n)}})}),this.setState({suggestedBinding:null})}if(o.altKey||this.flowChartNavigator.isExploring&&(this.flowChartNavigator.clear(),this.syncActionResult({captureUpdate:so.IMMEDIATELY})),!o[oe.CTRL_OR_CMD]&&this.flowChartCreator.isCreatingChart){this.flowChartCreator.pendingNodes?.length&&this.scene.insertElements(this.flowChartCreator.pendingNodes);let n=this.flowChartCreator.pendingNodes?.[0];n&&(this.setState(r=>({selectedElementIds:Oe({[n.id]:!0},r)})),Rx([n],this.canvas.width/window.devicePixelRatio,this.canvas.height/window.devicePixelRatio,{offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,zoom:this.state.zoom},this.scene.getNonDeletedElementsMap(),this.getEditorUIOffsets())||this.scrollToContent(n,{animate:!0,duration:300,canvasOffsets:this.getEditorUIOffsets()})),this.flowChartCreator.clear(),this.syncActionResult({captureUpdate:so.IMMEDIATELY})}}));A(this,"isToolSupported",o=>this.props.UIOptions.tools?.[o]!==!1);A(this,"setActiveTool",(o,n=!1)=>{if(!this.isToolSupported(o.type)){console.warn(`"${o.type}" tool is disabled via "UIOptions.canvasActions.tools.${o.type}"`);return}let r=er(this.state,o);r.type==="hand"?Re(this.interactiveCanvas,st.GRAB):Pi||Mo(this.interactiveCanvas,{...this.state,activeTool:r}),bj(document.activeElement)&&this.focusContainer(),Vj(r.type)||this.setState({suggestedBinding:null}),r.type==="image"&&this.onImageToolbarButtonClick(),this.setState(i=>{let a={snapLines:i.snapLines.length?[]:i.snapLines,originSnapOffset:null,activeEmbeddable:null,selectedLinearElement:Sg(r.type)?i.selectedLinearElement:null};return r.type==="freedraw"&&this.store.scheduleCapture(),r.type==="lasso"?{...i,...a,activeTool:r,...n?{}:{selectedElementIds:Oe({},i),selectedGroupIds:Oe({},i),editingGroupId:null,multiElement:null}}:r.type!=="selection"?{...i,...a,activeTool:r,selectedElementIds:Oe({},i),selectedGroupIds:Oe({},i),editingGroupId:null,multiElement:null}:{...i,...a,activeTool:r}})});A(this,"setOpenDialog",o=>{this.setState({openDialog:o})});A(this,"setCursor",o=>{Re(this.interactiveCanvas,o)});A(this,"resetCursor",()=>{So(this.interactiveCanvas)});A(this,"isTouchScreenMultiTouchGesture",()=>_e.pointers.size>=2);A(this,"getName",()=>this.state.name||this.props.name||`${f("labels.untitled")}-${C6()}`);A(this,"onGestureStart",mt(o=>{o.preventDefault(),this.isTouchScreenMultiTouchGesture()&&this.setState({selectedElementIds:Oe({},this.state),activeEmbeddable:null}),_e.initialScale=this.state.zoom.value}));A(this,"onGestureChange",mt(o=>{if(o.preventDefault(),this.isTouchScreenMultiTouchGesture())return;let n=_e.initialScale;n&&this.setState(r=>({...pr({viewportX:this.lastViewportPosition.x,viewportY:this.lastViewportPosition.y,nextZoom:Cn(n*o.scale)},r)}))}));A(this,"onGestureEnd",mt(o=>{o.preventDefault(),this.isTouchScreenMultiTouchGesture()&&this.setState({previousSelectedElementIds:{},selectedElementIds:Oe(this.state.previousSelectedElementIds,this.state)}),_e.initialScale=null}));A(this,"startTextEditing",({sceneX:o,sceneY:n,insertAtParentCenter:r=!0,container:i,autoEdit:a=!0})=>{let s=!1,l=r&&this.getTextWysiwygSnappedToCenterPosition(o,n,this.state,i);i&&l&&(Bx(i,this.scene.getNonDeletedElementsMap())||(s=!0));let c=null,m=this.scene.getSelectedElements(this.state);m.length===1?vn(m[0])?c=m[0]:i?c=Bx(m[0],this.scene.getNonDeletedElementsMap()):c=this.getTextElementAtPosition(o,n):c=this.getTextElementAtPosition(o,n);let p=c?.fontFamily||this.state.currentItemFontFamily,d=c?.lineHeight||v6(p),u=this.state.currentItemFontSize;if(!c&&s&&i&&!Al(i)){let w=yq(Tx({fontSize:u,fontFamily:p}),d),x=wq(u,d),y=Math.max(i.height,x),v=Math.max(i.width,w);this.scene.mutateElement(i,{height:y,width:v}),o=i.x+v/2,n=i.y+y/2,l&&(l=this.getTextWysiwygSnappedToCenterPosition(o,n,this.state,i))}let h=this.getTopLayerFrameAtSceneCoords({x:o,y:n}),g=c||_6({x:l?l.elementCenterX:o,y:l?l.elementCenterY:n,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,text:"",fontSize:u,fontFamily:p,textAlign:l?"center":this.state.currentItemTextAlign,verticalAlign:l?cj.MIDDLE:b6,containerId:s?i?.id:void 0,groupIds:i?.groupIds??[],lineHeight:d,angle:i?Al(i)?0:i.angle:0,frameId:h?h.id:null});if(!c&&s&&i&&this.scene.mutateElement(i,{boundElements:(i.boundElements||[]).concat({type:"text",id:g.id})}),this.setState({editingTextElement:g}),!c)if(i&&s){let E=this.scene.getElementIndex(i.id);this.scene.insertElementAtIndex(g,E+1)}else this.scene.insertElement(g);a||c||i?this.handleTextWysiwyg(g,{isExistingElement:!!c}):this.setState({newElement:g,multiElement:null})});A(this,"startImageCropping",o=>{this.store.scheduleCapture(),this.setState({croppingElementId:o.id})});A(this,"finishImageCropping",()=>{this.state.croppingElementId&&(this.store.scheduleCapture(),this.setState({croppingElementId:null}))});A(this,"handleCanvasDoubleClick",o=>{if(this.state.multiElement||this.state.activeTool.type!==this.state.preferredSelectionTool.type)return;let n=this.scene.getSelectedElements(this.state),{x:r,y:i}=ot(o,this.state);if(n.length===1&&ao(n[0])){let s=n[0];if((o[oe.CTRL_OR_CMD]&&Yx(s)||Wx(s))&&(!this.state.selectedLinearElement?.isEditing||this.state.selectedLinearElement.elementId!==s.id)){this.actionManager.executeAction(Qs);return}else if(this.state.selectedLinearElement&&vo(n[0])){let l=Me.getSegmentMidpointHitCoords(this.state.selectedLinearElement,{x:r,y:i},this.state,this.scene.getNonDeletedElementsMap()),c=l?Me.getSegmentMidPointIndex(this.state.selectedLinearElement,this.state,l,this.scene.getNonDeletedElementsMap()):-1;if(c&&c>-1){this.store.scheduleCapture(),Me.deleteFixedSegment(n[0],this.scene,c);let m=Me.getSegmentMidpointHitCoords({...this.state.selectedLinearElement,segmentMidPointHoveredCoords:null},{x:r,y:i},this.state,this.scene.getNonDeletedElementsMap()),p=m?Me.getSegmentMidPointIndex(this.state.selectedLinearElement,this.state,m,this.scene.getNonDeletedElementsMap()):null;this.setState({selectedLinearElement:{...this.state.selectedLinearElement,initialState:{...this.state.selectedLinearElement.initialState,segmentMidpoint:{index:p,value:l,added:!1}},segmentMidPointHoveredCoords:m}});return}}else if(this.state.selectedLinearElement?.isEditing&&this.state.selectedLinearElement.elementId===s.id&&Wx(s))return}if(n.length===1&&Mi(n[0])){this.startImageCropping(n[0]);return}if(So(this.interactiveCanvas),kq(this.state).length>0){let s=this.getElementAtPosition(r,i),l=s&&Cq(s,this.state.selectedGroupIds);if(l){this.store.scheduleCapture(),this.setState(c=>({...c,...nn({editingGroupId:l,selectedElementIds:{[s.id]:!0}},this.scene.getNonDeletedElements(),c,this)}));return}}if(So(this.interactiveCanvas),!o[oe.CTRL_OR_CMD]&&!this.state.viewModeEnabled){let s=this.getElementAtPosition(r,i);if(Lx(s)){this.setState({activeEmbeddable:{element:s,state:"active"}});return}if(!this.state.selectedLinearElement?.isEditing){let l=this.getTextBindableContainerAtPosition(r,i);if(l&&(R6(l)||!Ej(l.backgroundColor)||Ad({point:de(r,i),element:l,elementsMap:this.scene.getNonDeletedElementsMap(),threshold:this.getElementHitThreshold(l)}))){let c=Fx(l,this.state,this.scene.getNonDeletedElementsMap());r=c.x,i=c.y}this.startTextEditing({sceneX:r,sceneY:i,insertAtParentCenter:!o.altKey,container:l})}}});A(this,"getElementLinkAtPosition",(o,n)=>{if(n&&n.locked)return;let r=this.scene.getNonDeletedElements(),i=-1;for(let a=r.length-1;a>=0;a--){let s=r[a];if(n&&s.id===n.id&&(i=a),s.link&&a>=i&&jd(s,this.scene.getNonDeletedElementsMap(),this.state,de(o.x,o.y),this.editorInterface.formFactor==="phone"))return s}});A(this,"handleElementLinkClick",o=>{let n=Ti(de(this.lastPointerDownEvent.clientX,this.lastPointerDownEvent.clientY),de(this.lastPointerUpEvent.clientX,this.lastPointerUpEvent.clientY));if(!this.hitLinkElement||n>x6)return;let r=ot(this.lastPointerDownEvent,this.state),i=this.scene.getNonDeletedElementsMap(),a=jd(this.hitLinkElement,i,this.state,de(r.x,r.y),this.editorInterface.formFactor==="phone"),s=ot(this.lastPointerUpEvent,this.state),l=jd(this.hitLinkElement,i,this.state,de(s.x,s.y),this.editorInterface.formFactor==="phone");if(a&&l){tb();let c=this.hitLinkElement.link;if(c){c=Ix(c);let m;if(this.props.onLinkOpen&&(m=xj(ue.EXCALIDRAW_LINK,o.nativeEvent),this.props.onLinkOpen({...this.hitLinkElement,link:c},m)),!m?.defaultPrevented){let p=gj(c)?"_self":"_blank",d=window.open(void 0,p);d&&(d.opener=null,d.location=c)}}}});A(this,"getTopLayerFrameAtSceneCoords",o=>{let n=this.scene.getNonDeletedElementsMap(),r=this.scene.getNonDeletedFramesLikes().filter(i=>!i.locked&&U6(o,i,n));return r.length?r[r.length-1]:null});A(this,"handleCanvasPointerMove",o=>{this.savePointer(o.clientX,o.clientY,this.state.cursorButton),this.lastPointerMoveEvent=o.nativeEvent;let n=ot(o,this.state),{x:r,y:i}=n;this.lastPointerMoveCoords={x:r,y:i},_e.pointers.has(o.pointerId)&&_e.pointers.set(o.pointerId,{x:o.clientX,y:o.clientY});let a=_e.initialScale;if(_e.pointers.size===2&&_e.lastCenter&&a&&_e.initialDistance){let g=f0(_e.pointers),E=g.x-_e.lastCenter.x,w=g.y-_e.lastCenter.y;_e.lastCenter=g;let x=b0(Array.from(_e.pointers.values())),y=this.state.activeTool.type==="freedraw"&&this.state.penMode?1:x/_e.initialDistance,v=y?Cn(a*y):this.state.zoom.value;this.setState(I=>{let k=pr({viewportX:g.x,viewportY:g.y,nextZoom:v},I);return this.translateCanvas({zoom:k.zoom,scrollX:k.scrollX+2*(E/v),scrollY:k.scrollY+2*(w/v),shouldCacheIgnoreZoom:!0}),null}),this.resetShouldCacheIgnoreZoomDebounced()}else _e.lastCenter=_e.initialDistance=_e.initialScale=null;if(Pi||Rd||Xx||sr(this.state))return;let l=V0(Nd,o.clientX-this.state.offsetLeft,o.clientY-this.state.offsetTop).isOverEither;if(!this.state.newElement&&!this.state.selectionElement&&!this.state.selectedElementsAreBeingDragged&&!this.state.multiElement&&(l?So(this.interactiveCanvas):Mo(this.interactiveCanvas,this.state)),!this.state.newElement&&J5(this.state.activeTool.type)){let{originOffset:g,snapLines:E}=q5(this.scene.getNonDeletedElements(),this,{x:r,y:i},o,this.scene.getNonDeletedElementsMap());this.setState(w=>{let x=Sd(w.snapLines,E),y=w.originSnapOffset?Sd(w.originSnapOffset,g):g;return w.snapLines===x&&w.originSnapOffset===y?null:{snapLines:x,originSnapOffset:y}})}else!this.state.newElement&&!this.state.selectedElementsAreBeingDragged&&!this.state.selectionElement&&this.setState(g=>g.snapLines.length?{snapLines:[]}:null);if(this.state.selectedLinearElement?.isEditing&&!this.state.selectedLinearElement.isDragging){let g=this.state.newElement?null:Me.handlePointerMoveInEditMode(o,r,i,this);g&&g!==this.state.selectedLinearElement&&wo(()=>{this.setState({selectedLinearElement:g})})}if(Yj(this.state.activeTool.type)){let{newElement:g}=this.state;if(!g&&Md(this.state)){let E=de(r,i),w=this.scene.getNonDeletedElementsMap(),x=wn(E,this.scene.getNonDeletedElements(),w,Vx(this.state.zoom));x?this.setState({suggestedBinding:{element:x,midPoint:$x(E,x,w,this.state.zoom)}}):this.state.suggestedBinding&&this.setState({suggestedBinding:null})}}if(this.state.multiElement&&this.state.selectedLinearElement){let{multiElement:g,selectedLinearElement:E}=this.state,{x:w,y:x,points:y}=g,v=y[y.length-1],{lastCommittedPoint:I}=E;if(Mo(this.interactiveCanvas,this.state),v===I)Al(this.state.newElement)&&Md(this.state)&&wn(de(r,i),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap(),Vx(this.state.zoom))?(this.actionManager.executeAction(to,"ui",{event:o.nativeEvent,sceneCoords:{x:r,y:i}}),this.setState({suggestedBinding:null,startBoundElement:null}),this.state.activeTool.locked||(So(this.interactiveCanvas),this.setState(L=>({newElement:null,activeTool:er(this.state,{type:this.state.preferredSelectionTool.type}),selectedElementIds:Oe({...L.selectedElementIds,[g.id]:!0},L),selectedLinearElement:new Me(g,this.scene.getNonDeletedElementsMap())})))):Ti(de(r-w,i-x),v)>=vx?(this.scene.mutateElement(g,{points:[...y,de(r-w,i-x)]},{informMutation:!1,isDragging:!1}),tr(this.state.selectedLinearElement?.initialState,"initialState must be set"),this.setState({selectedLinearElement:{...this.state.selectedLinearElement,lastCommittedPoint:y[y.length-1],selectedPointsIndices:[g.points.length-1],initialState:{...this.state.selectedLinearElement.initialState,lastClickedPoint:g.points.length-1}}})):Re(this.interactiveCanvas,st.POINTER);else if(y.length>2&&I&&Ti(de(r-w,i-x),I)<vx)Re(this.interactiveCanvas,st.POINTER),this.scene.mutateElement(g,{points:y.slice(0,-1)},{informMutation:!1,isDragging:!1}),this.setState({selectedLinearElement:{...E,selectedPointsIndices:E.selectedPointsIndices?.includes(g.points.length)?[...E.selectedPointsIndices.filter(k=>k!==g.points.length&&k!==g.points.length-1),g.points.length-1]:E.selectedPointsIndices,lastCommittedPoint:g.points[g.points.length-1],initialState:{...E.initialState,lastClickedPoint:g.points.length-1}}});else{O6(y,this.state.zoom.value)&&Re(this.interactiveCanvas,st.POINTER);let k=this.scene.getNonDeletedElementsMap();if(Yx(g)){let S=wn(de(r,i),this.scene.getNonDeletedElements(),k);Ar("COMPLEX_BINDINGS")&&this.handleDelayedBindModeChange(g,S)}tr(this.state.selectedLinearElement,"Expected selectedLinearElement to be set to operate on a linear element");let L=Me.handlePointerMove(o.nativeEvent,this,r,i,this.state.selectedLinearElement);L&&this.setState(L)}return}if(this.state.activeTool.type==="arrow"){let g=wn(de(r,i),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap(),Vx(this.state.zoom)),E=de(r,i),w=this.scene.getNonDeletedElementsMap();g&&!zq(E,g,w)&&this.setState({suggestedBinding:{element:g,midPoint:$x(E,g,w,this.state.zoom)}})}let c=!!o.buttons,m=this.state.activeTool.type==="laser";if(c||!m&&this.state.activeTool.type!=="selection"&&this.state.activeTool.type!=="lasso"&&this.state.activeTool.type!=="text"&&this.state.activeTool.type!=="eraser")return;let p=this.scene.getNonDeletedElements(),d=this.scene.getSelectedElements(this.state);if(d.length===1&&!l&&!this.state.selectedLinearElement?.isEditing){if(this.state.selectedLinearElement&&this.handleHoverSelectedLinearElement(this.state.selectedLinearElement,r,i),(!this.state.selectedLinearElement||this.state.selectedLinearElement.hoverPointIndex===-1)&&this.state.openDialog?.name!=="elementLinkSelector"&&!(d.length===1&&vo(d[0]))&&!(ao(d[0])&&(this.editorInterface.userAgent.isMobileDevice||d[0].points.length===2))){let g=j6(p,this.state,r,i,this.state.zoom,o.pointerType,this.scene.getNonDeletedElementsMap(),this.editorInterface);if(g&&g.transformHandleType){Re(this.interactiveCanvas,Z6(g));return}}}else if(d.length>1&&!l&&this.state.openDialog?.name!=="elementLinkSelector"){let g=q6(Pl(d),r,i,this.state.zoom,o.pointerType,this.editorInterface);if(g){Re(this.interactiveCanvas,Z6({transformHandleType:g}));return}}if(po(this.state))return;let u=this.getElementAtPosition(r,i,{preferSelected:!0,includeLockedElements:!0}),h=null;if(u&&u.locked?h=null:h=u,this.handleIframeLikeElementHover({hitElement:h,scenePointer:n,moveEvent:o})||(this.hitLinkElement=this.getElementLinkAtPosition(n,u)),this.hitLinkElement&&!this.state.selectedElementIds[this.hitLinkElement.id])Re(this.interactiveCanvas,st.POINTER),YI(this.hitLinkElement,this.state,this.scene.getNonDeletedElementsMap());else{if(tb(),m)return;h&&(h.link||Lr(h))&&this.state.selectedElementIds[h.id]&&!this.state.contextMenu&&!this.state.showHyperlinkPopup?this.setState({showHyperlinkPopup:"info"}):this.state.activeTool.type==="text"?Re(this.interactiveCanvas,vn(h)?st.TEXT:st.CROSSHAIR):this.state.viewModeEnabled?Re(this.interactiveCanvas,st.GRAB):this.state.openDialog?.name==="elementLinkSelector"?Re(this.interactiveCanvas,st.AUTO):l?Re(this.interactiveCanvas,st.AUTO):o[oe.CTRL_OR_CMD]?Re(this.interactiveCanvas,st.AUTO):(h||this.isHittingCommonBoundingBoxOfSelectedElements(n,d))&&!h?.locked&&(!h||!vo(h)||!(h.startBinding||h.endBinding))&&(this.state.activeTool.type!=="lasso"||d.length>0)&&Re(this.interactiveCanvas,st.MOVE),this.state.selectedLinearElement&&this.handleHoverSelectedLinearElement(this.state.selectedLinearElement,r,i)}this.state.openDialog?.name==="elementLinkSelector"&&h?this.setState(g=>({hoveredElementIds:Sd(g.hoveredElementIds,nn({editingGroupId:g.editingGroupId,selectedElementIds:{[h.id]:!0}},this.scene.getNonDeletedElements(),g,this).selectedElementIds)})):this.state.openDialog?.name==="elementLinkSelector"&&!h&&this.setState(g=>({hoveredElementIds:Sd(g.hoveredElementIds,{})}))});A(this,"handleEraser",(o,n)=>{let r=this.eraserTrail.addPointToPath(n.x,n.y,o.altKey);this.elementsPendingErasure=new Set(r),this.triggerRender()});A(this,"handleTouchMove",o=>{Bd=!0});A(this,"handleCanvasPointerDown",o=>{let n=ot(o,this.state),{x:r,y:i}=n;this.lastPointerMoveCoords={x:r,y:i};let a=o.target;if(a.setPointerCapture&&a.setPointerCapture(o.pointerId),this.maybeCleanupAfterMissingPointerUp(o.nativeEvent),this.maybeUnfollowRemoteUser(),this.state.searchMatches&&(this.setState(h=>({searchMatches:h.searchMatches&&{focusedId:null,matches:h.searchMatches.matches.map(g=>({...g,focus:!1}))}})),this.updateEditorAtom(I1,null)),Et.get(gn)&&this.updateEditorAtom(gn,null),this.state.contextMenu&&this.setState({contextMenu:null}),this.state.snapLines&&this.setAppState({snapLines:[]}),this.state.openPopup&&this.setState({openPopup:null}),this.updateGestureOnPointerDown(o),o.pointerType==="touch"&&this.state.newElement&&this.state.newElement.type==="freedraw"){let h=this.state.newElement;this.updateScene({...h.points.length<10?{elements:this.scene.getElementsIncludingDeleted().filter(g=>g.id!==h.id)}:{},appState:{newElement:null,editingTextElement:null,startBoundElement:null,suggestedBinding:null,selectedElementIds:Oe(Object.keys(this.state.selectedElementIds).filter(g=>g!==h.id).reduce((g,E)=>(g[E]=this.state.selectedElementIds[E],g),{}),this.state)},captureUpdate:this.state.openDialog?.name==="elementLinkSelector"?so.EVENTUALLY:so.NEVER});return}let s=document.getSelection();if(s?.anchorNode&&s.removeAllRanges(),this.maybeOpenContextMenuAfterPointerDownOnTouchDevices(o),!this.state.penDetected&&o.pointerType==="pen"&&this.setState(h=>({penMode:!0,penDetected:!0})),!this.editorInterface.isTouchScreen&&["pen","touch"].includes(o.pointerType)&&(this.editorInterface=kx(this.editorInterface,{isTouchScreen:!0})),Rd||(this.lastPointerDownEvent=o,this.handleCanvasPanUsingWheelOrSpaceDrag(o)))return;if(this.setState({lastPointerDownWith:o.pointerType,cursorButton:"down"}),this.savePointer(o.clientX,o.clientY,"down"),o.button===Ci.ERASER&&this.state.activeTool.type!==Qn.eraser){this.setState({activeTool:er(this.state,{type:Qn.eraser,lastActiveToolBeforeEraser:this.state.activeTool})},()=>{this.handleCanvasPointerDown(o);let h=()=>{g(),E?.(),po(this.state)&&this.setState({activeTool:er(this.state,{...this.state.activeTool.lastActiveTool||{type:Qn.selection},lastActiveToolBeforeEraser:null})})},g=gt(window,ue.POINTER_UP,h,{once:!0}),E;requestAnimationFrame(()=>{E=this.missingPointerEventCleanupEmitter.once(h)})});return}if(o.button!==Ci.MAIN&&o.button!==Ci.TOUCH&&o.button!==Ci.ERASER||_e.pointers.size>1)return;let l=this.initialPointerDownState(o);if(this.setState({selectedElementsAreBeingDragged:!1}),this.handleDraggingScrollBar(o,l)||(this.clearSelectionIfNotUsingSelection(),this.updateBindingEnabledOnPointerMove(o),this.handleSelectionOnPointerDown(o,l))||!(!this.state.penMode||o.pointerType!=="touch"||this.state.activeTool.type==="selection"||this.state.activeTool.type==="lasso"||this.state.activeTool.type==="text"||this.state.activeTool.type==="image"))return;if(this.state.activeTool.type==="lasso"){let h=l.hit.element&&this.isASelectedElement(l.hit.element);!l.hit.hasHitCommonBoundingBoxOfSelectedElements&&!l.resize.handleType&&!h&&(this.lassoTrail.startPath(l.origin.x,l.origin.y,o.shiftKey),l.drag.blockDragging=this.editorInterface.formFactor==="desktop"),this.editorInterface.formFactor!=="desktop"&&l.hit.element&&!h&&(this.setState(g=>{let E={...g.selectedElementIds,[l.hit.element.id]:!0},w=[];Object.keys(g.selectedElementIds).forEach(y=>{let v=this.scene.getElement(y);v&&w.push(v)});let x=l.hit.element;if(jt(x))Ox(w,x.id).forEach(y=>{delete E[y.id]});else if(x.frameId)E[x.frameId]&&delete E[x.id];else{let y=x.groupIds,v=new Set(y.flatMap(I=>Ca(this.scene.getNonDeletedElements(),I)).filter(I=>jt(I)).map(I=>I.id));v.size>0&&w.forEach(I=>{I.frameId&&v.has(I.frameId)&&(delete E[I.id],I.groupIds.flatMap(k=>Ca(this.scene.getNonDeletedElements(),k)).forEach(k=>{delete E[k.id]}))})}return{...nn({editingGroupId:g.editingGroupId,selectedElementIds:E},this.scene.getNonDeletedElements(),g,this),showHyperlinkPopup:x.link||Lr(x)?"info":!1}}),l.hit.wasAddedToSelection=!0)}else this.state.activeTool.type==="text"?this.handleTextOnPointerDown(o,l):this.state.activeTool.type==="arrow"||this.state.activeTool.type==="line"?this.handleLinearElementOnPointerDown(o,this.state.activeTool.type,l):this.state.activeTool.type==="freedraw"?this.handleFreeDrawElementOnPointerDown(o,this.state.activeTool.type,l):this.state.activeTool.type==="custom"?Mo(this.interactiveCanvas,this.state):this.state.activeTool.type===Qn.frame||this.state.activeTool.type===Qn.magicframe?this.createFrameElementOnPointerDown(l,this.state.activeTool.type):this.state.activeTool.type==="laser"?this.laserTrails.startPath(l.lastCoords.x,l.lastCoords.y):this.state.activeTool.type!=="eraser"&&this.state.activeTool.type!=="hand"&&this.state.activeTool.type!=="image"&&this.createGenericElementOnPointerDown(this.state.activeTool.type,l);this.props?.onPointerDown?.(this.state.activeTool,l),this.onPointerDownEmitter.trigger(this.state.activeTool,l,o),this.state.activeTool.type==="eraser"&&this.eraserTrail.startPath(l.lastCoords.x,l.lastCoords.y);let m=this.onPointerMoveFromPointerDownHandler(l),p=this.onPointerUpFromPointerDownHandler(l),d=this.onKeyDownFromPointerDownHandler(l),u=this.onKeyUpFromPointerDownHandler(l);this.missingPointerEventCleanupEmitter.once(h=>p(h||o.nativeEvent)),(!this.state.viewModeEnabled||this.state.activeTool.type==="laser")&&(window.addEventListener(ue.POINTER_MOVE,m),window.addEventListener(ue.POINTER_UP,p),window.addEventListener(ue.KEYDOWN,d),window.addEventListener(ue.KEYUP,u),l.eventListeners.onMove=m,l.eventListeners.onUp=p,l.eventListeners.onKeyUp=u,l.eventListeners.onKeyDown=d)});A(this,"handleCanvasPointerUp",o=>{Ar("COMPLEX_BINDINGS")&&this.resetDelayedBindMode(),this.removePointer(o),this.lastPointerUpEvent=o;let n=ot({clientX:o.clientX,clientY:o.clientY},this.state),{x:r,y:i}=n;if(this.lastPointerMoveCoords={x:r,y:i},!this.handleIframeLikeCenterClick()){if(this.editorInterface.isTouchScreen){let a=this.getElementAtPosition(n.x,n.y,{includeLockedElements:!0});this.hitLinkElement=this.getElementLinkAtPosition(n,a)}this.hitLinkElement&&!this.state.selectedElementIds[this.hitLinkElement.id]?this.handleElementLinkClick(o):this.state.viewModeEnabled&&this.setState({activeEmbeddable:null,selectedElementIds:{}})}});A(this,"maybeOpenContextMenuAfterPointerDownOnTouchDevices",o=>{o.pointerType==="touch"&&(Bd=!1,Ai?Bd=!0:Ai=window.setTimeout(()=>{Ai=0,Bd||this.handleCanvasContextMenu(o)},lj))});A(this,"resetContextMenuTimer",()=>{clearTimeout(Ai),Ai=0,Bd=!1});A(this,"maybeCleanupAfterMissingPointerUp",o=>{Fd?.(),this.missingPointerEventCleanupEmitter.trigger(o).clear()});A(this,"handleCanvasPanUsingWheelOrSpaceDrag",o=>{if(!(_e.pointers.size<=1&&(o.button===Ci.WHEEL||o.button===Ci.MAIN&&Pi||sr(this.state)||this.state.viewModeEnabled&&this.state.activeTool.type!=="laser")))return!1;Rd=!0,this.focusContainer(),this.state.editingTextElement||o.preventDefault();let n=!1,r=typeof window===void 0?!1:/Linux/.test(window.navigator.platform);Re(this.interactiveCanvas,st.GRABBING);let{clientX:i,clientY:a}=o,s=Su(c=>{let m=i-c.clientX,p=a-c.clientY;if(i=c.clientX,a=c.clientY,r&&!n&&(Math.abs(m)>1||Math.abs(p)>1)){n=!0;let d=h=>{document.body.removeEventListener(ue.PASTE,d),h.stopPropagation()},u=()=>{setTimeout(()=>{document.body.removeEventListener(ue.PASTE,d),window.removeEventListener(ue.POINTER_UP,u)},100)};document.body.addEventListener(ue.PASTE,d),window.addEventListener(ue.POINTER_UP,u)}this.translateCanvas({scrollX:this.state.scrollX-m/this.state.zoom.value,scrollY:this.state.scrollY-p/this.state.zoom.value})}),l=mt(Fd=()=>{Fd=null,Rd=!1,Pi||(this.state.viewModeEnabled&&this.state.activeTool.type!=="laser"?Re(this.interactiveCanvas,st.GRAB):Mo(this.interactiveCanvas,this.state)),this.setState({cursorButton:"up"}),this.savePointer(o.clientX,o.clientY,"up"),window.removeEventListener(ue.POINTER_MOVE,s),window.removeEventListener(ue.POINTER_UP,l),window.removeEventListener(ue.BLUR,l),s.flush()});return window.addEventListener(ue.BLUR,l),window.addEventListener(ue.POINTER_MOVE,s,{passive:!0}),window.addEventListener(ue.POINTER_UP,l),!0});A(this,"clearSelectionIfNotUsingSelection",()=>{Sg(this.state.activeTool.type)||this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null})});A(this,"handleSelectionOnPointerDown",(o,n)=>{if(Sg(this.state.activeTool.type)){let r=this.scene.getNonDeletedElements(),i=this.scene.getNonDeletedElementsMap(),a=this.scene.getSelectedElements(this.state);if(a.length===1&&!this.state.selectedLinearElement?.isEditing&&!vo(a[0])&&!(ao(a[0])&&(this.editorInterface.userAgent.isMobileDevice||a[0].points.length===2))&&!(this.state.selectedLinearElement&&this.state.selectedLinearElement.hoverPointIndex!==-1)){let s=j6(r,this.state,n.origin.x,n.origin.y,this.state.zoom,o.pointerType,this.scene.getNonDeletedElementsMap(),this.editorInterface);s!=null&&(s.transformHandleType==="rotation"?(this.setState({resizingElement:s.element}),n.resize.handleType=s.transformHandleType):(this.state.croppingElementId||this.setState({resizingElement:s.element}),n.resize.handleType=s.transformHandleType))}else a.length>1&&(n.resize.handleType=q6(Pl(a),n.origin.x,n.origin.y,this.state.zoom,o.pointerType,this.editorInterface));if(n.resize.handleType)n.resize.isResizing=!0,n.resize.offset=Cx(Aq(n.resize.handleType,a,i,n.origin.x,n.origin.y)),a.length===1&&ao(a[0])&&a[0].points.length===2&&(n.resize.arrowDirection=Lq(n.resize.handleType,a[0]));else{if(this.state.selectedLinearElement){let d=this.state.selectedLinearElement,u=Me.handlePointerDown(o,this,this.store,n.origin,d,this.scene);if(u.hitElement&&(n.hit.element=u.hitElement),u.linearElementEditor&&this.setState({selectedLinearElement:u.linearElementEditor}),u.didAddPoint)return!0;let h=this.scene.getNonDeletedElementsMap(),g=Me.getElement(d.elementId,h);if(g&&or(g)){let{hitFocusPoint:E,pointerOffset:w}=Uq(g,n,h,this.state);if(E)return this.setState({selectedLinearElement:{...d,hoveredFocusPointBinding:E,draggedFocusPointBinding:E,pointerOffset:w}}),!1}}let s=this.getElementsAtPosition(n.origin.x,n.origin.y,{includeLockedElements:!0}),l=s.filter(d=>!d.locked),c=this.getElementAtPosition(n.origin.x,n.origin.y,{allHitElements:s});if((!c||c.id!==this.state.activeLockedId)&&this.setState({activeLockedId:null}),c&&c.locked&&!l.some(d=>this.state.selectedElementIds[d.id])?n.hit.element=null:n.hit.element=n.hit.element??this.getElementAtPosition(n.origin.x,n.origin.y),this.hitLinkElement=this.getElementLinkAtPosition(n.origin,c),this.hitLinkElement)return!0;if(this.state.croppingElementId&&n.hit.element?.id!==this.state.croppingElementId&&this.finishImageCropping(),n.hit.element&&this.getElementLinkAtPosition({x:n.origin.x,y:n.origin.y},n.hit.element))return!1;n.hit.allHitElements=l;let m=n.hit.element,p=n.hit.allHitElements.some(d=>this.isASelectedElement(d));if((m===null||!p)&&!o.shiftKey&&!n.hit.hasHitCommonBoundingBoxOfSelectedElements&&(!this.state.selectedLinearElement?.isEditing||m&&m?.id!==this.state.selectedLinearElement?.elementId)&&this.clearSelection(m),this.state.selectedLinearElement?.isEditing)this.setState(d=>({selectedLinearElement:d.selectedLinearElement?{...d.selectedLinearElement,isEditing:!!m&&m.id===this.state.selectedLinearElement?.elementId}:null,selectedElementIds:d.selectedLinearElement?Oe({[d.selectedLinearElement.elementId]:!0},this.state):Oe({},d)}));else if(m!=null){if(o[oe.CTRL_OR_CMD])return o.altKey?(this.state.openDialog?.name==="elementLinkSelector"&&this.setOpenDialog(null),this.lassoTrail.startPath(n.origin.x,n.origin.y,o.shiftKey),this.setActiveTool({type:"lasso",fromSelection:!0}),!1):(this.state.selectedElementIds[m.id]||(n.hit.wasAddedToSelection=!0),this.setState(d=>({...Tq(d,m),previousSelectedElementIds:this.state.selectedElementIds})),!1);this.state.selectedElementIds[m.id]||(this.state.editingGroupId&&!K6(m,this.state.editingGroupId)&&this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null}),!p&&!n.hit.hasHitCommonBoundingBoxOfSelectedElements&&(this.setState(d=>{let u={...d.selectedElementIds,[m.id]:!0},h=[];if(Object.keys(d.selectedElementIds).forEach(g=>{let E=this.scene.getElement(g);E&&h.push(E)}),jt(m))Ox(h,m.id).forEach(g=>{delete u[g.id]});else if(m.frameId)u[m.frameId]&&delete u[m.id];else{let g=m.groupIds,E=new Set(g.flatMap(w=>Ca(this.scene.getNonDeletedElements(),w)).filter(w=>jt(w)).map(w=>w.id));E.size>0&&h.forEach(w=>{w.frameId&&E.has(w.frameId)&&(delete u[w.id],w.groupIds.flatMap(x=>Ca(this.scene.getNonDeletedElements(),x)).forEach(x=>{delete u[x.id]}))})}return d.openDialog?.name==="elementLinkSelector"&&(m.groupIds.some(g=>d.selectedGroupIds[g])||(u={[m.id]:!0})),{...nn({editingGroupId:d.editingGroupId,selectedElementIds:u},this.scene.getNonDeletedElements(),d,this),showHyperlinkPopup:m.link||Lr(m)?"info":!1}}),n.hit.wasAddedToSelection=!0))}this.setState({previousSelectedElementIds:this.state.selectedElementIds})}}return!1});A(this,"handleTextOnPointerDown",(o,n)=>{if(this.state.editingTextElement)return;let r=n.origin.x,i=n.origin.y,a=this.getElementAtPosition(r,i,{includeBoundTextElement:!0}),s=this.getTextBindableContainerAtPosition(r,i);R6(a)&&(s=a,r=a.x+a.width/2,i=a.y+a.height/2),this.startTextEditing({sceneX:r,sceneY:i,insertAtParentCenter:!o.altKey,container:s,autoEdit:!1}),So(this.interactiveCanvas),this.state.activeTool.locked||this.setState({activeTool:er(this.state,{type:this.state.preferredSelectionTool.type})})});A(this,"handleFreeDrawElementOnPointerDown",(o,n,r)=>{let[i,a]=Zt(r.origin.x,r.origin.y,null),s=this.getTopLayerFrameAtSceneCoords({x:i,y:a}),l=o.pressure===.5,c=Oj({type:n,x:i,y:a,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,roundness:null,simulatePressure:l,locked:!1,frameId:s?s.id:null,points:[de(0,0)],pressures:l?[]:[o.pressure]});this.scene.insertElement(c),this.setState(p=>{let d={...p.selectedElementIds};return delete d[c.id],{selectedElementIds:Oe(d,p)}});let m=wn(de(r.origin.x,r.origin.y),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap());this.setState({newElement:c,startBoundElement:m,suggestedBinding:null})});A(this,"insertIframeElement",({sceneX:o,sceneY:n,width:r,height:i})=>{let[a,s]=Zt(o,n,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),l=zj({type:"iframe",x:a,y:s,strokeColor:"transparent",backgroundColor:"transparent",fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,roundness:this.getCurrentItemRoundness("iframe"),opacity:this.state.currentItemOpacity,locked:!1,width:r,height:i});return this.scene.insertElement(l),l});A(this,"insertEmbeddableElement",({sceneX:o,sceneY:n,link:r})=>{let[i,a]=Zt(o,n,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),s=Ag(r);if(!s)return;s.error instanceof URIError&&this.setToast({message:f("toast.unrecognizedLinkFormat"),closable:!0});let l=A6({type:"embeddable",x:i,y:a,strokeColor:"transparent",backgroundColor:"transparent",fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,roundness:this.getCurrentItemRoundness("embeddable"),opacity:this.state.currentItemOpacity,locked:!1,width:s.intrinsicSize.w,height:s.intrinsicSize.h,link:r});return this.scene.insertElement(l),l});A(this,"newImagePlaceholder",({sceneX:o,sceneY:n,addToFrameUnderCursor:r=!0})=>{let[i,a]=Zt(o,n,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),s=r?this.getTopLayerFrameAtSceneCoords({x:i,y:a}):null,l=100/this.state.zoom.value;return Mx({type:"image",strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,roundness:null,opacity:this.state.currentItemOpacity,locked:!1,frameId:s?s.id:null,x:i-l/2,y:a-l/2,width:l,height:l})});A(this,"handleLinearElementOnPointerDown",(o,n,r)=>{if(o.ctrlKey&&wo(()=>{this.setState({isBindingEnabled:!1})}),this.state.multiElement){let{multiElement:i,selectedLinearElement:a}=this.state;if(tr(a,"selectedLinearElement is expected to be set"),i.type==="line"&&O6(i.points,this.state.zoom.value)){wo(()=>{this.setState({selectedLinearElement:{...a,lastCommittedPoint:i.points[i.points.length-1],initialState:{...a.initialState,lastClickedPoint:-1}}})}),this.actionManager.executeAction(to);return}if(vo(i)&&i.points.length>1){this.actionManager.executeAction(to,"ui",{event:o.nativeEvent,sceneCoords:{x:r.origin.x,y:r.origin.y}});return}let{x:s,y:l}=i,{lastCommittedPoint:c}=a,m=Md(this.state)&&wn(de(this.lastPointerMoveCoords?.x??s+i.points[i.points.length-1][0],this.lastPointerMoveCoords?.y??l+i.points[i.points.length-1][1]),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap());if(or(i)&&m||i.points.length>1&&c&&Ti(de(r.origin.x-s,r.origin.y-l),c)<vx){this.actionManager.executeAction(to,"ui",{event:o.nativeEvent,sceneCoords:{x:r.origin.x,y:r.origin.y}});return}this.setState(p=>({selectedElementIds:Oe({...p.selectedElementIds,[i.id]:!0},p)})),Re(this.interactiveCanvas,st.POINTER)}else{let[i,a]=Zt(r.origin.x,r.origin.y,o[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),s=this.getTopLayerFrameAtSceneCoords({x:i,y:a}),{currentItemStartArrowhead:l,currentItemEndArrowhead:c}=this.state,[m,p]=n==="arrow"?[l,c]:[null,null],d=n==="arrow"?Hj({type:n,x:i,y:a,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,roundness:this.state.currentItemArrowType===ki.round?{type:vg.PROPORTIONAL_RADIUS}:null,startArrowhead:m,endArrowhead:p,locked:!1,frameId:s?s.id:null,elbowed:this.state.currentItemArrowType===ki.elbow,fixedSegments:this.state.currentItemArrowType===ki.elbow?[]:null}):Uj({type:n,x:i,y:a,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,roundness:this.state.currentItemRoundness==="round"?{type:vg.PROPORTIONAL_RADIUS}:null,locked:!1,frameId:s?s.id:null}),u=de(r.origin.x,r.origin.y),h=this.scene.getNonDeletedElementsMap(),g=Md(this.state)?wn(u,this.scene.getNonDeletedElements(),h):null;this.scene.mutateElement(d,{points:[de(0,0),de(0,0)]}),this.scene.insertElement(d),or(d)&&Fq(d,new Map([[0,{point:de(0,0),isDragging:!1}]]),u[0],u[1],this.scene,this.state,{newArrow:!0,altKey:o.altKey,initialBinding:!0,angleLocked:f6(o.nativeEvent)}),wo(()=>{this.setState(E=>{let w=null,x=E.selectedElementIds;if(ao(d)){w=new Me(d,this.scene.getNonDeletedElementsMap());let y=d.points.length-1;w={...w,selectedPointsIndices:[y],initialState:{...w.initialState,arrowStartIsInside:o.altKey,lastClickedPoint:y,origin:de(r.origin.x,r.origin.y)}}}return x=this.state.activeTool.locked?E.selectedElementIds:Oe({[d.id]:!0},E),{...E,bindMode:"orbit",newElement:d,startBoundElement:g,suggestedBinding:g&&or(d)?{element:g,midPoint:$x(u,g,h,this.state.zoom)}:null,selectedElementIds:x,selectedLinearElement:w}})}),or(d)&&Ar("COMPLEX_BINDINGS")&&this.handleDelayedBindModeChange(d,g)}});A(this,"createGenericElementOnPointerDown",(o,n)=>{let[r,i]=Zt(n.origin.x,n.origin.y,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),a=this.getTopLayerFrameAtSceneCoords({x:r,y:i}),s={x:r,y:i,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,roundness:this.getCurrentItemRoundness(o),locked:!1,frameId:a?a.id:null},l;o==="embeddable"?l=A6({type:"embeddable",...s}):l=Gj({type:o,...s}),l.type==="selection"?this.setState({selectionElement:l}):(this.scene.insertElement(l),this.setState({multiElement:null,newElement:l}))});A(this,"createFrameElementOnPointerDown",(o,n)=>{let[r,i]=Zt(o.origin.x,o.origin.y,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),a={x:r,y:i,opacity:this.state.currentItemOpacity,locked:!1,...on},s=n===Qn.magicframe?L6(a):P6(a);this.scene.insertElement(s),this.setState({multiElement:null,newElement:s})});A(this,"restoreReadyToEraseElements",()=>{this.elementsPendingErasure=new Set,this.triggerRender()});A(this,"eraseElements",()=>{let o=!1;this.elementsPendingErasure.forEach(r=>{let i=this.scene.getElement(r);if(or(i)){if(i.startBinding){let a=this.scene.getElement(i.startBinding.elementId);Lg(a,this.scene.getElementsMapIncludingDeleted(),{boundElements:a.boundElements.filter(s=>s.id!==i.id)})}if(i.endBinding){let a=this.scene.getElement(i.endBinding.elementId);Lg(a,this.scene.getElementsMapIncludingDeleted(),{boundElements:a.boundElements.filter(s=>s.id!==i.id)})}}else Dx(i)&&i.boundElements?.forEach(a=>{if(a.type==="arrow"){let s=this.scene.getElement(a.id);s?.startBinding?.elementId===i.id&&Lg(s,this.scene.getElementsMapIncludingDeleted(),{startBinding:null}),s?.endBinding?.elementId===i.id&&Lg(s,this.scene.getElementsMapIncludingDeleted(),{endBinding:null})}})});let n=this.scene.getElementsIncludingDeleted().map(r=>this.elementsPendingErasure.has(r.id)||r.frameId&&this.elementsPendingErasure.has(r.frameId)||Ax(r)&&this.elementsPendingErasure.has(r.containerId)?(o=!0,Si(r,{isDeleted:!0})):r);this.elementsPendingErasure=new Set,o&&(this.store.scheduleCapture(),this.scene.replaceAllElements(n))});A(this,"initializeImage",async(o,n)=>{if(!Jg(n))throw new Error(f("errors.unsupportedFileType"));let r=n.type;if(Re(this.interactiveCanvas,"wait"),r===Jn.svg)try{n=oh(H6(await n.text()),n.name)}catch(l){throw console.warn(l),new Error(f("errors.svgImageInsertError"))}let i=await(this.props.generateIdForFile?.(n)||JE(n));if(!i)throw console.warn("Couldn't generate file id or the supplied `generateIdForFile` didn't resolve to one."),new Error(f("errors.imageInsertError"));if(!this.files[i]?.dataURL){try{n=await tm(n,{maxWidthOrHeight:ej})}catch(l){console.error("Error trying to resizing image file on insertion",l)}if(n.size>y6)throw new Error(f("errors.fileTooBig",{maxSize:`${Math.trunc(y6/1024/1024)}MB`}))}let s=this.files[i]?.dataURL||await za(n);return new Promise(async(l,c)=>{try{let m=this.getLatestInitializedImageElement(o,i);if(this.addMissingFiles([{mimeType:r,id:i,dataURL:s,created:Date.now(),lastRetrieved:Date.now()}]),!this.imageCache.get(i)){this.addNewImagesToImageCache();let{erroredFiles:d}=await this.updateImageCache([m]);if(d.size)throw new Error("Image cache update resulted with an error.")}let p=await this.imageCache.get(i)?.image;if(p&&this.state.newElement?.id!==m.id){m=this.getLatestInitializedImageElement(o,i);let d=this.getImageNaturalDimensions(m,p);Object.assign(m,d)}l(m)}catch(m){console.error(m),c(new Error(f("errors.imageInsertError")))}})});A(this,"getLatestInitializedImageElement",(o,n)=>{let r=this.scene.getElement(o.id)??o;return Si(r,{fileId:n})});A(this,"onImageToolbarButtonClick",async()=>{try{let o=this.state.width/2+this.state.offsetLeft,n=this.state.height/2+this.state.offsetTop,{x:r,y:i}=ot({clientX:o,clientY:n},this.state),a=await Xd({description:"Image",extensions:Object.keys(oj),multiple:!0});this.insertImages(a,r,i)}catch(o){o.name!=="AbortError"?console.error(o):console.warn(o),this.setState({newElement:null,activeTool:er(this.state,{type:this.state.preferredSelectionTool.type})},()=>{this.actionManager.executeAction(to)})}});A(this,"getImageNaturalDimensions",(o,n)=>{let r=Math.max(this.state.height-120,160),i=Math.min(r,Math.floor(this.state.height*.5)/this.state.zoom.value),a=Math.min(n.naturalHeight,i),s=a*(n.naturalWidth/n.naturalHeight),l=o.x+o.width/2-s/2,c=o.y+o.height/2-a/2;return{x:l,y:c,width:s,height:a,crop:null}});A(this,"updateImageCache",async(o,n=this.files)=>{let{updatedFiles:r,erroredFiles:i}=await Jj({imageCache:this.imageCache,fileIds:o.map(a=>a.fileId),files:n});return i.size&&(this.store.scheduleAction(so.NEVER),this.scene.replaceAllElements(this.scene.getElementsIncludingDeleted().map(a=>Pd(a)&&i.has(a.fileId)?Si(a,{status:"error"}):a))),{updatedFiles:r,erroredFiles:i}});A(this,"addNewImagesToImageCache",async(o=qj(this.scene.getNonDeletedElements()),n=this.files)=>{let r=o.filter(i=>!i.isDeleted&&!this.imageCache.has(i.fileId));if(r.length){let{updatedFiles:i}=await this.updateImageCache(r,n);if(i.size)for(let a of r)i.has(a.fileId)&&Ld.delete(a);i.size&&this.scene.triggerUpdate()}});A(this,"scheduleImageRefresh",jZ(()=>{this.addNewImagesToImageCache()},nj));A(this,"updateBindingEnabledOnPointerMove",o=>{let n=Fj(o);this.state.isBindingEnabled!==n&&this.setState({isBindingEnabled:n})});A(this,"handleInteractiveCanvasRef",o=>{o!==null?(this.interactiveCanvas=o,this.interactiveCanvas.addEventListener(ue.TOUCH_START,this.onTouchStart,{passive:!1}),this.interactiveCanvas.addEventListener(ue.TOUCH_END,this.onTouchEnd)):(this.interactiveCanvas?.removeEventListener(ue.TOUCH_START,this.onTouchStart),this.interactiveCanvas?.removeEventListener(ue.TOUCH_END,this.onTouchEnd))});A(this,"insertImages",async(o,n,r)=>{let i=50/this.state.zoom.value,a=oP(o.map(()=>this.newImagePlaceholder({sceneX:n,sceneY:r})),n,r,i);a.forEach(d=>this.scene.insertElement(d));let s=await Promise.all(a.map(async(d,u)=>{try{return await this.initializeImage(d,await Kl(o[u]))}catch(h){return this.setState({errorMessage:h.message||f("errors.imageInsertError")}),Si(d,{isDeleted:!0})}})),l=kg(s),c=oP(s.filter(d=>!d.isDeleted),n,r,i),m=kg(c),p=this.scene.getElementsIncludingDeleted().map(d=>m.get(d.id)??l.get(d.id)??d);this.updateScene({appState:{selectedElementIds:Oe(Object.fromEntries(c.map(d=>[d.id,!0])),this.state)},elements:p,captureUpdate:so.IMMEDIATELY}),this.setState({},()=>{this.actionManager.executeAction(to)})});A(this,"handleAppOnDrop",async o=>{let{x:n,y:r}=ot(o,this.state),i=await Is(o),a=i.getFiles();if(a.length===1){let{file:p,fileHandle:d}=a[0];if(p&&(p.type===Jn.png||p.type===Jn.svg))try{let u=await em(p,this.state,this.scene.getElementsIncludingDeleted(),d);this.syncActionResult({...u,appState:{...u.appState||this.state,isLoading:!1},replaceFiles:!0,captureUpdate:so.IMMEDIATELY});return}catch(u){if(u.name!=="EncodingError")throw new Error(f("alerts.couldNotLoadInvalidFile"))}}let s=a.map(p=>p.file).filter(p=>Jg(p));if(s.length>0&&this.isToolSupported("image"))return this.insertImages(s,n,r);let l=i.getData(Jn.excalidrawlibIds),c=i.getData(Jn.excalidrawlib);if(l||c){try{let p=null;if(l){let{itemIds:d}=JSON.parse(l);p=(await this.library.getLatestLibrary()).filter(h=>d.includes(h.id))}else c&&(p=qE(c));p?.length&&(p=p.map(d=>({...d,elements:Px({type:"everything",elements:d.elements,randomizeSeed:!0}).duplicatedElements})),this.addElementsFromPasteOrLibrary({elements:Us(p),position:o,files:null}))}catch(p){this.setState({errorMessage:p.message})}return}if(a.length>0){let{file:p,fileHandle:d}=a[0];p&&await this.loadFileToCanvas(p,d)}let m=i.findByType(Jn.text);if(m){let p=m.value;if(p&&Nx(p,this.props.validateEmbeddable)&&(/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(p)||Ag(p)?.type==="video")){let d=this.insertEmbeddableElement({sceneX:n,sceneY:r,link:Ix(p)});d&&(this.store.scheduleCapture(),this.setState({selectedElementIds:{[d.id]:!0}}))}}});A(this,"loadFileToCanvas",async(o,n)=>{o=await Kl(o);try{let r=this.scene.getElementsIncludingDeleted(),i;try{i=await Qg(o,this.state,r,n)}catch(a){let s=a instanceof HE;if(s&&a.code==="IMAGE_NOT_CONTAINS_SCENE_DATA"&&!this.isToolSupported("image")){this.setState({isLoading:!1,errorMessage:f("errors.imageToolNotSupported")});return}let l=s?f("alerts.cannotRestoreFromImage"):f("alerts.couldNotLoadInvalidFile");this.setState({isLoading:!1,errorMessage:l})}if(!i)return;i.type===Jn.excalidraw?(pP(r.concat(i.data.elements)),this.store.scheduleMicroAction({action:so.NEVER,elements:r,appState:void 0}),this.setState({isLoading:!0}),this.syncActionResult({...i.data,appState:{...i.data.appState||this.state,isLoading:!1},replaceFiles:!0,captureUpdate:so.IMMEDIATELY})):i.type===Jn.excalidrawlib&&await this.library.updateLibrary({libraryItems:o,merge:!0,openLibraryMenu:!0}).catch(a=>{console.error(a),this.setState({errorMessage:f("errors.importLibraryError")})})}catch(r){this.setState({isLoading:!1,errorMessage:r.message})}});A(this,"handleCanvasContextMenu",o=>{if(o.preventDefault(),("pointerType"in o.nativeEvent&&o.nativeEvent.pointerType==="touch"||"pointerType"in o.nativeEvent&&o.nativeEvent.pointerType==="pen"&&o.button!==Ci.SECONDARY)&&this.state.activeTool.type!==this.state.preferredSelectionTool.type)return;let{x:n,y:r}=ot(o,this.state),i=this.getElementAtPosition(n,r,{preferSelected:!0,includeLockedElements:!0}),a=this.scene.getSelectedElements(this.state),s=this.isHittingCommonBoundingBoxOfSelectedElements({x:n,y:r},a),l=i||s?"element":"canvas",c=this.excalidrawContainerRef.current,{top:m,left:p}=c.getBoundingClientRect(),d=o.clientX-p,u=o.clientY-m;ge("contextMenu","openContextMenu",l),this.setState({...i&&!this.state.selectedElementIds[i.id]?{...this.state,...nn({editingGroupId:this.state.editingGroupId,selectedElementIds:{[i.id]:!0}},this.scene.getNonDeletedElements(),this.state,this),selectedLinearElement:ao(i)?new Me(i,this.scene.getNonDeletedElementsMap()):null}:this.state,showHyperlinkPopup:!1},()=>{this.setState({contextMenu:{top:u,left:d,items:this.getContextMenuItems(l)}})})});A(this,"maybeDragNewGenericElement",(o,n,r=!0)=>{let i=this.state.selectionElement,a=o.lastCoords;if(i&&o.boxSelection.hasOccurred&&this.state.activeTool.type!=="eraser"){J6({newElement:i,elementType:this.state.activeTool.type,originX:o.origin.x,originY:o.origin.y,x:a.x,y:a.y,width:Ml(o.origin.x,a.x),height:Ml(o.origin.y,a.y),shouldMaintainAspectRatio:Cd(n),shouldResizeFromCenter:!1,scene:this.scene,zoom:this.state.zoom.value,informMutation:!1});return}let s=this.state.newElement;if(!s)return;let[l,c]=Zt(a.x,a.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),m=Pd(s)&&this.imageCache.get(s.fileId)?.image,p=m&&!(m instanceof Promise)?m.width/m.height:null;this.maybeCacheReferenceSnapPoints(n,[s]);let{snapOffset:d,snapLines:u}=j5(s,this,n,{x:o.originInGrid.x+(this.state.originSnapOffset?.x??0),y:o.originInGrid.y+(this.state.originSnapOffset?.y??0)},{x:l-o.originInGrid.x,y:c-o.originInGrid.y},this.scene.getNonDeletedElementsMap());l+=d.x,c+=d.y,this.setState({snapLines:u}),or(s)||J6({newElement:s,elementType:this.state.activeTool.type,originX:o.originInGrid.x,originY:o.originInGrid.y,x:l,y:c,width:Ml(o.originInGrid.x,l),height:Ml(o.originInGrid.y,c),shouldMaintainAspectRatio:Mi(s)?!Cd(n):Cd(n),shouldResizeFromCenter:h6(n),zoom:this.state.zoom.value,scene:this.scene,widthAspectRatio:p,originOffset:this.state.originSnapOffset,informMutation:r}),this.setState({newElement:s}),(this.state.activeTool.type===Qn.frame||this.state.activeTool.type===Qn.magicframe)&&this.setState({elementsToHighlight:Hx(this.scene.getNonDeletedElements(),s,this.state,this.scene.getNonDeletedElementsMap())})});A(this,"maybeHandleCrop",(o,n)=>{if(!this.state.croppingElementId)return!1;let r=o.resize.handleType,i=o.lastCoords,[a,s]=Zt(i.x-o.resize.offset.x,i.y-o.resize.offset.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),l=this.scene.getNonDeletedElementsMap().get(this.state.croppingElementId);if(r&&l&&Mi(l)){let c=o.originalElements.get(l.id),m=Pd(l)&&this.imageCache.get(l.fileId)?.image;if(c&&Mi(c)&&m&&!(m instanceof Promise)){let[p,d]=Zt(i.x,i.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),u={x:p-o.originInGrid.x,y:d-o.originInGrid.y};this.maybeCacheReferenceSnapPoints(n,[l]);let{snapOffset:h,snapLines:g}=w0([l],[c],this,n,u,r);this.scene.mutateElement(l,gq(l,this.scene.getNonDeletedElementsMap(),r,m.naturalWidth,m.naturalHeight,a+h.x,s+h.y,n.shiftKey?c.width/c.height:void 0)),Pg(l,this.scene),this.setState({isCropping:r&&r!=="rotation",snapLines:g})}return!0}return!1});A(this,"maybeHandleResize",(o,n)=>{let r=this.scene.getSelectedElements(this.state),i=r.filter(p=>jt(p)),a=o.resize.handleType;if(i.length>0&&a==="rotation"||r.length===1&&vo(r[0])||this.state.croppingElementId)return!1;this.setState({isResizing:a&&a!=="rotation",isRotating:a==="rotation",activeEmbeddable:null});let s=o.lastCoords,[l,c]=Zt(s.x-o.resize.offset.x,s.y-o.resize.offset.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),m=new Map;if(i.forEach(p=>{Ox(this.scene.getNonDeletedElements(),p.id).forEach(u=>{m.set(p.id+u.id,{x:u.x-p.x,y:u.y-p.y})})}),!this.state.selectedElementsAreBeingDragged){let[p,d]=Zt(s.x,s.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),u={x:p-o.originInGrid.x,y:d-o.originInGrid.y},h=[...o.originalElements.values()];this.maybeCacheReferenceSnapPoints(n,r);let{snapOffset:g,snapLines:E}=w0(r,le(h,this.state),this,n,u,a);l+=g.x,c+=g.y,this.setState({snapLines:E})}if(_q(o.originalElements,a,r,this.scene,f6(n),h6(n),r.some(p=>Mi(p))?!Cd(n):Cd(n),l,c,o.resize.center.x,o.resize.center.y)){let p=new Set;return i.forEach(d=>{Hx(this.scene.getNonDeletedElements(),d,this.state,this.scene.getNonDeletedElementsMap()).forEach(u=>p.add(u))}),this.setState({elementsToHighlight:[...p]}),!0}return!1});A(this,"getContextMenuItems",o=>{let n=[];if(n.push(mp,dp),o==="canvas")return this.state.viewModeEnabled?[...n,_s,jr,ea,qr]:[Uf,yt,mp,dp,pp,yt,Nh,jI,yt,_s,Cc,jr,ea,qr];if(n.push(pp),this.state.viewModeEnabled)return[Ls,...n];let r=this.editorInterface.formFactor==="desktop"?[yt,Lh,_h,Dh,Rh]:[];return[yt,cp,Ls,Uf,yt,S5,M5,P5,yt,Kc,yt,...n,yt,_f,Df,yt,Nf,F5,Vf,$f,NI,Bf,yt,zf,...r,yt,Hf,Gf,yt,Qs,yt,Mc,yp,yt,Bh,Pc,yt,nc]});A(this,"handleWheel",mt(o=>{if(!(o.target instanceof HTMLCanvasElement||o.target instanceof HTMLTextAreaElement||o.target instanceof HTMLIFrameElement||o.target instanceof HTMLElement&&o.target.classList.contains(Sx.FRAME_NAME))){o[oe.CTRL_OR_CMD]&&o.preventDefault();return}if(o.preventDefault(),Rd)return;let{deltaX:n,deltaY:r}=o;if(o.metaKey||o.ctrlKey){let i=Math.sign(r),a=dj*100,s=Math.abs(r),l=r;s>a&&(l=a*i);let c=this.state.zoom.value-l/100;c+=Math.log10(Math.max(1,this.state.zoom.value))*-i*Math.min(1,s/20),this.translateCanvas(m=>({...pr({viewportX:this.lastViewportPosition.x,viewportY:this.lastViewportPosition.y,nextZoom:Cn(c)},m),shouldCacheIgnoreZoom:!0})),this.resetShouldCacheIgnoreZoomDebounced();return}if(o.shiftKey){this.translateCanvas(({zoom:i,scrollX:a})=>({scrollX:a-(r||n)/i.value}));return}this.translateCanvas(({zoom:i,scrollX:a,scrollY:s})=>({scrollX:a-n/i.value,scrollY:s-r/i.value}))}));A(this,"savePointer",(o,n,r)=>{if(!o||!n)return;let{x:i,y:a}=ot({clientX:o,clientY:n},this.state);isNaN(i)||isNaN(a);let s={x:i,y:a,tool:this.state.activeTool.type==="laser"?"laser":"pointer"};this.props.onPointerUpdate?.({pointer:s,button:r,pointersMap:_e.pointers})});A(this,"resetShouldCacheIgnoreZoomDebounced",I6(()=>{this.unmounted||this.setState({shouldCacheIgnoreZoom:!1})},300));A(this,"updateDOMRect",o=>{if(this.excalidrawContainerRef?.current){let n=this.excalidrawContainerRef.current,{width:r,height:i,left:a,top:s}=n.getBoundingClientRect(),{width:l,height:c,offsetTop:m,offsetLeft:p}=this.state;if(r===l&&i===c&&a===p&&s===m){o&&o();return}this.setState({width:r,height:i,offsetLeft:a,offsetTop:s},()=>{o&&o()})}});A(this,"refresh",()=>{this.setState({...this.getCanvasOffsets()})});A(this,"watchState",()=>{});let n=Rr(),{excalidrawAPI:r,viewModeEnabled:i=!1,zenModeEnabled:a=!1,gridModeEnabled:s=!1,objectsSnapModeEnabled:l=!1,theme:c=n.theme,name:m=`${f("labels.untitled")}-${C6()}`}=o;if(this.state={...n,theme:c,isLoading:!0,...this.getCanvasOffsets(),viewModeEnabled:i,zenModeEnabled:a,objectsSnapModeEnabled:l,gridModeEnabled:s??n.gridModeEnabled,name:m,width:window.innerWidth,height:window.innerHeight},this.refreshEditorInterface(),this.stylesPanelMode=Dg(this.editorInterface),this.id=Ex(),this.library=new vT(this),this.actionManager=new nu(this.syncActionResult,()=>this.state,()=>this.scene.getElementsIncludingDeleted(),this),this.scene=new eP,this.canvas=document.createElement("canvas"),this.rc=qZ.canvas(this.canvas),this.renderer=new qc(this.scene),this.visibleElements=[],this.store=new Nq(this),this.history=new Xc(this.store),r){let p={updateScene:this.updateScene,applyDeltas:this.applyDeltas,mutateElement:this.mutateElement,updateLibrary:this.library.updateLibrary,addFiles:this.addFiles,resetScene:this.resetScene,getSceneElementsIncludingDeleted:this.getSceneElementsIncludingDeleted,getSceneElementsMapIncludingDeleted:this.getSceneElementsMapIncludingDeleted,history:{clear:this.resetHistory},scrollToContent:this.scrollToContent,getSceneElements:this.getSceneElements,getAppState:()=>this.state,getFiles:()=>this.files,getName:this.getName,registerAction:d=>{this.actionManager.registerAction(d)},refresh:this.refresh,setToast:this.setToast,id:this.id,setActiveTool:this.setActiveTool,setCursor:this.setCursor,resetCursor:this.resetCursor,getEditorInterface:()=>this.editorInterface,updateFrameRendering:this.updateFrameRendering,toggleSidebar:this.toggleSidebar,onChange:d=>this.onChangeEmitter.on(d),onIncrement:d=>this.store.onStoreIncrementEmitter.on(d),onPointerDown:d=>this.onPointerDownEmitter.on(d),onPointerUp:d=>this.onPointerUpEmitter.on(d),onScrollChange:d=>this.onScrollChangeEmitter.on(d),onUserFollow:d=>this.onUserFollowEmitter.on(d)};typeof r=="function"?r(p):console.error("excalidrawAPI should be a function!")}this.excalidrawContainerValue={container:this.excalidrawContainerRef.current,id:this.id},this.fonts=new Mn(this.scene),this.history=new Xc(this.store),this.actionManager.registerAll(xm),this.actionManager.registerAction(D5(this.history)),this.actionManager.registerAction(R5(this.history))}onWindowMessage(o){if(o.origin!=="https://player.vimeo.com"&&o.origin!=="https://www.youtube.com")return;let n=null;try{n=JSON.parse(o.data)}catch{}if(n)switch(o.origin){case"https://player.vimeo.com":if(n.method==="paused"){let r=null,i=document.body.querySelectorAll("iframe.excalidraw__embeddable");if(!i)break;for(let a of i)a.contentWindow===o.source&&(r=a.contentWindow);r?.postMessage(JSON.stringify({method:n.value?"play":"pause",value:!0}),"*")}break;case"https://www.youtube.com":if(n.event==="infoDelivery"&&n.info&&n.id&&typeof n.info.playerState=="number"){let r=n.id,i=n.info.playerState;Object.values(Tg).includes(i)&&Zx.set(r,i)}break}}handleSkipBindMode(){if(this.state.selectedLinearElement?.initialState&&!this.state.selectedLinearElement.initialState.arrowStartIsInside){tr(this.lastPointerMoveCoords,"Missing last pointer move coords when changing bind skip mode for arrow start");let o=this.scene.getNonDeletedElementsMap(),n=wn(de(this.lastPointerMoveCoords.x,this.lastPointerMoveCoords.y),this.scene.getNonDeletedElements(),o),r=Me.getElement(this.state.selectedLinearElement.elementId,o);r?.startBinding&&n?.id===r.startBinding.elementId&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,initialState:{...this.state.selectedLinearElement.initialState,arrowStartIsInside:!0}}})}if(this.state.bindMode==="orbit"&&(this.bindModeHandler&&(clearTimeout(this.bindModeHandler),this.bindModeHandler=null),wo(()=>{this.setState({bindMode:"skip"})}),this.lastPointerMoveCoords&&this.state.selectedLinearElement?.selectedPointsIndices&&this.state.selectedLinearElement?.selectedPointsIndices.length)){let{x:o,y:n}=this.lastPointerMoveCoords,r=this.lastPointerMoveEvent??this.lastPointerDownEvent?.nativeEvent;tr(r,"Last event must exist");let i=o-this.state.selectedLinearElement.pointerOffset.x,a=n-this.state.selectedLinearElement.pointerOffset.y,s=this.state.multiElement?Me.handlePointerMove(r,this,i,a,this.state.selectedLinearElement):Me.handlePointDragging(r,this,i,a,this.state.selectedLinearElement);s&&this.setState(s)}}resetDelayedBindMode(){this.bindModeHandler&&(clearTimeout(this.bindModeHandler),this.bindModeHandler=null),this.state.bindMode!=="orbit"&&setTimeout(()=>this.setState({bindMode:"orbit"}))}handleDelayedBindModeChange(o,n){if(o.isDeleted||vo(o))return;let r=()=>{if(this.bindModeHandler=null,tr(this.lastPointerMoveCoords,"Expected lastPointerMoveCoords to be set"),!this.state.multiElement){if(!this.state.selectedLinearElement||!this.state.selectedLinearElement.selectedPointsIndices||!this.state.selectedLinearElement.selectedPointsIndices.length)return;let h=this.state.selectedLinearElement.selectedPointsIndices.includes(0),g=this.state.selectedLinearElement.selectedPointsIndices.includes(o.points.length-1);if(!h&&!g||h&&g)return}let{x:p,y:d}=this.lastPointerMoveCoords,u=wn(de(p,d),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap());if(u&&this.state.bindMode!=="skip"){tr(this.state.selectedLinearElement?.elementId===o.id,"The selectedLinearElement is expected to not change while a bind mode timeout is ticking");let h=this.state.selectedLinearElement.initialState.arrowStartIsInside||o.startBinding?.elementId===u.id;wo(()=>{tr(this.state.selectedLinearElement,"this.state.selectedLinearElement must exist"),this.setState({bindMode:"inside",selectedLinearElement:{...this.state.selectedLinearElement,initialState:{...this.state.selectedLinearElement.initialState,arrowStartIsInside:h}}})});let g=this.lastPointerMoveEvent??this.lastPointerDownEvent?.nativeEvent;tr(g,"Last event must exist");let E=p-this.state.selectedLinearElement.pointerOffset.x,w=d-this.state.selectedLinearElement.pointerOffset.y,x=this.state.multiElement?Me.handlePointerMove(g,this,E,w,this.state.selectedLinearElement):Me.handlePointDragging(g,this,E,w,this.state.selectedLinearElement);x&&this.setState(x)}},i=!1;if(this.state.selectedLinearElement?.selectedPointsIndices){let p=this.scene.getNonDeletedElementsMap(),d=this.state.selectedLinearElement.selectedPointsIndices.includes(0),u=this.state.selectedLinearElement.selectedPointsIndices.includes(o.points.length-1),h=d?n:o.startBinding&&p.get(o.startBinding.elementId),g=u?n:o.endBinding&&p.get(o.endBinding.elementId),E=h&&rP(h,p),w=g&&rP(g,p);i=!!(E&&w&&h.id!==g.id&&Oq(E,w))}let a=this.state.selectedLinearElement?.selectedPointsIndices?.includes(0),s=this.state.selectedLinearElement?.selectedPointsIndices?.includes(o.points.length-1),l=a?"startBinding":s?"endBinding":null,c=a?"endBinding":s?"startBinding":null,m=c&&o[c]?.mode==="inside"&&o[c]?.elementId===n?.id||l&&o[l]?.mode==="inside"&&n?.id===o[l]?.elementId;l&&c&&o[l]?.mode==="inside"&&n?.id!==o[l]?.elementId&&o[c]?.elementId!==o[l]?.elementId&&this.scene.mutateElement(o,{[l]:{...o[l],mode:"orbit"}},{informMutation:!1,isDragging:!0}),!n||this.previousHoveredBindableElement&&n.id!==this.previousHoveredBindableElement.id?(this.bindModeHandler&&(clearTimeout(this.bindModeHandler),this.bindModeHandler=null),this.state.bindMode==="inside"&&wo(()=>{this.setState({bindMode:"orbit"})}),this.previousHoveredBindableElement=null):!this.bindModeHandler&&(!this.state.newElement||!o.startBinding||i)&&!m&&(this.bindModeHandler=setTimeout(r,Mj)),this.previousHoveredBindableElement=n}cacheEmbeddableRef(o,n){n&&this.iFrameRefs.set(o.id,n)}getHTMLIFrameElement(o){return this.iFrameRefs.get(o.id)}handleIframeLikeCenterClick(){if(!this.lastPointerDownEvent||!this.lastPointerUpEvent||this.lastPointerDownEvent.button!==Ci.MAIN||Pi||!S6(this.state.activeTool.type,["laser","selection","lasso"]))return!1;let o=de(ot({clientX:this.lastPointerDownEvent.clientX,clientY:this.lastPointerDownEvent.clientY},this.state)),n=de(ot({clientX:this.lastPointerUpEvent.clientX,clientY:this.lastPointerUpEvent.clientY},this.state));if(Ti(o,n)>x6)return!1;let i=this.getElementAtPosition(o[0],o[1]);if(!(i&&this.lastPointerUpEvent.timeStamp-this.lastPointerDownEvent.timeStamp<=300&&_e.pointers.size<2&&Lx(i)&&(this.state.viewModeEnabled||this.state.activeTool.type==="laser"||this.isIframeLikeElementCenter(i,this.lastPointerUpEvent,n[0],n[1]))))return!1;let s=i;if(this.state.activeEmbeddable?.element===s&&this.state.activeEmbeddable?.state==="active"||(setTimeout(()=>{this.setState({activeEmbeddable:{element:s,state:"active"},selectedElementIds:{[s.id]:!0},newElement:null,selectionElement:null})},100),Ll(s)))return!0;let l=this.getHTMLIFrameElement(s);if(!l?.contentWindow)return!0;if(l.src.includes("youtube")){let c=Zx.get(s.id);switch(c||(Zx.set(s.id,Tg.UNSTARTED),l.contentWindow.postMessage(JSON.stringify({event:"listening",id:s.id}),"*")),c){case Tg.PLAYING:case Tg.BUFFERING:l.contentWindow?.postMessage(JSON.stringify({event:"command",func:"pauseVideo",args:""}),"*");break;default:l.contentWindow?.postMessage(JSON.stringify({event:"command",func:"playVideo",args:""}),"*")}}return l.src.includes("player.vimeo.com")&&l.contentWindow.postMessage(JSON.stringify({method:"paused"}),"*"),!0}isIframeLikeElementCenter(o,n,r,i){return o&&!n.altKey&&!n.shiftKey&&!n.metaKey&&!n.ctrlKey&&(this.state.activeEmbeddable?.element!==o||this.state.activeEmbeddable?.state==="hover"||!this.state.activeEmbeddable)&&r>=o.x+o.width/3&&r<=o.x+2*o.width/3&&i>=o.y+o.height/3&&i<=o.y+2*o.height/3}renderEmbeddables(){let o=this.state.zoom.value,n=this.state.width,r=this.state.height,i=this.scene.getNonDeletedElements().filter(a=>Lr(a)&&this.embedsValidationStatus.get(a.id)===!0||Ll(a));return Se(lP,{children:i.map(a=>{let{x:s,y:l}=Cg({sceneX:a.x,sceneY:a.y},this.state),c=B6(a,n,r,this.state,this.scene.getNonDeletedElementsMap()),m=this.initializedEmbeds.has(a.id);if(c&&!m&&this.initializedEmbeds.add(a.id),!(c||m))return null;let d;if(Ll(a)){d=null;let g=(a.customData?.generationData??this.magicGenerations.get(a.id))||{status:"error",message:"No generation data",code:"ERR_NO_GENERATION_DATA"};if(g.status==="done"){let E=g.html;d={intrinsicSize:{w:a.width,h:a.height},type:"document",srcdoc:()=>E}}else if(g.status==="pending")d={intrinsicSize:{w:a.width,h:a.height},type:"document",srcdoc:()=>z6(`
122
+ Please fix the Mermaid syntax and regenerate a valid diagram.`;await w({prompt:$,isRepairFlow:!0})},N=async D=>{let F=m.messages.findIndex(z=>z.id===D.id);if(F>0){let z=m.messages[F-1];z.type==="user"&&typeof z.content=="string"&&(g(),await w({prompt:z.content,isRepairFlow:!0}))}},O=()=>{gd({app:i,data:E})},B=D=>{let F=m.messages.findIndex($=>$.id===D&&$.type==="assistant"),z=m.messages.slice(0,F-1);p({...m,messages:z})},U=D=>{p(F=>({...F,currentPrompt:D}))};return ZV("div",{className:`ttd-dialog-layout ${d?"ttd-dialog-layout--split":"ttd-dialog-layout--chat-only"}`,children:[N1(dM,{chatId:m.id,messages:m.messages,currentPrompt:m.currentPrompt,onPromptChange:U,onGenerate:w,isGenerating:h?.isGenerating??!1,generatedResponse:h?.content,isMenuOpen:y,onMenuToggle:L,onMenuClose:S,onNewChat:k,onRestoreChat:v,onDeleteChat:I,savedChats:u,activeSessionId:m.id,onAbort:x,onMermaidTabClick:P,onAiRepairClick:M,onDeleteMessage:B,onInsertMessage:T,onRetry:N,onViewAsMermaid:_,renderWarning:n,renderWelcomeScreen:o}),d&&N1(pM,{canvasRef:s,hideErrorDetails:h?.errorType==="parse",error:l,loaded:e.loaded,onInsert:O})]})},XV=({mermaidToExcalidrawLib:e,onTextSubmit:t,renderWelcomeScreen:o,renderWarning:n,persistenceAdapter:r})=>N1(KV,{mermaidToExcalidrawLib:e,onTextSubmit:t,renderWelcomeScreen:o,renderWarning:n,persistenceAdapter:r}),uM=XV;import{Tabs as jV}from"radix-ui";import{useRef as gM}from"react";import{isMemberOf as qV}from"@orangecatai/common";import{jsx as JV}from"react/jsx-runtime";var hM=e=>{let t=ve(),o=gM(null),n=gM(0);return JV(jV.Root,{ref:o,className:"ttd-dialog-tabs-root",value:e.tab,onValueChange:r=>{if(!r)return;let i=o.current?.closest(".Modal__content");if(i){let a=i.offsetHeight||0;a>n.current&&(n.current=a,i.style.minHeight=`min(${n.current}px, 100%)`)}e.dialog==="ttd"&&qV(["text-to-diagram","mermaid"],r)&&t({openDialog:{name:e.dialog,tab:r}})},children:e.children})};hM.displayName="TTDDialogTabs";var fM=hM;import{Tabs as QV}from"radix-ui";import{jsx as e$}from"react/jsx-runtime";var B1=({children:e,...t})=>e$(QV.List,{className:"ttd-dialog-triggers",...t,children:e});B1.displayName="TTDDialogTabTriggers";import{Tabs as t$}from"radix-ui";import{jsx as bM}from"react/jsx-runtime";var ng=({children:e,tab:t,onSelect:o,...n})=>bM(t$.Trigger,{value:t,asChild:!0,onSelect:o,children:bM("button",{type:"button",className:"ttd-dialog-tab-trigger",...n,children:e})});ng.displayName="TTDDialogTabTrigger";import{Tabs as o$}from"radix-ui";import{jsx as n$}from"react/jsx-runtime";var rg=({tab:e,children:t,...o})=>n$(o$.Content,{...o,value:e,children:t});rg.displayName="TTDDialogTab";import{jsx as jn,jsxs as F1}from"react/jsx-runtime";var ig=e=>{let t=ye();return t.openDialog?.name!=="ttd"?null:jn(a$,{...e,tab:t.openDialog.tab})};ig.WelcomeMessage=Ju;var a$=Mr("TTDDialogBase",({tab:e,...t})=>{let o=Qe(),[n,r]=i$({loaded:!1,api:import("@excalidraw/mermaid-to-excalidraw")});return r$(()=>{(async()=>{await n.api,r(a=>({...a,loaded:!0}))})()},[n.api]),jn(ht,{className:"ttd-dialog",onCloseRequest:()=>{o.setOpenDialog(null)},size:1520,title:!1,...t,autofocus:!1,children:F1(fM,{dialog:"ttd",tab:e,children:["__fallback"in t&&t.__fallback?jn("p",{className:"dialog-mermaid-title",children:f("mermaid.title")}):F1(B1,{children:[jn(ng,{tab:"text-to-diagram",children:F1("div",{className:"ttd-dialog-tab-trigger__content",children:[f("labels.textToDiagram"),jn("div",{className:"ttd-dialog-tab-trigger__badge",children:f("chat.aiBeta")})]})}),jn(ng,{tab:"mermaid",children:f("mermaid.label")})]}),!("__fallback"in t)&&jn(rg,{className:"ttd-dialog-content",tab:"text-to-diagram",children:jn(uM,{mermaidToExcalidrawLib:n,onTextSubmit:t.onTextSubmit,renderWelcomeScreen:t.renderWelcomeScreen,renderWarning:t.renderWarning,persistenceAdapter:t.persistenceAdapter})}),jn(rg,{className:"ttd-dialog-content",tab:"mermaid",children:jn(ZS,{mermaidToExcalidrawLib:n,isActive:e==="mermaid"})})]})})});import{round as r4}from"@orangecatai/math";import yK from"clsx";import wK from"lodash.throttle";import{useEffect as i4,useMemo as q1,useState as vK,memo as IK}from"react";import{STATS_PANELS as ug}from"@orangecatai/common";import{getCommonBounds as TK}from"@orangecatai/element";import{getUncroppedWidthAndHeight as CK}from"@orangecatai/element";import{isImageElement as J1}from"@orangecatai/element";import{frameAndChildrenSelectedTogether as kK}from"@orangecatai/element";import{elementsAreInSameGroup as SK}from"@orangecatai/element";import{degreesToRadians as CM,radiansToDegrees as PM}from"@orangecatai/math";import{getBoundTextElement as kM}from"@orangecatai/element";import{isArrowElement as SM,isElbowArrow as E$}from"@orangecatai/element";import{updateBindings as MM}from"@orangecatai/element";import u$ from"clsx";import{useEffect as IM,useRef as sg,useState as g$}from"react";import{EVENT as yl,KEYS as h$,cloneJSON as O1}from"@orangecatai/common";import{deepCopyElement as f$}from"@orangecatai/element";import{CaptureUpdateAction as TM}from"@orangecatai/element";import{pointFrom as xi,pointRotateRads as ag}from"@orangecatai/math";import{getBoundTextElement as s$,isBindingElement as l$,unbindBindingElement as xM}from"@orangecatai/element";import{isFrameLikeElement as wM}from"@orangecatai/element";import{getSelectedGroupIds as c$,getElementsInGroup as d$,isInGroup as m$}from"@orangecatai/element";import{getFrameChildren as p$}from"@orangecatai/element";import{updateBindings as EM}from"@orangecatai/element";import{DRAGGING_THRESHOLD as yM}from"@orangecatai/common";var vM=.01,xd=10,Eo=(e,t)=>!(t==="angle"&&wM(e)),at=(e,t)=>{let o=e+t/2;return o-o%t},xl=(e,t,o)=>Object.keys(e).map(n=>({original:(o??t).get(n),latest:t.get(n)})).filter(n=>n.original!==void 0&&n.latest!==void 0);var va=(e,t,o,n,r,i,a=!0)=>{if(l$(o)&&(o.startBinding||o.endBinding)){if(Math.abs(e-o.x)<yM&&Math.abs(t-o.y)<yM)return;xM(o,"start",n),xM(o,"end",n)}let s=n.getNonDeletedElementsMap(),l=s.get(o.id);if(!l)return;let[c,m]=[o.x+o.width/2,o.y+o.height/2],[p,d]=ag(xi(o.x,o.y),xi(c,m),o.angle),u=e-p,h=t-d,[g,E]=ag(xi(e,t),xi(c+u,m+h),-o.angle);n.mutateElement(l,{x:g,y:E},{informMutation:a,isDragging:!1}),EM(l,n,r);let w=s$(o,i);if(w){let x=s.get(w.id);x&&n.mutateElement(x,{x:w.x+u,y:w.y+h},{informMutation:a,isDragging:!1})}if(wM(o)){let x=p$(i,o.id);x.forEach(y=>{let v=s.get(y.id);if(!v)return;let[I,k]=[y.x+y.width/2,y.y+y.height/2],[L,S]=ag(xi(y.x,y.y),xi(I,k),y.angle),_=Math.round(L+u),P=Math.round(S+h),[T,M]=ag(xi(_,P),xi(I+u,k+h),-y.angle);n.mutateElement(v,{x:T,y:M},{informMutation:a,isDragging:!1}),EM(v,n,r,{simultaneouslyUpdated:x})})}},El=(e,t)=>{let n=c$(t).map(r=>d$(e,r).reduce((i,a)=>(i[a.id]=!0,i),{}));return e.filter(r=>!m$(r)).forEach(r=>{n.push({[r.id]:!0})}),n};import{jsx as z1,jsxs as x$}from"react/jsx-runtime";var b$=({label:e,icon:t,dragInputCallback:o,value:n,elements:r,editable:i=!0,shouldKeepAspectRatio:a,property:s,scene:l,appState:c,sensitivity:m=1,dragFinishedCallback:p})=>{let d=Qe(),u=ve(),h=sg(null),g=sg(null),[E,w]=g$(n.toString()),x=sg(null);x.current||(x.current={originalAppState:O1(c),originalElements:r,lastUpdatedValue:E,updatePending:!1}),IM(()=>{let I=n.toString();w(I),x.current.lastUpdatedValue=I},[n]);let y=(I,k,L)=>{if(!x.current.updatePending)return!1;x.current.updatePending=!1;let S=Number(I);if(isNaN(S)){w(n.toString());return}let _=Number(S.toFixed(2)),P=Number(n);(isNaN(P)||Math.abs(_-P)>=vM)&&(x.current.lastUpdatedValue=I,o({accumulatedChange:0,instantChange:0,originalElements:k,originalElementsMap:d.scene.getNonDeletedElementsMap(),shouldKeepAspectRatio:a,shouldChangeByStepSize:!1,scene:l,nextValue:_,property:s,originalAppState:L,setInputValue:T=>w(String(T)),app:d,setAppState:u}),d.syncActionResult({captureUpdate:TM.IMMEDIATELY}))},v=sg({});return v.current.handleInputValue=y,IM(()=>{let I=h.current,k=v.current;return()=>{let L=I?.value;L&&k.handleInputValue?.(L,x.current.originalElements,x.current.originalAppState),window.removeEventListener(yl.POINTER_MOVE,k.onPointerMove,!1),window.removeEventListener(yl.POINTER_UP,k.onPointerUp,!1)}},[i]),i?x$("div",{className:u$("drag-input-container",!i&&"disabled"),"data-testid":e,children:[z1("div",{className:"drag-input-label",ref:g,onPointerDown:I=>{if(h.current&&i){document.body.classList.add("excalidraw-cursor-resize");let k=Number(h.current.value);isNaN(k)&&(k=0);let L=null,S=d.scene.getNonDeletedElements().reduce((B,U)=>(B.set(U.id,f$(U)),B),new Map),_=r.map(B=>S.get(B.id)),P=O1(c),T=0,M=0,N=B=>{if(L&&S!==null&&_!==null){let U=B.clientX-L.x;U!==0&&(M+=U,Math.abs(M)>=m&&(M=Math.sign(M)*Math.floor(Math.abs(M)/m),T+=M,o({accumulatedChange:T,instantChange:M,originalElements:_,originalElementsMap:S,shouldKeepAspectRatio:a,shouldChangeByStepSize:B.shiftKey,property:s,scene:l,originalAppState:P,setInputValue:D=>w(String(D)),app:d,setAppState:u}),M=0))}L={x:B.clientX,y:B.clientY}},O=()=>{window.removeEventListener(yl.POINTER_MOVE,N,!1),d.syncActionResult({captureUpdate:TM.IMMEDIATELY}),p?.({app:d,setAppState:u,originalElements:_,originalAppState:P}),L=null,T=0,M=0,_=null,S=null,document.body.classList.remove("excalidraw-cursor-resize"),window.removeEventListener(yl.POINTER_UP,O,!1)};v.current.onPointerMove=N,v.current.onPointerUp=O,window.addEventListener(yl.POINTER_MOVE,N,!1),window.addEventListener(yl.POINTER_UP,O,!1)}},onPointerEnter:()=>{g.current&&(g.current.style.cursor="ew-resize")},children:t?z1(Bn,{icon:t}):e}),z1("input",{className:"drag-input",autoComplete:"off",spellCheck:"false",onKeyDown:I=>{if(i){let k=I.target;k instanceof HTMLInputElement&&I.key===h$.ENTER&&(y(k.value,r,c),d.focusContainer())}},ref:h,value:E,onChange:I=>{x.current.updatePending=!0,w(I.target.value)},onFocus:I=>{I.target.select(),x.current.originalElements=r,x.current.originalAppState=O1(c)},onBlur:I=>{E?i&&y(I.target.value,x.current.originalElements,x.current.originalAppState):w(n.toString())},disabled:!i})]}):null},Ot=b$;import{jsx as I$}from"react/jsx-runtime";var y$=15,w$=({accumulatedChange:e,originalElements:t,shouldChangeByStepSize:o,nextValue:n,scene:r,app:i})=>{let a=r.getNonDeletedElementsMap(),s=t[0];if(s&&!E$(s)){let l=a.get(s.id);if(!l)return;if(n!==void 0){let h=CM(n);r.mutateElement(l,{angle:h}),MM(l,r,i.state);let g=kM(l,a);g&&!SM(l)&&r.mutateElement(g,{angle:h});return}let c=Math.round(PM(s.angle)*100)/100,m=Math.round(e),p=(c+m)%360;o&&(p=at(p,y$)),p=p<0?p+360:p;let d=CM(p);r.mutateElement(l,{angle:d}),MM(l,r,i.state);let u=kM(l,a);u&&!SM(l)&&r.mutateElement(u,{angle:d})}},v$=({element:e,scene:t,appState:o,property:n})=>I$(Ot,{label:"A",icon:gm,value:Math.round(PM(e.angle)%360*100)/100,elements:[e],dragInputCallback:w$,editable:Eo(e,"angle"),scene:t,appState:o,property:n}),AM=v$;import{jsx as C$}from"react/jsx-runtime";var LM=5,T$=({property:e,scene:t,appState:o,setAppState:n})=>C$(Ot,{label:"Grid step",sensitivity:8,elements:[],dragInputCallback:({nextValue:r,instantChange:i,shouldChangeByStepSize:a,setInputValue:s})=>{n(l=>{let c;return r?c=r:i&&(c=a?at(l.gridStep+LM*Math.sign(i),LM):l.gridStep+i),c?(c=OE(c),s(c),{gridStep:c}):(s(l.gridStep),null)})},scene:t,value:o.gridStep,property:e,appState:o}),_M=T$;import{clamp as lg,round as H1}from"@orangecatai/math";import{MIN_WIDTH_OR_HEIGHT as cg}from"@orangecatai/common";import{MINIMAL_CROP_SIZE as DM,getUncroppedWidthAndHeight as BM}from"@orangecatai/element";import{resizeSingleElement as RM}from"@orangecatai/element";import{isImageElement as FM}from"@orangecatai/element";import{isFrameLikeElement as G1}from"@orangecatai/element";import{getElementsInResizingFrame as U1}from"@orangecatai/element";import{replaceAllElementsInFrame as OM}from"@orangecatai/element";import{jsx as A$}from"react/jsx-runtime";var NM=10,k$=e=>e.type==="image",S$=({accumulatedChange:e,originalElements:t,originalElementsMap:o,shouldKeepAspectRatio:n,shouldChangeByStepSize:r,nextValue:i,property:a,originalAppState:s,instantChange:l,scene:c,app:m,setAppState:p})=>{let d=c.getNonDeletedElementsMap(),u=t[0],h=d.get(u.id);if(u&&h){let g=n||k$(u),E=u.width/u.height;if(s.croppingElementId===u.id){let w=d.get(u.id);if(!w||!FM(w)||!w.crop)return;let x=w.crop,y={...x},v=w.scale[0]===-1,I=w.scale[1]===-1,{width:k,height:L}=BM(w),S=x.naturalWidth/k,_=x.naturalHeight/L,P=v?x.width+x.x:x.naturalWidth-x.x,T=I?x.height+x.y:x.naturalHeight-x.y,M=DM*S,N=DM*_;if(i!==void 0){if(a==="width"){let F=i*S,z=lg(F,M,P);y={...y,width:z,x:v?x.x+x.width-z:x.x}}else if(a==="height"){let F=i*_,z=lg(F,N,T);y={...y,height:z,y:I?x.y+x.height-z:x.y}}c.mutateElement(w,{crop:y,width:y.width/(x.naturalWidth/k),height:y.height/(x.naturalHeight/L)});return}let O=a==="width"?l:0,B=a==="height"?l:0,U=lg(x.width+O,M,P),D=lg(x.height+B,M,T);y={...x,x:v?x.x+x.width-U:x.x,y:I?x.y+x.height-D:x.y,width:U,height:D},c.mutateElement(w,{crop:y,width:y.width/(x.naturalWidth/k),height:y.height/(x.naturalHeight/L)});return}if(i!==void 0){let w=Math.max(a==="width"?i:g?i*E:u.width,cg),x=Math.max(a==="height"?i:g?i/E:u.height,cg);if(RM(w,x,h,u,o,c,a==="width"?"e":"s",{shouldMaintainAspectRatio:g}),G1(h)){let y=U1(c.getElementsIncludingDeleted(),h,s,c.getNonDeletedElementsMap()),v=OM(c.getElementsIncludingDeleted(),y,h,m);c.replaceAllElements(v)}return}{let w=a==="width"?e:0,x=a==="height"?e:0,y=Math.max(0,u.width+w);a==="width"&&(r?y=at(y,NM):y=Math.round(y));let v=Math.max(0,u.height+x);if(a==="height"&&(r?v=at(v,NM):v=Math.round(v)),g&&(a==="width"?v=Math.round(y/E*100)/100:y=Math.round(v*E*100)/100),v=Math.max(cg,v),y=Math.max(cg,y),RM(y,v,h,u,o,c,a==="width"?"e":"s",{shouldMaintainAspectRatio:g}),G1(h)){let I=U1(c.getElementsIncludingDeleted(),h,s,c.getNonDeletedElementsMap());p({elementsToHighlight:I})}}}},M$=({setAppState:e,app:t,originalElements:o,originalAppState:n})=>{let r=t.scene.getNonDeletedElementsMap(),i=o?.[0],a=i&&r.get(i.id);if(a&&G1(a)){let s=U1(t.scene.getElementsIncludingDeleted(),a,n,t.scene.getNonDeletedElementsMap()),l=OM(t.scene.getElementsIncludingDeleted(),s,a,t);t.scene.replaceAllElements(l),e({elementsToHighlight:null})}},P$=({property:e,element:t,scene:o,appState:n})=>{let r=H1(e==="width"?t.width:t.height,2);if(n.croppingElementId&&n.croppingElementId===t.id&&FM(t)&&t.crop){let{width:i,height:a}=BM(t);if(e==="width"){let s=i/t.crop.naturalWidth;r=H1(t.crop.width*s,2)}if(e==="height"){let s=a/t.crop.naturalHeight;r=H1(t.crop.height*s,2)}}return A$(Ot,{label:e==="width"?"W":"H",elements:[t],dragInputCallback:S$,value:r,editable:Eo(t,e),scene:o,appState:n,property:e,dragFinishedCallback:M$})},W1=P$;import{getBoundTextElement as L$,redrawTextBoundingBox as _$}from"@orangecatai/element";import{hasBoundTextElement as D$,isTextElement as HM}from"@orangecatai/element";import{jsx as F$}from"react/jsx-runtime";var zM=4,R$=4,N$=({accumulatedChange:e,originalElements:t,shouldChangeByStepSize:o,nextValue:n,scene:r})=>{let i=r.getNonDeletedElementsMap(),a=t[0];if(a){let s=i.get(a.id);if(!s||!HM(s))return;let l;if(n!==void 0)l=Math.max(Math.round(n),zM);else if(a.type==="text"){let c=Math.round(a.fontSize),m=Math.round(e);l=Math.max(c+m,zM),o&&(l=at(l,R$))}l&&(r.mutateElement(s,{fontSize:l}),_$(s,r.getContainerElement(s),r))}},B$=({element:e,scene:t,appState:o,property:n})=>{let r=HM(e)?e:D$(e)?L$(e,t.getNonDeletedElementsMap()):null;return r?F$(Ot,{label:"F",value:Math.round(r.fontSize*10)/10,elements:[r],dragInputCallback:N$,icon:Hi,appState:o,scene:t,property:n}):null},GM=B$;import{degreesToRadians as UM,radiansToDegrees as VM}from"@orangecatai/math";import{getBoundTextElement as WM}from"@orangecatai/element";import{isArrowElement as YM}from"@orangecatai/element";import{isInGroup as Y1}from"@orangecatai/element";import{jsx as G$}from"react/jsx-runtime";var O$=15,z$=({accumulatedChange:e,originalElements:t,shouldChangeByStepSize:o,nextValue:n,property:r,scene:i})=>{let a=i.getNonDeletedElementsMap(),s=t.map(c=>a.get(c.id)).filter(c=>c&&!Y1(c)&&Eo(c,r)),l=t.filter(c=>!Y1(c)&&Eo(c,r));if(n!==void 0){let c=UM(n);for(let m of s){if(!m)continue;i.mutateElement(m,{angle:c});let p=WM(m,a);p&&!YM(m)&&i.mutateElement(p,{angle:c})}i.triggerUpdate();return}for(let c=0;c<s.length;c++){let m=s[c];if(!m)continue;let p=l[c],d=Math.round(VM(p.angle)*100)/100,u=Math.round(e),h=(d+u)%360;o&&(h=at(h,O$)),h=h<0?h+360:h;let g=UM(h);i.mutateElement(m,{angle:g});let E=WM(m,a);E&&!YM(m)&&i.mutateElement(E,{angle:g})}i.triggerUpdate()},H$=({elements:e,scene:t,appState:o,property:n})=>{let r=e.filter(l=>!Y1(l)&&Eo(l,"angle")),i=r.map(l=>Math.round(VM(l.angle)%360*100)/100),a=new Set(i).size===1?i[0]:"Mixed",s=r.some(l=>Eo(l,"angle"));return G$(Ot,{label:"A",icon:gm,value:a,elements:e,dragInputCallback:z$,editable:s,appState:o,scene:t,property:n})},$M=H$;import{pointFrom as KM}from"@orangecatai/math";import{useMemo as U$}from"react";import{MIN_WIDTH_OR_HEIGHT as Ei}from"@orangecatai/common";import{getElementsInResizingFrame as V1,isFrameLikeElement as $1,replaceAllElementsInFrame as jM,updateBoundElements as W$}from"@orangecatai/element";import{rescalePointsInElement as Y$,resizeSingleElement as XM}from"@orangecatai/element";import{getBoundTextElement as V$,handleBindTextResize as $$}from"@orangecatai/element";import{isTextElement as qM}from"@orangecatai/element";import{getCommonBounds as dg}from"@orangecatai/element";import{jsx as J$}from"react/jsx-runtime";var wl=10,K$=(e,t,o,n)=>{let r=n.x-e,i=n.y-t,a=n.width*o,s=n.height*o,l=e+r*o,c=t+i*o;return{width:a,height:s,x:l,y:c,...Y$(n,a,s,!1),...qM(n)?{fontSize:n.fontSize*o}:{}}},X$=(e,t,o,n,r,i,a,s)=>{let l=s.getNonDeletedElementsMap(),c=K$(e,t,n,i);s.mutateElement(r,c);let m=V$(i,a);if(m){let p=m.fontSize*n;W$(r,s);let d=l.get(m.id);d&&qM(d)&&(s.mutateElement(d,{fontSize:p}),$$(r,s,o==="width"?"e":"s",!0))}},ZM=(e,t,o,n,r,i,a,s,l,c)=>{i==="width"?t=Math.round(e/n*100)/100:e=Math.round(t*n*100)/100;let m=t/o;for(let p=0;p<s.length;p++){let d=s[p],u=a[p];X$(r[0],r[1],i,m,u,d,l,c)}},Z$=({accumulatedChange:e,originalElements:t,originalElementsMap:o,originalAppState:n,shouldChangeByStepSize:r,nextValue:i,scene:a,property:s,setAppState:l,app:c})=>{let m=a.getNonDeletedElementsMap(),p=El(t,n);if(i!==void 0){for(let g of p){let E=xl(g,m,o);if(E.length>1){let w=E.map(M=>M.latest),x=E.map(M=>M.original),[y,v,I,k]=dg(x),L=I-y,S=k-v,_=L/S,P=Math.max(Ei,s==="width"?Math.max(0,i):L),T=Math.max(Ei,s==="height"?Math.max(0,i):S);ZM(P,T,S,_,KM(y,v),s,w,x,o,a)}else{let[w]=E,x=w?.latest,y=w?.original;if(x&&y&&Eo(x,s)){let v=s==="width"?Math.max(0,i):x.width;s==="width"&&(r?v=at(v,wl):v=Math.round(v));let I=s==="height"?Math.max(0,i):x.height;if(s==="height"&&(r?I=at(I,wl):I=Math.round(I)),v=Math.max(Ei,v),I=Math.max(Ei,I),XM(v,I,x,y,o,a,s==="width"?"e":"s",{shouldInformMutation:!1}),$1(x)){let k=V1(a.getElementsIncludingDeleted(),x,n,a.getNonDeletedElementsMap()),L=jM(a.getElementsIncludingDeleted(),k,x,c);a.replaceAllElements(L)}}}}a.triggerUpdate();return}let d=s==="width"?e:0,u=s==="height"?e:0,h=[];for(let g of p){let E=xl(g,m,o);if(E.length>1){let w=E.map(M=>M.latest),x=E.map(M=>M.original),[y,v,I,k]=dg(x),L=I-y,S=k-v,_=L/S,P=Math.max(0,L+d);s==="width"&&(r?P=at(P,wl):P=Math.round(P));let T=Math.max(0,S+u);s==="height"&&(r?T=at(T,wl):T=Math.round(T)),P=Math.max(Ei,P),T=Math.max(Ei,T),ZM(P,T,S,_,KM(y,v),s,w,x,o,a)}else{let[w]=E,x=w?.latest,y=w?.original;if(x&&y&&Eo(x,s)){let v=Math.max(0,y.width+d);s==="width"&&(r?v=at(v,wl):v=Math.round(v));let I=Math.max(0,y.height+u);if(s==="height"&&(r?I=at(I,wl):I=Math.round(I)),v=Math.max(Ei,v),I=Math.max(Ei,I),XM(v,I,x,y,o,a,s==="width"?"e":"s",{shouldInformMutation:!1}),$1(x)){let k=V1(a.getElementsIncludingDeleted(),x,n,a.getNonDeletedElementsMap());h.push(...k)}}}}l({elementsToHighlight:h}),a.triggerUpdate()},j$=({setAppState:e,app:t,originalElements:o,originalAppState:n})=>{let r=t.scene.getNonDeletedElementsMap(),i=o?.[0],a=i&&r.get(i.id);if(a&&$1(a)){let s=V1(t.scene.getElementsIncludingDeleted(),a,n,t.scene.getNonDeletedElementsMap()),l=jM(t.scene.getElementsIncludingDeleted(),s,a,t);t.scene.replaceAllElements(l),e({elementsToHighlight:null})}},q$=({property:e,elements:t,elementsMap:o,atomicUnits:n,scene:r,appState:i})=>{let a=U$(()=>n.map(c=>{let m=xl(c,o);if(m.length>1){let[d,u,h,g]=dg(m.map(E=>E.latest));return Math.round((e==="width"?h-d:g-u)*100)/100}let[p]=m;return Math.round((e==="width"?p.latest.width:p.latest.height)*100)/100}),[o,n,e]),s=new Set(a).size===1?Math.round(a[0]*100)/100:"Mixed",l=a.length>0;return J$(Ot,{label:e==="width"?"W":"H",elements:t,dragInputCallback:Z$,value:s,editable:l,appState:i,property:e,scene:r,dragFinishedCallback:j$})},K1=q$;import{getBoundTextElement as Q$,redrawTextBoundingBox as JM}from"@orangecatai/element";import{hasBoundTextElement as eK,isTextElement as tK}from"@orangecatai/element";import{isInGroup as oK}from"@orangecatai/element";import{jsx as sK}from"react/jsx-runtime";var QM=4,nK=4,rK=(e,t)=>e.reduce((o,n)=>{if(!n||oK(n))return o;if(tK(n))return o.push(n),o;if(eK(n)){let r=Q$(n,t);if(r)return o.push(r),o}return o},[]),iK=({accumulatedChange:e,originalElements:t,shouldChangeByStepSize:o,nextValue:n,scene:r})=>{let i=r.getNonDeletedElementsMap(),a=t.map(l=>i.get(l.id)),s;if(n){s=Math.max(Math.round(n),QM);for(let l of a)r.mutateElement(l,{fontSize:s}),JM(l,r.getContainerElement(l),r);r.triggerUpdate()}else{let l=t;for(let c=0;c<a.length;c++){let m=a[c],p=l[c],d=Math.round(p.fontSize),u=Math.round(e),h=Math.max(d+u,QM);o&&(h=at(h,nK)),r.mutateElement(m,{fontSize:h}),JM(m,r.getContainerElement(m),r)}r.triggerUpdate()}},aK=({elements:e,scene:t,appState:o,property:n,elementsMap:r})=>{let i=rK(e,r);if(!i.length)return null;let a=i.map(c=>Math.round(c.fontSize*10)/10),s=new Set(a).size===1?a[0]:"Mixed",l=a.length>0;return sK(Ot,{label:"F",icon:Hi,elements:i,dragInputCallback:iK,value:s,editable:l,scene:t,property:n,appState:o})},e4=aK;import{pointFrom as yi,pointRotateRads as mg}from"@orangecatai/math";import{useMemo as lK}from"react";import{isTextElement as cK}from"@orangecatai/element";import{getCommonBounds as X1}from"@orangecatai/element";import{jsx as gK}from"react/jsx-runtime";var dK=(e,t,o,n,r,i,a)=>{for(let s=0;s<n.length;s++){let l=n[s],[c,m]=[l.x+l.width/2,l.y+l.height/2],[p,d]=mg(yi(l.x,l.y),yi(c,m),l.angle),u=e==="x"?Math.round(p+t):p,h=e==="y"?Math.round(d+o):d;va(u,h,l,i,a,r,!1)}},mK=(e,t,o,n,r,i)=>{let a=r.getNonDeletedElementsMap(),[s,l,,]=X1(o),c=e-s,m=t-l;for(let p=0;p<o.length;p++){let d=o[p],u=a.get(d.id);if(u&&(!cK(u)||!u.containerId)){let[h,g]=[u.x+u.width/2,u.y+u.height/2],[E,w]=mg(yi(u.x,u.y),yi(h,g),u.angle);va(E+c,w+m,d,r,i,n,!1)}}},pK=({accumulatedChange:e,originalElements:t,originalElementsMap:o,shouldChangeByStepSize:n,nextValue:r,property:i,scene:a,originalAppState:s,app:l})=>{let c=a.getNonDeletedElementsMap();if(r!==void 0){for(let u of El(t,s)){let h=xl(u,c,o);if(h.length>1){let[g,E,,]=X1(h.map(y=>y.latest));mK(i==="x"?r:g,i==="y"?r:E,h.map(y=>y.original),o,a,l.state)}else{let g=h[0]?.original,E=h[0]?.latest;if(g&&E&&Eo(E,i)){let[w,x]=[g.x+g.width/2,g.y+g.height/2],[y,v]=mg(yi(g.x,g.y),yi(w,x),g.angle);va(i==="x"?r:y,i==="y"?r:v,g,a,l.state,o,!1)}}}a.triggerUpdate();return}let m=n?at(e,xd):e;dK(i,i==="x"?m:0,i==="y"?m:0,t,o,a,l.state),a.triggerUpdate()},uK=({property:e,elements:t,elementsMap:o,atomicUnits:n,scene:r,appState:i})=>{let a=lK(()=>n.map(l=>{let c=Object.keys(l).map(g=>o.get(g)).filter(g=>g!==void 0);if(c.length>1){let[g,E]=X1(c);return Math.round((e==="x"?g:E)*100)/100}let[m]=c,[p,d]=[m.x+m.width/2,m.y+m.height/2],[u,h]=mg(yi(m.x,m.y),yi(p,d),m.angle);return Math.round((e==="x"?u:h)*100)/100}),[n,o,e]),s=new Set(a).size===1?a[0]:"Mixed";return gK(Ot,{label:e==="x"?"X":"Y",elements:t,dragInputCallback:pK,value:s,property:e,scene:r,appState:i})},Z1=uK;import{clamp as Ed,pointFrom as pg,pointRotateRads as o4,round as t4}from"@orangecatai/math";import{getFlipAdjustedCropPosition as hK,getUncroppedWidthAndHeight as fK}from"@orangecatai/element";import{isImageElement as n4}from"@orangecatai/element";import{jsx as EK}from"react/jsx-runtime";var bK=({accumulatedChange:e,instantChange:t,originalElements:o,originalElementsMap:n,shouldChangeByStepSize:r,nextValue:i,property:a,scene:s,originalAppState:l,app:c})=>{let m=s.getNonDeletedElementsMap(),p=o[0],[d,u]=[p.x+p.width/2,p.y+p.height/2],[h,g]=o4(pg(p.x,p.y),pg(d,u),p.angle);if(l.croppingElementId===p.id){let v=m.get(p.id);if(!v||!n4(v)||!v.crop)return;let I=v.crop,k=I,L=v.scale[0]===-1,S=v.scale[1]===-1,{width:_,height:P}=fK(v);if(i!==void 0){if(a==="x"){let N=i*(I.naturalWidth/_);L?k={...I,x:Ed(I.naturalWidth-N-I.width,0,I.naturalWidth-I.width)}:k={...I,x:Ed(i*(I.naturalWidth/_),0,I.naturalWidth-I.width)}}a==="y"&&(k={...I,y:Ed(i*(I.naturalHeight/P),0,I.naturalHeight-I.height)}),s.mutateElement(v,{crop:k});return}let T=(a==="x"?t:0)*(L?-1:1),M=(a==="y"?t:0)*(S?-1:1);k={...I,x:Ed(I.x+T,0,I.naturalWidth-I.width),y:Ed(I.y+M,0,I.naturalHeight-I.height)},s.mutateElement(v,{crop:k});return}if(i!==void 0){va(a==="x"?i:h,a==="y"?i:g,p,s,c.state,n);return}let E=a==="x"?e:0,w=a==="y"?e:0,x=a==="x"?Math.round(r?at(p.x+E,xd):h+E):h,y=a==="y"?Math.round(r?at(p.y+w,xd):g+w):g;va(x,y,p,s,c.state,n)},xK=({property:e,element:t,elementsMap:o,scene:n,appState:r})=>{let[i,a]=o4(pg(t.x,t.y),pg(t.x+t.width/2,t.y+t.height/2),t.angle),s=t4(e==="x"?i:a,2);if(r.croppingElementId===t.id&&n4(t)&&t.crop){let l=hK(t);l&&(s=t4(e==="x"?l.x:l.y,2))}return EK(Ot,{label:e==="x"?"X":"Y",elements:[t],dragInputCallback:bK,scene:n,value:s,property:e,appState:r})},j1=xK;import{Fragment as Q1,jsx as ce,jsxs as yo}from"react/jsx-runtime";var MK=50,yd=e=>{let t=Go(),o=e.app.scene.getSceneNonce()||1,n=e.app.scene.getSelectedElements({selectedElementIds:t.selectedElementIds,includeBoundTextElement:!1}),r=ai(e.app);return ce(PK,{...e,appState:t,sceneNonce:o,selectedElements:n,gridModeEnabled:r})},et=({children:e,columns:t=1,heading:o,style:n,...r})=>ce("div",{className:yK("exc-stats__row",{"exc-stats__row--heading":o}),style:{gridTemplateColumns:`repeat(${t}, 1fr)`,...n},...r,children:e});et.displayName="StatsRow";var gg=({children:e,order:t,style:o,...n})=>ce("div",{className:"exc-stats__rows",style:{order:t,...o},...n,children:e});gg.displayName="StatsRows";yd.StatsRow=et;yd.StatsRows=gg;var PK=IK(({app:e,onClose:t,renderCustomStats:o,selectedElements:n,appState:r,sceneNonce:i,gridModeEnabled:a})=>{let s=e.scene,l=s.getNonDeletedElements(),c=s.getNonDeletedElementsMap(),m=ve(),p=n.length===1?n[0]:null,d=n.length>1?n:null,u=r.croppingElementId&&J1(p),h=u?CK(p):null,[g,E]=vK({width:0,height:0}),w=q1(()=>wK(v=>{let I=TK(v);E({width:Math.round(I[2])-Math.round(I[0]),height:Math.round(I[3])-Math.round(I[1])})},MK),[]);i4(()=>{w(l)},[i,l,w]),i4(()=>()=>w.cancel(),[w]);let x=q1(()=>El(n,r),[n,r]),y=q1(()=>kK(n),[n]);return ce("div",{className:"exc-stats",children:yo(ut,{padding:3,children:[yo("div",{className:"title",children:[ce("h2",{children:f("stats.title")}),ce("div",{className:"close",onClick:t,children:Fo})]}),yo(gc,{label:ce("h3",{children:f("stats.generalStats")}),open:!!(r.stats.panels&ug.generalStats),openTrigger:()=>m(v=>({stats:{open:!0,panels:v.stats.panels^ug.generalStats}})),children:[yo(gg,{children:[ce(et,{heading:!0,children:f("stats.scene")}),yo(et,{columns:2,children:[ce("div",{children:f("stats.shapes")}),ce("div",{children:l.length})]}),yo(et,{columns:2,children:[ce("div",{children:f("stats.width")}),ce("div",{children:g.width})]}),yo(et,{columns:2,children:[ce("div",{children:f("stats.height")}),ce("div",{children:g.height})]}),a&&yo(Q1,{children:[ce(et,{heading:!0,children:"Canvas"}),ce(et,{children:ce(_M,{property:"gridStep",scene:s,appState:r,setAppState:m})})]})]}),o?.(l,r)]}),!y&&n.length>0&&ce("div",{id:"elementStats",style:{marginTop:12},children:ce(gc,{label:ce("h3",{children:f("stats.elementProperties")}),open:!!(r.stats.panels&ug.elementProperties),openTrigger:()=>m(v=>({stats:{open:!0,panels:v.stats.panels^ug.elementProperties}})),children:yo(gg,{children:[p&&yo(Q1,{children:[u&&ce(et,{heading:!0,children:f("labels.unCroppedDimension")}),r.croppingElementId&&J1(p)&&h&&yo(et,{columns:2,children:[ce("div",{children:f("stats.width")}),ce("div",{children:r4(h.width,2)})]}),r.croppingElementId&&J1(p)&&h&&yo(et,{columns:2,children:[ce("div",{children:f("stats.height")}),ce("div",{children:r4(h.height,2)})]}),ce(et,{heading:!0,"data-testid":"stats-element-type",style:{margin:"0.3125rem 0"},children:r.croppingElementId?f("labels.imageCropping"):f(`element.${p.type}`)}),ce(et,{children:ce(j1,{element:p,property:"x",elementsMap:c,scene:s,appState:r})}),ce(et,{children:ce(j1,{element:p,property:"y",elementsMap:c,scene:s,appState:r})}),ce(et,{children:ce(W1,{property:"width",element:p,scene:s,appState:r})}),ce(et,{children:ce(W1,{property:"height",element:p,scene:s,appState:r})}),ce(et,{children:ce(AM,{property:"angle",element:p,scene:s,appState:r})}),ce(et,{children:ce(GM,{property:"fontSize",element:p,scene:s,appState:r})})]}),d&&yo(Q1,{children:[SK(d)&&ce(et,{heading:!0,children:f("element.group")}),yo(et,{columns:2,style:{margin:"0.3125rem 0"},children:[ce("div",{children:f("stats.shapes")}),ce("div",{children:n.length})]}),ce(et,{children:ce(Z1,{property:"x",elements:d,elementsMap:c,atomicUnits:x,scene:s,appState:r})}),ce(et,{children:ce(Z1,{property:"y",elements:d,elementsMap:c,atomicUnits:x,scene:s,appState:r})}),ce(et,{children:ce(K1,{property:"width",elements:d,elementsMap:c,atomicUnits:x,scene:s,appState:r})}),ce(et,{children:ce(K1,{property:"height",elements:d,elementsMap:c,atomicUnits:x,scene:s,appState:r})}),ce(et,{children:ce($M,{property:"angle",elements:d,scene:s,appState:r})}),ce(et,{children:ce(e4,{property:"fontSize",elements:d,scene:s,appState:r,elementsMap:c})})]})]})})})]})})},(e,t)=>e.sceneNonce===t.sceneNonce&&e.selectedElements===t.selectedElements&&e.appState.stats.panels===t.appState.stats.panels&&e.gridModeEnabled===t.gridModeEnabled&&e.appState.gridStep===t.appState.gridStep&&e.appState.croppingElementId===t.appState.croppingElementId);import{useCallback as AK,useEffect as a4,useState as s4}from"react";import{normalizeLink as LK,KEYS as ex}from"@orangecatai/common";import{defaultGetElementLinkFromSelection as _K,getLinkIdAndTypeFromSelection as DK}from"@orangecatai/element";import{jsx as vl,jsxs as hg}from"react/jsx-runtime";var RK=({sourceElementId:e,onClose:t,appState:o,scene:n,generateLinkForSelection:r=_K})=>{let i=n.getNonDeletedElementsMap(),a=i.get(e)?.link??null,[s,l]=s4(a),[c,m]=s4(!1);a4(()=>{let d=le(i,o),u=a;if(d.length>0&&r){let h=DK(d,o);h&&(u=LK(r(h.id,h.type)))}l(u)},[i,o,o.selectedElementIds,a,r]);let p=AK(()=>{if(s&&s!==i.get(e)?.link){let d=i.get(e);d&&n.mutateElement(d,{link:s})}if(!s&&c&&e){let d=i.get(e);d&&n.mutateElement(d,{link:null})}t?.()},[e,s,i,c,n,t]);return a4(()=>{let d=u=>{o.openDialog?.name==="elementLinkSelector"&&u.key===ex.ENTER&&p(),o.openDialog?.name==="elementLinkSelector"&&u.key===ex.ESCAPE&&t?.()};return window.addEventListener("keydown",d),()=>{window.removeEventListener("keydown",d)}},[o,t,p]),hg("div",{className:"ElementLinkDialog",children:[hg("div",{className:"ElementLinkDialog__header",children:[vl("h2",{children:f("elementLink.title")}),vl("p",{children:f("elementLink.desc")})]}),hg("div",{className:"ElementLinkDialog__input",children:[vl(ti,{value:s??"",onChange:d=>{c||m(!0),l(d)},onKeyDown:d=>{d.key===ex.ENTER&&p()},className:"ElementLinkDialog__input-field",selectOnRender:!0}),a&&s&&vl(ne,{type:"button",title:f("buttons.remove"),"aria-label":f("buttons.remove"),label:f("buttons.remove"),onClick:()=>{l(null),m(!0)},className:"ElementLinkDialog__remove",icon:Ht})]}),hg("div",{className:"ElementLinkDialog__actions",children:[vl(br,{label:f("buttons.cancel"),onClick:()=>{t?.()},style:{marginRight:10}}),vl(br,{label:f("buttons.confirm"),onClick:p,actionType:"primary"})]})]})},l4=RK;import NK,{useState as BK}from"react";import{Fragment as FK,jsx as tx}from"react/jsx-runtime";var c4=({children:e,onClose:t})=>{let[o,n]=BK(!!e),{container:r}=qe(),i=NK.useCallback(()=>{n(!1),t&&t(),r?.focus()},[t,r]);return tx(FK,{children:o&&tx(ht,{size:"small",onCloseRequest:i,title:f("errorDialog.title"),children:tx("div",{style:{whiteSpace:"pre-wrap"},children:e})})})};import OK from"react";import{isDarwin as d4,isFirefox as m4,isWindows as zK}from"@orangecatai/common";import{KEYS as pt}from"@orangecatai/common";import{Fragment as u4,jsx as Z,jsxs as _o}from"react/jsx-runtime";var HK=()=>_o("div",{className:"HelpDialog__header",children:[_o("a",{className:"HelpDialog__btn",href:"https://docs.excalidraw.com",target:"_blank",rel:"noopener",children:[Z("div",{className:"HelpDialog__link-icon",children:ah}),f("helpDialog.documentation")]}),_o("a",{className:"HelpDialog__btn",href:"https://plus.excalidraw.com/blog",target:"_blank",rel:"noopener",children:[Z("div",{className:"HelpDialog__link-icon",children:ah}),f("helpDialog.blog")]}),_o("a",{className:"HelpDialog__btn",href:"https://github.com/excalidraw/excalidraw/issues",target:"_blank",rel:"noopener noreferrer",children:[Z("div",{className:"HelpDialog__link-icon",children:lm}),f("helpDialog.github")]}),_o("a",{className:"HelpDialog__btn",href:"https://youtube.com/@excalidraw",target:"_blank",rel:"noopener noreferrer",children:[Z("div",{className:"HelpDialog__link-icon",children:Ww}),"YouTube"]})]}),GK=e=>_o(u4,{children:[Z("h3",{children:e.title}),Z("div",{className:"HelpDialog__islands-container",children:e.children})]}),ox=e=>_o("div",{className:`HelpDialog__island ${e.className}`,children:[Z("h4",{className:"HelpDialog__island-title",children:e.caption}),Z("div",{className:"HelpDialog__island-content",children:e.children})]});function*UK(e,t){let o=!0;for(let n of e)o||(yield t),o=!1,yield n}var WK=e=>e.replace(/\b[a-z]\b/,t=>t.toUpperCase()),J=({label:e,shortcuts:t,isOr:o=!0})=>{let n=t.map(r=>(r.endsWith("++")?[...r.slice(0,-2).split("+"),"+"]:r.split("+")).map(a=>Z(YK,{children:WK(a)},a)));return _o("div",{className:"HelpDialog__shortcut",children:[Z("div",{children:e}),Z("div",{className:"HelpDialog__key-container",children:[...UK(n,o?f("helpDialog.or"):null)]})]})},YK=e=>Z("kbd",{className:"HelpDialog__key",...e}),p4=({onClose:e})=>{let t=OK.useCallback(()=>{e&&e()},[e]);return Z(u4,{children:_o(ht,{onCloseRequest:t,title:f("helpDialog.title"),className:"HelpDialog",children:[Z(HK,{}),_o(GK,{title:f("helpDialog.shortcuts"),children:[_o(ox,{className:"HelpDialog__island--tools",caption:f("helpDialog.tools"),children:[Z(J,{label:f("toolBar.hand"),shortcuts:[pt.H]}),Z(J,{label:f("toolBar.selection"),shortcuts:[pt.V,pt[1]]}),Z(J,{label:f("toolBar.rectangle"),shortcuts:[pt.R,pt[2]]}),Z(J,{label:f("toolBar.diamond"),shortcuts:[pt.D,pt[3]]}),Z(J,{label:f("toolBar.ellipse"),shortcuts:[pt.O,pt[4]]}),Z(J,{label:f("toolBar.arrow"),shortcuts:[pt.A,pt[5]]}),Z(J,{label:f("toolBar.line"),shortcuts:[pt.L,pt[6]]}),Z(J,{label:f("toolBar.freedraw"),shortcuts:[pt.P,pt[7]]}),Z(J,{label:f("toolBar.text"),shortcuts:[pt.T,pt[8]]}),Z(J,{label:f("toolBar.image"),shortcuts:[pt[9]]}),Z(J,{label:f("toolBar.eraser"),shortcuts:[pt.E,pt[0]]}),Z(J,{label:f("toolBar.frame"),shortcuts:[pt.F]}),Z(J,{label:f("toolBar.laser"),shortcuts:[pt.K]}),Z(J,{label:f("labels.eyeDropper"),shortcuts:[pt.I,"Shift+S","Shift+G"]}),Z(J,{label:f("helpDialog.editLineArrowPoints"),shortcuts:[G("CtrlOrCmd+Enter")]}),Z(J,{label:f("helpDialog.editText"),shortcuts:[G("Enter")]}),Z(J,{label:f("helpDialog.textNewLine"),shortcuts:[G("Enter"),G("Shift+Enter")]}),Z(J,{label:f("helpDialog.textFinish"),shortcuts:[G("Esc"),G("CtrlOrCmd+Enter")]}),Z(J,{label:f("helpDialog.curvedArrow"),shortcuts:["A",f("helpDialog.click"),f("helpDialog.click"),f("helpDialog.click")],isOr:!1}),Z(J,{label:f("helpDialog.curvedLine"),shortcuts:["L",f("helpDialog.click"),f("helpDialog.click"),f("helpDialog.click")],isOr:!1}),Z(J,{label:f("helpDialog.cropStart"),shortcuts:[f("helpDialog.doubleClick"),G("Enter")],isOr:!0}),Z(J,{label:f("helpDialog.cropFinish"),shortcuts:[G("Enter"),G("Escape")],isOr:!0}),Z(J,{label:f("toolBar.lock"),shortcuts:[pt.Q]}),Z(J,{label:f("helpDialog.preventBinding"),shortcuts:[G("CtrlOrCmd")]}),Z(J,{label:f("toolBar.link"),shortcuts:[G("CtrlOrCmd+K")]}),Z(J,{label:f("toolBar.convertElementType"),shortcuts:["Tab","Shift+Tab"],isOr:!0})]}),_o(ox,{className:"HelpDialog__island--view",caption:f("helpDialog.view"),children:[Z(J,{label:f("buttons.zoomIn"),shortcuts:[G("CtrlOrCmd++")]}),Z(J,{label:f("buttons.zoomOut"),shortcuts:[G("CtrlOrCmd+-")]}),Z(J,{label:f("buttons.resetZoom"),shortcuts:[G("CtrlOrCmd+0")]}),Z(J,{label:f("helpDialog.zoomToFit"),shortcuts:["Shift+1"]}),Z(J,{label:f("helpDialog.zoomToSelection"),shortcuts:["Shift+2"]}),Z(J,{label:f("helpDialog.movePageUpDown"),shortcuts:["PgUp/PgDn"]}),Z(J,{label:f("helpDialog.movePageLeftRight"),shortcuts:["Shift+PgUp/PgDn"]}),Z(J,{label:f("buttons.zenMode"),shortcuts:[G("Alt+Z")]}),Z(J,{label:f("buttons.objectsSnapMode"),shortcuts:[G("Alt+S")]}),Z(J,{label:f("labels.toggleGrid"),shortcuts:[G("CtrlOrCmd+'")]}),Z(J,{label:f("labels.viewMode"),shortcuts:[G("Alt+R")]}),Z(J,{label:f("labels.toggleTheme"),shortcuts:[G("Alt+Shift+D")]}),Z(J,{label:f("stats.fullTitle"),shortcuts:[G("Alt+/")]}),Z(J,{label:f("search.title"),shortcuts:[Ke("searchMenu")]}),Z(J,{label:f("commandPalette.title"),shortcuts:m4?[Ke("commandPalette")]:[Ke("commandPalette"),Ke("commandPalette",1)]})]}),_o(ox,{className:"HelpDialog__island--editor",caption:f("helpDialog.editor"),children:[Z(J,{label:f("helpDialog.createFlowchart"),shortcuts:[G("CtrlOrCmd+Arrow Key")],isOr:!0}),Z(J,{label:f("helpDialog.navigateFlowchart"),shortcuts:[G("Alt+Arrow Key")],isOr:!0}),Z(J,{label:f("labels.moveCanvas"),shortcuts:[G(`Space+${f("helpDialog.drag")}`),G(`Wheel+${f("helpDialog.drag")}`)],isOr:!0}),Z(J,{label:f("buttons.clearReset"),shortcuts:[G("CtrlOrCmd+Delete")]}),Z(J,{label:f("labels.delete"),shortcuts:[G("Delete")]}),Z(J,{label:f("labels.cut"),shortcuts:[G("CtrlOrCmd+X")]}),Z(J,{label:f("labels.copy"),shortcuts:[G("CtrlOrCmd+C")]}),Z(J,{label:f("labels.paste"),shortcuts:[G("CtrlOrCmd+V")]}),Z(J,{label:f("labels.pasteAsPlaintext"),shortcuts:[G("CtrlOrCmd+Shift+V")]}),Z(J,{label:f("labels.selectAll"),shortcuts:[G("CtrlOrCmd+A")]}),Z(J,{label:f("labels.multiSelect"),shortcuts:[G(`Shift+${f("helpDialog.click")}`)]}),Z(J,{label:f("helpDialog.deepSelect"),shortcuts:[G(`CtrlOrCmd+${f("helpDialog.click")}`)]}),Z(J,{label:f("helpDialog.deepBoxSelect"),shortcuts:[G(`CtrlOrCmd+${f("helpDialog.drag")}`)]}),(vs||m4)&&Z(J,{label:f("labels.copyAsPng"),shortcuts:[G("Shift+Alt+C")]}),Z(J,{label:f("labels.copyStyles"),shortcuts:[G("CtrlOrCmd+Alt+C")]}),Z(J,{label:f("labels.pasteStyles"),shortcuts:[G("CtrlOrCmd+Alt+V")]}),Z(J,{label:f("labels.sendToBack"),shortcuts:[d4?G("CtrlOrCmd+Alt+["):G("CtrlOrCmd+Shift+[")]}),Z(J,{label:f("labels.bringToFront"),shortcuts:[d4?G("CtrlOrCmd+Alt+]"):G("CtrlOrCmd+Shift+]")]}),Z(J,{label:f("labels.sendBackward"),shortcuts:[G("CtrlOrCmd+[")]}),Z(J,{label:f("labels.bringForward"),shortcuts:[G("CtrlOrCmd+]")]}),Z(J,{label:f("labels.alignTop"),shortcuts:[G("CtrlOrCmd+Shift+Up")]}),Z(J,{label:f("labels.alignBottom"),shortcuts:[G("CtrlOrCmd+Shift+Down")]}),Z(J,{label:f("labels.alignLeft"),shortcuts:[G("CtrlOrCmd+Shift+Left")]}),Z(J,{label:f("labels.alignRight"),shortcuts:[G("CtrlOrCmd+Shift+Right")]}),Z(J,{label:f("labels.duplicateSelection"),shortcuts:[G("CtrlOrCmd+D"),G(`Alt+${f("helpDialog.drag")}`)]}),Z(J,{label:f("helpDialog.toggleElementLock"),shortcuts:[G("CtrlOrCmd+Shift+L")]}),Z(J,{label:f("buttons.undo"),shortcuts:[G("CtrlOrCmd+Z")]}),Z(J,{label:f("buttons.redo"),shortcuts:zK?[G("CtrlOrCmd+Y"),G("CtrlOrCmd+Shift+Z")]:[G("CtrlOrCmd+Shift+Z")]}),Z(J,{label:f("labels.group"),shortcuts:[G("CtrlOrCmd+G")]}),Z(J,{label:f("labels.ungroup"),shortcuts:[G("CtrlOrCmd+Shift+G")]}),Z(J,{label:f("labels.flipHorizontal"),shortcuts:[G("Shift+H")]}),Z(J,{label:f("labels.flipVertical"),shortcuts:[G("Shift+V")]}),Z(J,{label:f("labels.showStroke"),shortcuts:[G("S")]}),Z(J,{label:f("labels.showBackground"),shortcuts:[G("G")]}),Z(J,{label:f("labels.showFonts"),shortcuts:[G("Shift+F")]}),Z(J,{label:f("labels.decreaseFontSize"),shortcuts:[G("CtrlOrCmd+Shift+<")]}),Z(J,{label:f("labels.increaseFontSize"),shortcuts:[G("CtrlOrCmd+Shift+>")]})]})]})]})})};import{CANVAS_SEARCH_TAB as VK,DEFAULT_SIDEBAR as $K}from"@orangecatai/common";import{isFlowchartNodeElement as KK,isImageElement as g4,isLinearElement as h4,isLineElement as XK,isTextBindableContainer as ZK,isTextElement as jK}from"@orangecatai/element";import{isNodeInFlowchart as qK}from"@orangecatai/element";import{jsx as nx}from"react/jsx-runtime";var Fe=e=>Array.isArray(e)?`<kbd>${e.map(G).join(" + ")}</kbd>`:`<kbd>${G(e)}</kbd>`,JK=({appState:e,isMobile:t,editorInterface:o,app:n})=>{let{activeTool:r,isResizing:i,isRotating:a,lastPointerDownWith:s}=e,l=e.multiElement!==null;if(e.openSidebar?.name===$K.name&&e.openSidebar.tab===VK&&e.searchMatches?.matches.length)return f("hints.dismissSearch",{shortcut:Fe("Escape")});if(e.openSidebar&&!o.canFitSidebar)return null;if(po(e))return f("hints.eraserRevert",{shortcut:Fe("Alt")});let c=n.scene.getSelectedElements(e);if(e.selectedLinearElement?.isDragging&&c[0]?.type==="arrow")return f("hints.arrowBindModifiers",{shortcut_1:Fe("Ctrl"),shortcut_2:Fe("Alt")});if(r.type==="arrow"||r.type==="line")return l?f("hints.linearElementMulti",{shortcut_1:Fe("Escape"),shortcut_2:Fe("Enter")}):r.type==="arrow"?f("hints.arrowTool",{shortcut:Fe("A")}):f("hints.linearElement");if(r.type==="freedraw")return f("hints.freeDraw");if(r.type==="text")return f("hints.text");if(r.type==="embeddable")return f("hints.embeddable");if(i&&s==="mouse"&&c.length===1){let m=c[0];return h4(m)&&m.points.length===2?f("hints.lockAngle",{shortcut:Fe("Shift")}):g4(m)?f("hints.resizeImage",{shortcut_1:Fe("Shift"),shortcut_2:Fe("Alt")}):f("hints.resize",{shortcut_1:Fe("Shift"),shortcut_2:Fe("Alt")})}if(a&&s==="mouse")return f("hints.rotate",{shortcut:Fe("Shift")});if(c.length===1&&jK(c[0]))return f("hints.text_selected",{shortcut:Fe("Enter")});if(e.editingTextElement)return f("hints.text_editing",{shortcut_1:Fe("Escape"),shortcut_2:Fe(["CtrlOrCmd","Enter"])});if(e.croppingElementId)return f("hints.leaveCropEditor",{shortcut_1:Fe("Enter"),shortcut_2:Fe("Escape")});if(c.length===1&&g4(c[0]))return f("hints.enterCropEditor",{shortcut:Fe("Enter")});if(r.type==="selection"){if(e.selectionElement&&!c.length&&!e.editingTextElement&&!e.selectedLinearElement?.isEditing)return f("hints.deepBoxSelect",{shortcut:Fe("CtrlOrCmd")});if(ai(n)&&e.selectedElementsAreBeingDragged)return f("hints.disableSnapping",{shortcut:Fe("CtrlOrCmd")});if(!c.length&&!t)return f("hints.canvasPanning",{shortcut_1:Fe(f("keys.mmb")),shortcut_2:Fe("Space")});if(c.length===1){if(h4(c[0]))return e.selectedLinearElement?.isEditing?e.selectedLinearElement.selectedPointsIndices?f("hints.lineEditor_pointSelected",{shortcut_1:Fe("Delete"),shortcut_2:Fe(["CtrlOrCmd","D"])}):f("hints.lineEditor_nothingSelected",{shortcut_1:Fe("Shift"),shortcut_2:Fe("Alt")}):XK(c[0])?f("hints.lineEditor_line_info",{shortcut:Fe("Enter")}):f("hints.lineEditor_info",{shortcut_1:Fe("CtrlOrCmd"),shortcut_2:Fe(["CtrlOrCmd","Enter"])});if(!e.newElement&&!e.selectedElementsAreBeingDragged&&ZK(c[0])){let m=f("hints.bindTextToElement",{shortcut:Fe("Enter")}),p=f("hints.createFlowchart",{shortcut:Fe(["CtrlOrCmd","\u2191\u2193"])});return KK(c[0])?qK(c[0],n.scene.getNonDeletedElementsMap())?[m,p]:[m,p]:m}}}return null},f4=({appState:e,isMobile:t,editorInterface:o,app:n})=>{let r=JK({appState:e,isMobile:t,editorInterface:o,app:n});if(!r)return null;let a=(Array.isArray(r)?r.map(s=>s.replace(/\. ?$/,"")).join(", "):r).split(/(<kbd>[^<]+<\/kbd>)/g).map((s,l)=>{if(l%2===1){let c=s[0]==="<"&&s.match(/^<kbd>([^<]+)<\/kbd>$/);return nx("kbd",{children:c?c[1]:s},l)}return s});return nx("div",{className:"HintViewer",children:nx("span",{children:a})})};import{useEffect as E4,useRef as rX,useState as wi}from"react";import{DEFAULT_EXPORT_PADDING as iX,EXPORT_IMAGE_TYPES as rx,isFirefox as aX,EXPORT_SCALES as sX,cloneJSON as y4}from"@orangecatai/common";import{useCallback as QK,useRef as eX,useState as tX}from"react";var oX=2e3,b4=()=>{let[e,t]=tX(null),o=eX(0),n=()=>{clearTimeout(o.current),t("success"),o.current=window.setTimeout(()=>{t(null)},oX)},r=QK(()=>{t(null)},[]);return{copyStatus:e,resetCopyStatus:r,onCopy:n}};import nX from"clsx";import{jsx as x4}from"react/jsx-runtime";var wd=({title:e,name:t,checked:o,onChange:n,disabled:r=!1})=>x4("div",{className:nX("Switch",{toggled:o,disabled:r}),children:x4("input",{name:t,id:t,title:e,type:"checkbox",checked:o,disabled:r,onChange:()=>n(!o),onKeyDown:i=>{i.key===" "&&n(!o)}})});import{jsx as tt,jsxs as vi}from"react/jsx-runtime";var lX=()=>vi("div",{children:[tt("h3",{children:f("canvasError.cannotShowPreview")}),tt("p",{children:tt("span",{children:f("canvasError.canvasTooBig")})}),vi("em",{children:["(",f("canvasError.canvasTooBigTip"),")"]})]}),cX=({appStateSnapshot:e,elementsSnapshot:t,files:o,actionManager:n,onExportImage:r,name:i})=>{let a=He(t,e),[s,l]=wi(i),[c,m]=wi(a),[p,d]=wi(e.exportBackground),[u,h]=wi(e.exportWithDarkMode),[g,E]=wi(e.exportEmbedScene),[w,x]=wi(e.exportScale),y=rX(null),[v,I]=wi(null),{onCopy:k,copyStatus:L,resetCopyStatus:S}=b4();E4(()=>{S()},[s,p,u,w,g,S]);let{exportedElements:_,exportingFrame:P}=Ki(t,e,c);return E4(()=>{let T=y.current;if(!T)return;let M=T.offsetWidth,N=T.offsetHeight;M&&Jr({elements:_,appState:{...e,name:s,exportBackground:p,exportWithDarkMode:u,exportScale:w,exportEmbedScene:g},files:o,exportPadding:iX,maxWidthOrHeight:Math.max(M,N),exportingFrame:P}).then(O=>(I(null),Bi(O).then(()=>{T.replaceChildren(O)}).catch(B=>{throw B.name==="CANVAS_POSSIBLY_TOO_BIG"?new Error(f("canvasError.canvasTooBig")):B}))).catch(O=>{console.error(O),I(O)})},[e,o,_,P,s,p,u,w,g]),vi("div",{className:"ImageExportModal",children:[tt("h3",{children:f("imageExportDialog.header")}),vi("div",{className:"ImageExportModal__preview",children:[tt("div",{className:"ImageExportModal__preview__canvas",ref:y,children:v&&tt(lX,{})}),tt("div",{className:"ImageExportModal__preview__filename",children:!Na&&tt("input",{type:"text",className:"TextInput",value:s,style:{width:"30ch"},onChange:T=>{l(T.target.value),n.executeAction(Mf,"ui",T.target.value)}})})]}),vi("div",{className:"ImageExportModal__settings",children:[tt("h3",{children:f("imageExportDialog.header")}),a&&tt(vd,{label:f("imageExportDialog.label.onlySelected"),name:"exportOnlySelected",children:tt(wd,{name:"exportOnlySelected",checked:c,onChange:T=>{m(T)}})}),tt(vd,{label:f("imageExportDialog.label.withBackground"),name:"exportBackgroundSwitch",children:tt(wd,{name:"exportBackgroundSwitch",checked:p,onChange:T=>{d(T),n.executeAction(Pf,"ui",T)}})}),tt(vd,{label:f("imageExportDialog.label.darkMode"),name:"exportDarkModeSwitch",children:tt(wd,{name:"exportDarkModeSwitch",checked:u,onChange:T=>{h(T),n.executeAction(J2,"ui",T)}})}),tt(vd,{label:f("imageExportDialog.label.embedScene"),tooltip:f("imageExportDialog.tooltip.embedScene"),name:"exportEmbedSwitch",children:tt(wd,{name:"exportEmbedSwitch",checked:g,onChange:T=>{E(T),n.executeAction(tp,"ui",T)}})}),tt(vd,{label:f("imageExportDialog.label.scale"),name:"exportScale",children:tt(Wu,{name:"exportScale",value:w,onChange:T=>{x(T),n.executeAction(q2,"ui",T)},choices:sX.map(T=>({value:T,label:`${T}\xD7`}))})}),vi("div",{className:"ImageExportModal__settings__buttons",children:[tt(qo,{className:"ImageExportModal__settings__buttons__button",label:f("imageExportDialog.title.exportToPng"),onClick:()=>r(rx.png,_,{exportingFrame:P}),icon:Ih,children:f("imageExportDialog.button.exportToPng")}),tt(qo,{className:"ImageExportModal__settings__buttons__button",label:f("imageExportDialog.title.exportToSvg"),onClick:()=>r(rx.svg,_,{exportingFrame:P}),icon:Ih,children:f("imageExportDialog.button.exportToSvg")}),(vs||aX)&&tt(qo,{className:"ImageExportModal__settings__buttons__button",label:f("imageExportDialog.title.copyPngToClipboard"),status:L,onClick:async()=>{await r(rx.clipboard,_,{exportingFrame:P}),k()},icon:Qa,children:f("imageExportDialog.button.copyPngToClipboard")})]})]})]})},vd=({label:e,children:t,tooltip:o,name:n})=>vi("div",{className:"ImageExportModal__settings__setting",title:e,children:[vi("label",{htmlFor:n,className:"ImageExportModal__settings__setting__label",children:[e,o&&tt(Vt,{label:o,long:!0,children:yw})]}),tt("div",{className:"ImageExportModal__settings__setting__content",children:t})]}),w4=({elements:e,appState:t,files:o,actionManager:n,onExportImage:r,onCloseRequest:i,name:a})=>{let[{appStateSnapshot:s,elementsSnapshot:l}]=wi(()=>({appStateSnapshot:y4(t),elementsSnapshot:y4(e)}));return tt(ht,{onCloseRequest:i,size:"wide",title:!1,children:tt(cX,{elementsSnapshot:l,appStateSnapshot:s,files:o,actionManager:n,onExportImage:r,name:a})})};import mX from"react";import{getFrame as pX}from"@orangecatai/common";import{jsx as dX}from"react/jsx-runtime";var ix={primary:{base:"var(--color-primary)",darker:"var(--color-primary-darker)",darkest:"var(--color-primary-darkest)"},lime:{base:"#74b816",darker:"#66a80f",darkest:"#5c940d"},pink:{base:"#d6336c",darker:"#c2255c",darkest:"#a61e4d"}},ax=({children:e,color:t})=>dX("div",{className:"Card",style:{"--card-color":ix[t].base,"--card-color-darker":ix[t].darker,"--card-color-darkest":ix[t].darkest},children:e});import{Fragment as gX,jsx as yn,jsxs as fg}from"react/jsx-runtime";var uX=({elements:e,appState:t,setAppState:o,files:n,actionManager:r,exportOpts:i,canvas:a,onCloseRequest:s})=>{let{onExportToBackend:l}=i;return yn("div",{className:"ExportDialog ExportDialog--json",children:fg("div",{className:"ExportDialog-cards",children:[i.saveFileToDisk&&fg(ax,{color:"lime",children:[yn("div",{className:"Card-icon",children:Sy}),yn("h2",{children:f("exportDialog.disk_title")}),fg("div",{className:"Card-details",children:[f("exportDialog.disk_details"),!Na&&r.renderAction("changeProjectName")]}),yn(ne,{className:"Card-button",type:"button",title:f("exportDialog.disk_button"),"aria-label":f("exportDialog.disk_button"),showAriaLabel:!0,onClick:()=>{r.executeAction(Ic,"ui")}})]}),l&&fg(ax,{color:"pink",children:[yn("div",{className:"Card-icon",children:ql}),yn("h2",{children:f("exportDialog.link_title")}),yn("div",{className:"Card-details",children:f("exportDialog.link_details")}),yn(ne,{className:"Card-button",type:"button",title:f("exportDialog.link_button"),"aria-label":f("exportDialog.link_button"),showAriaLabel:!0,onClick:async()=>{try{ge("export","link",`ui (${pX()})`),await l(e,t,n),s()}catch(c){o({errorMessage:c.message})}}})]}),i.renderCustomUI&&i.renderCustomUI(e,t,n,a)]})})},v4=({elements:e,appState:t,files:o,actionManager:n,exportOpts:r,canvas:i,setAppState:a})=>{let s=mX.useCallback(()=>{a({openDialog:null})},[a]);return yn(gX,{children:t.openDialog?.name==="jsonExport"&&yn(ht,{onCloseRequest:s,title:f("buttons.export"),children:yn(uX,{elements:e,appState:t,setAppState:a,files:o,actionManager:n,onCloseRequest:s,exportOpts:r,canvas:i})})})};import hX from"clsx";import{jsx as I4,jsxs as bX}from"react/jsx-runtime";var fX="small",T4=e=>bX("label",{className:hX("ToolIcon ToolIcon__LaserPointer",`ToolIcon_size_${fX}`,{"is-mobile":e.isMobile}),title:`${e.title}`,children:[I4("input",{className:"ToolIcon_type_checkbox",type:"checkbox",name:e.name,onChange:e.onChange,checked:e.checked,"aria-label":e.title,"data-testid":"toolbar-LaserPointer"}),I4("div",{className:"ToolIcon__icon",children:Rn})]});import{Fragment as S4,jsx as se,jsxs as Do}from"react/jsx-runtime";var CX=({UIOptions:e})=>Do(Kt,{__fallback:!0,children:[se(Kt.DefaultItems.LoadScene,{}),se(Kt.DefaultItems.SaveToActiveFile,{}),e.canvasActions.export&&se(Kt.DefaultItems.Export,{}),e.canvasActions.saveAsImage&&se(Kt.DefaultItems.SaveAsImage,{}),se(Kt.DefaultItems.SearchMenu,{}),se(Kt.DefaultItems.Help,{}),se(Kt.DefaultItems.ClearCanvas,{}),se(Kt.Separator,{}),se(Kt.Group,{title:"Excalidraw links",children:se(Kt.DefaultItems.Socials,{})}),se(Kt.Separator,{}),se(Kt.DefaultItems.ToggleTheme,{}),se(Kt.DefaultItems.ChangeCanvasBackground,{})]}),kX=()=>Do(Ku,{__fallback:!0,children:[se(Ku.Actions.SaveToDisk,{}),se(Ku.Actions.ExportToImage,{})]}),SX=({actionManager:e,appState:t,files:o,setAppState:n,elements:r,canvas:i,onLockToggle:a,onHandToolToggle:s,onPenModeToggle:l,showExitZenModeBtn:c,renderTopLeftUI:m,renderTopRightUI:p,renderCustomStats:d,UIOptions:u,onExportImage:h,renderWelcomeScreen:g,children:E,app:w,isCollaborating:x,generateLinkForSelection:y})=>{let v=we(),k=_t()==="compact",L=wC(),S=k?{menuTopGap:4,toolbarColGap:4,toolbarRowGap:1,toolbarInnerRowGap:.5,islandPadding:1,collabMarginLeft:8}:{menuTopGap:6,toolbarColGap:4,toolbarRowGap:1,toolbarInnerRowGap:1,islandPadding:1,collabMarginLeft:8},_=L.tunnelsJotai.Provider,[P,T]=ae(zr),M=()=>u.canvasActions.export?se(v4,{elements:r,appState:t,files:o,actionManager:e,exportOpts:u.canvasActions.export,canvas:i,setAppState:n}):null,N=()=>!u.canvasActions.saveAsImage||t.openDialog?.name!=="imageExport"?null:se(w4,{elements:r,appState:t,files:o,actionManager:e,onExportImage:h,onCloseRequest:()=>n({openDialog:null}),name:w.getName()}),O=()=>Do("div",{style:{position:"relative"},children:[se(L.MainMenuTunnel.Out,{}),g&&se(L.WelcomeScreenMenuHintTunnel.Out,{})]}),B=()=>{let $=k;return se(ad,{heading:"selectedShapeActions",className:Ia("selected-shape-actions zen-mode-transition",{"transition-left":t.zenModeEnabled}),children:$?se(ut,{className:Ia("compact-shape-actions-island"),padding:0,style:{maxHeight:`${t.height-166}px`},children:se(NC,{appState:t,elementsMap:w.scene.getNonDeletedElementsMap(),renderAction:e.renderAction,app:w,setAppState:n})}):se(ut,{className:EX.SHAPE_ACTIONS_MENU,padding:2,style:{maxHeight:`${t.height-166}px`},children:se(AC,{appState:t,elementsMap:w.scene.getNonDeletedElementsMap(),renderAction:e.renderAction,app:w})})})},U=()=>{let $=IX(t,r),V=t.stats.open&&!t.zenModeEnabled&&!t.viewModeEnabled&&t.openDialog?.name!=="elementLinkSelector";return se(Nu,{side:"top",children:Do("div",{className:"App-menu App-menu_top",children:[Do(Dt.Col,{gap:S.menuTopGap,className:Ia("App-menu_top__left"),children:[O(),se("div",{className:Ia("selected-shape-actions-container",{"selected-shape-actions-container--compact":k}),children:$&&B()})]}),!t.viewModeEnabled&&t.openDialog?.name!=="elementLinkSelector"&&se(ad,{heading:"shapes",className:"shapes-section",children:Q=>Do("div",{style:{position:"relative"},children:[g&&se(L.WelcomeScreenToolbarHintTunnel.Out,{}),se(Dt.Col,{gap:S.toolbarColGap,align:"start",children:Do(Dt.Row,{gap:S.toolbarRowGap,className:Ia("App-toolbar-container",{"zen-mode":t.zenModeEnabled}),children:[Do(ut,{padding:S.islandPadding,className:Ia("App-toolbar",{"zen-mode":t.zenModeEnabled,"App-toolbar--compact":k}),children:[se(f4,{appState:t,isMobile:v.formFactor==="phone",editorInterface:v,app:w}),Q,Do(Dt.Row,{gap:S.toolbarInnerRowGap,children:[se(Bu,{zenModeEnabled:t.zenModeEnabled,checked:t.penMode,onChange:()=>l(null),title:f("toolBar.penMode"),penDetected:t.penDetected}),se(Tk,{checked:t.activeTool.locked,onChange:a,title:f("toolBar.lock")}),se("div",{className:"App-toolbar__divider"}),se(FC,{setAppState:n,activeTool:t.activeTool,UIOptions:u,app:w})]})]}),x&&se(ut,{style:{marginLeft:S.collabMarginLeft,alignSelf:"center",height:"fit-content"},children:se(T4,{title:f("toolBar.laser"),checked:t.activeTool.type===C4.laser,onChange:()=>w.setActiveTool({type:C4.laser}),isMobile:!0})})]})})]})}),Do("div",{className:Ia("layer-ui__wrapper__top-right zen-mode-transition",{"transition-right":t.zenModeEnabled,"layer-ui__wrapper__top-right--compact":k}),children:[t.collaborators.size>0&&se(Hu,{collaborators:t.collaborators,userToFollow:t.userToFollow?.socketId||null}),p?.(v.formFactor==="phone",t),w.props.showLibraryButton===!0&&!t.viewModeEnabled&&t.openDialog?.name!=="elementLinkSelector"&&(!F||t.openSidebar?.name!==sx.name)&&se(L.DefaultSidebarTriggerTunnel.Out,{}),V&&se(yd,{app:w,onClose:()=>{e.executeAction(qr)},renderCustomStats:d})]})]})})},D=()=>se(ju,{__fallback:!0,onDock:$=>{ge("sidebar",`toggleDock (${$?"dock":"undock"})`,`(${v.formFactor==="phone"?"mobile":"desktop"})`)}}),F=Ha(dd),z=Do(S4,{children:[E,se(CX,{UIOptions:u}),se(ju.Trigger,{__fallback:!0,icon:qw,title:wX(f("toolBar.library")),onToggle:$=>{$&&ge("sidebar",`${sx.name} (open)`,`button (${v.formFactor==="phone"?"mobile":"desktop"})`)},tab:sx.defaultTab}),se(kX,{}),t.openDialog?.name==="ttd"&&se(ig,{__fallback:!0}),t.isLoading&&se(_u,{delay:250}),t.errorMessage&&se(c4,{onClose:()=>n({errorMessage:null}),children:t.errorMessage}),P&&v.formFactor!=="phone"&&se(hv,{colorPickerType:P.colorPickerType,onCancel:()=>{T(null)},onChange:($,V,Q,{altKey:ee})=>{if(!($!=="elementBackground"&&$!=="elementStroke"))if(Q.length){for(let ie of Q)vX(ie,yX(r),{[ee&&P.swapPreviewOnAlt?$==="elementBackground"?"strokeColor":"backgroundColor":$==="elementBackground"?"backgroundColor":"strokeColor"]:V}),TX.delete(ie);w.scene.triggerUpdate()}else n($==="elementBackground"?{currentItemBackgroundColor:V}:{currentItemStrokeColor:V})},onSelect:($,V)=>{T(Q=>Q?.keepOpenOnAlt&&V.altKey?Q:null),P?.onSelect?.($,V)}}),t.openDialog?.name==="help"&&se(p4,{onClose:()=>{n({openDialog:null})}}),se(WC,{}),t.openDialog?.name==="elementLinkSelector"&&se(l4,{sourceElementId:t.openDialog.sourceElementId,onClose:()=>{n({openDialog:null})},scene:w.scene,appState:t,generateLinkForSelection:y}),se(L.OverwriteConfirmDialogTunnel.Out,{}),N(),M(),t.pasteDialog.shown&&se(Dk,{setAppState:n,appState:t,onClose:()=>n({pasteDialog:{shown:!1,data:null}})}),v.formFactor==="phone"&&se(Lk,{app:w,appState:t,elements:r,actionManager:e,renderJSONExportDialog:M,renderImageExportDialog:N,setAppState:n,onHandToolToggle:s,onPenModeToggle:l,renderTopLeftUI:m,renderTopRightUI:p,renderSidebars:D,renderWelcomeScreen:g,UIOptions:u}),v.formFactor!=="phone"&&Do(S4,{children:[Do("div",{className:"layer-ui__wrapper",style:t.openSidebar&&F&&v.canFitSidebar?{width:"calc(100% - var(--right-sidebar-width))"}:{},children:[g&&se(L.WelcomeScreenCenterTunnel.Out,{}),U(),se(Gk,{appState:t,actionManager:e,showExitZenModeBtn:c,renderWelcomeScreen:g}),t.scrolledOutside&&se("button",{type:"button",className:"scroll-back-to-content",onClick:()=>{n($=>({...Ri(r,$)}))},children:f("buttons.scrollBackToContent")})]}),D()]})]});return se(Oh.Provider,{value:t,children:se(_,{children:se(zb.Provider,{value:L,children:z})})})},k4=e=>{let{startBoundElement:t,cursorButton:o,scrollX:n,scrollY:r,...i}=e;return i},MX=(e,t)=>{if(e.children!==t.children)return!1;let{canvas:o,appState:n,...r}=e,{canvas:i,appState:a,...s}=t;return bg(k4(n),k4(a),{selectedElementIds:bg,selectedGroupIds:bg})&&bg(r,s)},M4=xX.memo(SX,MX);import PX from"clsx";import{jsx as P4,jsxs as LX}from"react/jsx-runtime";var AX="small",xg=e=>LX("label",{className:PX("ToolIcon ToolIcon__MagicButton",`ToolIcon_size_${AX}`,{"is-mobile":e.isMobile}),title:`${e.title}`,children:[P4("input",{className:"ToolIcon_type_checkbox",type:"checkbox",name:e.name,onChange:e.onChange,checked:e.checked,"aria-label":e.title}),P4("div",{className:"ToolIcon__icon",children:e.icon})]});import{useEffect as _X,useRef as DX}from"react";import{jsx as A4}from"react/jsx-runtime";var L4=({trails:e})=>{let t=DX(null);return _X(()=>{if(t.current)for(let o of e)o.start(t.current);return()=>{for(let o of e)o.stop()}},e),A4("div",{className:"SVGLayer",children:A4("svg",{ref:t})})};import bZ,{useEffect as xZ,useRef as X4}from"react";import{CURSOR_TYPE as Z4,isShallowEqual as EZ,sceneCoordsToViewportCoords as yZ}from"@orangecatai/common";var zt=class zt{static start(t,o){let n=o({deltaTime:0,state:void 0});n&&(zt.animations.set(t,{animation:o,lastTime:0,state:n}),zt.isRunning||(zt.isRunning=!0,ha()?requestAnimationFrame(zt.tick):setTimeout(zt.tick,0)))}static tick(){if(zt.animations.size>0){for(let[t,o]of zt.animations){let n=performance.now(),r=o.lastTime===0?0:n-o.lastTime,i=o.animation({deltaTime:r,state:o.state});if(i)o.lastTime=n,o.state=i;else if(zt.animations.delete(t),zt.animations.size===0){zt.isRunning=!1;return}}ha()?requestAnimationFrame(zt.tick):setTimeout(zt.tick,0)}}static running(t){return zt.animations.has(t)}static cancel(t){zt.animations.delete(t)}};A(zt,"isRunning",!1),A(zt,"animations",new Map);var Id=zt;import{clamp as mx,pointFrom as Il,pointsEqual as HX,bezierEquation as W4,pointRotateRads as Eg,pointDistance as GX}from"@orangecatai/math";import{arrayToMap as UX,BIND_MODE_TIMEOUT as Td,DEFAULT_TRANSFORM_HANDLE_SPACING as hx,FRAME_STYLE as tn,getFeatureFlag as WX,invariant as B4,THEME as Ii}from"@orangecatai/common";import{deconstructDiamondElement as px,deconstructRectanguloidElement as Y4,elementCenterPoint as Tl,getDiamondBaseCorners as YX,FOCUS_POINT_SIZE as VX,getOmitSidesForEditorInterface as lx,getTransformHandles as $X,getTransformHandlesFromCoords as KX,hasBoundingBox as XX,hitElementItself as ZX,isArrowElement as jX,isBindableElement as V4,isElbowArrow as Cl,isFrameLikeElement as kl,isImageElement as F4,isLinearElement as qX,isLineElement as JX,maxBindingDistance_simple as QX,isTextElement as O4,LinearElementEditor as qn}from"@orangecatai/element";import{renderSelectionElement as eZ}from"@orangecatai/element";import{getElementsInGroup as ux,getSelectedGroupIds as tZ,isSelectedViaGroup as oZ,selectGroupsFromGivenElements as nZ}from"@orangecatai/element";import{getCommonBounds as gx,getElementAbsoluteCoords as yg}from"@orangecatai/element";import{getGlobalFixedPointForBindableElement as z4,isFocusPointVisible as rZ}from"@orangecatai/element";import{pointFrom as Xt}from"@orangecatai/math";import{THEME as RX}from"@orangecatai/common";var NX="#ff6b6b",BX="#ff0000",_4=1,D4=2,R4=(e,t)=>{if(!t.snapLines.length)return;let o=t.theme===RX.LIGHT||t.zenModeEnabled?NX:BX,n=(t.zenModeEnabled?_4*1.5:_4)/t.zoom.value;e.save(),e.translate(t.scrollX,t.scrollY);for(let r of t.snapLines)r.type==="pointer"?(e.lineWidth=n,e.strokeStyle=o,OX(r,e,t)):r.type==="gap"?(e.lineWidth=n,e.strokeStyle=o,zX(r.points[0],r.points[1],r.direction,t,e)):r.type==="points"&&(e.lineWidth=n,e.strokeStyle=o,FX(r,e,t));e.restore()},FX=(e,t,o)=>{if(!o.zenModeEnabled){let n=e.points[0],r=e.points[e.points.length-1];en(n,r,t)}for(let n of e.points)N4(n,o,t)},OX=(e,t,o)=>{N4(e.points[0],o,t),o.zenModeEnabled||en(e.points[0],e.points[1],t)},N4=([e,t],o,n)=>{n.save();let r=(o.zenModeEnabled?D4*1.5:D4)/o.zoom.value;n.beginPath(),n.moveTo(e-r,t-r),n.lineTo(e+r,t+r),n.moveTo(e+r,t-r),n.lineTo(e-r,t+r),n.stroke(),n.restore()},en=(e,t,o)=>{o.beginPath(),o.lineTo(e[0],e[1]),o.lineTo(t[0],t[1]),o.stroke()},zX=(e,t,o,n,r)=>{let i=8/n.zoom.value,a=i/2,s=i/4;if(o==="horizontal"){let l=[(e[0]+t[0])/2,e[1]];n.zenModeEnabled||en(Xt(e[0],e[1]-i),Xt(e[0],e[1]+i),r),en(Xt(l[0]-s,l[1]-a),Xt(l[0]-s,l[1]+a),r),en(Xt(l[0]+s,l[1]-a),Xt(l[0]+s,l[1]+a),r),n.zenModeEnabled||(en(Xt(t[0],t[1]-i),Xt(t[0],t[1]+i),r),en(e,t,r))}else{let l=[e[0],(e[1]+t[1])/2];n.zenModeEnabled||en(Xt(e[0]-i,e[1]),Xt(e[0]+i,e[1]),r),en(Xt(l[0]-a,l[1]-s),Xt(l[0]+a,l[1]-s),r),en(Xt(l[0]-a,l[1]+s),Xt(l[0]+a,l[1]+s),r),n.zenModeEnabled||(en(Xt(t[0]-i,t[1]),Xt(t[0]+i,t[1]),r),en(e,t,r))}};var iZ=(e,t)=>{B4(t.selectedLinearElement,"selectedLinearElement is null");let{segmentMidPointHoveredCoords:o}=t.selectedLinearElement;B4(o,"midPointCoords is null"),e.save(),e.translate(t.scrollX,t.scrollY),fx(o,e,t),e.restore()},aZ=(e,t,o)=>{let{elementId:n,hoverPointIndex:r}=t.selectedLinearElement;if(t.selectedLinearElement?.isEditing&&t.selectedLinearElement?.selectedPointsIndices?.includes(r)||t.selectedLinearElement?.isDragging)return;let i=qn.getElement(n,o);if(!i)return;let a=qn.getPointAtIndexGlobalCoordinates(i,r,o);e.save(),e.translate(t.scrollX,t.scrollY),fx(a,e,t),e.restore()},fx=(e,t,o)=>{t.fillStyle="rgba(105, 101, 219, 0.4)",Yl(t,e[0],e[1],qn.POINT_HANDLE_SIZE/o.zoom.value,!1)},sZ=(e,t,o)=>{e.save(),e.translate(t.scrollX,t.scrollY),fx(o,e,t),e.restore()},cx=(e,t,o,n,r,i,a)=>{e.strokeStyle="#5e5ad8",e.setLineDash([]),e.fillStyle="rgba(255, 255, 255, 0.9)",r?e.fillStyle="rgba(134, 131, 226, 0.9)":i&&(e.fillStyle="rgba(177, 151, 252, 0.7)"),Yl(e,o[0],o[1],(a?n*(t.selectedLinearElement?.isEditing?1.5:2):n)/t.zoom.value,!i,!a||r)},lZ=(e,t,o,n,r)=>{let i=t.element.frameId&&o.get(t.element.frameId);switch(i&&kl(i)&&(e.translate(i.x,i.y),e.beginPath(),tn.radius&&e.roundRect?e.roundRect(-1,-1,i.width+1,i.height+1,tn.radius/n.zoom.value):e.rect(-1,-1,i.width+1,i.height+1),e.clip(),e.translate(-i.x,-i.y)),t.element.type){case"magicframe":case"frame":e.save(),e.translate(t.element.x,t.element.y),e.lineWidth=tn.strokeWidth/n.zoom.value,e.strokeStyle=n.theme===Ii.DARK?"rgba(3, 93, 161, 1)":"rgba(106, 189, 252, 1)",tn.radius&&e.roundRect?(e.beginPath(),e.roundRect(0,0,t.element.width,t.element.height,tn.radius/n.zoom.value),e.stroke(),e.closePath()):e.strokeRect(0,0,t.element.width,t.element.height),e.restore();break;default:e.save();let a=Tl(t.element,o);switch(e.translate(a[0],a[1]),e.rotate(t.element.angle),e.translate(-a[0],-a[1]),e.translate(t.element.x,t.element.y),e.lineWidth=mx(1.75,t.element.strokeWidth,4)/Math.max(.25,n.zoom.value),e.strokeStyle=n.theme===Ii.DARK?"rgba(3, 93, 161, 1)":"rgba(106, 189, 252, 1)",t.element.type){case"ellipse":e.beginPath(),e.ellipse(t.element.width/2,t.element.height/2,t.element.width/2,t.element.height/2,0,0,2*Math.PI),e.closePath(),e.stroke();break;case"diamond":{let[s,l]=px(t.element);s.forEach(c=>{e.beginPath(),e.moveTo(c[0][0]-t.element.x,c[0][1]-t.element.y),e.lineTo(c[1][0]-t.element.x,c[1][1]-t.element.y),e.stroke()}),l.forEach(c=>{let[m,p,d,u]=c;e.beginPath(),e.moveTo(m[0]-t.element.x,m[1]-t.element.y),e.bezierCurveTo(p[0]-t.element.x,p[1]-t.element.y,d[0]-t.element.x,d[1]-t.element.y,u[0]-t.element.x,u[1]-t.element.y),e.stroke()})}break;default:{let[s,l]=Y4(t.element);s.forEach(c=>{e.beginPath(),e.moveTo(c[0][0]-t.element.x,c[0][1]-t.element.y),e.lineTo(c[1][0]-t.element.x,c[1][1]-t.element.y),e.stroke()}),l.forEach(c=>{let[m,p,d,u]=c;e.beginPath(),e.moveTo(m[0]-t.element.x,m[1]-t.element.y),e.bezierCurveTo(p[0]-t.element.x,p[1]-t.element.y,d[0]-t.element.x,d[1]-t.element.y,u[0]-t.element.x,u[1]-t.element.y),e.stroke()})}break}e.restore();break}if(kl(t.element)||V4(t.element)){let a=n.selectedLinearElement,s=a?.elementId&&qn.getElement(a?.elementId,o),l=r&&ZX({point:r,element:t.element,elementsMap:o,threshold:0,overrideShouldTestInside:!0}),c=s&&Cl(s)||n.activeTool.type==="arrow"&&n.currentItemArrowType==="elbow";if(!l||c){e.save();let m=Tl(t.element,o),p;if(t.element.type==="diamond"){let g=Tl(t.element,o);p=YX(t.element).map(E=>{let w=W4(E,.5),x=Eg(w,g,t.element.angle);return Il(x[0],x[1])})}else p=[{x:t.element.width,y:t.element.height/2},{x:t.element.width/2,y:t.element.height},{x:0,y:t.element.height/2},{x:t.element.width/2,y:0}].map(E=>{let w=Il(E.x+t.element.x,E.y+t.element.y),x=Eg(w,m,t.element.angle);return Il(x[0],x[1])});let d=r&&p.reduce((g,E,w)=>{let x=GX(E,r);return w===-1||x<g.distance?{idx:w,distance:x}:g},{idx:-1,distance:1/0}),u=4/n.zoom.value,h=QX(n.zoom)+t.element.strokeWidth/2;p.forEach((g,E)=>{let w=(!l||c)&&d?.idx===E&&d.distance<=h,x=!w&&(c||E===d?.idx&&d.distance<=h*2);w?(e.fillStyle=n.theme===Ii.DARK?"rgba(3, 93, 161, 1)":"rgba(106, 189, 252, 1)",e.beginPath(),e.arc(g[0],g[1],u,0,2*Math.PI),e.fill()):x&&(e.fillStyle=n.theme===Ii.DARK?"rgba(0, 0, 0, 0.8)":"rgba(65, 65, 65, 0.5)",e.beginPath(),e.arc(g[0],g[1],u,0,2*Math.PI),e.fill())}),e.restore()}}},cZ=(e,t,o,n,r,i,a)=>{let s=e.state.bindMode==="orbit"&&e.bindModeHandler!==null,l=Td-(a?.runtime??(s?0:Td)),c=mx(1/Td*l,1e-4,1),m=o.strokeWidth/2,p=o.frameId&&n.get(o.frameId);switch(p&&kl(p)&&(t.translate(p.x,p.y),t.beginPath(),tn.radius&&t.roundRect?t.roundRect(-1,-1,p.width+1,p.height+1,tn.radius/r.zoom.value):t.rect(-1,-1,p.width+1,p.height+1),t.clip(),t.translate(-p.x,-p.y)),o.type){case"magicframe":case"frame":t.save(),t.translate(o.x,o.y),t.lineWidth=tn.strokeWidth/r.zoom.value,t.strokeStyle=r.theme===Ii.DARK?`rgba(3, 93, 161, ${c})`:`rgba(106, 189, 252, ${c})`,tn.radius&&t.roundRect?(t.beginPath(),t.roundRect(0,0,o.width,o.height,tn.radius/r.zoom.value),t.stroke(),t.closePath()):t.strokeRect(0,0,o.width,o.height),t.restore();break;default:t.save();let u=Tl(o,n),h=u[0]+r.scrollX,g=u[1]+r.scrollY;switch(t.translate(h,g),t.rotate(o.angle),t.translate(-h,-g),t.translate(o.x+r.scrollX-m,o.y+r.scrollY-m),t.lineWidth=mx(2.5,o.strokeWidth*1.75,4)/Math.max(.25,r.zoom.value),t.strokeStyle=r.theme===Ii.DARK?`rgba(3, 93, 161, ${c/2})`:`rgba(106, 189, 252, ${c/2})`,o.type){case"ellipse":t.beginPath(),t.ellipse((o.width+m*2)/2,(o.height+m*2)/2,(o.width+m*2)/2,(o.height+m*2)/2,0,0,2*Math.PI),t.closePath(),t.stroke();break;case"diamond":{let[E,w]=px(o,m);E.forEach(x=>{t.beginPath(),t.moveTo(x[0][0]-o.x+m,x[0][1]-o.y+m),t.lineTo(x[1][0]-o.x+m,x[1][1]-o.y+m),t.stroke()}),w.forEach(x=>{let[y,v,I,k]=x;t.beginPath(),t.moveTo(y[0]-o.x+m,y[1]-o.y+m),t.bezierCurveTo(v[0]-o.x+m,v[1]-o.y+m,I[0]-o.x+m,I[1]-o.y+m,k[0]-o.x+m,k[1]-o.y+m),t.stroke()})}break;default:{let[E,w]=Y4(o,m);E.forEach(x=>{t.beginPath(),t.moveTo(x[0][0]-o.x+m,x[0][1]-o.y+m),t.lineTo(x[1][0]-o.x+m,x[1][1]-o.y+m),t.stroke()}),w.forEach(x=>{let[y,v,I,k]=x;t.beginPath(),t.moveTo(y[0]-o.x+m,y[1]-o.y+m),t.bezierCurveTo(v[0]-o.x+m,v[1]-o.y+m,I[0]-o.x+m,I[1]-o.y+m,k[0]-o.x+m,k[1]-o.y+m),t.stroke()})}break}t.restore();break}if(!s||(a?.runtime??0)>Td)return;let d=.5*(Math.min(o.width,o.height)/2);if(!kl(o)){t.save(),t.translate(o.x+r.scrollX,o.y+r.scrollY);let u=1/Td*l;t.strokeStyle="rgba(0, 0, 0, 0.2)",t.lineWidth=1/r.zoom.value,t.setLineDash([4/r.zoom.value,4/r.zoom.value]),t.lineDashOffset=-u*10/r.zoom.value,t.beginPath(),t.ellipse(o.width/2,o.height/2,d,d,0,0,2*Math.PI),t.stroke(),t.fillStyle="rgba(0, 0, 0, 0.04)",t.beginPath(),t.ellipse(o.width/2,o.height/2,d*(1-c),d*(1-c),0,0,2*Math.PI),t.fill(),t.restore(),t.save(),t.translate(o.x+r.scrollX,o.y+r.scrollY);let h=5/r.zoom.value,g=5/r.zoom.value,E=h+g,w;if(o.type==="diamond"){let[,x]=px(o),y=Tl(o,n);w=x.map(v=>{let I=W4(v,.5),k=Eg(I,y,o.angle);return{x:k[0]-o.x,y:k[1]-o.y}})}else{let x=Tl(o,n);w=[{x:o.width/2,y:0},{x:o.width,y:o.height/2},{x:o.width/2,y:o.height},{x:0,y:o.height/2}].map(v=>{let I=Il(v.x+o.x,v.y+o.y),k=Eg(I,x,o.angle);return{x:k[0]-o.x,y:k[1]-o.y}})}w.forEach(x=>{t.clearRect(x.x-E,x.y-E,E*2,E*2)}),t.fillStyle=r.theme===Ii.DARK?`rgba(3, 93, 161, ${c})`:`rgba(106, 189, 252, ${c})`,w.forEach(x=>{t.beginPath(),t.arc(x.x,x.y,h,0,2*Math.PI),t.fill()}),t.restore()}return{runtime:(a?.runtime??0)+i}},dZ=(e,t,o,n,r,i,a)=>{if(o===null)return;if(WX("COMPLEX_BINDINGS"))return cZ(e,t,o.element,n,r,i,a);t.save(),t.translate(r.scrollX,r.scrollY);let s=e.lastPointerMoveCoords?Il(e.lastPointerMoveCoords.x,e.lastPointerMoveCoords.y):null;lZ(t,o,n,r,s),t.restore()},$4=(e,t,o)=>{let{angle:n,x1:r,y1:i,x2:a,y2:s,selectionColors:l,cx:c,cy:m,dashed:p,activeEmbeddable:d}=o,u=a-r,h=s-i,E=(o.padding??hx*2)/t.zoom.value,w=8/t.zoom.value,x=4/t.zoom.value;e.save(),e.translate(t.scrollX,t.scrollY),e.lineWidth=(d?4:1)/t.zoom.value;let y=l.length;for(let v=0;v<y;++v)e.strokeStyle=l[v],p&&e.setLineDash([w,x+(w+x)*(y-1)]),e.lineDashOffset=(w+x)*v,Vl(e,r-E,i-E,u+E*2,h+E*2,c,m,n);e.restore()},mZ=(e,t,o,n)=>{let[r,i,a,s]=yg(o,n),l=a-r,c=s-i;e.strokeStyle="rgb(0,118,255)",e.lineWidth=tn.strokeWidth/t.zoom.value,e.save(),e.translate(t.scrollX,t.scrollY),Vl(e,r,i,l,c,r+l/2,i+c/2,o.angle,!1,tn.radius/t.zoom.value),e.restore()},H4=(e,t,o,n)=>{let{colors:r=["rgb(0,118,255)"],dashed:i=!1}=n||{},a=o.filter(m=>m.groupIds.length===0),s=o.filter(m=>m.groupIds.length>0),l=m=>{let[p,d,u,h]=gx(m);return{angle:0,x1:p,x2:u,y1:d,y2:h,selectionColors:r,dashed:i,cx:p+(u-p)/2,cy:d+(h-d)/2,activeEmbeddable:!1}},c=m=>{let p=ux(o,m);return l(p)};Object.entries(nZ(s,t)).filter(([m,p])=>p).map(([m,p])=>m).map(m=>c(m)).concat(a.map(m=>l([m]))).forEach(m=>$4(e,t,m))},dx=(e,t,o,n)=>{if(!t.selectedLinearElement)return;e.save(),e.translate(t.scrollX,t.scrollY),e.lineWidth=1/t.zoom.value;let r=qn.getPointsGlobalCoordinates(o,n),{POINT_HANDLE_SIZE:i}=qn,a=t.selectedLinearElement?.isEditing?i:i/2,s=Cl(o),l=JX(o);if(r.forEach((c,m)=>{if(s&&m!==0&&m!==r.length-1)return;let p=m>0&&(m!==r.length-1||!l||!o.polygon)&&HX(c,m===r.length-1?r[0]:r[m-1],2/t.zoom.value),d=!!t.selectedLinearElement?.isEditing&&!!t.selectedLinearElement?.selectedPointsIndices?.includes(m);l&&o.polygon&&!d&&m===o.points.length-1&&t.selectedLinearElement?.isEditing&&t.selectedLinearElement?.selectedPointsIndices?.includes(0)&&(d=!0),cx(e,t,c,a,d,!1,p)}),Cl(o)){let c=o.fixedSegments?.map(m=>m.index)||[];r.slice(0,-1).forEach((m,p)=>{qn.isSegmentTooShort(o,r[p+1],r[p],p,t.zoom)||cx(e,t,Il((m[0]+r[p+1][0])/2,(m[1]+r[p+1][1])/2),i/2,!1,!c.includes(p+1),!1)})}else qn.getEditorMidPoints(o,n,t).filter((m,p,d)=>m!==null&&!(Cl(o)&&(p===0||p===d.length-1))).forEach(m=>{(t.selectedLinearElement?.isEditing||r.length===2)&&cx(e,t,m,i/2,!1,!0,!1)});e.restore()},pZ=(e,t,o,n)=>{e.save(),e.translate(t.scrollX,t.scrollY),e.strokeStyle="rgba(134, 131, 226, 0.6)",e.lineWidth=1/t.zoom.value,e.setLineDash([4/t.zoom.value,4/t.zoom.value]),e.beginPath(),e.moveTo(o[0],o[1]),e.lineTo(n[0],n[1]),e.stroke(),e.restore()},uZ=(e,t,o,n,r)=>{e.save(),e.translate(t.scrollX,t.scrollY),e.strokeStyle="rgba(134, 131, 226, 0.6)",e.lineWidth=1/t.zoom.value,e.setLineDash([]),e.fillStyle=r?"rgba(134, 131, 226, 0.9)":"rgba(255, 255, 255, 0.9)",Yl(e,o[0],o[1],n/t.zoom.value,!0,!0),e.restore()},G4=({arrow:e,appState:t,type:o,context:n,elementsMap:r})=>{let i=o==="start"?e.startBinding:e.endBinding,a=i?.elementId&&r.get(i.elementId);if(!a||!V4(a)||a.isDeleted)return;let s=z4(i.fixedPoint,a,r);if(!rZ(s,e,a,r,t,o))return;let l=t.selectedLinearElement,c=!!l?.isDragging,m=o==="start"?0:e.points.length-1,p=!!l?.selectedPointsIndices?.includes(m);if(l?.hoveredFocusPointBinding===o&&!l.draggedFocusPointBinding&&sZ(n,t,s),!(p&&c)){let d=z4(i.fixedPoint,a,r),u=l?.hoveredFocusPointBinding===o,h=qn.getPointAtIndexGlobalCoordinates(e,m,r);pZ(n,t,h,d),uZ(n,t,d,VX/1.5,u)}},U4=(e,t,o,n,r)=>{Object.keys(n).forEach(i=>{let a=n[i];if(a!==void 0){let[s,l,c,m]=a;e.save(),e.lineWidth=1/o.zoom.value,t.selectionColor&&(e.strokeStyle=t.selectionColor),i==="rotation"?Yl(e,s+c/2,l+m/2,c/2,!0):e.roundRect?(e.beginPath(),e.roundRect(s,l,c,m,2/o.zoom.value),e.fill(),e.stroke()):Vl(e,s,l,c,m,s+c/2,l+m/2,r,!0),e.restore()}})},gZ=(e,t,o,n,r)=>{let[i,a,,,s,l]=yg(n,r),c=3,m=20,p=c/o.zoom.value,d=p/2,u=s-i+p,h=l-a+p,g=Math.min(m/o.zoom.value,u),E=Math.min(m/o.zoom.value,h);e.save(),e.fillStyle=t.selectionColor,e.strokeStyle=t.selectionColor,e.lineWidth=p,[[[-u,-h],[0,d],[g,d],[d,0],[d,E]],[[u-d,-h],[d,d],[-g+d,d],[0,0],[0,E]],[[-u,h],[0,-d],[g,-d],[d,0],[d,-E]],[[u-d,h],[d,-d],[-g+d,-d],[0,0],[0,-E]]].forEach(x=>{let[[y,v],[I,k],[L,S],[_,P],[T,M]]=x;e.save(),e.translate(s,l),e.rotate(n.angle),e.beginPath(),e.moveTo(y+I,v+k),e.lineTo(y+L,v+S),e.stroke(),e.beginPath(),e.moveTo(y+_,v+P),e.lineTo(y+T,v+M),e.stroke(),e.restore()}),e.restore()},hZ=(e,t,o,n)=>{t.save();let r=hx*2/o.zoom.value,i=e.width+r*2,a=e.height+r*2,s=e.x+i/2,l=e.y+a/2,c=-(i/2+r),m=-(a/2+r);t.translate(s+o.scrollX,l+o.scrollY),t.rotate(e.angle),t.lineWidth=1/o.zoom.value,t.strokeStyle=n,t.strokeRect(c,m,i,a),t.restore()},fZ=({app:e,canvas:t,elementsMap:o,visibleElements:n,selectedElements:r,allElementsMap:i,scale:a,appState:s,renderConfig:l,editorInterface:c,animationState:m,deltaTime:p})=>{if(t===null)return{atLeastOneVisibleElement:!1,elementsMap:o};let[d,u]=qd(t,a),h=m,g=Jd({canvas:t,scale:a,normalizedWidth:d,normalizedHeight:u});g.save(),g.scale(s.zoom.value,s.zoom.value);let E;if(n.forEach(I=>{s.selectedLinearElement?.isEditing&&s.selectedLinearElement.elementId===I.id&&I&&(E=I)}),E&&dx(g,s,E,o),s.selectionElement&&!s.isCropping)try{eZ(s.selectionElement,g,s,l.selectionColor)}catch(I){console.error(I)}if(s.editingTextElement&&O4(s.editingTextElement)){let I=i.get(s.editingTextElement.id);I&&!I.autoResize&&hZ(I,g,s,l.selectionColor)}if(s.isBindingEnabled&&s.suggestedBinding?h={...m,bindingHighlight:dZ(e,g,s.suggestedBinding,i,s,p,m?.bindingHighlight)}:h={...m,bindingHighlight:void 0},s.frameToHighlight&&mZ(g,s,s.frameToHighlight,o),s.elementsToHighlight&&H4(g,s,s.elementsToHighlight),s.activeLockedId){let I=i.get(s.activeLockedId),k=I?[I]:ux(i,s.activeLockedId);H4(g,s,k,{colors:["#ced4da"],dashed:!0})}let w=r.some(I=>kl(I));r.length===1&&s.selectedLinearElement?.isEditing&&s.selectedLinearElement.elementId===r[0].id&&dx(g,s,r[0],o);let x=s.selectedLinearElement,y=x&&qn.getElement(x.elementId,i);if(y&&(s.selectedLinearElement.isDragging||(x.segmentMidPointHoveredCoords?iZ(g,s):(Cl(y)?x.hoverPointIndex===0||x.hoverPointIndex===y.points.length-1:x.hoverPointIndex>=0)&&aZ(g,s,o)),jX(y)&&(G4({arrow:y,elementsMap:i,appState:s,context:g,type:"start"}),G4({arrow:y,elementsMap:i,appState:s,context:g,type:"end"}))),!s.multiElement&&!s.newElement&&!s.selectedLinearElement?.isEditing){let I=XX(r,s,c),k=r.length===1&&qX(r[0]);k&&s.selectedLinearElement?.elementId===r[0].id&&!r[0].locked&&dx(g,s,r[0],o);let L=l.selectionColor||"#000";if(I){let S=UX(r),_=[];for(let T of o.values()){let M=[],N=l.remoteSelectedElementIds.get(T.id);if(k&&Cl(T)&&(T.startBinding||T.endBinding)||(S.has(T.id)&&!oZ(s,T)&&M.push(L),N&&M.push(...N.map(O=>qi(O,s.collaborators.get(O))))),M.length){let[O,B,U,D,F,z]=yg(T,o,!0);_.push({angle:T.angle,x1:O,y1:B,x2:U,y2:D,selectionColors:T.locked?["#ced4da"]:M,dashed:!!N||T.locked,cx:F,cy:z,activeEmbeddable:s.activeEmbeddable?.element===T&&s.activeEmbeddable.state==="active",padding:T.id===s.croppingElementId||F4(T)?0:void 0})}}let P=T=>{let M=ux(o,T),[N,O,B,U]=gx(M);_.push({angle:0,x1:N,x2:B,y1:O,y2:U,selectionColors:M.some(D=>D.locked)?["#ced4da"]:["#000"],dashed:!0,cx:N+(B-N)/2,cy:O+(U-O)/2,activeEmbeddable:!1})};for(let T of tZ(s))P(T);s.editingGroupId&&P(s.editingGroupId),_.forEach(T=>$4(g,s,T))}if(g.save(),g.translate(s.scrollX,s.scrollY),r.length===1){g.fillStyle="#fff";let S=$X(r[0],s.zoom,o,"mouse",lx(c));if(!s.viewModeEnabled&&I&&!O4(s.editingTextElement)&&!s.croppingElementId&&U4(g,l,s,S,r[0].angle),s.croppingElementId&&!s.isCropping){let _=o.get(s.croppingElementId);_&&F4(_)&&gZ(g,l,s,_,o)}}else if(r.length>1&&!s.isRotating&&!r.some(S=>S.locked)){let S=hx*2/s.zoom.value;g.fillStyle="#fff";let[_,P,T,M]=gx(r,o),N=g.getLineDash();g.setLineDash([2/s.zoom.value]);let O=g.lineWidth;g.lineWidth=1/s.zoom.value,g.strokeStyle=L,Vl(g,_-S,P-S,T-_+S*2,M-P+S*2,(_+T)/2,(P+M)/2,0),g.lineWidth=O,g.setLineDash(N);let B=KX([_,P,T,M,(_+T)/2,(P+M)/2],0,s.zoom,"mouse",w?{...lx(c),rotation:!0}:lx(c));r.some(U=>!U.locked)&&U4(g,l,s,B,0)}g.restore()}s.searchMatches?.matches.forEach(({id:I,focus:k,matchedLines:L})=>{let S=o.get(I);if(S){let[_,P,,,T,M]=yg(S,o,!0);g.save(),s.theme===Ii.LIGHT?k?g.fillStyle="rgba(255, 124, 0, 0.4)":g.fillStyle="rgba(255, 226, 0, 0.4)":k?g.fillStyle="rgba(229, 82, 0, 0.4)":g.fillStyle="rgba(99, 52, 0, 0.4)";let N=kl(S)?s.zoom.value:1;g.translate(s.scrollX,s.scrollY),g.translate(T,M),g.rotate(S.angle),L.forEach(O=>{(O.showOnCanvas||k)&&g.fillRect(_+O.offsetX/N-T,P+O.offsetY/N-M,O.width/N,O.height/N)}),g.restore()}}),R4(g,s),g.restore(),lI({context:g,renderConfig:l,appState:s,normalizedWidth:d,normalizedHeight:u});let v;return l.renderScrollbars&&(v=J3(o,d,u,s),g.save(),g.fillStyle=q3,g.strokeStyle="rgba(255,255,255,0.8)",[v.horizontal,v.vertical].forEach(I=>{I&&ap(g,I.x,I.y,I.width,I.height,Ko/2)}),g.restore()),{scrollBars:v,atLeastOneVisibleElement:n.length>0,elementsMap:o,animationState:h}},K4=e=>{let t=fZ(e);return e.callback(t),t};import{jsx as IZ}from"react/jsx-runtime";var j4="animateInteractiveScene",wZ=e=>{let t=X4(!1),o=X4(null);return xZ(()=>{if(!t.current){t.current=!0;return}let n=new Map,r=new Map,i=new Map,a=new Map,s=new Map;e.appState.collaborators.forEach((c,m)=>{if(c.selectedElementIds)for(let p of Object.keys(c.selectedElementIds))i.has(p)||i.set(p,[]),i.get(p).push(m);!c.pointer||c.pointer.renderCursor===!1||(c.username&&a.set(m,c.username),c.userState&&s.set(m,c.userState),r.set(m,yZ({sceneX:c.pointer.x,sceneY:c.pointer.y},e.appState)),n.set(m,c.button))});let l=e.containerRef?.current&&getComputedStyle(e.containerRef.current).getPropertyValue("--color-selection")||"#6965db";o.current={app:e.app,canvas:e.canvas,elementsMap:e.elementsMap,visibleElements:e.visibleElements,selectedElements:e.selectedElements,allElementsMap:e.allElementsMap,scale:window.devicePixelRatio,appState:e.appState,renderConfig:{remotePointerViewportCoords:r,remotePointerButton:n,remoteSelectedElementIds:i,remotePointerUsernames:a,remotePointerUserStates:s,selectionColor:l,renderScrollbars:e.renderScrollbars,lastViewportPosition:e.app.lastViewportPosition},editorInterface:e.editorInterface,callback:e.renderInteractiveSceneCallback,animationState:{bindingHighlight:void 0},deltaTime:0},Id.running(j4)||Id.start(j4,({deltaTime:c,state:m})=>{let p=K4({...o.current,deltaTime:c,animationState:m}).animationState;if(p){for(let d in p)if(p[d]!==void 0)return p}})}),IZ("canvas",{className:"excalidraw__canvas interactive",style:{width:e.appState.width,height:e.appState.height,cursor:e.appState.viewModeEnabled&&e.appState.activeTool.type!=="laser"?Z4.GRAB:Z4.AUTO},width:e.appState.width*e.scale,height:e.appState.height*e.scale,ref:e.handleCanvasRef,onContextMenu:e.onContextMenu,onPointerMove:e.onPointerMove,onPointerUp:e.onPointerUp,onPointerCancel:e.onPointerCancel,onTouchMove:e.onTouchMove,onPointerDown:e.onPointerDown,onDoubleClick:e.appState.viewModeEnabled?void 0:e.onDoubleClick,children:f("labels.drawingCanvas")})},q4=e=>({zoom:e.zoom,scrollX:e.scrollX,scrollY:e.scrollY,width:e.width,height:e.height,viewModeEnabled:e.viewModeEnabled,activeTool:e.activeTool,openDialog:e.openDialog,editingGroupId:e.editingGroupId,selectedElementIds:e.selectedElementIds,frameToHighlight:e.frameToHighlight,offsetLeft:e.offsetLeft,offsetTop:e.offsetTop,theme:e.theme,selectionElement:e.selectionElement,selectedGroupIds:e.selectedGroupIds,selectedLinearElement:e.selectedLinearElement,multiElement:e.multiElement,newElement:e.newElement,isBindingEnabled:e.isBindingEnabled,suggestedBinding:e.suggestedBinding,isRotating:e.isRotating,elementsToHighlight:e.elementsToHighlight,collaborators:e.collaborators,activeEmbeddable:e.activeEmbeddable,snapLines:e.snapLines,zenModeEnabled:e.zenModeEnabled,editingTextElement:e.editingTextElement,isCropping:e.isCropping,croppingElementId:e.croppingElementId,searchMatches:e.searchMatches,activeLockedId:e.activeLockedId,hoveredElementIds:e.hoveredElementIds,frameRendering:e.frameRendering,shouldCacheIgnoreZoom:e.shouldCacheIgnoreZoom,exportScale:e.exportScale,currentItemArrowType:e.currentItemArrowType}),vZ=(e,t)=>e.selectionNonce!==t.selectionNonce||e.sceneNonce!==t.sceneNonce||e.scale!==t.scale||e.elementsMap!==t.elementsMap||e.visibleElements!==t.visibleElements||e.selectedElements!==t.selectedElements||e.renderScrollbars!==t.renderScrollbars?!1:EZ(q4(e.appState),q4(t.appState)),bx=bZ.memo(wZ,vZ);import TZ,{useEffect as J4,useRef as Q4}from"react";import{isShallowEqual as e6}from"@orangecatai/common";import{jsx as SZ}from"react/jsx-runtime";var CZ=e=>{let t=Q4(null),o=Q4(!1);return J4(()=>{e.canvas.style.width=`${e.appState.width}px`,e.canvas.style.height=`${e.appState.height}px`,e.canvas.width=e.appState.width*e.scale,e.canvas.height=e.appState.height*e.scale},[e.appState.height,e.appState.width,e.canvas,e.scale]),J4(()=>{let n=t.current;if(!n)return;let r=e.canvas;o.current||(o.current=!0,n.replaceChildren(r),r.classList.add("excalidraw__canvas","static")),VE({canvas:r,rc:e.rc,scale:e.scale,elementsMap:e.elementsMap,allElementsMap:e.allElementsMap,visibleElements:e.visibleElements,appState:e.appState,renderConfig:e.renderConfig},ha())}),SZ("div",{className:"excalidraw__canvas-wrapper",ref:t})},t6=e=>({zoom:e.zoom,scrollX:e.scrollX,scrollY:e.scrollY,width:e.width,height:e.height,viewModeEnabled:e.viewModeEnabled,openDialog:e.openDialog,hoveredElementIds:e.hoveredElementIds,offsetLeft:e.offsetLeft,offsetTop:e.offsetTop,theme:e.theme,shouldCacheIgnoreZoom:e.shouldCacheIgnoreZoom,viewBackgroundColor:e.viewBackgroundColor,exportScale:e.exportScale,selectedElementsAreBeingDragged:e.selectedElementsAreBeingDragged,gridSize:e.gridSize,gridStep:e.gridStep,frameRendering:e.frameRendering,selectedElementIds:e.selectedElementIds,frameToHighlight:e.frameToHighlight,editingGroupId:e.editingGroupId,currentHoveredFontFamily:e.currentHoveredFontFamily,croppingElementId:e.croppingElementId,suggestedBinding:e.suggestedBinding}),kZ=(e,t)=>e.sceneNonce!==t.sceneNonce||e.scale!==t.scale||e.elementsMap!==t.elementsMap||e.visibleElements!==t.visibleElements?!1:e6(t6(e.appState),t6(t.appState))&&e6(e.renderConfig,t.renderConfig),xx=TZ.memo(CZ,kZ);import{useEffect as RZ,useRef as NZ}from"react";import{throttleRAF as MZ}from"@orangecatai/common";import{getTargetFrame as PZ,isInvisiblySmallElement as AZ,renderElement as LZ,shouldApplyFrameClip as _Z}from"@orangecatai/element";var o6=({canvas:e,rc:t,newElement:o,elementsMap:n,allElementsMap:r,scale:i,appState:a,renderConfig:s})=>{if(e){let[l,c]=qd(e,i),m=Jd({canvas:e,scale:i,normalizedWidth:l,normalizedHeight:c});if(m.save(),m.scale(a.zoom.value,a.zoom.value),o&&o.type!=="selection"){if(AZ(o))return;if((o.frameId||a.frameToHighlight?.id)&&a.frameRendering.enabled&&a.frameRendering.clip){let d=PZ(o,n,a);d&&_Z(o,d,a,n)&&WE(d,m,s,a)}LZ(o,n,r,t,m,s,a)}else m.clearRect(0,0,l,c);m.restore()}},DZ=MZ(e=>{o6(e)},{trailing:!0}),n6=(e,t)=>{if(t){DZ(e);return}o6(e)};import{jsx as FZ}from"react/jsx-runtime";var BZ=e=>{let t=NZ(null);return RZ(()=>{t.current&&n6({canvas:t.current,scale:e.scale,newElement:e.appState.newElement,elementsMap:e.elementsMap,allElementsMap:e.allElementsMap,rc:e.rc,renderConfig:e.renderConfig,appState:e.appState},ha())}),FZ("canvas",{className:"excalidraw__canvas",style:{width:e.appState.width,height:e.appState.height},width:e.appState.width*e.scale,height:e.appState.height*e.scale,ref:t})},r6=BZ;import{useCallback as OZ,useEffect as zZ,useRef as HZ}from"react";import{jsx as i6,jsxs as UZ}from"react/jsx-runtime";var GZ=5e3,a6=({message:e,onClose:t,closable:o=!1,duration:n=GZ,style:r})=>{let i=HZ(0),a=n!==1/0,s=OZ(()=>{a&&(i.current=window.setTimeout(()=>t(),n))},[t,n,a]);return zZ(()=>{if(a)return s(),()=>clearTimeout(i.current)},[s,e,n,a]),UZ("div",{className:"Toast",onMouseEnter:a?()=>clearTimeout(i?.current):void 0,onMouseLeave:a?s:void 0,style:r,children:[i6("p",{className:"Toast__message",children:e}),o&&i6(ne,{icon:Fo,"aria-label":"close",type:"icon",onClick:t,className:"close"})]})};import{getCommonBounds as WZ,getElementsInGroup as YZ,selectGroupsFromGivenElements as VZ}from"@orangecatai/element";import{sceneCoordsToViewportCoords as $Z}from"@orangecatai/common";import{flushSync as KZ}from"react-dom";import{jsx as ZZ}from"react/jsx-runtime";var XZ=({app:e,activeLockedId:t})=>{let o=e.scene.getElement(t),n=o?[o]:YZ(e.scene.getNonDeletedElementsMap(),t);if(n.length===0)return null;let[r,i]=WZ(n),{x:a,y:s}=$Z({sceneX:r,sceneY:i},e.state);return ZZ("div",{className:"UnlockPopup",style:{bottom:`${e.state.height+12-s+e.state.offsetTop}px`,left:`${a-e.state.offsetLeft}px`},onClick:()=>{KZ(()=>{let l=VZ(n,e.state);e.setState({selectedElementIds:n.reduce((c,m)=>({...c,[m.id]:!0}),{}),selectedGroupIds:l,activeLockedId:null})}),e.actionManager.executeAction(Pc)},title:f("labels.elementLock.unlock"),children:uy})},s6=XZ;import{Fragment as lP,jsx as Se,jsxs as Od}from"react/jsx-runtime";var uP=nr.createContext(null),gP=nr.createContext(null),qx={formFactor:"desktop",desktopUIMode:"full",userAgent:mP(typeof navigator<"u"?navigator.userAgent:""),isTouchScreen:!1,canFitSidebar:!1,isLandscape:!0},Qx=nr.createContext(qx);Qx.displayName="EditorInterfaceContext";var eE=nr.createContext({container:null,id:null});eE.displayName="ExcalidrawContainerContext";var tE=nr.createContext([]);tE.displayName="ExcalidrawElementsContext";var oE=nr.createContext({...Rr(),width:0,height:0,offsetLeft:0,offsetTop:0});oE.displayName="ExcalidrawAppStateContext";var nE=nr.createContext(()=>{console.warn("Uninitialized ExcalidrawSetAppStateContext context!")});nE.displayName="ExcalidrawSetAppStateContext";var rE=nr.createContext(null);rE.displayName="ExcalidrawActionManagerContext";var Qe=()=>Li(uP),Nn=()=>Li(gP),we=()=>Li(Qx),_t=()=>Dg(we()),qe=()=>Li(eE),Hr=()=>Li(tE),Go=()=>Li(oE),ve=()=>Li(nE),nt=()=>Li(rE),_d=!1,Kx=0,Dd=null,Pi=!1,Rd=!1,Xx=!1,Nd={horizontal:null,vertical:null},Ai=0,Bd=!1,Zx=new Map,jx=!1,aP=0,sP=!1,Fd=null,De={pointers:new Map,lastCenter:null,initialDistance:null,initialScale:null},Jx=class e extends nr.Component{constructor(o){super(o);A(this,"canvas");A(this,"interactiveCanvas",null);A(this,"rc");A(this,"unmounted",!1);A(this,"actionManager");A(this,"editorInterface",qx);A(this,"stylesPanelMode",Dg(qx));A(this,"excalidrawContainerRef",nr.createRef());A(this,"scene");A(this,"fonts");A(this,"renderer");A(this,"visibleElements");A(this,"resizeObserver");A(this,"library");A(this,"libraryItemsFromStorage");A(this,"id");A(this,"store");A(this,"history");A(this,"excalidrawContainerValue");A(this,"files",{});A(this,"imageCache",new Map);A(this,"iFrameRefs",new Map);A(this,"embedsValidationStatus",new Map);A(this,"initializedEmbeds",new Set);A(this,"handleToastClose",()=>{this.setToast(null)});A(this,"elementsPendingErasure",new Set);A(this,"flowChartCreator",new pq);A(this,"flowChartNavigator",new uq);A(this,"bindModeHandler",null);A(this,"hitLinkElement");A(this,"lastPointerDownEvent",null);A(this,"lastPointerUpEvent",null);A(this,"lastPointerMoveEvent",null);A(this,"lastPointerMoveCoords",null);A(this,"previousPointerMoveCoords",null);A(this,"lastViewportPosition",{x:0,y:0});A(this,"animationFrameHandler",new ru);A(this,"laserTrails",new ku(this.animationFrameHandler,this));A(this,"eraserTrail",new Lu(this.animationFrameHandler,this));A(this,"lassoTrail",new Au(this.animationFrameHandler,this));A(this,"onChangeEmitter",new Ta);A(this,"onPointerDownEmitter",new Ta);A(this,"onPointerUpEmitter",new Ta);A(this,"onUserFollowEmitter",new Ta);A(this,"onScrollChangeEmitter",new Ta);A(this,"missingPointerEventCleanupEmitter",new Ta);A(this,"onRemoveEventListenersEmitter",new Ta);A(this,"updateEditorAtom",(o,...n)=>{let r=xt.set(o,...n);return this.triggerRender(),r});A(this,"previousHoveredBindableElement",null);A(this,"getEffectiveGridSize",()=>ai(this)?this.state.gridSize:null);A(this,"handleIframeLikeElementHover",({hitElement:o,scenePointer:n,moveEvent:r})=>o&&Lx(o)&&(this.state.viewModeEnabled||this.state.activeTool.type==="laser"||this.isIframeLikeElementCenter(o,r,n.x,n.y))?(Ne(this.interactiveCanvas,st.POINTER),this.setState({activeEmbeddable:{element:o,state:"hover"}}),!0):(this.state.activeEmbeddable?.state==="hover"&&this.setState({activeEmbeddable:null}),!1));A(this,"updateEmbedValidationStatus",(o,n)=>{this.embedsValidationStatus.set(o.id,n),Ld.delete(o)});A(this,"updateEmbeddables",()=>{let o=new Set,n=!1;this.scene.getNonDeletedElements().filter(r=>{if(Lr(r)){if(o.add(r.id),!this.embedsValidationStatus.has(r.id)){n=!0;let i=Nx(r.link,this.props.validateEmbeddable);this.updateEmbedValidationStatus(r,i)}}else Ll(r)&&o.add(r.id);return!1}),n&&this.scene.triggerUpdate(),this.iFrameRefs.forEach((r,i)=>{o.has(i)||this.iFrameRefs.delete(i)})});A(this,"getFrameNameDOMId",o=>`${this.id}-frame-name-${o.id}`);A(this,"frameNameBoundsCache",{get:o=>{let n=this.frameNameBoundsCache._cache.get(o.id);if(!n||n.zoom!==this.state.zoom.value||n.versionNonce!==o.versionNonce){let r=document.getElementById(this.getFrameNameDOMId(o));if(r){let i=r.getBoundingClientRect(),a=ot({clientX:i.x,clientY:i.y},this.state),s=ot({clientX:i.right,clientY:i.bottom},this.state);return n={x:a.x,y:a.y,width:s.x-a.x,height:s.y-a.y,angle:0,zoom:this.state.zoom.value,versionNonce:o.versionNonce},this.frameNameBoundsCache._cache.set(o.id,n),n}return null}return n},_cache:new Map});A(this,"resetEditingFrame",o=>{o&&this.scene.mutateElement(o,{name:o.name?.trim()||null}),this.setState({editingFrame:null})});A(this,"renderFrameNames",()=>{if(!this.state.frameRendering.enabled||!this.state.frameRendering.name)return this.state.editingFrame&&this.resetEditingFrame(null),null;let o=this.state.theme===Ig.DARK,n=this.scene.getNonDeletedFramesLikes(),r=n.length>0&&this.state.searchMatches?.focusedId&&jt(this.scene.getElement(this.state.searchMatches.focusedId))?this.state.searchMatches.matches.find(i=>i.focus):null;return n.map(i=>{if(!B6(i,this.canvas.width/window.devicePixelRatio,this.canvas.height/window.devicePixelRatio,{offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,zoom:this.state.zoom},this.scene.getNonDeletedElementsMap()))return this.state.editingFrame===i.id&&this.resetEditingFrame(i),null;let{x:a,y:s}=Cg({sceneX:i.x,sceneY:i.y},this.state),l=6,c,m=aq(i),p=`${Math.round(i.width)} x ${Math.round(i.height)}`;if(i.id===this.state.editingFrame){let d=m;c=Se("input",{autoFocus:!0,value:d,onChange:u=>{this.scene.mutateElement(i,{name:u.target.value})},onFocus:u=>u.target.select(),onBlur:()=>this.resetEditingFrame(i),onKeyDown:u=>{(u.key===oe.ESCAPE||u.key===oe.ENTER)&&this.resetEditingFrame(i)},style:{background:o?Tj(this.state.viewBackgroundColor):this.state.viewBackgroundColor,zIndex:2,border:"none",display:"block",padding:`${l}px`,borderRadius:4,boxShadow:"inset 0 0 0 1px var(--color-primary)",fontFamily:"Assistant",fontSize:`${on.nameFontSize}px`,transform:`translate(-${l}px, ${l}px)`,color:o?on.nameColorDarkTheme:on.nameColorLightTheme,overflow:"hidden",maxWidth:`${document.body.clientWidth-a-l}px`},size:d.length+1||1,dir:"auto",autoComplete:"off",autoCapitalize:"off",autoCorrect:"off"})}else c=Od(lP,{children:[Se("span",{children:m}),Se("span",{style:{marginLeft:8,opacity:.7,fontSize:on.nameFontSize-1},children:p})]});return Se("div",{id:this.getFrameNameDOMId(i),className:Sx.FRAME_NAME,style:{position:"absolute",bottom:`${this.state.height+on.nameOffsetY-s+this.state.offsetTop}px`,left:`${a-this.state.offsetLeft}px`,zIndex:2,fontSize:on.nameFontSize,color:o?on.nameColorDarkTheme:on.nameColorLightTheme,lineHeight:on.nameLineHeight,width:"max-content",maxWidth:r?.id===i.id&&r?.focus?"none":`${i.width*this.state.zoom.value}px`,overflow:i.id===this.state.editingFrame?"visible":"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis",cursor:st.MOVE,pointerEvents:this.state.viewModeEnabled?Sl.disabled:Sl.enabled},onPointerDown:d=>this.handleCanvasPointerDown(d),onWheel:d=>this.handleWheel(d),onContextMenu:this.handleCanvasContextMenu,onDoubleClick:()=>{this.setState({editingFrame:i.id})},children:c},i.id)})});A(this,"focusContainer",()=>{this.excalidrawContainerRef.current?.focus()});A(this,"getSceneElementsIncludingDeleted",()=>this.scene.getElementsIncludingDeleted());A(this,"getSceneElementsMapIncludingDeleted",()=>this.scene.getElementsMapIncludingDeleted());A(this,"getSceneElements",()=>this.scene.getNonDeletedElements());A(this,"onInsertElements",o=>{this.addElementsFromPasteOrLibrary({elements:o,position:"center",files:null})});A(this,"onExportImage",async(o,n,r)=>{ge("export",o,"ui");let i=await Xi(o,n,this.state,this.files,{exportBackground:this.state.exportBackground,name:this.getName(),viewBackgroundColor:this.state.viewBackgroundColor,exportingFrame:r.exportingFrame}).catch(wj).catch(a=>{console.error(a),this.setState({errorMessage:a.message})});this.state.exportEmbedScene&&i&&Qd(i)&&this.setState({fileHandle:i})});A(this,"magicGenerations",new Map);A(this,"updateMagicGeneration",({frameElement:o,data:n})=>{n.status==="pending"?this.scene.mutateElement(o,{customData:{generationData:void 0}},{informMutation:!1,isDragging:!1}):this.scene.mutateElement(o,{customData:{generationData:n}},{informMutation:!1,isDragging:!1}),this.magicGenerations.set(o.id,n),this.triggerRender()});A(this,"plugins",{});A(this,"onMagicframeToolSelect",()=>{let o=this.scene.getSelectedElements({selectedElementIds:this.state.selectedElementIds});if(o.length===0)this.setActiveTool({type:Qn.magicframe}),ge("ai","tool-select (empty-selection)","d2c");else{let n=o.length===1&&_x(o[0])&&o[0];if(!n&&o.some(i=>jt(i)||i.frameId)){this.setActiveTool({type:Qn.magicframe});return}ge("ai","tool-select (existing selection)","d2c");let r;if(n)r=n;else{let[i,a,s,l]=Pl(o),c=50;r=L6({...on,x:i-c,y:a-c,width:s-i+c*2,height:l-a+c*2,opacity:100,locked:!1}),this.scene.insertElement(r);for(let m of o)this.scene.mutateElement(m,{frameId:r.id});this.setState({selectedElementIds:{[r.id]:!0}})}this.onMagicFrameGenerate(r,"upstream")}});A(this,"onImageGeneratorSelect",()=>{let r=(this.canvas.width/window.devicePixelRatio/2-this.state.offsetLeft)/this.state.zoom.value-this.state.scrollX,i=(this.canvas.height/window.devicePixelRatio/2-this.state.offsetTop)/this.state.zoom.value-this.state.scrollY,a=P6({...on,x:r-896/2,y:i-1344/2,width:896,height:1344,opacity:100,locked:!1,backgroundColor:"#cce8f5",fillStyle:"solid",customData:{type:"image-generator",imageGeneratorAutoFitPending:!0}});this.scene.insertElement(a),this.setActiveTool({type:"selection"}),this.setState({selectedElementIds:{[a.id]:!0}})});A(this,"insertGeneratedImageIntoFrame",async(o,n)=>{let r=Ex(),i=Mx({type:"image",x:n.x,y:n.y,width:n.width,height:n.height,fileId:r,status:"pending",scale:[1,1],frameId:null});this.scene.insertElement(i),this.scene.mutateElement(i,{frameId:n.id}),this.addFiles([{id:r,dataURL:o,mimeType:Bo(o),created:Date.now(),lastRetrieved:Date.now()}])});A(this,"insertGeneratedImageNearElement",async(o,n,r,i)=>{let s=this.scene.getNonDeletedElementsMap(),l=this.scene.getNonDeletedElements().filter(x=>x.id!==n.id),[c,m,p,d]=Mg(n,s),u=[{x:p+25,y:m},{x:c,y:d+25},{x:c-r-25,y:m},{x:c,y:m-i-25}],h=(x,y)=>{let v=x+r,I=y+i,k=x-25,L=y-25,S=v+25,_=I+25;return l.some(P=>{let[T,M,N,O]=Mg(P,s);return T<S&&N>k&&M<_&&O>L})},g=u.find(x=>!h(x.x,x.y))??u[0],E=Ex(),w=Mx({type:"image",x:g.x,y:g.y,width:r,height:i,fileId:E,status:"pending",scale:[1,1],frameId:null});this.scene.insertElement(w),this.addFiles([{id:E,dataURL:o,mimeType:Bo(o),created:Date.now(),lastRetrieved:Date.now()}]),this.setState({selectedElementIds:{[w.id]:!0}})});A(this,"openEyeDropper",({type:o})=>{this.updateEditorAtom(zr,{swapPreviewOnAlt:!0,colorPickerType:o==="stroke"?"elementStroke":"elementBackground",onSelect:(n,r)=>{let i=o==="background"&&r.altKey||o==="stroke"&&!r.altKey;!this.scene.getSelectedElements(this.state).length||this.state.activeTool.type!=="selection"?i?this.syncActionResult({appState:{...this.state,currentItemStrokeColor:n},captureUpdate:lo.IMMEDIATELY}):this.syncActionResult({appState:{...this.state,currentItemBackgroundColor:n},captureUpdate:lo.IMMEDIATELY}):this.updateScene({elements:this.scene.getElementsIncludingDeleted().map(s=>this.state.selectedElementIds[s.id]?Si(s,{[i?"strokeColor":"backgroundColor"]:n}):s),captureUpdate:lo.IMMEDIATELY})},keepOpenOnAlt:!1})});A(this,"dismissLinearEditor",()=>{setTimeout(()=>{this.state.selectedLinearElement?.isEditing&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,isEditing:!1}})})});A(this,"syncActionResult",mt(o=>{if(this.unmounted||o===!1)return;this.store.scheduleAction(o.captureUpdate);let n=!1,r=null;if(o.elements&&(this.scene.replaceAllElements(o.elements),n=!0),o.files&&(this.addMissingFiles(o.files,o.replaceFiles),this.addNewImagesToImageCache()),o.appState||r||this.state.contextMenu){let i=o?.appState?.viewModeEnabled||!1,a=o?.appState?.zenModeEnabled||!1,s=o?.appState?.theme||this.props.theme||Ig.LIGHT,l=o?.appState?.name??this.state.name,c=o?.appState?.errorMessage??this.state.errorMessage;typeof this.props.viewModeEnabled<"u"&&(i=this.props.viewModeEnabled),typeof this.props.zenModeEnabled<"u"&&(a=this.props.zenModeEnabled),r=o.appState?.editingTextElement||null,o.elements&&r&&o.elements.forEach(m=>{r?.id===m.id&&r!==m&&Q6(m)&&vn(m)&&(r=m)}),r?.isDeleted&&(r=null),this.setState(m=>{let p=o.appState||{};return{...m,...p,contextMenu:null,editingTextElement:r,viewModeEnabled:i,zenModeEnabled:a,theme:s,name:l,errorMessage:c}}),n=!0}n||this.scene.triggerUpdate()}));A(this,"onBlur",mt(()=>{Pi=!1,this.setState({isBindingEnabled:!0})}));A(this,"onUnload",()=>{this.onBlur()});A(this,"disableEvent",o=>{o.preventDefault()});A(this,"resetHistory",()=>{this.history.clear()});A(this,"resetStore",()=>{this.store.clear()});A(this,"resetScene",mt(o=>{this.scene.replaceAllElements([]),this.setState(n=>({...Rr(),isLoading:o?.resetLoadingState?!1:n.isLoading,theme:this.state.theme})),this.resetStore(),this.resetHistory()}));A(this,"initializeScene",async()=>{"launchQueue"in window&&"LaunchParams"in window&&window.launchQueue.setConsumer(async a=>{if(!a.files.length)return;let s=a.files[0],l=await s.getFile();this.loadFileToCanvas(new File([l],l.name||"",{type:l.type}),s)}),this.props.theme&&this.setState({theme:this.props.theme}),this.state.isLoading||this.setState({isLoading:!0});let o=null;try{typeof this.props.initialData=="function"?o=await this.props.initialData()||null:o=await this.props.initialData||null,o?.libraryItems&&this.library.updateLibrary({libraryItems:o.libraryItems,merge:!0}).catch(a=>{console.error(a)})}catch(a){console.error(a),o={appState:{errorMessage:a.message||"Encountered an error during importing or restoring scene data"}}}let n=Ni(o?.elements,null,{repairBindings:!0,deleteInvisibleElements:!0}),r=Oa(o?.appState,null),i=r.activeTool;r.preferredSelectionTool.initialized||(r.preferredSelectionTool={type:this.editorInterface.formFactor==="phone"?"lasso":"selection",initialized:!0}),r={...r,theme:this.props.theme||r.theme,openSidebar:r?.openSidebar||this.state.openSidebar,activeTool:i.type==="image"||i.type==="lasso"||i.type==="selection"?{...i,type:r.preferredSelectionTool.type}:r.activeTool,isLoading:!1,toast:this.state.toast},o?.scrollToContent&&(r={...r,...Ri(n,{...r,width:this.state.width,height:this.state.height,offsetTop:this.state.offsetTop,offsetLeft:this.state.offsetLeft})}),this.resetStore(),this.resetHistory(),this.syncActionResult({elements:n,appState:r,files:o?.files,captureUpdate:lo.NEVER}),this.clearImageShapeCache(),this.fonts.loadSceneFonts().then(a=>{this.fonts.onLoaded(a)}),Ux(window.location.href)&&this.scrollToContent(window.location.href,{animate:!1})});A(this,"getFormFactor",(o,n)=>this.props.UIOptions.getFormFactor?.(o,n)??Pj(o,n));A(this,"refreshEditorInterface",()=>{let o=this.excalidrawContainerRef.current;if(!o)return;let{width:n,height:r}=o.getBoundingClientRect(),i=Dj(),a=mP(typeof navigator<"u"?navigator.userAgent:""),s=this.props.UIOptions.dockedSidebarBreakpoint!=null?this.props.UIOptions.dockedSidebarBreakpoint:rj,l=kx(this.editorInterface,{desktopUIMode:i??this.editorInterface.desktopUIMode,formFactor:this.getFormFactor(n,r),userAgent:a,canFitSidebar:n>s,isLandscape:n>r});this.editorInterface=l,this.reconcileStylesPanelMode(l)});A(this,"reconcileStylesPanelMode",o=>{let n=Dg(o);if(n===this.stylesPanelMode)return;let r=this.stylesPanelMode;this.stylesPanelMode=n,r!=="full"&&n==="full"&&this.setState(i=>({preferredSelectionTool:{type:"selection",initialized:!0}}))});A(this,"setDesktopUIMode",o=>{let n=Rj(o);this.editorInterface=kx(this.editorInterface,{desktopUIMode:n}),this.reconcileStylesPanelMode(this.editorInterface)});A(this,"onResize",mt(()=>{this.scene.getElementsIncludingDeleted().forEach(o=>Ld.delete(o)),this.refreshEditorInterface(),this.updateDOMRect(),this.setState({})}));A(this,"onFullscreenChange",()=>{!document.fullscreenElement&&this.state.activeEmbeddable?.state==="active"&&this.setState({activeEmbeddable:null})});A(this,"renderInteractiveSceneCallback",({atLeastOneVisibleElement:o,scrollBars:n,elementsMap:r})=>{n&&(Nd=n);let i=this.state.editingTextElement?!1:!o&&r.size>0;this.state.scrolledOutside!==i&&this.setState({scrolledOutside:i}),this.scheduleImageRefresh()});A(this,"onScroll",I6(()=>{let{offsetTop:o,offsetLeft:n}=this.getCanvasOffsets();this.setState(r=>r.offsetLeft===n&&r.offsetTop===o?null:{offsetTop:o,offsetLeft:n})},ij));A(this,"onCut",mt(o=>{!this.excalidrawContainerRef.current?.contains(document.activeElement)||kd(o.target)||(this.actionManager.executeAction(cp,"keyboard",o),o.preventDefault(),o.stopPropagation())}));A(this,"onCopy",mt(o=>{!this.excalidrawContainerRef.current?.contains(document.activeElement)||kd(o.target)||(this.actionManager.executeAction(Ls,"keyboard",o),o.preventDefault(),o.stopPropagation())}));A(this,"onTouchStart",o=>{if(Aj&&o.preventDefault(),!_d){_d=!0,o.touches.length===1&&(Dd={x:o.touches[0].clientX,y:o.touches[0].clientY}),clearTimeout(Kx),Kx=window.setTimeout(e.resetTapTwice,aj);return}if(_d&&o.touches.length===1&&Dd){let n=o.touches[0];Ti(de(n.clientX,n.clientY),de(Dd.x,Dd.y))<=Sj&&(this.lassoTrail.endPath(),this.deselectElements(),this.handleCanvasDoubleClick({clientX:n.clientX,clientY:n.clientY})),_d=!1,clearTimeout(Kx)}o.touches.length===2&&this.setState({selectedElementIds:Oe({},this.state),activeEmbeddable:null})});A(this,"onTouchEnd",o=>{this.resetContextMenuTimer(),o.touches.length>0?this.setState({previousSelectedElementIds:{},selectedElementIds:Oe(this.state.previousSelectedElementIds,this.state)}):De.pointers.clear()});A(this,"pasteFromClipboard",mt(async o=>{let n=!!jx,r=document.activeElement,i=this.excalidrawContainerRef.current?.contains(r);if(o&&!i)return;let a=document.elementFromPoint(this.lastViewportPosition.x,this.lastViewportPosition.y);if(o&&(!(a instanceof HTMLCanvasElement)||kd(r)))return;let s=await Is(o),l=s.getFiles(),c=await Qm(s,n);if(this.props.onPaste)try{if(await this.props.onPaste(c,o)===!1)return}catch(m){console.error(m)}await this.insertClipboardContent(c,l,n),this.setActiveTool({type:this.state.preferredSelectionTool.type},!0),o?.preventDefault()}));A(this,"addElementsFromPasteOrLibrary",o=>{let n=Ni(o.elements,null,{deleteInvisibleElements:!0}),[r,i,a,s]=Pl(n),l=Ml(r,a)/2,c=Ml(i,s)/2,m=typeof o.position=="object"?o.position.clientX:o.position==="cursor"?this.lastViewportPosition.x:this.state.width/2+this.state.offsetLeft,p=typeof o.position=="object"?o.position.clientY:o.position==="cursor"?this.lastViewportPosition.y:this.state.height/2+this.state.offsetTop,{x:d,y:u}=ot({clientX:m,clientY:p},this.state),h=d-l,g=u-c,[E,w]=Zt(h,g,this.getEffectiveGridSize()),{duplicatedElements:x}=Px({type:"everything",elements:n.map(S=>Si(S,{x:S.x+E-r,y:S.y+w-i})),randomizeSeed:!o.retainSeed}),y=this.scene.getElementsIncludingDeleted(),v=[...y,...x];v=this.props.onDuplicate?.(v,y)||v,X6(v,kg(x));let k=this.getTopLayerFrameAtSceneCoords({x:d,y:u});if(k){let S=lq(x,k);zx(v,S,k,this.state)}this.scene.replaceAllElements(v),x.forEach(S=>{if(vn(S)&&Ax(S)){let _=G6(S,this.scene.getElementsMapIncludingDeleted());eq(S,_,this.scene)}}),_j&&Mn.loadElementsFonts(x).then(S=>{this.fonts.onLoaded(S)}),o.files&&this.addMissingFiles(o.files);let L=Mq(x);this.store.scheduleCapture(),this.setState({...this.state,openSidebar:this.state.openSidebar&&this.editorInterface.canFitSidebar&&xt.get(dd)?this.state.openSidebar:null,...nn({editingGroupId:null,selectedElementIds:L.reduce((S,_)=>(Ax(_)||(S[_.id]=!0),S),{})},this.scene.getNonDeletedElements(),this.state,this)},()=>{o.files&&this.addNewImagesToImageCache()}),this.setActiveTool({type:this.state.preferredSelectionTool.type},!0),o.fitToContent&&this.scrollToContent(x,{fitToContent:!0,canvasOffsets:this.getEditorUIOffsets()})});A(this,"setAppState",(o,n)=>{this.setState(o,n)});A(this,"removePointer",o=>{Ai&&this.resetContextMenuTimer(),De.pointers.delete(o.pointerId)});A(this,"toggleLock",(o="ui")=>{this.state.activeTool.locked||ge("toolbar","toggleLock",`${o} (${this.editorInterface.formFactor==="phone"?"mobile":"desktop"})`),this.setState(n=>({activeTool:{...n.activeTool,...er(this.state,n.activeTool.locked?{type:this.state.preferredSelectionTool.type}:n.activeTool),locked:!n.activeTool.locked}}))});A(this,"updateFrameRendering",o=>{this.setState(n=>{let r=typeof o=="function"?o(n.frameRendering):o;return{frameRendering:{enabled:r?.enabled??n.frameRendering.enabled,clip:r?.clip??n.frameRendering.clip,name:r?.name??n.frameRendering.name,outline:r?.outline??n.frameRendering.outline}}})});A(this,"togglePenMode",o=>{this.setState(n=>({penMode:o??!n.penMode,penDetected:!0}))});A(this,"onHandToolToggle",()=>{this.actionManager.executeAction(x2)});A(this,"zoomCanvas",o=>{this.setState({...pr({viewportX:this.state.width/2+this.state.offsetLeft,viewportY:this.state.height/2+this.state.offsetTop,nextZoom:Cn(o)},this.state)})});A(this,"cancelInProgressAnimation",null);A(this,"scrollToContent",(o=this.scene.getNonDeletedElements(),n)=>{if(typeof o=="string"){let l;if(Ux(o)?l=fq(o):l=o,l){let c=this.scene.getElementsFromId(l);c?.length?this.scrollToContent(c,{fitToContent:n?.fitToContent??!0,animate:n?.animate??!0}):Ux(o)&&this.setState({toast:{message:f("elementLink.notFound"),duration:3e3,closable:!0}})}return}this.cancelInProgressAnimation?.();let r=Array.isArray(o)?o:[o],i=this.state.zoom,a=this.state.scrollX,s=this.state.scrollY;if(n?.fitToContent||n?.fitToViewport){let{appState:l}=ys({canvasOffsets:n.canvasOffsets,targetElements:r,appState:this.state,fitToViewport:!!n?.fitToViewport,viewportZoomFactor:n?.viewportZoomFactor,minZoom:n?.minZoom,maxZoom:n?.maxZoom});i=l.zoom,a=l.scrollX,s=l.scrollY}else{let l=Ri(r,this.state);a=l.scrollX,s=l.scrollY}if(n?.animate){let l=this.state.scrollX,c=this.state.scrollY,m=this.state.zoom.value,p=yj({fromValues:{scrollX:l,scrollY:c,zoom:m},toValues:{scrollX:a,scrollY:s,zoom:i.value},interpolateValue:(d,u,h,g)=>{if(g==="zoom")return d*Math.pow(u/d,vj(h))},onStep:({scrollX:d,scrollY:u,zoom:h})=>{this.setState({scrollX:d,scrollY:u,zoom:{value:h}})},onStart:()=>{this.setState({shouldCacheIgnoreZoom:!0})},onEnd:()=>{this.setState({shouldCacheIgnoreZoom:!1})},onCancel:()=>{this.setState({shouldCacheIgnoreZoom:!1})},duration:n?.duration??500});this.cancelInProgressAnimation=()=>{p(),this.cancelInProgressAnimation=null}}else this.setState({scrollX:a,scrollY:s,zoom:i})});A(this,"maybeUnfollowRemoteUser",()=>{this.state.userToFollow&&this.setState({userToFollow:null})});A(this,"translateCanvas",o=>{this.cancelInProgressAnimation?.(),this.maybeUnfollowRemoteUser(),this.setState(o)});A(this,"setToast",o=>{this.setState({toast:o})});A(this,"restoreFileFromShare",async()=>{try{let o=await caches.open("web-share-target"),n=await o.match("shared-file");if(n){let r=await n.blob(),i=new File([r],r.name||"",{type:r.type});this.loadFileToCanvas(i,null),await o.delete("shared-file"),window.history.replaceState(null,QZ,window.location.pathname)}}catch(o){this.setState({errorMessage:o.message})}});A(this,"addFiles",mt(o=>{let{addedFiles:n}=this.addMissingFiles(o);this.clearImageShapeCache(n),this.scene.triggerUpdate(),this.addNewImagesToImageCache()}));A(this,"addMissingFiles",(o,n=!1)=>{let r=n?{}:{...this.files},i={},a=Array.isArray(o)?o:Object.values(o);for(let s of a)if(!r[s.id]&&(i[s.id]=s,r[s.id]=s,s.mimeType===Jn.svg))try{let l=QE(H6(ey(s.dataURL)),Jn.svg);s.dataURL!==l&&(s.version=(s.version??1)+1,s.dataURL=l)}catch(l){console.error(l)}return this.files=r,{addedFiles:i}});A(this,"updateScene",mt(o=>{let{elements:n,appState:r,collaborators:i,captureUpdate:a}=o;if(a){let s=n||void 0,l=r?Nj({...this.store.snapshot.appState,...r}):void 0;this.store.scheduleMicroAction({action:a,elements:s,appState:l})}r&&this.setState(r),n&&this.scene.replaceAllElements(n),i&&this.setState({collaborators:i})}));A(this,"applyDeltas",(o,n)=>{let r=tP.squash(...o),i={...this.state},a=new Map(this.scene.getElementsMapIncludingDeleted());return tP.applyTo(r,a,i,n)});A(this,"mutateElement",(o,n,r=!0)=>this.scene.mutateElement(o,n,{informMutation:r,isDragging:!1}));A(this,"triggerRender",o=>{o===!0?this.scene.triggerUpdate():this.setState({})});A(this,"toggleSidebar",({name:o,tab:n,force:r})=>{let i;r===void 0?i=this.state.openSidebar?.name===o&&this.state.openSidebar?.tab===n?null:o:i=r?o:null;let a=i?{name:i}:null;return a&&n&&(a.tab=n),this.setState({openSidebar:a}),!!i});A(this,"updateCurrentCursorPosition",mt(o=>{this.lastViewportPosition.x=o.clientX,this.lastViewportPosition.y=o.clientY}));A(this,"getEditorUIOffsets",()=>{let o=this.excalidrawContainerRef?.current?.querySelector(".App-toolbar")?.getBoundingClientRect()?.bottom??0,n=this.excalidrawContainerRef?.current?.querySelector(".sidebar")?.getBoundingClientRect(),r=this.excalidrawContainerRef?.current?.querySelector(".App-menu__left")?.getBoundingClientRect(),i=16;return lr().rtl?{top:o+i,right:Math.max(this.state.width-(r?.left??this.state.width),0)+i,bottom:i,left:Math.max(n?.right??0,0)+i}:{top:o+i,right:Math.max(this.state.width-(n?.left??this.state.width)+i,0),bottom:i,left:Math.max(r?.right??0,0)+i}});A(this,"onKeyDown",mt(o=>{if("Proxy"in window&&(!o.shiftKey&&/^[A-Z]$/.test(o.key)||o.shiftKey&&/^[a-z]$/.test(o.key))&&(o=new Proxy(o,{get(s,l){let c=s[l];return typeof c=="function"?c.bind(s):l==="key"?o.shiftKey?s.key.toUpperCase():s.key.toLowerCase():c}})),!T6(o.target)){if((o.key===oe.ESCAPE||o.key===oe.ENTER)&&this.state.croppingElementId){this.finishImageCropping();return}let s=le(this.scene.getNonDeletedElementsMap(),this.state);if(s.length===1&&Mi(s[0])&&o.key===oe.ENTER){this.startImageCropping(s[0]);return}if(o.key===oe.ESCAPE)this.updateEditorAtom(gn,null);else if(o.key===oe.TAB&&(document.activeElement===this.excalidrawContainerRef?.current||document.activeElement?.classList.contains(Sx.CONVERT_ELEMENT_TYPE_POPUP))){o.preventDefault();let c=Os(s);xt.get(gn)?.type==="panel"&&pb(this,{conversionType:c,direction:o.shiftKey?"left":"right"})&&this.store.scheduleCapture(),c&&this.updateEditorAtom(gn,{type:"panel"})}if(o.key===oe.ESCAPE&&this.flowChartCreator.isCreatingChart){this.flowChartCreator.clear(),this.triggerRender(!0);return}let l=wg(o.key);if(o[oe.CTRL_OR_CMD]&&l&&!o.shiftKey){o.preventDefault();let c=le(this.scene.getNonDeletedElementsMap(),this.state);c.length===1&&Kj(c[0])&&this.flowChartCreator.createNodes(c[0],this.state,V6(o.key),this.scene),this.flowChartCreator.pendingNodes?.length&&!Rx(this.flowChartCreator.pendingNodes,this.canvas.width/window.devicePixelRatio,this.canvas.height/window.devicePixelRatio,{offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,zoom:this.state.zoom},this.scene.getNonDeletedElementsMap(),this.getEditorUIOffsets())&&this.scrollToContent(this.flowChartCreator.pendingNodes,{animate:!0,duration:300,fitToContent:!0,canvasOffsets:this.getEditorUIOffsets()});return}if(o.altKey){let c=le(this.scene.getNonDeletedElementsMap(),this.state);if(c.length===1&&l){o.preventDefault();let m=this.flowChartNavigator.exploreByDirection(c[0],this.scene.getNonDeletedElementsMap(),V6(o.key));if(m){this.setState(d=>({selectedElementIds:Oe({[m]:!0},d)}));let p=this.scene.getNonDeletedElementsMap().get(m);p&&!Rx([p],this.canvas.width/window.devicePixelRatio,this.canvas.height/window.devicePixelRatio,{offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,zoom:this.state.zoom},this.scene.getNonDeletedElementsMap(),this.getEditorUIOffsets())&&this.scrollToContent(p,{animate:!0,duration:300,canvasOffsets:this.getEditorUIOffsets()})}return}}}if(o[oe.CTRL_OR_CMD]&&o.key===oe.P&&!o.shiftKey&&!o.altKey){this.setToast({message:f("commandPalette.shortcutHint",{shortcut:Ke("commandPalette")})}),o.preventDefault();return}if(o[oe.CTRL_OR_CMD]&&o.key.toLowerCase()===oe.V&&(jx=o.shiftKey,clearTimeout(aP),aP=window.setTimeout(()=>{jx=!1},100)),o[oe.CTRL_OR_CMD]&&kd(o.target)&&(o.code===g6.MINUS||o.code===g6.EQUAL)){o.preventDefault();return}if(kd(o.target)&&o.key!==oe.ESCAPE||wg(o.key)&&T6(o.target))return;if(o.key===oe.QUESTION_MARK){this.setState({openDialog:{name:"help"}});return}else if(o.key.toLowerCase()===oe.E&&o.shiftKey&&o[oe.CTRL_OR_CMD]){o.preventDefault(),this.setState({openDialog:{name:"imageExport"}});return}if(o.key===oe.PAGE_UP||o.key===oe.PAGE_DOWN){let s=(o.shiftKey?this.state.width:this.state.height)/this.state.zoom.value;o.key===oe.PAGE_DOWN&&(s=-s),o.shiftKey?this.translateCanvas(l=>({scrollX:l.scrollX+s})):this.translateCanvas(l=>({scrollY:l.scrollY+s}))}if(this.state.openDialog?.name==="elementLinkSelector"||(o.key===oe.ALT&&(Ar("COMPLEX_BINDINGS")?this.handleSkipBindMode():_g({app:this,event:o})),this.actionManager.handleKeyDown(o)))return;let n=this.props.viewModeEnabled===!0;if(!n&&this.state.viewModeEnabled&&o.key===oe.ESCAPE){this.setActiveTool({type:"hand"});return}if(!n&&!o.ctrlKey&&!o.altKey&&!o.metaKey&&!this.state.newElement&&!this.state.selectionElement&&!this.state.selectedElementsAreBeingDragged){let s=yC(o.key,this);if(this.state.viewModeEnabled&&!S6(s,["laser","hand"]))return;if(s){this.state.activeTool.type!==s&&ge("toolbar",s,`keyboard (${this.editorInterface.formFactor==="phone"?"mobile":"desktop"})`),s==="arrow"&&this.state.activeTool.type==="arrow"&&this.setState(l=>({currentItemArrowType:l.currentItemArrowType===ki.sharp?ki.round:l.currentItemArrowType===ki.round?ki.elbow:ki.sharp})),s==="lasso"&&this.state.activeTool.type==="laser"?this.setActiveTool({type:this.state.preferredSelectionTool.type}):this.setActiveTool({type:s}),o.stopPropagation();return}else if(o.key===oe.Q){this.toggleLock("keyboard"),o.stopPropagation();return}}if(this.state.viewModeEnabled)return;if(o[oe.CTRL_OR_CMD]&&this.state.isBindingEnabled&&(Ar("COMPLEX_BINDINGS")&&this.resetDelayedBindMode(),wo(()=>{this.setState({isBindingEnabled:!1})}),_g({app:this,event:o})),wg(o.key)){let s=this.scene.getSelectedElements({selectedElementIds:this.state.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0}),l=new Set;s.filter(d=>or(d)).filter(d=>{let u=d.startBinding&&!s.some(g=>g.id===d.startBinding?.elementId),h=d.endBinding&&!s.some(g=>g.id===d.endBinding?.elementId);return u||h}).forEach(d=>l.add(d.id)),s=s.filter(d=>!l.has(d.id));let c=this.getEffectiveGridSize()&&(o.shiftKey?E6:this.getEffectiveGridSize())||(o.shiftKey?tj:E6),m=0,p=0;o.key===oe.ARROW_LEFT?m=-c:o.key===oe.ARROW_RIGHT?m=c:o.key===oe.ARROW_UP?p=-c:o.key===oe.ARROW_DOWN&&(p=c),s.forEach(d=>{this.scene.mutateElement(d,{x:d.x+m,y:d.y+p},{informMutation:!1,isDragging:!1}),Pg(d,this.scene,{simultaneouslyUpdated:s})}),this.scene.triggerUpdate(),o.preventDefault()}else if(o.key===oe.ENTER){let s=this.scene.getSelectedElements(this.state);if(s.length===1){let l=s[0];if(o[oe.CTRL_OR_CMD]||Wx(l))so(l)&&(!this.state.selectedLinearElement?.isEditing||this.state.selectedLinearElement.elementId!==l.id)&&(this.store.scheduleCapture(),vo(l)||this.actionManager.executeAction(Qs));else if(vn(l)||Qj(l)){let c;vn(l)||(c=l);let m=Fx(l,this.state,this.scene.getNonDeletedElementsMap()),p=m.x,d=m.y;this.startTextEditing({sceneX:p,sceneY:d,container:c}),o.preventDefault();return}else jt(l)&&this.setState({editingFrame:l.id})}}if(o.key===oe.SPACE&&De.pointers.size===0&&(Pi=!0,Ne(this.interactiveCanvas,st.GRAB),o.preventDefault()),(o.key===oe.G||o.key===oe.S)&&!o.altKey&&!o[oe.CTRL_OR_CMD]){let s=this.scene.getSelectedElements(this.state);if(this.state.activeTool.type==="selection"&&!s.length)return;o.key===oe.G&&(kn(this.state.activeTool.type)||s.some(l=>kn(l.type)))&&(this.setState({openPopup:"elementBackground"}),o.stopPropagation()),o.key===oe.S&&(this.setState({openPopup:"elementStroke"}),o.stopPropagation())}if(!o[oe.CTRL_OR_CMD]&&o.shiftKey&&o.key.toLowerCase()===oe.F){let s=this.scene.getSelectedElements(this.state);if(this.state.activeTool.type==="selection"&&!s.length)return;(this.state.activeTool.type==="text"||s.find(l=>vn(l)||Bx(l,this.scene.getNonDeletedElementsMap())))&&(o.preventDefault(),this.setState({openPopup:"fontFamily"}))}o[oe.CTRL_OR_CMD]&&(o.key===oe.BACKSPACE||o.key===oe.DELETE)&&this.updateEditorAtom(ta,"clearCanvas");let r=o.key.toLocaleLowerCase(),i=r===oe.S&&o.shiftKey,a=o.key===oe.I||r===oe.G&&o.shiftKey;(i||a)&&this.openEyeDropper({type:i?"stroke":"background"})}));A(this,"onKeyUp",mt(o=>{if(o.key===oe.SPACE&&(this.state.viewModeEnabled&&this.state.activeTool.type!=="laser"||this.state.openDialog?.name==="elementLinkSelector"?Ne(this.interactiveCanvas,st.GRAB):Sg(this.state.activeTool.type)?ko(this.interactiveCanvas):(So(this.interactiveCanvas,this.state),this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null})),Pi=!1),o.key===oe.ALT&&_g({app:this,event:o}),(o.key===oe.ALT&&this.state.bindMode==="skip"||!o[oe.CTRL_OR_CMD]&&!Md(this.state))&&(this.setState({bindMode:"orbit"}),this.lastPointerMoveEvent&&Ar("COMPLEX_BINDINGS"))){let n=ot({clientX:this.lastPointerMoveEvent.clientX,clientY:this.lastPointerMoveEvent.clientY},this.state),r=wn(de(n.x,n.y),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap());if(this.state.selectedLinearElement){let i=Me.getElement(this.state.selectedLinearElement.elementId,this.scene.getNonDeletedElementsMap());or(i)&&this.handleDelayedBindModeChange(i,r)}}if(!o[oe.CTRL_OR_CMD]&&!this.state.isBindingEnabled&&(wo(()=>{this.setState({isBindingEnabled:!0})}),_g({app:this,event:o})),wg(o.key)){M6(this.scene.getSelectedElements(this.state).filter(Al),this.scene,this.state);let n=this.scene.getNonDeletedElementsMap();this.scene.getSelectedElements(this.state).filter(Yx).forEach(r=>{r.startBinding&&this.scene.mutateElement(r,{startBinding:{...r.startBinding,...nP(r,n.get(r.startBinding.elementId),"start",n)}}),r.endBinding&&this.scene.mutateElement(r,{endBinding:{...r.endBinding,...nP(r,n.get(r.endBinding.elementId),"end",n)}})}),this.setState({suggestedBinding:null})}if(o.altKey||this.flowChartNavigator.isExploring&&(this.flowChartNavigator.clear(),this.syncActionResult({captureUpdate:lo.IMMEDIATELY})),!o[oe.CTRL_OR_CMD]&&this.flowChartCreator.isCreatingChart){this.flowChartCreator.pendingNodes?.length&&this.scene.insertElements(this.flowChartCreator.pendingNodes);let n=this.flowChartCreator.pendingNodes?.[0];n&&(this.setState(r=>({selectedElementIds:Oe({[n.id]:!0},r)})),Rx([n],this.canvas.width/window.devicePixelRatio,this.canvas.height/window.devicePixelRatio,{offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,zoom:this.state.zoom},this.scene.getNonDeletedElementsMap(),this.getEditorUIOffsets())||this.scrollToContent(n,{animate:!0,duration:300,canvasOffsets:this.getEditorUIOffsets()})),this.flowChartCreator.clear(),this.syncActionResult({captureUpdate:lo.IMMEDIATELY})}}));A(this,"isToolSupported",o=>this.props.UIOptions.tools?.[o]!==!1);A(this,"setActiveTool",(o,n=!1)=>{if(!this.isToolSupported(o.type)){console.warn(`"${o.type}" tool is disabled via "UIOptions.canvasActions.tools.${o.type}"`);return}let r=er(this.state,o);r.type==="hand"?Ne(this.interactiveCanvas,st.GRAB):Pi||So(this.interactiveCanvas,{...this.state,activeTool:r}),bj(document.activeElement)&&this.focusContainer(),Vj(r.type)||this.setState({suggestedBinding:null}),r.type==="image"&&this.onImageToolbarButtonClick(),this.setState(i=>{let a={snapLines:i.snapLines.length?[]:i.snapLines,originSnapOffset:null,activeEmbeddable:null,selectedLinearElement:Sg(r.type)?i.selectedLinearElement:null};return r.type==="freedraw"&&this.store.scheduleCapture(),r.type==="lasso"?{...i,...a,activeTool:r,...n?{}:{selectedElementIds:Oe({},i),selectedGroupIds:Oe({},i),editingGroupId:null,multiElement:null}}:r.type!=="selection"?{...i,...a,activeTool:r,selectedElementIds:Oe({},i),selectedGroupIds:Oe({},i),editingGroupId:null,multiElement:null}:{...i,...a,activeTool:r}})});A(this,"setOpenDialog",o=>{this.setState({openDialog:o})});A(this,"setCursor",o=>{Ne(this.interactiveCanvas,o)});A(this,"resetCursor",()=>{ko(this.interactiveCanvas)});A(this,"isTouchScreenMultiTouchGesture",()=>De.pointers.size>=2);A(this,"getName",()=>this.state.name||this.props.name||`${f("labels.untitled")}-${C6()}`);A(this,"onGestureStart",mt(o=>{o.preventDefault(),this.isTouchScreenMultiTouchGesture()&&this.setState({selectedElementIds:Oe({},this.state),activeEmbeddable:null}),De.initialScale=this.state.zoom.value}));A(this,"onGestureChange",mt(o=>{if(o.preventDefault(),this.isTouchScreenMultiTouchGesture())return;let n=De.initialScale;n&&this.setState(r=>({...pr({viewportX:this.lastViewportPosition.x,viewportY:this.lastViewportPosition.y,nextZoom:Cn(n*o.scale)},r)}))}));A(this,"onGestureEnd",mt(o=>{o.preventDefault(),this.isTouchScreenMultiTouchGesture()&&this.setState({previousSelectedElementIds:{},selectedElementIds:Oe(this.state.previousSelectedElementIds,this.state)}),De.initialScale=null}));A(this,"startTextEditing",({sceneX:o,sceneY:n,insertAtParentCenter:r=!0,container:i,autoEdit:a=!0})=>{let s=!1,l=r&&this.getTextWysiwygSnappedToCenterPosition(o,n,this.state,i);i&&l&&(Bx(i,this.scene.getNonDeletedElementsMap())||(s=!0));let c=null,m=this.scene.getSelectedElements(this.state);m.length===1?vn(m[0])?c=m[0]:i?c=Bx(m[0],this.scene.getNonDeletedElementsMap()):c=this.getTextElementAtPosition(o,n):c=this.getTextElementAtPosition(o,n);let p=c?.fontFamily||this.state.currentItemFontFamily,d=c?.lineHeight||v6(p),u=this.state.currentItemFontSize;if(!c&&s&&i&&!Al(i)){let w=yq(Tx({fontSize:u,fontFamily:p}),d),x=wq(u,d),y=Math.max(i.height,x),v=Math.max(i.width,w);this.scene.mutateElement(i,{height:y,width:v}),o=i.x+v/2,n=i.y+y/2,l&&(l=this.getTextWysiwygSnappedToCenterPosition(o,n,this.state,i))}let h=this.getTopLayerFrameAtSceneCoords({x:o,y:n}),g=c||_6({x:l?l.elementCenterX:o,y:l?l.elementCenterY:n,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,text:"",fontSize:u,fontFamily:p,textAlign:l?"center":this.state.currentItemTextAlign,verticalAlign:l?cj.MIDDLE:b6,containerId:s?i?.id:void 0,groupIds:i?.groupIds??[],lineHeight:d,angle:i?Al(i)?0:i.angle:0,frameId:h?h.id:null});if(!c&&s&&i&&this.scene.mutateElement(i,{boundElements:(i.boundElements||[]).concat({type:"text",id:g.id})}),this.setState({editingTextElement:g}),!c)if(i&&s){let E=this.scene.getElementIndex(i.id);this.scene.insertElementAtIndex(g,E+1)}else this.scene.insertElement(g);a||c||i?this.handleTextWysiwyg(g,{isExistingElement:!!c}):this.setState({newElement:g,multiElement:null})});A(this,"startImageCropping",o=>{this.store.scheduleCapture(),this.setState({croppingElementId:o.id})});A(this,"finishImageCropping",()=>{this.state.croppingElementId&&(this.store.scheduleCapture(),this.setState({croppingElementId:null}))});A(this,"handleCanvasDoubleClick",o=>{if(this.state.multiElement||this.state.activeTool.type!==this.state.preferredSelectionTool.type)return;let n=this.scene.getSelectedElements(this.state),{x:r,y:i}=ot(o,this.state);if(n.length===1&&so(n[0])){let s=n[0];if((o[oe.CTRL_OR_CMD]&&Yx(s)||Wx(s))&&(!this.state.selectedLinearElement?.isEditing||this.state.selectedLinearElement.elementId!==s.id)){this.actionManager.executeAction(Qs);return}else if(this.state.selectedLinearElement&&vo(n[0])){let l=Me.getSegmentMidpointHitCoords(this.state.selectedLinearElement,{x:r,y:i},this.state,this.scene.getNonDeletedElementsMap()),c=l?Me.getSegmentMidPointIndex(this.state.selectedLinearElement,this.state,l,this.scene.getNonDeletedElementsMap()):-1;if(c&&c>-1){this.store.scheduleCapture(),Me.deleteFixedSegment(n[0],this.scene,c);let m=Me.getSegmentMidpointHitCoords({...this.state.selectedLinearElement,segmentMidPointHoveredCoords:null},{x:r,y:i},this.state,this.scene.getNonDeletedElementsMap()),p=m?Me.getSegmentMidPointIndex(this.state.selectedLinearElement,this.state,m,this.scene.getNonDeletedElementsMap()):null;this.setState({selectedLinearElement:{...this.state.selectedLinearElement,initialState:{...this.state.selectedLinearElement.initialState,segmentMidpoint:{index:p,value:l,added:!1}},segmentMidPointHoveredCoords:m}});return}}else if(this.state.selectedLinearElement?.isEditing&&this.state.selectedLinearElement.elementId===s.id&&Wx(s))return}if(n.length===1&&Mi(n[0])){this.startImageCropping(n[0]);return}if(ko(this.interactiveCanvas),kq(this.state).length>0){let s=this.getElementAtPosition(r,i),l=s&&Cq(s,this.state.selectedGroupIds);if(l){this.store.scheduleCapture(),this.setState(c=>({...c,...nn({editingGroupId:l,selectedElementIds:{[s.id]:!0}},this.scene.getNonDeletedElements(),c,this)}));return}}if(ko(this.interactiveCanvas),!o[oe.CTRL_OR_CMD]&&!this.state.viewModeEnabled){let s=this.getElementAtPosition(r,i);if(Lx(s)){this.setState({activeEmbeddable:{element:s,state:"active"}});return}if(!this.state.selectedLinearElement?.isEditing){let l=this.getTextBindableContainerAtPosition(r,i);if(l&&(R6(l)||!Ej(l.backgroundColor)||Ad({point:de(r,i),element:l,elementsMap:this.scene.getNonDeletedElementsMap(),threshold:this.getElementHitThreshold(l)}))){let c=Fx(l,this.state,this.scene.getNonDeletedElementsMap());r=c.x,i=c.y}this.startTextEditing({sceneX:r,sceneY:i,insertAtParentCenter:!o.altKey,container:l})}}});A(this,"getElementLinkAtPosition",(o,n)=>{if(n&&n.locked)return;let r=this.scene.getNonDeletedElements(),i=-1;for(let a=r.length-1;a>=0;a--){let s=r[a];if(n&&s.id===n.id&&(i=a),s.link&&a>=i&&jd(s,this.scene.getNonDeletedElementsMap(),this.state,de(o.x,o.y),this.editorInterface.formFactor==="phone"))return s}});A(this,"handleElementLinkClick",o=>{let n=Ti(de(this.lastPointerDownEvent.clientX,this.lastPointerDownEvent.clientY),de(this.lastPointerUpEvent.clientX,this.lastPointerUpEvent.clientY));if(!this.hitLinkElement||n>x6)return;let r=ot(this.lastPointerDownEvent,this.state),i=this.scene.getNonDeletedElementsMap(),a=jd(this.hitLinkElement,i,this.state,de(r.x,r.y),this.editorInterface.formFactor==="phone"),s=ot(this.lastPointerUpEvent,this.state),l=jd(this.hitLinkElement,i,this.state,de(s.x,s.y),this.editorInterface.formFactor==="phone");if(a&&l){tb();let c=this.hitLinkElement.link;if(c){c=Ix(c);let m;if(this.props.onLinkOpen&&(m=xj(ue.EXCALIDRAW_LINK,o.nativeEvent),this.props.onLinkOpen({...this.hitLinkElement,link:c},m)),!m?.defaultPrevented){let p=gj(c)?"_self":"_blank",d=window.open(void 0,p);d&&(d.opener=null,d.location=c)}}}});A(this,"getTopLayerFrameAtSceneCoords",o=>{let n=this.scene.getNonDeletedElementsMap(),r=this.scene.getNonDeletedFramesLikes().filter(i=>!i.locked&&U6(o,i,n));return r.length?r[r.length-1]:null});A(this,"handleCanvasPointerMove",o=>{this.savePointer(o.clientX,o.clientY,this.state.cursorButton),this.lastPointerMoveEvent=o.nativeEvent;let n=ot(o,this.state),{x:r,y:i}=n;this.lastPointerMoveCoords={x:r,y:i},De.pointers.has(o.pointerId)&&De.pointers.set(o.pointerId,{x:o.clientX,y:o.clientY});let a=De.initialScale;if(De.pointers.size===2&&De.lastCenter&&a&&De.initialDistance){let g=f0(De.pointers),E=g.x-De.lastCenter.x,w=g.y-De.lastCenter.y;De.lastCenter=g;let x=b0(Array.from(De.pointers.values())),y=this.state.activeTool.type==="freedraw"&&this.state.penMode?1:x/De.initialDistance,v=y?Cn(a*y):this.state.zoom.value;this.setState(I=>{let k=pr({viewportX:g.x,viewportY:g.y,nextZoom:v},I);return this.translateCanvas({zoom:k.zoom,scrollX:k.scrollX+2*(E/v),scrollY:k.scrollY+2*(w/v),shouldCacheIgnoreZoom:!0}),null}),this.resetShouldCacheIgnoreZoomDebounced()}else De.lastCenter=De.initialDistance=De.initialScale=null;if(Pi||Rd||Xx||sr(this.state))return;let l=V0(Nd,o.clientX-this.state.offsetLeft,o.clientY-this.state.offsetTop).isOverEither;if(!this.state.newElement&&!this.state.selectionElement&&!this.state.selectedElementsAreBeingDragged&&!this.state.multiElement&&(l?ko(this.interactiveCanvas):So(this.interactiveCanvas,this.state)),!this.state.newElement&&J5(this.state.activeTool.type)){let{originOffset:g,snapLines:E}=q5(this.scene.getNonDeletedElements(),this,{x:r,y:i},o,this.scene.getNonDeletedElementsMap());this.setState(w=>{let x=Sd(w.snapLines,E),y=w.originSnapOffset?Sd(w.originSnapOffset,g):g;return w.snapLines===x&&w.originSnapOffset===y?null:{snapLines:x,originSnapOffset:y}})}else!this.state.newElement&&!this.state.selectedElementsAreBeingDragged&&!this.state.selectionElement&&this.setState(g=>g.snapLines.length?{snapLines:[]}:null);if(this.state.selectedLinearElement?.isEditing&&!this.state.selectedLinearElement.isDragging){let g=this.state.newElement?null:Me.handlePointerMoveInEditMode(o,r,i,this);g&&g!==this.state.selectedLinearElement&&wo(()=>{this.setState({selectedLinearElement:g})})}if(Yj(this.state.activeTool.type)){let{newElement:g}=this.state;if(!g&&Md(this.state)){let E=de(r,i),w=this.scene.getNonDeletedElementsMap(),x=wn(E,this.scene.getNonDeletedElements(),w,Vx(this.state.zoom));x?this.setState({suggestedBinding:{element:x,midPoint:$x(E,x,w,this.state.zoom)}}):this.state.suggestedBinding&&this.setState({suggestedBinding:null})}}if(this.state.multiElement&&this.state.selectedLinearElement){let{multiElement:g,selectedLinearElement:E}=this.state,{x:w,y:x,points:y}=g,v=y[y.length-1],{lastCommittedPoint:I}=E;if(So(this.interactiveCanvas,this.state),v===I)Al(this.state.newElement)&&Md(this.state)&&wn(de(r,i),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap(),Vx(this.state.zoom))?(this.actionManager.executeAction(oo,"ui",{event:o.nativeEvent,sceneCoords:{x:r,y:i}}),this.setState({suggestedBinding:null,startBoundElement:null}),this.state.activeTool.locked||(ko(this.interactiveCanvas),this.setState(L=>({newElement:null,activeTool:er(this.state,{type:this.state.preferredSelectionTool.type}),selectedElementIds:Oe({...L.selectedElementIds,[g.id]:!0},L),selectedLinearElement:new Me(g,this.scene.getNonDeletedElementsMap())})))):Ti(de(r-w,i-x),v)>=vx?(this.scene.mutateElement(g,{points:[...y,de(r-w,i-x)]},{informMutation:!1,isDragging:!1}),tr(this.state.selectedLinearElement?.initialState,"initialState must be set"),this.setState({selectedLinearElement:{...this.state.selectedLinearElement,lastCommittedPoint:y[y.length-1],selectedPointsIndices:[g.points.length-1],initialState:{...this.state.selectedLinearElement.initialState,lastClickedPoint:g.points.length-1}}})):Ne(this.interactiveCanvas,st.POINTER);else if(y.length>2&&I&&Ti(de(r-w,i-x),I)<vx)Ne(this.interactiveCanvas,st.POINTER),this.scene.mutateElement(g,{points:y.slice(0,-1)},{informMutation:!1,isDragging:!1}),this.setState({selectedLinearElement:{...E,selectedPointsIndices:E.selectedPointsIndices?.includes(g.points.length)?[...E.selectedPointsIndices.filter(k=>k!==g.points.length&&k!==g.points.length-1),g.points.length-1]:E.selectedPointsIndices,lastCommittedPoint:g.points[g.points.length-1],initialState:{...E.initialState,lastClickedPoint:g.points.length-1}}});else{O6(y,this.state.zoom.value)&&Ne(this.interactiveCanvas,st.POINTER);let k=this.scene.getNonDeletedElementsMap();if(Yx(g)){let S=wn(de(r,i),this.scene.getNonDeletedElements(),k);Ar("COMPLEX_BINDINGS")&&this.handleDelayedBindModeChange(g,S)}tr(this.state.selectedLinearElement,"Expected selectedLinearElement to be set to operate on a linear element");let L=Me.handlePointerMove(o.nativeEvent,this,r,i,this.state.selectedLinearElement);L&&this.setState(L)}return}if(this.state.activeTool.type==="arrow"){let g=wn(de(r,i),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap(),Vx(this.state.zoom)),E=de(r,i),w=this.scene.getNonDeletedElementsMap();g&&!zq(E,g,w)&&this.setState({suggestedBinding:{element:g,midPoint:$x(E,g,w,this.state.zoom)}})}let c=!!o.buttons,m=this.state.activeTool.type==="laser";if(c||!m&&this.state.activeTool.type!=="selection"&&this.state.activeTool.type!=="lasso"&&this.state.activeTool.type!=="text"&&this.state.activeTool.type!=="eraser")return;let p=this.scene.getNonDeletedElements(),d=this.scene.getSelectedElements(this.state);if(d.length===1&&!l&&!this.state.selectedLinearElement?.isEditing){if(this.state.selectedLinearElement&&this.handleHoverSelectedLinearElement(this.state.selectedLinearElement,r,i),(!this.state.selectedLinearElement||this.state.selectedLinearElement.hoverPointIndex===-1)&&this.state.openDialog?.name!=="elementLinkSelector"&&!(d.length===1&&vo(d[0]))&&!(so(d[0])&&(this.editorInterface.userAgent.isMobileDevice||d[0].points.length===2))){let g=j6(p,this.state,r,i,this.state.zoom,o.pointerType,this.scene.getNonDeletedElementsMap(),this.editorInterface);if(g&&g.transformHandleType){Ne(this.interactiveCanvas,Z6(g));return}}}else if(d.length>1&&!l&&this.state.openDialog?.name!=="elementLinkSelector"){let g=q6(Pl(d),r,i,this.state.zoom,o.pointerType,this.editorInterface);if(g){Ne(this.interactiveCanvas,Z6({transformHandleType:g}));return}}if(po(this.state))return;let u=this.getElementAtPosition(r,i,{preferSelected:!0,includeLockedElements:!0}),h=null;if(u&&u.locked?h=null:h=u,this.handleIframeLikeElementHover({hitElement:h,scenePointer:n,moveEvent:o})||(this.hitLinkElement=this.getElementLinkAtPosition(n,u)),this.hitLinkElement&&!this.state.selectedElementIds[this.hitLinkElement.id])Ne(this.interactiveCanvas,st.POINTER),YI(this.hitLinkElement,this.state,this.scene.getNonDeletedElementsMap());else{if(tb(),m)return;h&&(h.link||Lr(h))&&this.state.selectedElementIds[h.id]&&!this.state.contextMenu&&!this.state.showHyperlinkPopup?this.setState({showHyperlinkPopup:"info"}):this.state.activeTool.type==="text"?Ne(this.interactiveCanvas,vn(h)?st.TEXT:st.CROSSHAIR):this.state.viewModeEnabled?Ne(this.interactiveCanvas,st.GRAB):this.state.openDialog?.name==="elementLinkSelector"?Ne(this.interactiveCanvas,st.AUTO):l?Ne(this.interactiveCanvas,st.AUTO):o[oe.CTRL_OR_CMD]?Ne(this.interactiveCanvas,st.AUTO):(h||this.isHittingCommonBoundingBoxOfSelectedElements(n,d))&&!h?.locked&&(!h||!vo(h)||!(h.startBinding||h.endBinding))&&(this.state.activeTool.type!=="lasso"||d.length>0)&&Ne(this.interactiveCanvas,st.MOVE),this.state.selectedLinearElement&&this.handleHoverSelectedLinearElement(this.state.selectedLinearElement,r,i)}this.state.openDialog?.name==="elementLinkSelector"&&h?this.setState(g=>({hoveredElementIds:Sd(g.hoveredElementIds,nn({editingGroupId:g.editingGroupId,selectedElementIds:{[h.id]:!0}},this.scene.getNonDeletedElements(),g,this).selectedElementIds)})):this.state.openDialog?.name==="elementLinkSelector"&&!h&&this.setState(g=>({hoveredElementIds:Sd(g.hoveredElementIds,{})}))});A(this,"handleEraser",(o,n)=>{let r=this.eraserTrail.addPointToPath(n.x,n.y,o.altKey);this.elementsPendingErasure=new Set(r),this.triggerRender()});A(this,"handleTouchMove",o=>{Bd=!0});A(this,"handleCanvasPointerDown",o=>{let n=ot(o,this.state),{x:r,y:i}=n;this.lastPointerMoveCoords={x:r,y:i};let a=o.target;if(a.setPointerCapture&&a.setPointerCapture(o.pointerId),this.maybeCleanupAfterMissingPointerUp(o.nativeEvent),this.maybeUnfollowRemoteUser(),this.state.searchMatches&&(this.setState(h=>({searchMatches:h.searchMatches&&{focusedId:null,matches:h.searchMatches.matches.map(g=>({...g,focus:!1}))}})),this.updateEditorAtom(I1,null)),xt.get(gn)&&this.updateEditorAtom(gn,null),this.state.contextMenu&&this.setState({contextMenu:null}),this.state.snapLines&&this.setAppState({snapLines:[]}),this.state.openPopup&&this.setState({openPopup:null}),this.updateGestureOnPointerDown(o),o.pointerType==="touch"&&this.state.newElement&&this.state.newElement.type==="freedraw"){let h=this.state.newElement;this.updateScene({...h.points.length<10?{elements:this.scene.getElementsIncludingDeleted().filter(g=>g.id!==h.id)}:{},appState:{newElement:null,editingTextElement:null,startBoundElement:null,suggestedBinding:null,selectedElementIds:Oe(Object.keys(this.state.selectedElementIds).filter(g=>g!==h.id).reduce((g,E)=>(g[E]=this.state.selectedElementIds[E],g),{}),this.state)},captureUpdate:this.state.openDialog?.name==="elementLinkSelector"?lo.EVENTUALLY:lo.NEVER});return}let s=document.getSelection();if(s?.anchorNode&&s.removeAllRanges(),this.maybeOpenContextMenuAfterPointerDownOnTouchDevices(o),!this.state.penDetected&&o.pointerType==="pen"&&this.setState(h=>({penMode:!0,penDetected:!0})),!this.editorInterface.isTouchScreen&&["pen","touch"].includes(o.pointerType)&&(this.editorInterface=kx(this.editorInterface,{isTouchScreen:!0})),Rd||(this.lastPointerDownEvent=o,this.handleCanvasPanUsingWheelOrSpaceDrag(o)))return;if(this.setState({lastPointerDownWith:o.pointerType,cursorButton:"down"}),this.savePointer(o.clientX,o.clientY,"down"),o.button===Ci.ERASER&&this.state.activeTool.type!==Qn.eraser){this.setState({activeTool:er(this.state,{type:Qn.eraser,lastActiveToolBeforeEraser:this.state.activeTool})},()=>{this.handleCanvasPointerDown(o);let h=()=>{g(),E?.(),po(this.state)&&this.setState({activeTool:er(this.state,{...this.state.activeTool.lastActiveTool||{type:Qn.selection},lastActiveToolBeforeEraser:null})})},g=gt(window,ue.POINTER_UP,h,{once:!0}),E;requestAnimationFrame(()=>{E=this.missingPointerEventCleanupEmitter.once(h)})});return}if(o.button!==Ci.MAIN&&o.button!==Ci.TOUCH&&o.button!==Ci.ERASER||De.pointers.size>1)return;let l=this.initialPointerDownState(o);if(this.setState({selectedElementsAreBeingDragged:!1}),this.handleDraggingScrollBar(o,l)||(this.clearSelectionIfNotUsingSelection(),this.updateBindingEnabledOnPointerMove(o),this.handleSelectionOnPointerDown(o,l))||!(!this.state.penMode||o.pointerType!=="touch"||this.state.activeTool.type==="selection"||this.state.activeTool.type==="lasso"||this.state.activeTool.type==="text"||this.state.activeTool.type==="image"))return;if(this.state.activeTool.type==="lasso"){let h=l.hit.element&&this.isASelectedElement(l.hit.element);!l.hit.hasHitCommonBoundingBoxOfSelectedElements&&!l.resize.handleType&&!h&&(this.lassoTrail.startPath(l.origin.x,l.origin.y,o.shiftKey),l.drag.blockDragging=this.editorInterface.formFactor==="desktop"),this.editorInterface.formFactor!=="desktop"&&l.hit.element&&!h&&(this.setState(g=>{let E={...g.selectedElementIds,[l.hit.element.id]:!0},w=[];Object.keys(g.selectedElementIds).forEach(y=>{let v=this.scene.getElement(y);v&&w.push(v)});let x=l.hit.element;if(jt(x))Ox(w,x.id).forEach(y=>{delete E[y.id]});else if(x.frameId)E[x.frameId]&&delete E[x.id];else{let y=x.groupIds,v=new Set(y.flatMap(I=>Ca(this.scene.getNonDeletedElements(),I)).filter(I=>jt(I)).map(I=>I.id));v.size>0&&w.forEach(I=>{I.frameId&&v.has(I.frameId)&&(delete E[I.id],I.groupIds.flatMap(k=>Ca(this.scene.getNonDeletedElements(),k)).forEach(k=>{delete E[k.id]}))})}return{...nn({editingGroupId:g.editingGroupId,selectedElementIds:E},this.scene.getNonDeletedElements(),g,this),showHyperlinkPopup:x.link||Lr(x)?"info":!1}}),l.hit.wasAddedToSelection=!0)}else this.state.activeTool.type==="text"?this.handleTextOnPointerDown(o,l):this.state.activeTool.type==="arrow"||this.state.activeTool.type==="line"?this.handleLinearElementOnPointerDown(o,this.state.activeTool.type,l):this.state.activeTool.type==="freedraw"?this.handleFreeDrawElementOnPointerDown(o,this.state.activeTool.type,l):this.state.activeTool.type==="custom"?So(this.interactiveCanvas,this.state):this.state.activeTool.type===Qn.frame||this.state.activeTool.type===Qn.magicframe?this.createFrameElementOnPointerDown(l,this.state.activeTool.type):this.state.activeTool.type==="laser"?this.laserTrails.startPath(l.lastCoords.x,l.lastCoords.y):this.state.activeTool.type!=="eraser"&&this.state.activeTool.type!=="hand"&&this.state.activeTool.type!=="image"&&this.createGenericElementOnPointerDown(this.state.activeTool.type,l);this.props?.onPointerDown?.(this.state.activeTool,l),this.onPointerDownEmitter.trigger(this.state.activeTool,l,o),this.state.activeTool.type==="eraser"&&this.eraserTrail.startPath(l.lastCoords.x,l.lastCoords.y);let m=this.onPointerMoveFromPointerDownHandler(l),p=this.onPointerUpFromPointerDownHandler(l),d=this.onKeyDownFromPointerDownHandler(l),u=this.onKeyUpFromPointerDownHandler(l);this.missingPointerEventCleanupEmitter.once(h=>p(h||o.nativeEvent)),(!this.state.viewModeEnabled||this.state.activeTool.type==="laser")&&(window.addEventListener(ue.POINTER_MOVE,m),window.addEventListener(ue.POINTER_UP,p),window.addEventListener(ue.KEYDOWN,d),window.addEventListener(ue.KEYUP,u),l.eventListeners.onMove=m,l.eventListeners.onUp=p,l.eventListeners.onKeyUp=u,l.eventListeners.onKeyDown=d)});A(this,"handleCanvasPointerUp",o=>{Ar("COMPLEX_BINDINGS")&&this.resetDelayedBindMode(),this.removePointer(o),this.lastPointerUpEvent=o;let n=ot({clientX:o.clientX,clientY:o.clientY},this.state),{x:r,y:i}=n;if(this.lastPointerMoveCoords={x:r,y:i},!this.handleIframeLikeCenterClick()){if(this.editorInterface.isTouchScreen){let a=this.getElementAtPosition(n.x,n.y,{includeLockedElements:!0});this.hitLinkElement=this.getElementLinkAtPosition(n,a)}this.hitLinkElement&&!this.state.selectedElementIds[this.hitLinkElement.id]?this.handleElementLinkClick(o):this.state.viewModeEnabled&&this.setState({activeEmbeddable:null,selectedElementIds:{}})}});A(this,"maybeOpenContextMenuAfterPointerDownOnTouchDevices",o=>{o.pointerType==="touch"&&(Bd=!1,Ai?Bd=!0:Ai=window.setTimeout(()=>{Ai=0,Bd||this.handleCanvasContextMenu(o)},lj))});A(this,"resetContextMenuTimer",()=>{clearTimeout(Ai),Ai=0,Bd=!1});A(this,"maybeCleanupAfterMissingPointerUp",o=>{Fd?.(),this.missingPointerEventCleanupEmitter.trigger(o).clear()});A(this,"handleCanvasPanUsingWheelOrSpaceDrag",o=>{if(!(De.pointers.size<=1&&(o.button===Ci.WHEEL||o.button===Ci.MAIN&&Pi||sr(this.state)||this.state.viewModeEnabled&&this.state.activeTool.type!=="laser")))return!1;Rd=!0,this.focusContainer(),this.state.editingTextElement||o.preventDefault();let n=!1,r=typeof window===void 0?!1:/Linux/.test(window.navigator.platform);Ne(this.interactiveCanvas,st.GRABBING);let{clientX:i,clientY:a}=o,s=Su(c=>{let m=i-c.clientX,p=a-c.clientY;if(i=c.clientX,a=c.clientY,r&&!n&&(Math.abs(m)>1||Math.abs(p)>1)){n=!0;let d=h=>{document.body.removeEventListener(ue.PASTE,d),h.stopPropagation()},u=()=>{setTimeout(()=>{document.body.removeEventListener(ue.PASTE,d),window.removeEventListener(ue.POINTER_UP,u)},100)};document.body.addEventListener(ue.PASTE,d),window.addEventListener(ue.POINTER_UP,u)}this.translateCanvas({scrollX:this.state.scrollX-m/this.state.zoom.value,scrollY:this.state.scrollY-p/this.state.zoom.value})}),l=mt(Fd=()=>{Fd=null,Rd=!1,Pi||(this.state.viewModeEnabled&&this.state.activeTool.type!=="laser"?Ne(this.interactiveCanvas,st.GRAB):So(this.interactiveCanvas,this.state)),this.setState({cursorButton:"up"}),this.savePointer(o.clientX,o.clientY,"up"),window.removeEventListener(ue.POINTER_MOVE,s),window.removeEventListener(ue.POINTER_UP,l),window.removeEventListener(ue.BLUR,l),s.flush()});return window.addEventListener(ue.BLUR,l),window.addEventListener(ue.POINTER_MOVE,s,{passive:!0}),window.addEventListener(ue.POINTER_UP,l),!0});A(this,"clearSelectionIfNotUsingSelection",()=>{Sg(this.state.activeTool.type)||this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null})});A(this,"handleSelectionOnPointerDown",(o,n)=>{if(Sg(this.state.activeTool.type)){let r=this.scene.getNonDeletedElements(),i=this.scene.getNonDeletedElementsMap(),a=this.scene.getSelectedElements(this.state);if(a.length===1&&!this.state.selectedLinearElement?.isEditing&&!vo(a[0])&&!(so(a[0])&&(this.editorInterface.userAgent.isMobileDevice||a[0].points.length===2))&&!(this.state.selectedLinearElement&&this.state.selectedLinearElement.hoverPointIndex!==-1)){let s=j6(r,this.state,n.origin.x,n.origin.y,this.state.zoom,o.pointerType,this.scene.getNonDeletedElementsMap(),this.editorInterface);s!=null&&(s.transformHandleType==="rotation"?(this.setState({resizingElement:s.element}),n.resize.handleType=s.transformHandleType):(this.state.croppingElementId||this.setState({resizingElement:s.element}),n.resize.handleType=s.transformHandleType))}else a.length>1&&(n.resize.handleType=q6(Pl(a),n.origin.x,n.origin.y,this.state.zoom,o.pointerType,this.editorInterface));if(n.resize.handleType)n.resize.isResizing=!0,n.resize.offset=Cx(Aq(n.resize.handleType,a,i,n.origin.x,n.origin.y)),a.length===1&&so(a[0])&&a[0].points.length===2&&(n.resize.arrowDirection=Lq(n.resize.handleType,a[0]));else{if(this.state.selectedLinearElement){let d=this.state.selectedLinearElement,u=Me.handlePointerDown(o,this,this.store,n.origin,d,this.scene);if(u.hitElement&&(n.hit.element=u.hitElement),u.linearElementEditor&&this.setState({selectedLinearElement:u.linearElementEditor}),u.didAddPoint)return!0;let h=this.scene.getNonDeletedElementsMap(),g=Me.getElement(d.elementId,h);if(g&&or(g)){let{hitFocusPoint:E,pointerOffset:w}=Uq(g,n,h,this.state);if(E)return this.setState({selectedLinearElement:{...d,hoveredFocusPointBinding:E,draggedFocusPointBinding:E,pointerOffset:w}}),!1}}let s=this.getElementsAtPosition(n.origin.x,n.origin.y,{includeLockedElements:!0}),l=s.filter(d=>!d.locked),c=this.getElementAtPosition(n.origin.x,n.origin.y,{allHitElements:s});if((!c||c.id!==this.state.activeLockedId)&&this.setState({activeLockedId:null}),c&&c.locked&&!l.some(d=>this.state.selectedElementIds[d.id])?n.hit.element=null:n.hit.element=n.hit.element??this.getElementAtPosition(n.origin.x,n.origin.y),this.hitLinkElement=this.getElementLinkAtPosition(n.origin,c),this.hitLinkElement)return!0;if(this.state.croppingElementId&&n.hit.element?.id!==this.state.croppingElementId&&this.finishImageCropping(),n.hit.element&&this.getElementLinkAtPosition({x:n.origin.x,y:n.origin.y},n.hit.element))return!1;n.hit.allHitElements=l;let m=n.hit.element,p=n.hit.allHitElements.some(d=>this.isASelectedElement(d));if((m===null||!p)&&!o.shiftKey&&!n.hit.hasHitCommonBoundingBoxOfSelectedElements&&(!this.state.selectedLinearElement?.isEditing||m&&m?.id!==this.state.selectedLinearElement?.elementId)&&this.clearSelection(m),this.state.selectedLinearElement?.isEditing)this.setState(d=>({selectedLinearElement:d.selectedLinearElement?{...d.selectedLinearElement,isEditing:!!m&&m.id===this.state.selectedLinearElement?.elementId}:null,selectedElementIds:d.selectedLinearElement?Oe({[d.selectedLinearElement.elementId]:!0},this.state):Oe({},d)}));else if(m!=null){if(o[oe.CTRL_OR_CMD])return o.altKey?(this.state.openDialog?.name==="elementLinkSelector"&&this.setOpenDialog(null),this.lassoTrail.startPath(n.origin.x,n.origin.y,o.shiftKey),this.setActiveTool({type:"lasso",fromSelection:!0}),!1):(this.state.selectedElementIds[m.id]||(n.hit.wasAddedToSelection=!0),this.setState(d=>({...Tq(d,m),previousSelectedElementIds:this.state.selectedElementIds})),!1);this.state.selectedElementIds[m.id]||(this.state.editingGroupId&&!K6(m,this.state.editingGroupId)&&this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null}),!p&&!n.hit.hasHitCommonBoundingBoxOfSelectedElements&&(this.setState(d=>{let u={...d.selectedElementIds,[m.id]:!0},h=[];if(Object.keys(d.selectedElementIds).forEach(g=>{let E=this.scene.getElement(g);E&&h.push(E)}),jt(m))Ox(h,m.id).forEach(g=>{delete u[g.id]});else if(m.frameId)u[m.frameId]&&delete u[m.id];else{let g=m.groupIds,E=new Set(g.flatMap(w=>Ca(this.scene.getNonDeletedElements(),w)).filter(w=>jt(w)).map(w=>w.id));E.size>0&&h.forEach(w=>{w.frameId&&E.has(w.frameId)&&(delete u[w.id],w.groupIds.flatMap(x=>Ca(this.scene.getNonDeletedElements(),x)).forEach(x=>{delete u[x.id]}))})}return d.openDialog?.name==="elementLinkSelector"&&(m.groupIds.some(g=>d.selectedGroupIds[g])||(u={[m.id]:!0})),{...nn({editingGroupId:d.editingGroupId,selectedElementIds:u},this.scene.getNonDeletedElements(),d,this),showHyperlinkPopup:m.link||Lr(m)?"info":!1}}),n.hit.wasAddedToSelection=!0))}this.setState({previousSelectedElementIds:this.state.selectedElementIds})}}return!1});A(this,"handleTextOnPointerDown",(o,n)=>{if(this.state.editingTextElement)return;let r=n.origin.x,i=n.origin.y,a=this.getElementAtPosition(r,i,{includeBoundTextElement:!0}),s=this.getTextBindableContainerAtPosition(r,i);R6(a)&&(s=a,r=a.x+a.width/2,i=a.y+a.height/2),this.startTextEditing({sceneX:r,sceneY:i,insertAtParentCenter:!o.altKey,container:s,autoEdit:!1}),ko(this.interactiveCanvas),this.state.activeTool.locked||this.setState({activeTool:er(this.state,{type:this.state.preferredSelectionTool.type})})});A(this,"handleFreeDrawElementOnPointerDown",(o,n,r)=>{let[i,a]=Zt(r.origin.x,r.origin.y,null),s=this.getTopLayerFrameAtSceneCoords({x:i,y:a}),l=o.pressure===.5,c=Oj({type:n,x:i,y:a,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,roundness:null,simulatePressure:l,locked:!1,frameId:s?s.id:null,points:[de(0,0)],pressures:l?[]:[o.pressure]});this.scene.insertElement(c),this.setState(p=>{let d={...p.selectedElementIds};return delete d[c.id],{selectedElementIds:Oe(d,p)}});let m=wn(de(r.origin.x,r.origin.y),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap());this.setState({newElement:c,startBoundElement:m,suggestedBinding:null})});A(this,"insertIframeElement",({sceneX:o,sceneY:n,width:r,height:i})=>{let[a,s]=Zt(o,n,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),l=zj({type:"iframe",x:a,y:s,strokeColor:"transparent",backgroundColor:"transparent",fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,roundness:this.getCurrentItemRoundness("iframe"),opacity:this.state.currentItemOpacity,locked:!1,width:r,height:i});return this.scene.insertElement(l),l});A(this,"insertEmbeddableElement",({sceneX:o,sceneY:n,link:r})=>{let[i,a]=Zt(o,n,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),s=Ag(r);if(!s)return;s.error instanceof URIError&&this.setToast({message:f("toast.unrecognizedLinkFormat"),closable:!0});let l=A6({type:"embeddable",x:i,y:a,strokeColor:"transparent",backgroundColor:"transparent",fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,roundness:this.getCurrentItemRoundness("embeddable"),opacity:this.state.currentItemOpacity,locked:!1,width:s.intrinsicSize.w,height:s.intrinsicSize.h,link:r});return this.scene.insertElement(l),l});A(this,"newImagePlaceholder",({sceneX:o,sceneY:n,addToFrameUnderCursor:r=!0})=>{let[i,a]=Zt(o,n,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),s=r?this.getTopLayerFrameAtSceneCoords({x:i,y:a}):null,l=100/this.state.zoom.value;return Mx({type:"image",strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,roundness:null,opacity:this.state.currentItemOpacity,locked:!1,frameId:s?s.id:null,x:i-l/2,y:a-l/2,width:l,height:l})});A(this,"handleLinearElementOnPointerDown",(o,n,r)=>{if(o.ctrlKey&&wo(()=>{this.setState({isBindingEnabled:!1})}),this.state.multiElement){let{multiElement:i,selectedLinearElement:a}=this.state;if(tr(a,"selectedLinearElement is expected to be set"),i.type==="line"&&O6(i.points,this.state.zoom.value)){wo(()=>{this.setState({selectedLinearElement:{...a,lastCommittedPoint:i.points[i.points.length-1],initialState:{...a.initialState,lastClickedPoint:-1}}})}),this.actionManager.executeAction(oo);return}if(vo(i)&&i.points.length>1){this.actionManager.executeAction(oo,"ui",{event:o.nativeEvent,sceneCoords:{x:r.origin.x,y:r.origin.y}});return}let{x:s,y:l}=i,{lastCommittedPoint:c}=a,m=Md(this.state)&&wn(de(this.lastPointerMoveCoords?.x??s+i.points[i.points.length-1][0],this.lastPointerMoveCoords?.y??l+i.points[i.points.length-1][1]),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap());if(or(i)&&m||i.points.length>1&&c&&Ti(de(r.origin.x-s,r.origin.y-l),c)<vx){this.actionManager.executeAction(oo,"ui",{event:o.nativeEvent,sceneCoords:{x:r.origin.x,y:r.origin.y}});return}this.setState(p=>({selectedElementIds:Oe({...p.selectedElementIds,[i.id]:!0},p)})),Ne(this.interactiveCanvas,st.POINTER)}else{let[i,a]=Zt(r.origin.x,r.origin.y,o[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),s=this.getTopLayerFrameAtSceneCoords({x:i,y:a}),{currentItemStartArrowhead:l,currentItemEndArrowhead:c}=this.state,[m,p]=n==="arrow"?[l,c]:[null,null],d=n==="arrow"?Hj({type:n,x:i,y:a,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,roundness:this.state.currentItemArrowType===ki.round?{type:vg.PROPORTIONAL_RADIUS}:null,startArrowhead:m,endArrowhead:p,locked:!1,frameId:s?s.id:null,elbowed:this.state.currentItemArrowType===ki.elbow,fixedSegments:this.state.currentItemArrowType===ki.elbow?[]:null}):Uj({type:n,x:i,y:a,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,roundness:this.state.currentItemRoundness==="round"?{type:vg.PROPORTIONAL_RADIUS}:null,locked:!1,frameId:s?s.id:null}),u=de(r.origin.x,r.origin.y),h=this.scene.getNonDeletedElementsMap(),g=Md(this.state)?wn(u,this.scene.getNonDeletedElements(),h):null;this.scene.mutateElement(d,{points:[de(0,0),de(0,0)]}),this.scene.insertElement(d),or(d)&&Fq(d,new Map([[0,{point:de(0,0),isDragging:!1}]]),u[0],u[1],this.scene,this.state,{newArrow:!0,altKey:o.altKey,initialBinding:!0,angleLocked:f6(o.nativeEvent)}),wo(()=>{this.setState(E=>{let w=null,x=E.selectedElementIds;if(so(d)){w=new Me(d,this.scene.getNonDeletedElementsMap());let y=d.points.length-1;w={...w,selectedPointsIndices:[y],initialState:{...w.initialState,arrowStartIsInside:o.altKey,lastClickedPoint:y,origin:de(r.origin.x,r.origin.y)}}}return x=this.state.activeTool.locked?E.selectedElementIds:Oe({[d.id]:!0},E),{...E,bindMode:"orbit",newElement:d,startBoundElement:g,suggestedBinding:g&&or(d)?{element:g,midPoint:$x(u,g,h,this.state.zoom)}:null,selectedElementIds:x,selectedLinearElement:w}})}),or(d)&&Ar("COMPLEX_BINDINGS")&&this.handleDelayedBindModeChange(d,g)}});A(this,"createGenericElementOnPointerDown",(o,n)=>{let[r,i]=Zt(n.origin.x,n.origin.y,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),a=this.getTopLayerFrameAtSceneCoords({x:r,y:i}),s={x:r,y:i,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,roundness:this.getCurrentItemRoundness(o),locked:!1,frameId:a?a.id:null},l;o==="embeddable"?l=A6({type:"embeddable",...s}):l=Gj({type:o,...s}),l.type==="selection"?this.setState({selectionElement:l}):(this.scene.insertElement(l),this.setState({multiElement:null,newElement:l}))});A(this,"createFrameElementOnPointerDown",(o,n)=>{let[r,i]=Zt(o.origin.x,o.origin.y,this.lastPointerDownEvent?.[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),a={x:r,y:i,opacity:this.state.currentItemOpacity,locked:!1,...on},s=n===Qn.magicframe?L6(a):P6(a);this.scene.insertElement(s),this.setState({multiElement:null,newElement:s})});A(this,"restoreReadyToEraseElements",()=>{this.elementsPendingErasure=new Set,this.triggerRender()});A(this,"eraseElements",()=>{let o=!1;this.elementsPendingErasure.forEach(r=>{let i=this.scene.getElement(r);if(or(i)){if(i.startBinding){let a=this.scene.getElement(i.startBinding.elementId);Lg(a,this.scene.getElementsMapIncludingDeleted(),{boundElements:a.boundElements.filter(s=>s.id!==i.id)})}if(i.endBinding){let a=this.scene.getElement(i.endBinding.elementId);Lg(a,this.scene.getElementsMapIncludingDeleted(),{boundElements:a.boundElements.filter(s=>s.id!==i.id)})}}else Dx(i)&&i.boundElements?.forEach(a=>{if(a.type==="arrow"){let s=this.scene.getElement(a.id);s?.startBinding?.elementId===i.id&&Lg(s,this.scene.getElementsMapIncludingDeleted(),{startBinding:null}),s?.endBinding?.elementId===i.id&&Lg(s,this.scene.getElementsMapIncludingDeleted(),{endBinding:null})}})});let n=this.scene.getElementsIncludingDeleted().map(r=>this.elementsPendingErasure.has(r.id)||r.frameId&&this.elementsPendingErasure.has(r.frameId)||Ax(r)&&this.elementsPendingErasure.has(r.containerId)?(o=!0,Si(r,{isDeleted:!0})):r);this.elementsPendingErasure=new Set,o&&(this.store.scheduleCapture(),this.scene.replaceAllElements(n))});A(this,"initializeImage",async(o,n)=>{if(!Jg(n))throw new Error(f("errors.unsupportedFileType"));let r=n.type;if(Ne(this.interactiveCanvas,"wait"),r===Jn.svg)try{n=oh(H6(await n.text()),n.name)}catch(l){throw console.warn(l),new Error(f("errors.svgImageInsertError"))}let i=await(this.props.generateIdForFile?.(n)||JE(n));if(!i)throw console.warn("Couldn't generate file id or the supplied `generateIdForFile` didn't resolve to one."),new Error(f("errors.imageInsertError"));if(!this.files[i]?.dataURL){try{n=await tm(n,{maxWidthOrHeight:ej})}catch(l){console.error("Error trying to resizing image file on insertion",l)}if(n.size>y6)throw new Error(f("errors.fileTooBig",{maxSize:`${Math.trunc(y6/1024/1024)}MB`}))}let s=this.files[i]?.dataURL||await za(n);return new Promise(async(l,c)=>{try{let m=this.getLatestInitializedImageElement(o,i);if(this.addMissingFiles([{mimeType:r,id:i,dataURL:s,created:Date.now(),lastRetrieved:Date.now()}]),!this.imageCache.get(i)){this.addNewImagesToImageCache();let{erroredFiles:d}=await this.updateImageCache([m]);if(d.size)throw new Error("Image cache update resulted with an error.")}let p=await this.imageCache.get(i)?.image;if(p&&this.state.newElement?.id!==m.id){m=this.getLatestInitializedImageElement(o,i);let d=this.getImageNaturalDimensions(m,p);Object.assign(m,d)}l(m)}catch(m){console.error(m),c(new Error(f("errors.imageInsertError")))}})});A(this,"getLatestInitializedImageElement",(o,n)=>{let r=this.scene.getElement(o.id)??o;return Si(r,{fileId:n})});A(this,"onImageToolbarButtonClick",async()=>{try{let o=this.state.width/2+this.state.offsetLeft,n=this.state.height/2+this.state.offsetTop,{x:r,y:i}=ot({clientX:o,clientY:n},this.state),a=await Xd({description:"Image",extensions:Object.keys(oj),multiple:!0});this.insertImages(a,r,i)}catch(o){o.name!=="AbortError"?console.error(o):console.warn(o),this.setState({newElement:null,activeTool:er(this.state,{type:this.state.preferredSelectionTool.type})},()=>{this.actionManager.executeAction(oo)})}});A(this,"getImageNaturalDimensions",(o,n)=>{let r=Math.max(this.state.height-120,160),i=Math.min(r,Math.floor(this.state.height*.5)/this.state.zoom.value),a=Math.min(n.naturalHeight,i),s=a*(n.naturalWidth/n.naturalHeight),l=o.x+o.width/2-s/2,c=o.y+o.height/2-a/2;return{x:l,y:c,width:s,height:a,crop:null}});A(this,"updateImageCache",async(o,n=this.files)=>{let{updatedFiles:r,erroredFiles:i}=await Jj({imageCache:this.imageCache,fileIds:o.map(a=>a.fileId),files:n});return i.size&&(this.store.scheduleAction(lo.NEVER),this.scene.replaceAllElements(this.scene.getElementsIncludingDeleted().map(a=>Pd(a)&&i.has(a.fileId)?Si(a,{status:"error"}):a))),{updatedFiles:r,erroredFiles:i}});A(this,"addNewImagesToImageCache",async(o=qj(this.scene.getNonDeletedElements()),n=this.files)=>{let r=o.filter(i=>!i.isDeleted&&!this.imageCache.has(i.fileId));if(r.length){let{updatedFiles:i}=await this.updateImageCache(r,n);if(i.size)for(let a of r)i.has(a.fileId)&&Ld.delete(a);i.size&&this.scene.triggerUpdate()}});A(this,"scheduleImageRefresh",jZ(()=>{this.addNewImagesToImageCache()},nj));A(this,"updateBindingEnabledOnPointerMove",o=>{let n=Fj(o);this.state.isBindingEnabled!==n&&this.setState({isBindingEnabled:n})});A(this,"handleInteractiveCanvasRef",o=>{o!==null?(this.interactiveCanvas=o,this.interactiveCanvas.addEventListener(ue.TOUCH_START,this.onTouchStart,{passive:!1}),this.interactiveCanvas.addEventListener(ue.TOUCH_END,this.onTouchEnd)):(this.interactiveCanvas?.removeEventListener(ue.TOUCH_START,this.onTouchStart),this.interactiveCanvas?.removeEventListener(ue.TOUCH_END,this.onTouchEnd))});A(this,"insertImages",async(o,n,r)=>{let i=50/this.state.zoom.value,a=oP(o.map(()=>this.newImagePlaceholder({sceneX:n,sceneY:r})),n,r,i);a.forEach(d=>this.scene.insertElement(d));let s=await Promise.all(a.map(async(d,u)=>{try{return await this.initializeImage(d,await Kl(o[u]))}catch(h){return this.setState({errorMessage:h.message||f("errors.imageInsertError")}),Si(d,{isDeleted:!0})}})),l=kg(s),c=oP(s.filter(d=>!d.isDeleted),n,r,i),m=kg(c),p=this.scene.getElementsIncludingDeleted().map(d=>m.get(d.id)??l.get(d.id)??d);this.updateScene({appState:{selectedElementIds:Oe(Object.fromEntries(c.map(d=>[d.id,!0])),this.state)},elements:p,captureUpdate:lo.IMMEDIATELY}),this.setState({},()=>{this.actionManager.executeAction(oo)})});A(this,"handleAppOnDrop",async o=>{let{x:n,y:r}=ot(o,this.state),i=await Is(o),a=i.getFiles();if(a.length===1){let{file:p,fileHandle:d}=a[0];if(p&&(p.type===Jn.png||p.type===Jn.svg))try{let u=await em(p,this.state,this.scene.getElementsIncludingDeleted(),d);this.syncActionResult({...u,appState:{...u.appState||this.state,isLoading:!1},replaceFiles:!0,captureUpdate:lo.IMMEDIATELY});return}catch(u){if(u.name!=="EncodingError")throw new Error(f("alerts.couldNotLoadInvalidFile"))}}let s=a.map(p=>p.file).filter(p=>Jg(p));if(s.length>0&&this.isToolSupported("image"))return this.insertImages(s,n,r);let l=i.getData(Jn.excalidrawlibIds),c=i.getData(Jn.excalidrawlib);if(l||c){try{let p=null;if(l){let{itemIds:d}=JSON.parse(l);p=(await this.library.getLatestLibrary()).filter(h=>d.includes(h.id))}else c&&(p=qE(c));p?.length&&(p=p.map(d=>({...d,elements:Px({type:"everything",elements:d.elements,randomizeSeed:!0}).duplicatedElements})),this.addElementsFromPasteOrLibrary({elements:Us(p),position:o,files:null}))}catch(p){this.setState({errorMessage:p.message})}return}if(a.length>0){let{file:p,fileHandle:d}=a[0];p&&await this.loadFileToCanvas(p,d)}let m=i.findByType(Jn.text);if(m){let p=m.value;if(p&&Nx(p,this.props.validateEmbeddable)&&(/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(p)||Ag(p)?.type==="video")){let d=this.insertEmbeddableElement({sceneX:n,sceneY:r,link:Ix(p)});d&&(this.store.scheduleCapture(),this.setState({selectedElementIds:{[d.id]:!0}}))}}});A(this,"loadFileToCanvas",async(o,n)=>{o=await Kl(o);try{let r=this.scene.getElementsIncludingDeleted(),i;try{i=await Qg(o,this.state,r,n)}catch(a){let s=a instanceof HE;if(s&&a.code==="IMAGE_NOT_CONTAINS_SCENE_DATA"&&!this.isToolSupported("image")){this.setState({isLoading:!1,errorMessage:f("errors.imageToolNotSupported")});return}let l=s?f("alerts.cannotRestoreFromImage"):f("alerts.couldNotLoadInvalidFile");this.setState({isLoading:!1,errorMessage:l})}if(!i)return;i.type===Jn.excalidraw?(pP(r.concat(i.data.elements)),this.store.scheduleMicroAction({action:lo.NEVER,elements:r,appState:void 0}),this.setState({isLoading:!0}),this.syncActionResult({...i.data,appState:{...i.data.appState||this.state,isLoading:!1},replaceFiles:!0,captureUpdate:lo.IMMEDIATELY})):i.type===Jn.excalidrawlib&&await this.library.updateLibrary({libraryItems:o,merge:!0,openLibraryMenu:!0}).catch(a=>{console.error(a),this.setState({errorMessage:f("errors.importLibraryError")})})}catch(r){this.setState({isLoading:!1,errorMessage:r.message})}});A(this,"handleCanvasContextMenu",o=>{if(o.preventDefault(),("pointerType"in o.nativeEvent&&o.nativeEvent.pointerType==="touch"||"pointerType"in o.nativeEvent&&o.nativeEvent.pointerType==="pen"&&o.button!==Ci.SECONDARY)&&this.state.activeTool.type!==this.state.preferredSelectionTool.type)return;let{x:n,y:r}=ot(o,this.state),i=this.getElementAtPosition(n,r,{preferSelected:!0,includeLockedElements:!0}),a=this.scene.getSelectedElements(this.state),s=this.isHittingCommonBoundingBoxOfSelectedElements({x:n,y:r},a),l=i||s?"element":"canvas",c=this.excalidrawContainerRef.current,{top:m,left:p}=c.getBoundingClientRect(),d=o.clientX-p,u=o.clientY-m;ge("contextMenu","openContextMenu",l),this.setState({...i&&!this.state.selectedElementIds[i.id]?{...this.state,...nn({editingGroupId:this.state.editingGroupId,selectedElementIds:{[i.id]:!0}},this.scene.getNonDeletedElements(),this.state,this),selectedLinearElement:so(i)?new Me(i,this.scene.getNonDeletedElementsMap()):null}:this.state,showHyperlinkPopup:!1},()=>{this.setState({contextMenu:{top:u,left:d,items:this.getContextMenuItems(l)}})})});A(this,"maybeDragNewGenericElement",(o,n,r=!0)=>{let i=this.state.selectionElement,a=o.lastCoords;if(i&&o.boxSelection.hasOccurred&&this.state.activeTool.type!=="eraser"){J6({newElement:i,elementType:this.state.activeTool.type,originX:o.origin.x,originY:o.origin.y,x:a.x,y:a.y,width:Ml(o.origin.x,a.x),height:Ml(o.origin.y,a.y),shouldMaintainAspectRatio:Cd(n),shouldResizeFromCenter:!1,scene:this.scene,zoom:this.state.zoom.value,informMutation:!1});return}let s=this.state.newElement;if(!s)return;let[l,c]=Zt(a.x,a.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),m=Pd(s)&&this.imageCache.get(s.fileId)?.image,p=m&&!(m instanceof Promise)?m.width/m.height:null;this.maybeCacheReferenceSnapPoints(n,[s]);let{snapOffset:d,snapLines:u}=j5(s,this,n,{x:o.originInGrid.x+(this.state.originSnapOffset?.x??0),y:o.originInGrid.y+(this.state.originSnapOffset?.y??0)},{x:l-o.originInGrid.x,y:c-o.originInGrid.y},this.scene.getNonDeletedElementsMap());l+=d.x,c+=d.y,this.setState({snapLines:u}),or(s)||J6({newElement:s,elementType:this.state.activeTool.type,originX:o.originInGrid.x,originY:o.originInGrid.y,x:l,y:c,width:Ml(o.originInGrid.x,l),height:Ml(o.originInGrid.y,c),shouldMaintainAspectRatio:Mi(s)?!Cd(n):Cd(n),shouldResizeFromCenter:h6(n),zoom:this.state.zoom.value,scene:this.scene,widthAspectRatio:p,originOffset:this.state.originSnapOffset,informMutation:r}),this.setState({newElement:s}),(this.state.activeTool.type===Qn.frame||this.state.activeTool.type===Qn.magicframe)&&this.setState({elementsToHighlight:Hx(this.scene.getNonDeletedElements(),s,this.state,this.scene.getNonDeletedElementsMap())})});A(this,"maybeHandleCrop",(o,n)=>{if(!this.state.croppingElementId)return!1;let r=o.resize.handleType,i=o.lastCoords,[a,s]=Zt(i.x-o.resize.offset.x,i.y-o.resize.offset.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),l=this.scene.getNonDeletedElementsMap().get(this.state.croppingElementId);if(r&&l&&Mi(l)){let c=o.originalElements.get(l.id),m=Pd(l)&&this.imageCache.get(l.fileId)?.image;if(c&&Mi(c)&&m&&!(m instanceof Promise)){let[p,d]=Zt(i.x,i.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),u={x:p-o.originInGrid.x,y:d-o.originInGrid.y};this.maybeCacheReferenceSnapPoints(n,[l]);let{snapOffset:h,snapLines:g}=w0([l],[c],this,n,u,r);this.scene.mutateElement(l,gq(l,this.scene.getNonDeletedElementsMap(),r,m.naturalWidth,m.naturalHeight,a+h.x,s+h.y,n.shiftKey?c.width/c.height:void 0)),Pg(l,this.scene),this.setState({isCropping:r&&r!=="rotation",snapLines:g})}return!0}return!1});A(this,"maybeHandleResize",(o,n)=>{let r=this.scene.getSelectedElements(this.state),i=r.filter(p=>jt(p)),a=o.resize.handleType;if(i.length>0&&a==="rotation"||r.length===1&&vo(r[0])||this.state.croppingElementId)return!1;this.setState({isResizing:a&&a!=="rotation",isRotating:a==="rotation",activeEmbeddable:null});let s=o.lastCoords,[l,c]=Zt(s.x-o.resize.offset.x,s.y-o.resize.offset.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),m=new Map;if(i.forEach(p=>{Ox(this.scene.getNonDeletedElements(),p.id).forEach(u=>{m.set(p.id+u.id,{x:u.x-p.x,y:u.y-p.y})})}),!this.state.selectedElementsAreBeingDragged){let[p,d]=Zt(s.x,s.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),u={x:p-o.originInGrid.x,y:d-o.originInGrid.y},h=[...o.originalElements.values()];this.maybeCacheReferenceSnapPoints(n,r);let{snapOffset:g,snapLines:E}=w0(r,le(h,this.state),this,n,u,a);l+=g.x,c+=g.y,this.setState({snapLines:E})}if(_q(o.originalElements,a,r,this.scene,f6(n),h6(n),r.some(p=>Mi(p))?!Cd(n):Cd(n),l,c,o.resize.center.x,o.resize.center.y)){let p=new Set;return i.forEach(d=>{Hx(this.scene.getNonDeletedElements(),d,this.state,this.scene.getNonDeletedElementsMap()).forEach(u=>p.add(u))}),this.setState({elementsToHighlight:[...p]}),!0}return!1});A(this,"getContextMenuItems",o=>{let n=[];if(n.push(mp,dp),o==="canvas")return this.state.viewModeEnabled?[...n,_s,jr,ea,qr]:[Uf,Et,mp,dp,pp,Et,Nh,jI,Et,_s,Cc,jr,ea,qr];if(n.push(pp),this.state.viewModeEnabled)return[Ls,...n];let r=this.editorInterface.formFactor==="desktop"?[Et,Lh,_h,Dh,Rh]:[];return[Et,cp,Ls,Uf,Et,S5,M5,P5,Et,Kc,Et,...n,Et,_f,Df,Et,Nf,F5,Vf,$f,NI,Bf,Et,zf,...r,Et,Hf,Gf,Et,Qs,Et,Mc,yp,Et,Bh,Pc,Et,nc]});A(this,"handleWheel",mt(o=>{if(!(o.target instanceof HTMLCanvasElement||o.target instanceof HTMLTextAreaElement||o.target instanceof HTMLIFrameElement||o.target instanceof HTMLElement&&o.target.classList.contains(Sx.FRAME_NAME))){o[oe.CTRL_OR_CMD]&&o.preventDefault();return}if(o.preventDefault(),Rd)return;let{deltaX:n,deltaY:r}=o;if(o.metaKey||o.ctrlKey){let i=Math.sign(r),a=dj*100,s=Math.abs(r),l=r;s>a&&(l=a*i);let c=this.state.zoom.value-l/100;c+=Math.log10(Math.max(1,this.state.zoom.value))*-i*Math.min(1,s/20),this.translateCanvas(m=>({...pr({viewportX:this.lastViewportPosition.x,viewportY:this.lastViewportPosition.y,nextZoom:Cn(c)},m),shouldCacheIgnoreZoom:!0})),this.resetShouldCacheIgnoreZoomDebounced();return}if(o.shiftKey){this.translateCanvas(({zoom:i,scrollX:a})=>({scrollX:a-(r||n)/i.value}));return}this.translateCanvas(({zoom:i,scrollX:a,scrollY:s})=>({scrollX:a-n/i.value,scrollY:s-r/i.value}))}));A(this,"savePointer",(o,n,r)=>{if(!o||!n)return;let{x:i,y:a}=ot({clientX:o,clientY:n},this.state);isNaN(i)||isNaN(a);let s={x:i,y:a,tool:this.state.activeTool.type==="laser"?"laser":"pointer"};this.props.onPointerUpdate?.({pointer:s,button:r,pointersMap:De.pointers})});A(this,"resetShouldCacheIgnoreZoomDebounced",I6(()=>{this.unmounted||this.setState({shouldCacheIgnoreZoom:!1})},300));A(this,"updateDOMRect",o=>{if(this.excalidrawContainerRef?.current){let n=this.excalidrawContainerRef.current,{width:r,height:i,left:a,top:s}=n.getBoundingClientRect(),{width:l,height:c,offsetTop:m,offsetLeft:p}=this.state;if(r===l&&i===c&&a===p&&s===m){o&&o();return}this.setState({width:r,height:i,offsetLeft:a,offsetTop:s},()=>{o&&o()})}});A(this,"refresh",()=>{this.setState({...this.getCanvasOffsets()})});A(this,"watchState",()=>{});let n=Rr(),{excalidrawAPI:r,viewModeEnabled:i=!1,zenModeEnabled:a=!1,gridModeEnabled:s=!1,objectsSnapModeEnabled:l=!1,theme:c=n.theme,name:m=`${f("labels.untitled")}-${C6()}`}=o;if(this.state={...n,theme:c,isLoading:!0,...this.getCanvasOffsets(),viewModeEnabled:i,zenModeEnabled:a,objectsSnapModeEnabled:l,gridModeEnabled:s??n.gridModeEnabled,name:m,width:window.innerWidth,height:window.innerHeight},this.refreshEditorInterface(),this.stylesPanelMode=Dg(this.editorInterface),this.id=Ex(),this.library=new vT(this),this.actionManager=new nu(this.syncActionResult,()=>this.state,()=>this.scene.getElementsIncludingDeleted(),this),this.scene=new eP,this.canvas=document.createElement("canvas"),this.rc=qZ.canvas(this.canvas),this.renderer=new qc(this.scene),this.visibleElements=[],this.store=new Nq(this),this.history=new Xc(this.store),r){let p={updateScene:this.updateScene,applyDeltas:this.applyDeltas,mutateElement:this.mutateElement,updateLibrary:this.library.updateLibrary,addFiles:this.addFiles,resetScene:this.resetScene,getSceneElementsIncludingDeleted:this.getSceneElementsIncludingDeleted,getSceneElementsMapIncludingDeleted:this.getSceneElementsMapIncludingDeleted,history:{clear:this.resetHistory},scrollToContent:this.scrollToContent,getSceneElements:this.getSceneElements,getAppState:()=>this.state,getFiles:()=>this.files,getName:this.getName,registerAction:d=>{this.actionManager.registerAction(d)},refresh:this.refresh,setToast:this.setToast,id:this.id,setActiveTool:this.setActiveTool,setCursor:this.setCursor,resetCursor:this.resetCursor,getEditorInterface:()=>this.editorInterface,updateFrameRendering:this.updateFrameRendering,toggleSidebar:this.toggleSidebar,onChange:d=>this.onChangeEmitter.on(d),onIncrement:d=>this.store.onStoreIncrementEmitter.on(d),onPointerDown:d=>this.onPointerDownEmitter.on(d),onPointerUp:d=>this.onPointerUpEmitter.on(d),onScrollChange:d=>this.onScrollChangeEmitter.on(d),onUserFollow:d=>this.onUserFollowEmitter.on(d)};typeof r=="function"?r(p):console.error("excalidrawAPI should be a function!")}this.excalidrawContainerValue={container:this.excalidrawContainerRef.current,id:this.id},this.fonts=new Mn(this.scene),this.history=new Xc(this.store),this.actionManager.registerAll(xm),this.actionManager.registerAction(D5(this.history)),this.actionManager.registerAction(R5(this.history))}onWindowMessage(o){if(o.origin!=="https://player.vimeo.com"&&o.origin!=="https://www.youtube.com")return;let n=null;try{n=JSON.parse(o.data)}catch{}if(n)switch(o.origin){case"https://player.vimeo.com":if(n.method==="paused"){let r=null,i=document.body.querySelectorAll("iframe.excalidraw__embeddable");if(!i)break;for(let a of i)a.contentWindow===o.source&&(r=a.contentWindow);r?.postMessage(JSON.stringify({method:n.value?"play":"pause",value:!0}),"*")}break;case"https://www.youtube.com":if(n.event==="infoDelivery"&&n.info&&n.id&&typeof n.info.playerState=="number"){let r=n.id,i=n.info.playerState;Object.values(Tg).includes(i)&&Zx.set(r,i)}break}}handleSkipBindMode(){if(this.state.selectedLinearElement?.initialState&&!this.state.selectedLinearElement.initialState.arrowStartIsInside){tr(this.lastPointerMoveCoords,"Missing last pointer move coords when changing bind skip mode for arrow start");let o=this.scene.getNonDeletedElementsMap(),n=wn(de(this.lastPointerMoveCoords.x,this.lastPointerMoveCoords.y),this.scene.getNonDeletedElements(),o),r=Me.getElement(this.state.selectedLinearElement.elementId,o);r?.startBinding&&n?.id===r.startBinding.elementId&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,initialState:{...this.state.selectedLinearElement.initialState,arrowStartIsInside:!0}}})}if(this.state.bindMode==="orbit"&&(this.bindModeHandler&&(clearTimeout(this.bindModeHandler),this.bindModeHandler=null),wo(()=>{this.setState({bindMode:"skip"})}),this.lastPointerMoveCoords&&this.state.selectedLinearElement?.selectedPointsIndices&&this.state.selectedLinearElement?.selectedPointsIndices.length)){let{x:o,y:n}=this.lastPointerMoveCoords,r=this.lastPointerMoveEvent??this.lastPointerDownEvent?.nativeEvent;tr(r,"Last event must exist");let i=o-this.state.selectedLinearElement.pointerOffset.x,a=n-this.state.selectedLinearElement.pointerOffset.y,s=this.state.multiElement?Me.handlePointerMove(r,this,i,a,this.state.selectedLinearElement):Me.handlePointDragging(r,this,i,a,this.state.selectedLinearElement);s&&this.setState(s)}}resetDelayedBindMode(){this.bindModeHandler&&(clearTimeout(this.bindModeHandler),this.bindModeHandler=null),this.state.bindMode!=="orbit"&&setTimeout(()=>this.setState({bindMode:"orbit"}))}handleDelayedBindModeChange(o,n){if(o.isDeleted||vo(o))return;let r=()=>{if(this.bindModeHandler=null,tr(this.lastPointerMoveCoords,"Expected lastPointerMoveCoords to be set"),!this.state.multiElement){if(!this.state.selectedLinearElement||!this.state.selectedLinearElement.selectedPointsIndices||!this.state.selectedLinearElement.selectedPointsIndices.length)return;let h=this.state.selectedLinearElement.selectedPointsIndices.includes(0),g=this.state.selectedLinearElement.selectedPointsIndices.includes(o.points.length-1);if(!h&&!g||h&&g)return}let{x:p,y:d}=this.lastPointerMoveCoords,u=wn(de(p,d),this.scene.getNonDeletedElements(),this.scene.getNonDeletedElementsMap());if(u&&this.state.bindMode!=="skip"){tr(this.state.selectedLinearElement?.elementId===o.id,"The selectedLinearElement is expected to not change while a bind mode timeout is ticking");let h=this.state.selectedLinearElement.initialState.arrowStartIsInside||o.startBinding?.elementId===u.id;wo(()=>{tr(this.state.selectedLinearElement,"this.state.selectedLinearElement must exist"),this.setState({bindMode:"inside",selectedLinearElement:{...this.state.selectedLinearElement,initialState:{...this.state.selectedLinearElement.initialState,arrowStartIsInside:h}}})});let g=this.lastPointerMoveEvent??this.lastPointerDownEvent?.nativeEvent;tr(g,"Last event must exist");let E=p-this.state.selectedLinearElement.pointerOffset.x,w=d-this.state.selectedLinearElement.pointerOffset.y,x=this.state.multiElement?Me.handlePointerMove(g,this,E,w,this.state.selectedLinearElement):Me.handlePointDragging(g,this,E,w,this.state.selectedLinearElement);x&&this.setState(x)}},i=!1;if(this.state.selectedLinearElement?.selectedPointsIndices){let p=this.scene.getNonDeletedElementsMap(),d=this.state.selectedLinearElement.selectedPointsIndices.includes(0),u=this.state.selectedLinearElement.selectedPointsIndices.includes(o.points.length-1),h=d?n:o.startBinding&&p.get(o.startBinding.elementId),g=u?n:o.endBinding&&p.get(o.endBinding.elementId),E=h&&rP(h,p),w=g&&rP(g,p);i=!!(E&&w&&h.id!==g.id&&Oq(E,w))}let a=this.state.selectedLinearElement?.selectedPointsIndices?.includes(0),s=this.state.selectedLinearElement?.selectedPointsIndices?.includes(o.points.length-1),l=a?"startBinding":s?"endBinding":null,c=a?"endBinding":s?"startBinding":null,m=c&&o[c]?.mode==="inside"&&o[c]?.elementId===n?.id||l&&o[l]?.mode==="inside"&&n?.id===o[l]?.elementId;l&&c&&o[l]?.mode==="inside"&&n?.id!==o[l]?.elementId&&o[c]?.elementId!==o[l]?.elementId&&this.scene.mutateElement(o,{[l]:{...o[l],mode:"orbit"}},{informMutation:!1,isDragging:!0}),!n||this.previousHoveredBindableElement&&n.id!==this.previousHoveredBindableElement.id?(this.bindModeHandler&&(clearTimeout(this.bindModeHandler),this.bindModeHandler=null),this.state.bindMode==="inside"&&wo(()=>{this.setState({bindMode:"orbit"})}),this.previousHoveredBindableElement=null):!this.bindModeHandler&&(!this.state.newElement||!o.startBinding||i)&&!m&&(this.bindModeHandler=setTimeout(r,Mj)),this.previousHoveredBindableElement=n}cacheEmbeddableRef(o,n){n&&this.iFrameRefs.set(o.id,n)}getHTMLIFrameElement(o){return this.iFrameRefs.get(o.id)}handleIframeLikeCenterClick(){if(!this.lastPointerDownEvent||!this.lastPointerUpEvent||this.lastPointerDownEvent.button!==Ci.MAIN||Pi||!S6(this.state.activeTool.type,["laser","selection","lasso"]))return!1;let o=de(ot({clientX:this.lastPointerDownEvent.clientX,clientY:this.lastPointerDownEvent.clientY},this.state)),n=de(ot({clientX:this.lastPointerUpEvent.clientX,clientY:this.lastPointerUpEvent.clientY},this.state));if(Ti(o,n)>x6)return!1;let i=this.getElementAtPosition(o[0],o[1]);if(!(i&&this.lastPointerUpEvent.timeStamp-this.lastPointerDownEvent.timeStamp<=300&&De.pointers.size<2&&Lx(i)&&(this.state.viewModeEnabled||this.state.activeTool.type==="laser"||this.isIframeLikeElementCenter(i,this.lastPointerUpEvent,n[0],n[1]))))return!1;let s=i;if(this.state.activeEmbeddable?.element===s&&this.state.activeEmbeddable?.state==="active"||(setTimeout(()=>{this.setState({activeEmbeddable:{element:s,state:"active"},selectedElementIds:{[s.id]:!0},newElement:null,selectionElement:null})},100),Ll(s)))return!0;let l=this.getHTMLIFrameElement(s);if(!l?.contentWindow)return!0;if(l.src.includes("youtube")){let c=Zx.get(s.id);switch(c||(Zx.set(s.id,Tg.UNSTARTED),l.contentWindow.postMessage(JSON.stringify({event:"listening",id:s.id}),"*")),c){case Tg.PLAYING:case Tg.BUFFERING:l.contentWindow?.postMessage(JSON.stringify({event:"command",func:"pauseVideo",args:""}),"*");break;default:l.contentWindow?.postMessage(JSON.stringify({event:"command",func:"playVideo",args:""}),"*")}}return l.src.includes("player.vimeo.com")&&l.contentWindow.postMessage(JSON.stringify({method:"paused"}),"*"),!0}isIframeLikeElementCenter(o,n,r,i){return o&&!n.altKey&&!n.shiftKey&&!n.metaKey&&!n.ctrlKey&&(this.state.activeEmbeddable?.element!==o||this.state.activeEmbeddable?.state==="hover"||!this.state.activeEmbeddable)&&r>=o.x+o.width/3&&r<=o.x+2*o.width/3&&i>=o.y+o.height/3&&i<=o.y+2*o.height/3}renderEmbeddables(){let o=this.state.zoom.value,n=this.state.width,r=this.state.height,i=this.scene.getNonDeletedElements().filter(a=>Lr(a)&&this.embedsValidationStatus.get(a.id)===!0||Ll(a));return Se(lP,{children:i.map(a=>{let{x:s,y:l}=Cg({sceneX:a.x,sceneY:a.y},this.state),c=B6(a,n,r,this.state,this.scene.getNonDeletedElementsMap()),m=this.initializedEmbeds.has(a.id);if(c&&!m&&this.initializedEmbeds.add(a.id),!(c||m))return null;let d;if(Ll(a)){d=null;let g=(a.customData?.generationData??this.magicGenerations.get(a.id))||{status:"error",message:"No generation data",code:"ERR_NO_GENERATION_DATA"};if(g.status==="done"){let E=g.html;d={intrinsicSize:{w:a.width,h:a.height},type:"document",srcdoc:()=>E}}else if(g.status==="pending")d={intrinsicSize:{w:a.width,h:a.height},type:"document",srcdoc:()=>z6(`
123
123
  <style>
124
124
  html, body {
125
125
  width: 100%;
@@ -210,11 +210,11 @@ Please fix the Mermaid syntax and regenerate a valid diagram.`;await w({prompt:$
210
210
  </style>
211
211
  <h1>Error!</h1>
212
212
  <h3>${E}</h3>
213
- `)}}}else d=Ag(hj(a.link||""));let u=this.state.activeEmbeddable?.element===a&&this.state.activeEmbeddable?.state==="active",h=this.state.activeEmbeddable?.element===a&&this.state.activeEmbeddable?.state==="hover";return Se("div",{className:l6("excalidraw__embeddable-container",{"is-hovered":h}),style:{transform:c?`translate(${s-this.state.offsetLeft}px, ${l-this.state.offsetTop}px) scale(${o})`:"none",display:c?"block":"none",opacity:Iq(a,Gx(a,this.scene.getNonDeletedElementsMap()),this.elementsPendingErasure,null,this.state.openDialog?.name==="elementLinkSelector"?uj:1),"--embeddable-radius":`${Zj(Math.min(a.width,a.height),a)}px`},children:Od("div",{className:"excalidraw__embeddable-container__inner",style:{width:c?`${a.width}px`:0,height:c?`${a.height}px`:0,transform:c?`rotate(${a.angle}rad)`:"none",pointerEvents:u?Sl.enabled:Sl.disabled},children:[h&&Se("div",{className:"excalidraw__embeddable-hint",children:f("buttons.embeddableInteractionButton")}),Se("div",{className:"excalidraw__embeddable__outer",style:{padding:`${a.strokeWidth}px`},children:(Lr(a)?this.props.renderEmbeddable?.(a,this.state):null)??Se("iframe",{ref:g=>this.cacheEmbeddableRef(a,g),className:"excalidraw__embeddable",srcDoc:d?.type==="document"?d.srcdoc(this.state.theme):void 0,src:d?.type!=="document"?d?.link??"":void 0,scrolling:"no",referrerPolicy:"no-referrer-when-downgrade",title:"Excalidraw Embedded Content",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,sandbox:`${d?.sandbox?.allowSameOrigin?"allow-same-origin":""} allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation allow-downloads`})})]})},a.id)})})}toggleOverscrollBehavior(o){document.documentElement.style.overscrollBehaviorX=o.type==="pointerenter"?"none":"auto"}render(){let o=this.scene.getSelectedElements(this.state),{renderTopRightUI:n,renderTopLeftUI:r,renderCustomStats:i}=this.props,a=this.scene.getSceneNonce(),{elementsMap:s,visibleElements:l}=this.renderer.getRenderableElements({sceneNonce:a,zoom:this.state.zoom,offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,height:this.state.height,width:this.state.width,editingTextElement:this.state.editingTextElement,newElementId:this.state.newElement?.id});this.visibleElements=l;let c=this.scene.getNonDeletedElementsMap(),m="setPointerCapture"in HTMLElement.prototype?!1:this.state.selectionElement||this.state.newElement||this.state.selectedElementsAreBeingDragged||this.state.resizingElement||this.state.activeTool.type==="laser"&&this.state.cursorButton==="down",p=o[0],d=Et.get(gn)?.type==="panel";return Se("div",{translate:"no",className:l6("excalidraw excalidraw-container notranslate",{"excalidraw--view-mode":this.state.viewModeEnabled||this.state.openDialog?.name==="elementLinkSelector","excalidraw--mobile":this.editorInterface.formFactor==="phone"}),style:{"--ui-pointerEvents":m?Sl.disabled:Sl.enabled,"--right-sidebar-width":"302px"},ref:this.excalidrawContainerRef,onDrop:this.handleAppOnDrop,tabIndex:0,onKeyDown:this.props.handleKeyboardGlobally?void 0:this.onKeyDown,onPointerEnter:this.toggleOverscrollBehavior,onPointerLeave:this.toggleOverscrollBehavior,children:Se(uP.Provider,{value:this,children:Se(gP.Provider,{value:this.props,children:Se(eE.Provider,{value:this.excalidrawContainerValue,children:Se(Qx.Provider,{value:this.editorInterface,children:Se(nE.Provider,{value:this.setAppState,children:Se(oE.Provider,{value:this.state,children:Od(tE.Provider,{value:this.scene.getNonDeletedElements(),children:[Od(rE.Provider,{value:this.actionManager,children:[Se(M4,{canvas:this.canvas,appState:this.state,files:this.files,setAppState:this.setAppState,actionManager:this.actionManager,elements:this.scene.getNonDeletedElements(),onLockToggle:this.toggleLock,onPenModeToggle:this.togglePenMode,onHandToolToggle:this.onHandToolToggle,langCode:lr().code,renderTopLeftUI:r,renderTopRightUI:n,renderCustomStats:i,showExitZenModeBtn:typeof this.props?.zenModeEnabled>"u"&&this.state.zenModeEnabled,UIOptions:this.props.UIOptions,onExportImage:this.onExportImage,renderWelcomeScreen:!this.state.isLoading&&this.state.showWelcomeScreen&&this.state.activeTool.type===this.state.preferredSelectionTool.type&&!this.state.zenModeEnabled&&!this.scene.getElementsIncludingDeleted().length,app:this,isCollaborating:this.props.isCollaborating,generateLinkForSelection:this.props.generateLinkForSelection,children:this.props.children}),Se("div",{className:"excalidraw-textEditorContainer"}),Se("div",{className:"excalidraw-contextMenuContainer"}),Se("div",{className:"excalidraw-eye-dropper-container"}),Se(L4,{trails:[this.laserTrails,this.lassoTrail,this.eraserTrail]}),o.length===1&&this.state.openDialog?.name!=="elementLinkSelector"&&this.state.showHyperlinkPopup&&Se(UI,{element:p,scene:this.scene,setAppState:this.setAppState,onLinkOpen:this.props.onLinkOpen,setToast:this.setToast,updateEmbedValidationStatus:this.updateEmbedValidationStatus},p.id),this.props.aiEnabled!==!1&&o.length===1&&_x(p)&&Se(v0,{element:p,elementsMap:s,children:Se(xg,{title:f("labels.convertToCode"),icon:Gi,checked:!1,onChange:()=>this.onMagicFrameGenerate(p,"button")})}),o.length===1&&Ll(p)&&p.customData?.generationData?.status==="done"&&Od(v0,{element:p,elementsMap:s,children:[Se(xg,{title:f("labels.copySource"),icon:Qa,checked:!1,onChange:()=>this.onIframeSrcCopy(p)}),Se(xg,{title:"Enter fullscreen",icon:kw,checked:!1,onChange:()=>{let u=this.getHTMLIFrameElement(p);if(u)try{u.requestFullscreen(),this.setState({activeEmbeddable:{element:p,state:"active"},selectedElementIds:{[p.id]:!0},newElement:null,selectionElement:null})}catch(h){console.warn(h),this.setState({errorMessage:"Couldn't enter fullscreen"})}}})]}),o.length===1&&jt(p)&&p.customData?.type!=="image-generator"&&!this.state.viewModeEnabled&&Se(t3,{element:p,app:this}),Se(n3,{}),Se(M3,{app:this}),o.length===1&&jt(p)&&p.customData?.type==="image-generator"&&!this.state.viewModeEnabled&&Se(c3,{element:p,app:this,onBeforeImageGen:this.props.onBeforeImageGen,onAfterImageGen:this.props.onAfterImageGen}),o.length===1&&Mi(p)&&!this.state.viewModeEnabled&&Se(F3,{element:p,app:this,callbacks:this.props.imageEditToolbarCallbacks}),this.state.toast!==null&&Se(a6,{message:this.state.toast.message,onClose:this.handleToastClose,duration:this.state.toast.duration,closable:this.state.toast.closable}),this.state.contextMenu&&Se(Ek,{items:this.state.contextMenu.items,top:this.state.contextMenu.top,left:this.state.contextMenu.left,actionManager:this.actionManager,onClose:u=>{this.setState({contextMenu:null},()=>{this.focusContainer(),u?.()})}}),Se(xx,{canvas:this.canvas,rc:this.rc,elementsMap:s,allElementsMap:c,visibleElements:l,sceneNonce:a,selectionNonce:this.state.selectionElement?.versionNonce,scale:window.devicePixelRatio,appState:this.state,renderConfig:{imageCache:this.imageCache,isExporting:!1,renderGrid:ai(this),canvasBackgroundColor:this.state.viewBackgroundColor,embedsValidationStatus:this.embedsValidationStatus,elementsPendingErasure:this.elementsPendingErasure,pendingFlowchartNodes:this.flowChartCreator.pendingNodes,theme:this.state.theme}}),this.state.newElement&&Se(r6,{appState:this.state,scale:window.devicePixelRatio,rc:this.rc,elementsMap:s,allElementsMap:c,renderConfig:{imageCache:this.imageCache,isExporting:!1,renderGrid:!1,canvasBackgroundColor:this.state.viewBackgroundColor,embedsValidationStatus:this.embedsValidationStatus,elementsPendingErasure:this.elementsPendingErasure,pendingFlowchartNodes:null,theme:this.state.theme}}),Se(bx,{app:this,containerRef:this.excalidrawContainerRef,canvas:this.interactiveCanvas,elementsMap:s,visibleElements:l,allElementsMap:c,selectedElements:o,sceneNonce:a,selectionNonce:this.state.selectionElement?.versionNonce,scale:window.devicePixelRatio,appState:this.state,renderScrollbars:this.props.renderScrollbars===!0,editorInterface:this.editorInterface,renderInteractiveSceneCallback:this.renderInteractiveSceneCallback,handleCanvasRef:this.handleInteractiveCanvasRef,onContextMenu:this.handleCanvasContextMenu,onPointerMove:this.handleCanvasPointerMove,onPointerUp:this.handleCanvasPointerUp,onPointerCancel:this.removePointer,onTouchMove:this.handleTouchMove,onPointerDown:this.handleCanvasPointerDown,onDoubleClick:this.handleCanvasDoubleClick}),this.state.userToFollow&&Se(wk,{width:this.state.width,height:this.state.height,userToFollow:this.state.userToFollow,onDisconnect:this.maybeUnfollowRemoteUser}),this.renderFrameNames(),this.state.activeLockedId&&Se(s6,{app:this,activeLockedId:this.state.activeLockedId}),d&&Se(iT,{app:this})]}),this.renderEmbeddables()]})})})})})})})})}setPlugins(o){Object.assign(this.plugins,o)}async onMagicFrameGenerate(o,n){let r=this.plugins.diagramToCode?.generate;if(!r){this.setState({errorMessage:"No diagram to code plugin found"});return}let i=sq(this.scene.getNonDeletedElements(),o).filter(s=>!_x(s));if(!i.length){n==="button"?(this.setState({errorMessage:"Cannot generate from an empty frame"}),ge("ai","generate (no-children)","d2c")):this.setActiveTool({type:"magicframe"});return}let a=this.insertIframeElement({sceneX:o.x+o.width+30,sceneY:o.y,width:o.width,height:o.height});if(a){this.updateMagicGeneration({frameElement:a,data:{status:"pending"}}),this.setState({selectedElementIds:{[a.id]:!0}}),ge("ai","generate (start)","d2c");try{let{html:s}=await r({frame:o,children:i});if(ge("ai","generate (success)","d2c"),!s.trim()){this.updateMagicGeneration({frameElement:a,data:{status:"error",code:"ERR_OAI",message:"Nothing genereated :("}});return}let l=s.includes("<!DOCTYPE html>")&&s.includes("</html>")?s.slice(s.indexOf("<!DOCTYPE html>"),s.indexOf("</html>")+7):s;this.updateMagicGeneration({frameElement:a,data:{status:"done",html:l}})}catch(s){ge("ai","generate (failed)","d2c"),this.updateMagicGeneration({frameElement:a,data:{status:"error",code:"ERR_OAI",message:s.message||"Unknown error during generation"}})}}}onIframeSrcCopy(o){o.customData?.generationData?.status==="done"&&(pn(o.customData.generationData.html),this.setToast({message:"copied to clipboard",closable:!1,duration:1500}))}clearImageShapeCache(o){let n=o??this.files;this.scene.getNonDeletedElements().forEach(r=>{Pd(r)&&n[r.fileId]&&(this.imageCache.delete(r.fileId),Ld.delete(r))})}async componentDidMount(){if(this.unmounted=!1,this.excalidrawContainerValue.container=this.excalidrawContainerRef.current,cP()||dP()){let r=this.setState.bind(this);Object.defineProperties(window.h,{state:{configurable:!0,get:()=>this.state},setState:{configurable:!0,value:(...i)=>this.setState(...i)},app:{configurable:!0,value:this},history:{configurable:!0,value:this.history},store:{configurable:!0,value:this.store},fonts:{configurable:!0,value:this.fonts}})}this.store.onDurableIncrementEmitter.on(r=>{this.history.record(r.delta)});let{onIncrement:o}=this.props;o&&this.store.onStoreIncrementEmitter.on(r=>{o(r)}),this.scene.onUpdate(this.triggerRender),this.addEventListeners(),this.props.autoFocus&&this.excalidrawContainerRef.current&&this.focusContainer(),mj&&this.excalidrawContainerRef.current&&(this.resizeObserver=new ResizeObserver(()=>{this.refreshEditorInterface(),this.updateDOMRect()}),this.resizeObserver?.observe(this.excalidrawContainerRef.current)),new URLSearchParams(window.location.search.slice(1)).has("web-share-target")?this.restoreFileFromShare():this.updateDOMRect(this.initializeScene),Lj()&&!bq()&&this.setState({errorMessage:Se(hk,{})})}componentWillUnmount(){window.launchQueue?.setConsumer(()=>{}),this.renderer.destroy(),this.scene.destroy(),this.scene=new eP,this.fonts=new Mn(this.scene),this.renderer=new qc(this.scene),this.files={},this.imageCache.clear(),this.resizeObserver?.disconnect(),this.unmounted=!0,this.removeEventListeners(),this.library.destroy(),this.laserTrails.stop(),this.eraserTrail.stop(),this.onChangeEmitter.clear(),this.store.onStoreIncrementEmitter.clear(),this.store.onDurableIncrementEmitter.clear(),Ld.destroy(),$o.destroy(),clearTimeout(Ai),He.clearCache(),nn.clearCache(),Ai=0,document.documentElement.style.overscrollBehaviorX=""}removeEventListeners(){this.onRemoveEventListenersEmitter.trigger()}addEventListeners(){this.removeEventListeners(),this.props.handleKeyboardGlobally&&this.onRemoveEventListenersEmitter.once(gt(document,ue.KEYDOWN,this.onKeyDown,!1)),this.onRemoveEventListenersEmitter.once(gt(this.excalidrawContainerRef.current,ue.WHEEL,this.handleWheel,{passive:!1}),gt(window,ue.MESSAGE,this.onWindowMessage,!1),gt(document,ue.POINTER_UP,this.removePointer,{passive:!1}),gt(document,ue.COPY,this.onCopy,{passive:!1}),gt(document,ue.KEYUP,this.onKeyUp,{passive:!0}),gt(document,ue.POINTER_MOVE,this.updateCurrentCursorPosition,{passive:!1}),gt(document.fonts,"loadingdone",o=>{let n=o.fontfaces;this.fonts.onLoaded(n)},{passive:!1}),gt(document,ue.GESTURE_START,this.onGestureStart,!1),gt(document,ue.GESTURE_CHANGE,this.onGestureChange,!1),gt(document,ue.GESTURE_END,this.onGestureEnd,!1),gt(window,ue.FOCUS,()=>{this.maybeCleanupAfterMissingPointerUp(null),this.triggerRender(!0)},{passive:!1})),!this.state.viewModeEnabled&&(this.onRemoveEventListenersEmitter.once(gt(document,ue.FULLSCREENCHANGE,this.onFullscreenChange,{passive:!1}),gt(document,ue.PASTE,this.pasteFromClipboard,{passive:!1}),gt(document,ue.CUT,this.onCut,{passive:!1}),gt(window,ue.RESIZE,this.onResize,!1),gt(window,ue.UNLOAD,this.onUnload,!1),gt(window,ue.BLUR,this.onBlur,!1),gt(this.excalidrawContainerRef.current,ue.WHEEL,this.handleWheel,{passive:!1}),gt(this.excalidrawContainerRef.current,ue.DRAG_OVER,this.disableEvent,!1),gt(this.excalidrawContainerRef.current,ue.DROP,this.disableEvent,!1)),this.props.detectScroll&&this.onRemoveEventListenersEmitter.once(gt(fj(this.excalidrawContainerRef.current),ue.SCROLL,this.onScroll,{passive:!1})))}componentDidUpdate(o,n){this.updateEmbeddables();let r=this.scene.getElementsIncludingDeleted(),i=this.scene.getElementsMapIncludingDeleted();!this.state.showWelcomeScreen&&!r.length&&this.setState({showWelcomeScreen:!0}),n.userToFollow&&!this.state.collaborators.has(n.userToFollow.socketId)&&this.maybeUnfollowRemoteUser(),(n.zoom.value!==this.state.zoom.value||n.scrollX!==this.state.scrollX||n.scrollY!==this.state.scrollY)&&(this.props?.onScrollChange?.(this.state.scrollX,this.state.scrollY,this.state.zoom),this.onScrollChangeEmitter.trigger(this.state.scrollX,this.state.scrollY,this.state.zoom)),n.userToFollow!==this.state.userToFollow&&(n.userToFollow&&this.onUserFollowEmitter.trigger({userToFollow:n.userToFollow,action:"UNFOLLOW"}),this.state.userToFollow&&this.onUserFollowEmitter.trigger({userToFollow:this.state.userToFollow,action:"FOLLOW"})),Object.keys(this.state.selectedElementIds).length&&po(this.state)&&this.setState({activeTool:er(this.state,{type:"selection"})}),this.state.activeTool.type==="eraser"&&n.theme!==this.state.theme&&Ef(this.interactiveCanvas,this.state.theme),n.activeTool.type==="selection"&&this.state.activeTool.type!=="selection"&&this.state.showHyperlinkPopup&&this.setState({showHyperlinkPopup:!1}),o.langCode!==this.props.langCode&&this.updateLanguage(),po(n)&&!po(this.state)&&this.eraserTrail.endPath(),o.viewModeEnabled!==this.props.viewModeEnabled&&this.setState({viewModeEnabled:!!this.props.viewModeEnabled}),n.viewModeEnabled!==this.state.viewModeEnabled&&(this.addEventListeners(),this.deselectElements()),(n.openDialog?.name==="elementLinkSelector"||this.state.openDialog?.name==="elementLinkSelector")&&n.openDialog?.name!==this.state.openDialog?.name&&(this.deselectElements(),this.setState({hoveredElementIds:{}})),o.zenModeEnabled!==this.props.zenModeEnabled&&this.setState({zenModeEnabled:!!this.props.zenModeEnabled}),o.theme!==this.props.theme&&this.props.theme&&this.setState({theme:this.props.theme}),this.excalidrawContainerRef.current?.classList.toggle("theme--dark",this.state.theme===Ig.DARK),this.state.selectedLinearElement?.isEditing&&!this.state.selectedElementIds[this.state.selectedLinearElement.elementId]&&setTimeout(()=>{this.state.selectedLinearElement?.isEditing&&this.actionManager.executeAction(to)}),this.state.editingTextElement?.isDeleted&&this.setState({editingTextElement:null}),this.store.commit(i,this.state),this.state.isLoading||(this.props.onChange?.(r,this.state,this.files),this.onChangeEmitter.trigger(r,this.state,this.files))}static resetTapTwice(){_d=!1,Dd=null}async insertClipboardContent(o,n,r){let{x:i,y:a}=ot({clientX:this.lastViewportPosition.x,clientY:this.lastViewportPosition.y},this.state);if(o.errorMessage){this.setState({errorMessage:o.errorMessage});return}if(n.length===0&&!r&&o.mixedContent){await this.addElementsFromMixedContentPaste(o.mixedContent,{isPlainPaste:r,sceneX:i,sceneY:a});return}if(o.spreadsheet&&!r){this.setState({pasteDialog:{data:o.spreadsheet,shown:!0}});return}let s=n.map(m=>m.file);if(s.length===0&&o.text&&!r){let m=o.text.trim();m.startsWith("<svg")&&m.endsWith("</svg>")&&s.push(oh(m))}if(s.length>0){this.isToolSupported("image")?await this.insertImages(s,i,a):this.setState({errorMessage:f("errors.imageToolNotSupported")});return}if(o.elements){let m=o.programmaticAPI?iP(o.elements):o.elements;this.addElementsFromPasteOrLibrary({elements:m,files:o.files||null,position:this.editorInterface.formFactor==="desktop"?"cursor":"center",retainSeed:r});return}if(!o.text)return;if(!r&&Q3(o.text)){let m=await import("@excalidraw/mermaid-to-excalidraw");try{let{elements:p,files:d}=await m.parseMermaidToExcalidraw(o.text),u=iP(p,{regenerateIds:!0});this.addElementsFromPasteOrLibrary({elements:u,files:d,position:this.editorInterface.formFactor==="desktop"?"cursor":"center"});return}catch(p){console.warn(`parsing pasted text as mermaid definition failed: ${p.message}`)}}let l=Ij(o.text).split(/\n+/).map(m=>m.trim()).filter(Boolean),c=l.map(m=>jj(m)).filter(m=>Nx(m,this.props.validateEmbeddable)&&(/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(m)||Ag(m)?.type==="video"));if(!r&&c.length>0&&c.length===l.length){let m=[];for(let p of c){let d=m[m.length-1],u=this.insertEmbeddableElement({sceneX:d?d.x+d.width+20:i,sceneY:a,link:Ix(p)});u&&m.push(u)}m.length&&(this.store.scheduleCapture(),this.setState({selectedElementIds:Object.fromEntries(m.map(p=>[p.id,!0]))}));return}this.addTextFromPaste(o.text,r)}async addElementsFromMixedContentPaste(o,{isPlainPaste:n,sceneX:r,sceneY:i}){if(!n&&o.some(a=>a.type==="imageUrl")&&this.isToolSupported("image")){let a=o.filter(m=>m.type==="imageUrl").map(m=>m.value),s=await Promise.all(a.map(async m=>{try{return{file:await ty(m)}}catch(p){let d=p.message;return p.cause==="FETCH_ERROR"?d=f("errors.failedToFetchImage"):p.cause==="UNSUPPORTED"&&(d=f("errors.unsupportedFileType")),{errorMessage:d}}})),l=s.filter(m=>!!m.file).map(m=>m.file);await this.insertImages(l,r,i);let c=s.find(m=>!!m.errorMessage);c&&c.errorMessage&&this.setState({errorMessage:c.errorMessage})}else{let a=o.filter(s=>s.type==="text");a.length&&this.addTextFromPaste(a.map(s=>s.value).join(`
213
+ `)}}}else d=Ag(hj(a.link||""));let u=this.state.activeEmbeddable?.element===a&&this.state.activeEmbeddable?.state==="active",h=this.state.activeEmbeddable?.element===a&&this.state.activeEmbeddable?.state==="hover";return Se("div",{className:l6("excalidraw__embeddable-container",{"is-hovered":h}),style:{transform:c?`translate(${s-this.state.offsetLeft}px, ${l-this.state.offsetTop}px) scale(${o})`:"none",display:c?"block":"none",opacity:Iq(a,Gx(a,this.scene.getNonDeletedElementsMap()),this.elementsPendingErasure,null,this.state.openDialog?.name==="elementLinkSelector"?uj:1),"--embeddable-radius":`${Zj(Math.min(a.width,a.height),a)}px`},children:Od("div",{className:"excalidraw__embeddable-container__inner",style:{width:c?`${a.width}px`:0,height:c?`${a.height}px`:0,transform:c?`rotate(${a.angle}rad)`:"none",pointerEvents:u?Sl.enabled:Sl.disabled},children:[h&&Se("div",{className:"excalidraw__embeddable-hint",children:f("buttons.embeddableInteractionButton")}),Se("div",{className:"excalidraw__embeddable__outer",style:{padding:`${a.strokeWidth}px`},children:(Lr(a)?this.props.renderEmbeddable?.(a,this.state):null)??Se("iframe",{ref:g=>this.cacheEmbeddableRef(a,g),className:"excalidraw__embeddable",srcDoc:d?.type==="document"?d.srcdoc(this.state.theme):void 0,src:d?.type!=="document"?d?.link??"":void 0,scrolling:"no",referrerPolicy:"no-referrer-when-downgrade",title:"Excalidraw Embedded Content",allow:"accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture",allowFullScreen:!0,sandbox:`${d?.sandbox?.allowSameOrigin?"allow-same-origin":""} allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation allow-downloads`})})]})},a.id)})})}toggleOverscrollBehavior(o){document.documentElement.style.overscrollBehaviorX=o.type==="pointerenter"?"none":"auto"}render(){let o=this.scene.getSelectedElements(this.state),{renderTopRightUI:n,renderTopLeftUI:r,renderCustomStats:i}=this.props,a=this.scene.getSceneNonce(),{elementsMap:s,visibleElements:l}=this.renderer.getRenderableElements({sceneNonce:a,zoom:this.state.zoom,offsetLeft:this.state.offsetLeft,offsetTop:this.state.offsetTop,scrollX:this.state.scrollX,scrollY:this.state.scrollY,height:this.state.height,width:this.state.width,editingTextElement:this.state.editingTextElement,newElementId:this.state.newElement?.id});this.visibleElements=l;let c=this.scene.getNonDeletedElementsMap(),m="setPointerCapture"in HTMLElement.prototype?!1:this.state.selectionElement||this.state.newElement||this.state.selectedElementsAreBeingDragged||this.state.resizingElement||this.state.activeTool.type==="laser"&&this.state.cursorButton==="down",p=o[0],d=xt.get(gn)?.type==="panel";return Se("div",{translate:"no",className:l6("excalidraw excalidraw-container notranslate",{"excalidraw--view-mode":this.state.viewModeEnabled||this.state.openDialog?.name==="elementLinkSelector","excalidraw--mobile":this.editorInterface.formFactor==="phone"}),style:{"--ui-pointerEvents":m?Sl.disabled:Sl.enabled,"--right-sidebar-width":"302px"},ref:this.excalidrawContainerRef,onDrop:this.handleAppOnDrop,tabIndex:0,onKeyDown:this.props.handleKeyboardGlobally?void 0:this.onKeyDown,onPointerEnter:this.toggleOverscrollBehavior,onPointerLeave:this.toggleOverscrollBehavior,children:Se(uP.Provider,{value:this,children:Se(gP.Provider,{value:this.props,children:Se(eE.Provider,{value:this.excalidrawContainerValue,children:Se(Qx.Provider,{value:this.editorInterface,children:Se(nE.Provider,{value:this.setAppState,children:Se(oE.Provider,{value:this.state,children:Od(tE.Provider,{value:this.scene.getNonDeletedElements(),children:[Od(rE.Provider,{value:this.actionManager,children:[Se(M4,{canvas:this.canvas,appState:this.state,files:this.files,setAppState:this.setAppState,actionManager:this.actionManager,elements:this.scene.getNonDeletedElements(),onLockToggle:this.toggleLock,onPenModeToggle:this.togglePenMode,onHandToolToggle:this.onHandToolToggle,langCode:lr().code,renderTopLeftUI:r,renderTopRightUI:n,renderCustomStats:i,showExitZenModeBtn:typeof this.props?.zenModeEnabled>"u"&&this.state.zenModeEnabled,UIOptions:this.props.UIOptions,onExportImage:this.onExportImage,renderWelcomeScreen:!this.state.isLoading&&this.state.showWelcomeScreen&&this.state.activeTool.type===this.state.preferredSelectionTool.type&&!this.state.zenModeEnabled&&!this.scene.getElementsIncludingDeleted().length,app:this,isCollaborating:this.props.isCollaborating,generateLinkForSelection:this.props.generateLinkForSelection,children:this.props.children}),Se("div",{className:"excalidraw-textEditorContainer"}),Se("div",{className:"excalidraw-contextMenuContainer"}),Se("div",{className:"excalidraw-eye-dropper-container"}),Se(L4,{trails:[this.laserTrails,this.lassoTrail,this.eraserTrail]}),o.length===1&&this.state.openDialog?.name!=="elementLinkSelector"&&this.state.showHyperlinkPopup&&Se(UI,{element:p,scene:this.scene,setAppState:this.setAppState,onLinkOpen:this.props.onLinkOpen,setToast:this.setToast,updateEmbedValidationStatus:this.updateEmbedValidationStatus},p.id),this.props.aiEnabled!==!1&&o.length===1&&_x(p)&&Se(v0,{element:p,elementsMap:s,children:Se(xg,{title:f("labels.convertToCode"),icon:Gi,checked:!1,onChange:()=>this.onMagicFrameGenerate(p,"button")})}),o.length===1&&Ll(p)&&p.customData?.generationData?.status==="done"&&Od(v0,{element:p,elementsMap:s,children:[Se(xg,{title:f("labels.copySource"),icon:Qa,checked:!1,onChange:()=>this.onIframeSrcCopy(p)}),Se(xg,{title:"Enter fullscreen",icon:kw,checked:!1,onChange:()=>{let u=this.getHTMLIFrameElement(p);if(u)try{u.requestFullscreen(),this.setState({activeEmbeddable:{element:p,state:"active"},selectedElementIds:{[p.id]:!0},newElement:null,selectionElement:null})}catch(h){console.warn(h),this.setState({errorMessage:"Couldn't enter fullscreen"})}}})]}),o.length===1&&jt(p)&&p.customData?.type!=="image-generator"&&!this.state.viewModeEnabled&&Se(t3,{element:p,app:this}),Se(n3,{}),Se(M3,{app:this}),o.length===1&&jt(p)&&p.customData?.type==="image-generator"&&!this.state.viewModeEnabled&&Se(c3,{element:p,app:this,onBeforeImageGen:this.props.onBeforeImageGen,onAfterImageGen:this.props.onAfterImageGen}),o.length===1&&Mi(p)&&!this.state.viewModeEnabled&&Se(F3,{element:p,app:this,callbacks:this.props.imageEditToolbarCallbacks}),this.state.toast!==null&&Se(a6,{message:this.state.toast.message,onClose:this.handleToastClose,duration:this.state.toast.duration,closable:this.state.toast.closable}),this.state.contextMenu&&Se(Ek,{items:this.state.contextMenu.items,top:this.state.contextMenu.top,left:this.state.contextMenu.left,actionManager:this.actionManager,onClose:u=>{this.setState({contextMenu:null},()=>{this.focusContainer(),u?.()})}}),Se(xx,{canvas:this.canvas,rc:this.rc,elementsMap:s,allElementsMap:c,visibleElements:l,sceneNonce:a,selectionNonce:this.state.selectionElement?.versionNonce,scale:window.devicePixelRatio,appState:this.state,renderConfig:{imageCache:this.imageCache,isExporting:!1,renderGrid:ai(this),canvasBackgroundColor:this.state.viewBackgroundColor,embedsValidationStatus:this.embedsValidationStatus,elementsPendingErasure:this.elementsPendingErasure,pendingFlowchartNodes:this.flowChartCreator.pendingNodes,theme:this.state.theme}}),this.state.newElement&&Se(r6,{appState:this.state,scale:window.devicePixelRatio,rc:this.rc,elementsMap:s,allElementsMap:c,renderConfig:{imageCache:this.imageCache,isExporting:!1,renderGrid:!1,canvasBackgroundColor:this.state.viewBackgroundColor,embedsValidationStatus:this.embedsValidationStatus,elementsPendingErasure:this.elementsPendingErasure,pendingFlowchartNodes:null,theme:this.state.theme}}),Se(bx,{app:this,containerRef:this.excalidrawContainerRef,canvas:this.interactiveCanvas,elementsMap:s,visibleElements:l,allElementsMap:c,selectedElements:o,sceneNonce:a,selectionNonce:this.state.selectionElement?.versionNonce,scale:window.devicePixelRatio,appState:this.state,renderScrollbars:this.props.renderScrollbars===!0,editorInterface:this.editorInterface,renderInteractiveSceneCallback:this.renderInteractiveSceneCallback,handleCanvasRef:this.handleInteractiveCanvasRef,onContextMenu:this.handleCanvasContextMenu,onPointerMove:this.handleCanvasPointerMove,onPointerUp:this.handleCanvasPointerUp,onPointerCancel:this.removePointer,onTouchMove:this.handleTouchMove,onPointerDown:this.handleCanvasPointerDown,onDoubleClick:this.handleCanvasDoubleClick}),this.state.userToFollow&&Se(wk,{width:this.state.width,height:this.state.height,userToFollow:this.state.userToFollow,onDisconnect:this.maybeUnfollowRemoteUser}),this.renderFrameNames(),this.state.activeLockedId&&Se(s6,{app:this,activeLockedId:this.state.activeLockedId}),d&&Se(iT,{app:this})]}),this.renderEmbeddables()]})})})})})})})})}setPlugins(o){Object.assign(this.plugins,o)}async onMagicFrameGenerate(o,n){let r=this.plugins.diagramToCode?.generate;if(!r){this.setState({errorMessage:"No diagram to code plugin found"});return}let i=sq(this.scene.getNonDeletedElements(),o).filter(s=>!_x(s));if(!i.length){n==="button"?(this.setState({errorMessage:"Cannot generate from an empty frame"}),ge("ai","generate (no-children)","d2c")):this.setActiveTool({type:"magicframe"});return}let a=this.insertIframeElement({sceneX:o.x+o.width+30,sceneY:o.y,width:o.width,height:o.height});if(a){this.updateMagicGeneration({frameElement:a,data:{status:"pending"}}),this.setState({selectedElementIds:{[a.id]:!0}}),ge("ai","generate (start)","d2c");try{let{html:s}=await r({frame:o,children:i});if(ge("ai","generate (success)","d2c"),!s.trim()){this.updateMagicGeneration({frameElement:a,data:{status:"error",code:"ERR_OAI",message:"Nothing genereated :("}});return}let l=s.includes("<!DOCTYPE html>")&&s.includes("</html>")?s.slice(s.indexOf("<!DOCTYPE html>"),s.indexOf("</html>")+7):s;this.updateMagicGeneration({frameElement:a,data:{status:"done",html:l}})}catch(s){ge("ai","generate (failed)","d2c"),this.updateMagicGeneration({frameElement:a,data:{status:"error",code:"ERR_OAI",message:s.message||"Unknown error during generation"}})}}}onIframeSrcCopy(o){o.customData?.generationData?.status==="done"&&(pn(o.customData.generationData.html),this.setToast({message:"copied to clipboard",closable:!1,duration:1500}))}clearImageShapeCache(o){let n=o??this.files;this.scene.getNonDeletedElements().forEach(r=>{Pd(r)&&n[r.fileId]&&(this.imageCache.delete(r.fileId),Ld.delete(r))})}async componentDidMount(){if(this.unmounted=!1,this.excalidrawContainerValue.container=this.excalidrawContainerRef.current,cP()||dP()){let r=this.setState.bind(this);Object.defineProperties(window.h,{state:{configurable:!0,get:()=>this.state},setState:{configurable:!0,value:(...i)=>this.setState(...i)},app:{configurable:!0,value:this},history:{configurable:!0,value:this.history},store:{configurable:!0,value:this.store},fonts:{configurable:!0,value:this.fonts}})}this.store.onDurableIncrementEmitter.on(r=>{this.history.record(r.delta)});let{onIncrement:o}=this.props;o&&this.store.onStoreIncrementEmitter.on(r=>{o(r)}),this.scene.onUpdate(this.triggerRender),this.addEventListeners(),this.props.autoFocus&&this.excalidrawContainerRef.current&&this.focusContainer(),mj&&this.excalidrawContainerRef.current&&(this.resizeObserver=new ResizeObserver(()=>{this.refreshEditorInterface(),this.updateDOMRect()}),this.resizeObserver?.observe(this.excalidrawContainerRef.current)),new URLSearchParams(window.location.search.slice(1)).has("web-share-target")?this.restoreFileFromShare():this.updateDOMRect(this.initializeScene),Lj()&&!bq()&&this.setState({errorMessage:Se(hk,{})})}componentWillUnmount(){window.launchQueue?.setConsumer(()=>{}),this.renderer.destroy(),this.scene.destroy(),this.scene=new eP,this.fonts=new Mn(this.scene),this.renderer=new qc(this.scene),this.files={},this.imageCache.clear(),this.resizeObserver?.disconnect(),this.unmounted=!0,this.removeEventListeners(),this.library.destroy(),this.laserTrails.stop(),this.eraserTrail.stop(),this.onChangeEmitter.clear(),this.store.onStoreIncrementEmitter.clear(),this.store.onDurableIncrementEmitter.clear(),Ld.destroy(),$o.destroy(),clearTimeout(Ai),He.clearCache(),nn.clearCache(),Ai=0,document.documentElement.style.overscrollBehaviorX=""}removeEventListeners(){this.onRemoveEventListenersEmitter.trigger()}addEventListeners(){this.removeEventListeners(),this.props.handleKeyboardGlobally&&this.onRemoveEventListenersEmitter.once(gt(document,ue.KEYDOWN,this.onKeyDown,!1)),this.onRemoveEventListenersEmitter.once(gt(this.excalidrawContainerRef.current,ue.WHEEL,this.handleWheel,{passive:!1}),gt(window,ue.MESSAGE,this.onWindowMessage,!1),gt(document,ue.POINTER_UP,this.removePointer,{passive:!1}),gt(document,ue.COPY,this.onCopy,{passive:!1}),gt(document,ue.KEYUP,this.onKeyUp,{passive:!0}),gt(document,ue.POINTER_MOVE,this.updateCurrentCursorPosition,{passive:!1}),gt(document.fonts,"loadingdone",o=>{let n=o.fontfaces;this.fonts.onLoaded(n)},{passive:!1}),gt(document,ue.GESTURE_START,this.onGestureStart,!1),gt(document,ue.GESTURE_CHANGE,this.onGestureChange,!1),gt(document,ue.GESTURE_END,this.onGestureEnd,!1),gt(window,ue.FOCUS,()=>{this.maybeCleanupAfterMissingPointerUp(null),this.triggerRender(!0)},{passive:!1})),!this.state.viewModeEnabled&&(this.onRemoveEventListenersEmitter.once(gt(document,ue.FULLSCREENCHANGE,this.onFullscreenChange,{passive:!1}),gt(document,ue.PASTE,this.pasteFromClipboard,{passive:!1}),gt(document,ue.CUT,this.onCut,{passive:!1}),gt(window,ue.RESIZE,this.onResize,!1),gt(window,ue.UNLOAD,this.onUnload,!1),gt(window,ue.BLUR,this.onBlur,!1),gt(this.excalidrawContainerRef.current,ue.WHEEL,this.handleWheel,{passive:!1}),gt(this.excalidrawContainerRef.current,ue.DRAG_OVER,this.disableEvent,!1),gt(this.excalidrawContainerRef.current,ue.DROP,this.disableEvent,!1)),this.props.detectScroll&&this.onRemoveEventListenersEmitter.once(gt(fj(this.excalidrawContainerRef.current),ue.SCROLL,this.onScroll,{passive:!1})))}componentDidUpdate(o,n){this.updateEmbeddables();let r=this.scene.getElementsIncludingDeleted(),i=this.scene.getElementsMapIncludingDeleted();!this.state.showWelcomeScreen&&!r.length&&this.setState({showWelcomeScreen:!0}),n.userToFollow&&!this.state.collaborators.has(n.userToFollow.socketId)&&this.maybeUnfollowRemoteUser(),(n.zoom.value!==this.state.zoom.value||n.scrollX!==this.state.scrollX||n.scrollY!==this.state.scrollY)&&(this.props?.onScrollChange?.(this.state.scrollX,this.state.scrollY,this.state.zoom),this.onScrollChangeEmitter.trigger(this.state.scrollX,this.state.scrollY,this.state.zoom)),n.userToFollow!==this.state.userToFollow&&(n.userToFollow&&this.onUserFollowEmitter.trigger({userToFollow:n.userToFollow,action:"UNFOLLOW"}),this.state.userToFollow&&this.onUserFollowEmitter.trigger({userToFollow:this.state.userToFollow,action:"FOLLOW"})),Object.keys(this.state.selectedElementIds).length&&po(this.state)&&this.setState({activeTool:er(this.state,{type:"selection"})}),this.state.activeTool.type==="eraser"&&n.theme!==this.state.theme&&Ef(this.interactiveCanvas,this.state.theme),n.activeTool.type==="selection"&&this.state.activeTool.type!=="selection"&&this.state.showHyperlinkPopup&&this.setState({showHyperlinkPopup:!1}),o.langCode!==this.props.langCode&&this.updateLanguage(),po(n)&&!po(this.state)&&this.eraserTrail.endPath(),o.viewModeEnabled!==this.props.viewModeEnabled&&this.setState({viewModeEnabled:!!this.props.viewModeEnabled}),n.viewModeEnabled!==this.state.viewModeEnabled&&(this.addEventListeners(),this.deselectElements()),(n.openDialog?.name==="elementLinkSelector"||this.state.openDialog?.name==="elementLinkSelector")&&n.openDialog?.name!==this.state.openDialog?.name&&(this.deselectElements(),this.setState({hoveredElementIds:{}})),o.zenModeEnabled!==this.props.zenModeEnabled&&this.setState({zenModeEnabled:!!this.props.zenModeEnabled}),o.theme!==this.props.theme&&this.props.theme&&this.setState({theme:this.props.theme}),this.excalidrawContainerRef.current?.classList.toggle("theme--dark",this.state.theme===Ig.DARK),this.state.selectedLinearElement?.isEditing&&!this.state.selectedElementIds[this.state.selectedLinearElement.elementId]&&setTimeout(()=>{this.state.selectedLinearElement?.isEditing&&this.actionManager.executeAction(oo)}),this.state.editingTextElement?.isDeleted&&this.setState({editingTextElement:null}),this.store.commit(i,this.state),this.state.isLoading||(this.props.onChange?.(r,this.state,this.files),this.onChangeEmitter.trigger(r,this.state,this.files))}static resetTapTwice(){_d=!1,Dd=null}async insertClipboardContent(o,n,r){let{x:i,y:a}=ot({clientX:this.lastViewportPosition.x,clientY:this.lastViewportPosition.y},this.state);if(o.errorMessage){this.setState({errorMessage:o.errorMessage});return}if(n.length===0&&!r&&o.mixedContent){await this.addElementsFromMixedContentPaste(o.mixedContent,{isPlainPaste:r,sceneX:i,sceneY:a});return}if(o.spreadsheet&&!r){this.setState({pasteDialog:{data:o.spreadsheet,shown:!0}});return}let s=n.map(m=>m.file);if(s.length===0&&o.text&&!r){let m=o.text.trim();m.startsWith("<svg")&&m.endsWith("</svg>")&&s.push(oh(m))}if(s.length>0){this.isToolSupported("image")?await this.insertImages(s,i,a):this.setState({errorMessage:f("errors.imageToolNotSupported")});return}if(o.elements){let m=o.programmaticAPI?iP(o.elements):o.elements;this.addElementsFromPasteOrLibrary({elements:m,files:o.files||null,position:this.editorInterface.formFactor==="desktop"?"cursor":"center",retainSeed:r});return}if(!o.text)return;if(!r&&Q3(o.text)){let m=await import("@excalidraw/mermaid-to-excalidraw");try{let{elements:p,files:d}=await m.parseMermaidToExcalidraw(o.text),u=iP(p,{regenerateIds:!0});this.addElementsFromPasteOrLibrary({elements:u,files:d,position:this.editorInterface.formFactor==="desktop"?"cursor":"center"});return}catch(p){console.warn(`parsing pasted text as mermaid definition failed: ${p.message}`)}}let l=Ij(o.text).split(/\n+/).map(m=>m.trim()).filter(Boolean),c=l.map(m=>jj(m)).filter(m=>Nx(m,this.props.validateEmbeddable)&&(/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(m)||Ag(m)?.type==="video"));if(!r&&c.length>0&&c.length===l.length){let m=[];for(let p of c){let d=m[m.length-1],u=this.insertEmbeddableElement({sceneX:d?d.x+d.width+20:i,sceneY:a,link:Ix(p)});u&&m.push(u)}m.length&&(this.store.scheduleCapture(),this.setState({selectedElementIds:Object.fromEntries(m.map(p=>[p.id,!0]))}));return}this.addTextFromPaste(o.text,r)}async addElementsFromMixedContentPaste(o,{isPlainPaste:n,sceneX:r,sceneY:i}){if(!n&&o.some(a=>a.type==="imageUrl")&&this.isToolSupported("image")){let a=o.filter(m=>m.type==="imageUrl").map(m=>m.value),s=await Promise.all(a.map(async m=>{try{return{file:await ty(m)}}catch(p){let d=p.message;return p.cause==="FETCH_ERROR"?d=f("errors.failedToFetchImage"):p.cause==="UNSUPPORTED"&&(d=f("errors.unsupportedFileType")),{errorMessage:d}}})),l=s.filter(m=>!!m.file).map(m=>m.file);await this.insertImages(l,r,i);let c=s.find(m=>!!m.errorMessage);c&&c.errorMessage&&this.setState({errorMessage:c.errorMessage})}else{let a=o.filter(s=>s.type==="text");a.length&&this.addTextFromPaste(a.map(s=>s.value).join(`
214
214
 
215
215
  `),n)}}addTextFromPaste(o,n=!1){let{x:r,y:i}=ot({clientX:this.lastViewportPosition.x,clientY:this.lastViewportPosition.y},this.state),a={x:r,y:i,strokeColor:this.state.currentItemStrokeColor,backgroundColor:this.state.currentItemBackgroundColor,fillStyle:this.state.currentItemFillStyle,strokeWidth:this.state.currentItemStrokeWidth,strokeStyle:this.state.currentItemStrokeStyle,roundness:null,roughness:this.state.currentItemRoughness,opacity:this.state.currentItemOpacity,text:o,fontSize:this.state.currentItemFontSize,fontFamily:this.state.currentItemFontFamily,textAlign:pj,verticalAlign:b6,locked:!1},s=Tx({fontSize:a.fontSize,fontFamily:a.fontFamily}),l=v6(a.fontFamily),[c,,m]=mq(this.state),p=Math.max(Math.min((m-c)*.5,800),200),d=10,u=i,h=n?[o]:o.split(`
216
- `),g=h.reduce((E,w,x)=>{let y=xq(w).trim();if(y.length){let v=this.getTopLayerFrameAtSceneCoords({x:r,y:u}),I=$6(y,s,l),k=I.width>p,L=k?hq(y,s,p):y;I=k?$6(L,s,l):I;let S=r-I.width/2,_=u-I.height/2,P=_6({...a,x:S,y:_,text:L,originalText:y,lineHeight:l,autoResize:!k,frameId:v?v.id:null});E.push(P),u+=P.height+d}else h[x-1]?.trim()&&(u+=Eq(a.fontSize,l)+d);return E},[]);g.length!==0&&(this.scene.insertElements(g),this.store.scheduleCapture(),this.setState({selectedElementIds:Oe(Object.fromEntries(g.map(E=>[E.id,!0])),this.state)}),!n&&g.length>1&&sP===!1&&this.editorInterface.formFactor!=="phone"&&(this.setToast({message:f("toast.pasteAsSingleElement",{shortcut:G("CtrlOrCmd+Shift+V")}),duration:5e3}),sP=!0))}handleTextWysiwyg(o,{isExistingElement:n=!1}){let r=this.scene.getElementsMapIncludingDeleted(),i=(a,s)=>{this.scene.replaceAllElements([...this.scene.getElementsIncludingDeleted().map(l=>l.id===o.id&&vn(l)?Si(l,{originalText:a,isDeleted:s??l.isDeleted,...Wj(l,G6(l,r),r,a)}):l)])};j3({id:o.id,canvas:this.canvas,getViewportCoords:(a,s)=>{let{x:l,y:c}=Cg({sceneX:a,sceneY:s},this.state);return[l-this.state.offsetLeft,c-this.state.offsetTop]},onChange:mt(a=>{i(a,!1),Q6(o)&&Pg(o,this.scene)}),onSubmit:mt(({viaKeyboard:a,nextOriginalText:s})=>{let l=!s.trim();if(i(s,l),!l&&a){let c=o.containerId?o.containerId:o.id;wo(()=>{this.setState(m=>({selectedElementIds:Oe({...m.selectedElementIds,[c]:!0},m)}))})}l&&Bj(this.scene.getNonDeletedElements(),[o]),(!l||n)&&this.store.scheduleCapture(),wo(()=>{this.setState({newElement:null,editingTextElement:null})}),this.state.activeTool.locked&&Mo(this.interactiveCanvas,this.state),this.focusContainer()}),element:o,excalidrawContainer:this.excalidrawContainerRef.current,app:this,autoSelect:!this.editorInterface.isTouchScreen}),this.deselectElements(),i(o.originalText,!1)}deselectElements(){this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null})}getTextElementAtPosition(o,n){let r=this.getElementAtPosition(o,n,{includeBoundTextElement:!0});return r&&vn(r)&&!r.isDeleted?r:null}getElementAtPosition(o,n,r){let i=[];if(r&&"allHitElements"in r?i=r?.allHitElements||[]:i=this.getElementsAtPosition(o,n,{includeBoundTextElement:r?.includeBoundTextElement,includeLockedElements:r?.includeLockedElements}),i.length>1){if(r?.preferSelected){for(let s=i.length-1;s>-1;s--)if(this.state.selectedElementIds[i[s].id])return i[s]}let a=i[i.length-1];return Ad({point:de(o,n),element:a,threshold:this.getElementHitThreshold(a)/2,elementsMap:this.scene.getNonDeletedElementsMap(),frameNameBound:jt(a)?this.frameNameBoundsCache.get(a):null})?a:i[i.length-2]}return i.length===1?i[0]:null}getElementsAtPosition(o,n,r){let i=[],a=this.scene.getNonDeletedElementsMap();return(r?.includeBoundTextElement&&r?.includeLockedElements?this.scene.getNonDeletedElements():this.scene.getNonDeletedElements().filter(l=>(r?.includeLockedElements||!l.locked)&&(r?.includeBoundTextElement||!(vn(l)&&l.containerId)))).filter(l=>this.hitElement(o,n,l)).filter(l=>{let c=Gx(l,a);return c&&this.state.frameRendering.enabled&&this.state.frameRendering.clip?U6({x:o,y:n},c,a):!0}).filter(l=>Ll(l)?(i.push(l),!1):!0).concat(i)}getElementHitThreshold(o){return Math.max(o.strokeWidth/2+.1,.85*(w6/this.state.zoom.value))}hitElement(o,n,r,i=!0){return i&&this.state.selectedElementIds[r.id]&&tq([r],this.state,this.editorInterface)&&Bq(de(o,n),r,this.scene.getNonDeletedElementsMap(),this.getElementHitThreshold(r))||cq(de(o,n),r,this.scene.getNonDeletedElementsMap())?!0:Ad({point:de(o,n),element:r,threshold:this.getElementHitThreshold(r),elementsMap:this.scene.getNonDeletedElementsMap(),frameNameBound:jt(r)?this.frameNameBoundsCache.get(r):null})}getTextBindableContainerAtPosition(o,n){let r=this.scene.getNonDeletedElements(),i=this.scene.getSelectedElements(this.state);if(i.length===1)return N6(i[0],!1)?i[0]:null;let a=null;for(let s=r.length-1;s>=0;--s){if(r[s].isDeleted)continue;let[l,c,m,p]=Mg(r[s],this.scene.getNonDeletedElementsMap());if(Al(r[s])&&Ad({point:de(o,n),element:r[s],elementsMap:this.scene.getNonDeletedElementsMap(),threshold:this.getElementHitThreshold(r[s])})){a=r[s];break}else if(l<o&&o<m&&c<n&&n<p){a=r[s];break}}return N6(a,!1)?a:null}handleHoverSelectedLinearElement(o,n,r){let i=this.scene.getNonDeletedElementsMap(),a=Me.getElement(o.elementId,i);if(a)if(this.state.selectedLinearElement){let s=-1,l=null;Ad({point:de(n,r),element:a,elementsMap:i,threshold:this.getElementHitThreshold(a)})?(s=Me.getPointIndexUnderCursor(a,i,this.state.zoom,n,r),l=Me.getSegmentMidpointHitCoords(o,{x:n,y:r},this.state,this.scene.getNonDeletedElementsMap()),(vo(a)?s===0||s===a.points.length-1:s>=0)||l?Re(this.interactiveCanvas,st.POINTER):this.hitElement(n,r,a)&&(!vo(a)||!(a.startBinding||a.endBinding))&&(this.state.activeTool.type!=="lasso"||Object.keys(this.state.selectedElementIds).length>0)&&Re(this.interactiveCanvas,st.MOVE)):this.hitElement(n,r,a)&&(!vo(a)||!(a.startBinding||a.endBinding))&&(this.state.activeTool.type!=="lasso"||Object.keys(this.state.selectedElementIds).length>0)&&Re(this.interactiveCanvas,st.MOVE),this.state.selectedLinearElement.hoverPointIndex!==s&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,hoverPointIndex:s}}),Me.arePointsEqual(this.state.selectedLinearElement.segmentMidPointHoveredCoords,l)||this.setState({selectedLinearElement:{...this.state.selectedLinearElement,segmentMidPointHoveredCoords:l}});let c=null,m=a;(m.startBinding||m.endBinding)&&(c=Gq(a,n,r,this.scene,this.state)),this.state.selectedLinearElement.hoveredFocusPointBinding!==c&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,isDragging:!1,hoveredFocusPointBinding:c}}),c&&Re(this.interactiveCanvas,st.POINTER)}else Re(this.interactiveCanvas,st.AUTO)}updateGestureOnPointerDown(o){_e.pointers.set(o.pointerId,{x:o.clientX,y:o.clientY}),_e.pointers.size===2&&(_e.lastCenter=f0(_e.pointers),_e.initialScale=this.state.zoom.value,_e.initialDistance=b0(Array.from(_e.pointers.values())))}initialPointerDownState(o){let n=ot(o,this.state),r=this.scene.getSelectedElements(this.state),[i,a,s,l]=Pl(r),c=r.findIndex(vo)===0;return{origin:n,withCmdOrCtrl:o[oe.CTRL_OR_CMD],originInGrid:Cx(Zt(n.x,n.y,o[oe.CTRL_OR_CMD]||c?null:this.getEffectiveGridSize())),scrollbars:V0(Nd,o.clientX-this.state.offsetLeft,o.clientY-this.state.offsetTop),lastCoords:{...n},originalElements:this.scene.getNonDeletedElements().reduce((m,p)=>(m.set(p.id,D6(p)),m),new Map),resize:{handleType:!1,isResizing:!1,offset:{x:0,y:0},arrowDirection:"origin",center:{x:(s+i)/2,y:(l+a)/2}},hit:{element:null,allHitElements:[],wasAddedToSelection:!1,hasBeenDuplicated:!1,hasHitCommonBoundingBoxOfSelectedElements:this.isHittingCommonBoundingBoxOfSelectedElements(n,r)},drag:{hasOccurred:!1,offset:null,origin:{...n},blockDragging:!1},eventListeners:{onMove:null,onUp:null,onKeyUp:null,onKeyDown:null},boxSelection:{hasOccurred:!1}}}handleDraggingScrollBar(o,n){if(!(n.scrollbars.isOverEither&&!this.state.multiElement))return!1;Xx=!0,n.lastCoords.x=o.clientX,n.lastCoords.y=o.clientY;let r=Su(a=>{a.target instanceof HTMLElement&&this.handlePointerMoveOverScrollbars(a,n)}),i=mt(()=>{Fd=null,Xx=!1,Mo(this.interactiveCanvas,this.state),this.setState({cursorButton:"up"}),this.savePointer(o.clientX,o.clientY,"up"),window.removeEventListener(ue.POINTER_MOVE,r),window.removeEventListener(ue.POINTER_UP,i),r.flush()});return Fd=i,window.addEventListener(ue.POINTER_MOVE,r),window.addEventListener(ue.POINTER_UP,i),!0}isASelectedElement(o){return o!=null&&this.state.selectedElementIds[o.id]}isHittingCommonBoundingBoxOfSelectedElements(o,n){if(n.length<2)return!1;let r=Math.max(w6/this.state.zoom.value,1),[i,a,s,l]=Pl(n);return o.x>i-r&&o.x<s+r&&o.y>a-r&&o.y<l+r}getCurrentItemRoundness(o){return this.state.currentItemRoundness==="round"?{type:$j(o)?vg.ADAPTIVE_RADIUS:vg.PROPORTIONAL_RADIUS}:null}maybeCacheReferenceSnapPoints(o,n,r=!1){wr({event:o,app:this,selectedElements:n})&&(r||!$o.getReferenceSnapPoints())&&$o.setReferenceSnapPoints(X5(this.scene.getNonDeletedElements(),n,this.state,this.scene.getNonDeletedElementsMap()))}maybeCacheVisibleGaps(o,n,r=!1){wr({event:o,app:this,selectedElements:n})&&(r||!$o.getVisibleGaps())&&$o.setVisibleGaps(K5(this.scene.getNonDeletedElements(),n,this.state,this.scene.getNonDeletedElementsMap()))}onKeyDownFromPointerDownHandler(o){return mt(n=>{this.maybeHandleResize(o,n)||this.maybeDragNewGenericElement(o,n)})}onKeyUpFromPointerDownHandler(o){return mt(n=>{n.key===oe.ALT&&n.preventDefault(),!this.maybeHandleResize(o,n)&&this.maybeDragNewGenericElement(o,n)})}onPointerMoveFromPointerDownHandler(o){return Su(n=>{if(this.state.openDialog?.name==="elementLinkSelector")return;let r=ot(n,this.state);if(this.state.activeLockedId&&this.setState({activeLockedId:null}),this.state.selectedLinearElement&&this.state.selectedLinearElement.elbowed&&this.state.selectedLinearElement.initialState.segmentMidpoint.index){let[d,u]=Zt(r.x,r.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),h=this.state.selectedLinearElement.initialState.segmentMidpoint.index;if(h<0){let E=Me.getSegmentMidpointHitCoords({...this.state.selectedLinearElement,segmentMidPointHoveredCoords:null},{x:d,y:u},this.state,this.scene.getNonDeletedElementsMap());h=E?Me.getSegmentMidPointIndex(this.state.selectedLinearElement,this.state,E,this.scene.getNonDeletedElementsMap()):-1}let g=Me.moveFixedSegment(this.state.selectedLinearElement,h,d,u,this.scene);this.setState({selectedLinearElement:{...this.state.selectedLinearElement,isDragging:!0,segmentMidPointHoveredCoords:g.segmentMidPointHoveredCoords,initialState:g.initialState}});return}let i=this.previousPointerMoveCoords??o.origin;if(this.previousPointerMoveCoords=r,o.drag.offset===null&&(o.drag.offset=Cx(Rq(this.scene.getSelectedElements(this.state),o.origin.x,o.origin.y))),!(n.target instanceof HTMLElement)||this.handlePointerMoveOverScrollbars(n,o))return;if(po(this.state)){this.handleEraser(n,r);return}this.state.activeTool.type==="laser"&&this.laserTrails.addPointToPath(r.x,r.y);let[s,l]=Zt(r.x,r.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize());if(o.resize.isResizing&&(o.lastCoords.x=r.x,o.lastCoords.y=r.y,this.maybeHandleCrop(o,n)||this.maybeHandleResize(o,n)))return!0;let c=this.scene.getNonDeletedElementsMap();if(this.state.selectedLinearElement){let d=this.state.selectedLinearElement;if(d.draggedFocusPointBinding){Hq(d,c,r,this.scene,this.state,this.getEffectiveGridSize(),n.altKey),this.setState({selectedLinearElement:{...d,isDragging:!1,selectedPointsIndices:[],initialState:{...d.initialState,lastClickedPoint:-1}}});return}if(Me.shouldAddMidpoint(this.state.selectedLinearElement,r,this.state,c)){let u=Me.addMidpoint(this.state.selectedLinearElement,r,this,!n[oe.CTRL_OR_CMD],this.scene);if(!u)return;wo(()=>{this.state.selectedLinearElement&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,initialState:u.pointerDownState,selectedPointsIndices:u.selectedPointsIndices,segmentMidPointHoveredCoords:null}})});return}else{if(d.initialState.segmentMidpoint.value!==null&&!d.initialState.segmentMidpoint.added)return;if(d.initialState.lastClickedPoint>-1){let u=Me.getElement(d.elementId,c);if(u?.isDeleted)return;if(or(u)){let g=wn(de(r.x,r.y),this.scene.getNonDeletedElements(),c);Ar("COMPLEX_BINDINGS")&&this.handleDelayedBindModeChange(u,g)}if(n.altKey&&!this.state.selectedLinearElement?.initialState?.arrowStartIsInside&&Ar("COMPLEX_BINDINGS")&&this.handleSkipBindMode(),d.initialState.lastClickedPoint===-1)return;let h=Me.handlePointDragging(n,this,r.x,r.y,d);if(h){o.lastCoords.x=r.x,o.lastCoords.y=r.y,o.drag.hasOccurred=!0,(h.suggestedBinding!==this.state.suggestedBinding||!k6(h.selectedLinearElement?.selectedPointsIndices??[],this.state.selectedLinearElement?.selectedPointsIndices??[])||h.selectedLinearElement?.hoverPointIndex!==this.state.selectedLinearElement?.hoverPointIndex||h.selectedLinearElement?.customLineAngle!==this.state.selectedLinearElement?.customLineAngle||this.state.selectedLinearElement.isDragging!==h.selectedLinearElement?.isDragging||this.state.selectedLinearElement?.initialState?.altFocusPoint!==h.selectedLinearElement?.initialState?.altFocusPoint)&&this.setState(h);return}}}}let m=o.hit.allHitElements.some(d=>this.isASelectedElement(d)),p=this.state.selectedLinearElement?.isEditing&&n.shiftKey&&this.state.selectedLinearElement.elementId===o.hit.element?.id;if((m||o.hit.hasHitCommonBoundingBoxOfSelectedElements)&&!p&&!o.drag.blockDragging){let d=this.scene.getSelectedElements(this.state);if(d.length>0&&d.every(E=>E.locked))return;let u=d.find(E=>jt(E)),h=this.getTopLayerFrameAtSceneCoords(r),g=h&&!u?h:null;if(this.state.frameToHighlight!==g&&wo(()=>{this.setState({frameToHighlight:g})}),o.drag.hasOccurred=!0,this.state.activeTool.type==="lasso"&&this.lassoTrail.hasCurrentTrail&&!(this.editorInterface.formFactor!=="desktop"&&o.hit.element)&&!this.state.activeTool.fromSelection)return;if(this.state.activeTool.type==="lasso"&&d.length>0&&o.drag.hasOccurred&&!this.state.activeTool.fromSelection&&this.lassoTrail.endPath(),d.length>0&&!o.withCmdOrCtrl&&!this.state.editingTextElement&&this.state.activeEmbeddable?.state!=="active"){let E={x:r.x-o.drag.origin.x,y:r.y-o.drag.origin.y},w=[...o.originalElements.values()],x=n.shiftKey;if(x){let I=Math.abs(E.x),k=Math.abs(E.y),L=x&&I<k,S=x&&I>k;L&&(E.x=0),S&&(E.y=0)}if(this.state.croppingElementId){let I=this.scene.getNonDeletedElementsMap().get(this.state.croppingElementId);if(I&&Mi(I)&&I.crop!==null&&o.hit.element===I){let k=I.crop,L=Pd(I)&&this.imageCache.get(I.fileId)?.image;if(L&&!(L instanceof Promise)){let S=Yq(I),_=d6(r.x-i.x,r.y-i.y);_[0]*=L.naturalWidth/S.width,_[1]*=L.naturalHeight/S.height;let[P,T,M,N,O,B]=Mg(I,c),U=wx(yx(de(P,T),de(O,B),I.angle)),D=wx(yx(de(M,T),de(O,B),I.angle)),F=wx(yx(de(P,N),de(O,B),I.angle)),z=u6(m6(D,U)),$=u6(m6(F,U)),V=d6(p6(_,z),p6(_,$)),Q={...k,x:c6(k.x-V[0]*Math.sign(I.scale[0]),0,L.naturalWidth-k.width),y:c6(k.y-V[1]*Math.sign(I.scale[1]),0,L.naturalHeight-k.height)};this.scene.mutateElement(I,{crop:Q});return}}}this.maybeCacheVisibleGaps(n,d),this.maybeCacheReferenceSnapPoints(n,d);let{snapOffset:y,snapLines:v}=Z5(w,E,this,n,this.scene.getNonDeletedElementsMap());if(this.setState({snapLines:v}),this.state.editingFrame||Dq(o,d,E,this.scene,y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),this.setState({selectedElementsAreBeingDragged:!0,selectionElement:null}),n.altKey&&!o.hit.hasBeenDuplicated){o.hit.hasBeenDuplicated=!0;let I=this.scene.getElementsIncludingDeleted(),k=o.hit.element,L=this.scene.getSelectedElements({selectedElementIds:this.state.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});k&&o.hit.wasAddedToSelection&&!L.find(U=>U.id===k.id)&&L.push(k);let S=new Map(L.map(U=>[U.id,U])),{duplicatedElements:_,duplicateElementsMap:P,elementsWithDuplicates:T,origIdToDuplicateId:M}=Px({type:"in-place",elements:I,appState:this.state,randomizeSeed:!0,idsOfElementsToDuplicate:S,overrides:({duplicateElement:U,origElement:D})=>({frameId:U.frameId??D.frameId,seed:Cj()})});_.forEach(U=>{o.originalElements.set(U.id,D6(U))});let N=T.map(U=>{if(S.has(U.id)){let D=o.originalElements.get(U.id);if(D)return Si(U,{x:D.x,y:D.y})}return U}),O=this.props.onDuplicate?.(N,I),B=X6(O||N,kg(_));wo(()=>{if(o.hit.element){let U=M.get(o.hit.element.id),D=U&&P.get(U);o.hit.element=D||null}o.hit.allHitElements=o.hit.allHitElements.reduce((U,D)=>{let F=M.get(D.id),z=F&&P.get(F);return z&&U.push(z),U},[]),o.drag.origin=ot(n,this.state),this.setState(U=>({...Pq(_,this.scene.getNonDeletedElements(),U)})),this.scene.replaceAllElements(B),L.forEach(U=>{Dx(U)&&U.boundElements?.some(D=>D.type==="arrow")&&Pg(U,this.scene)}),this.maybeCacheVisibleGaps(n,L,!0),this.maybeCacheReferenceSnapPoints(n,L,!0)})}return}}if(this.state.selectionElement){if(o.lastCoords.x=r.x,o.lastCoords.y=r.y,n.altKey){this.setActiveTool({type:"lasso",fromSelection:!0},n.shiftKey),this.lassoTrail.startPath(o.origin.x,o.origin.y,n.shiftKey),this.setAppState({selectionElement:null});return}this.maybeDragNewGenericElement(o,n)}else if(this.state.activeTool.type==="lasso")!n.altKey&&this.state.activeTool.fromSelection?(this.setActiveTool({type:"selection"}),this.createGenericElementOnPointerDown("selection",o),o.lastCoords.x=r.x,o.lastCoords.y=r.y,this.maybeDragNewGenericElement(o,n),this.lassoTrail.endPath()):this.lassoTrail.addPointToPath(r.x,r.y,n.shiftKey);else{let d=this.state.newElement;if(!d)return;if(d.type==="freedraw"){let u=d.points,h=r.x-d.x,g=r.y-d.y,E=u.length>0&&u[u.length-1];if(!(E&&E[0]===h&&E[1]===g)){let x=d.simulatePressure?d.pressures:[...d.pressures,n.pressure];this.scene.mutateElement(d,{points:[...u,de(h,g)],pressures:x},{informMutation:!1,isDragging:!1}),this.setState({newElement:d})}}else if(ao(d)&&!d.isDeleted){o.drag.hasOccurred=!0;let u=d.points;tr(u.length>1,"Do not create linear elements with less than 2 points");let h=this.state.selectedLinearElement;h||(h=new Me(d,this.scene.getNonDeletedElementsMap()),h={...h,selectedPointsIndices:[1],initialState:{...h.initialState,lastClickedPoint:1}}),this.setState({newElement:d,...Me.handlePointDragging(n,this,s,l,h)})}else o.lastCoords.x=r.x,o.lastCoords.y=r.y,this.maybeDragNewGenericElement(o,n,!1)}if(this.state.activeTool.type==="selection"){o.boxSelection.hasOccurred=!0;let d=this.scene.getNonDeletedElements();if(this.state.selectedLinearElement?.isEditing)Me.handleBoxSelection(n,this.state,this.setState.bind(this),this.scene.getNonDeletedElementsMap());else{let u=!0;!n.shiftKey&&He(d,this.state)&&(o.withCmdOrCtrl&&o.hit.element?this.setState(g=>nn({...g,selectedElementIds:{[o.hit.element.id]:!0}},this.scene.getNonDeletedElements(),g,this)):u=!1);let h=this.state.selectionElement?zE(d,this.state.selectionElement,this.scene.getNonDeletedElementsMap(),!1):[];this.setState(g=>{let E={...u&&g.selectedElementIds,...h.reduce((w,x)=>(w[x.id]=!0,w),{})};return o.hit.element&&(h.length?delete E[o.hit.element.id]:E[o.hit.element.id]=!0),g=u?g:{...g,selectedGroupIds:{},editingGroupId:null},{...nn({editingGroupId:g.editingGroupId,selectedElementIds:E},this.scene.getNonDeletedElements(),g,this),selectedLinearElement:h.length===1&&ao(h[0])?new Me(h[0],this.scene.getNonDeletedElementsMap()):null,showHyperlinkPopup:h.length===1&&(h[0].link||Lr(h[0]))?"info":!1}})}}})}handlePointerMoveOverScrollbars(o,n){if(n.scrollbars.isOverHorizontal){let r=o.clientX,i=r-n.lastCoords.x;return this.translateCanvas({scrollX:this.state.scrollX-i*(Nd.horizontal?.deltaMultiplier||1)/this.state.zoom.value}),n.lastCoords.x=r,!0}if(n.scrollbars.isOverVertical){let r=o.clientY,i=r-n.lastCoords.y;return this.translateCanvas({scrollY:this.state.scrollY-i*(Nd.vertical?.deltaMultiplier||1)/this.state.zoom.value}),n.lastCoords.y=r,!0}return!1}onPointerUpFromPointerDownHandler(o){return mt(n=>{let r=this.scene.getNonDeletedElementsMap();this.removePointer(n),o.drag.blockDragging=!1,o.eventListeners.onMove&&o.eventListeners.onMove.flush();let{newElement:i,resizingElement:a,croppingElementId:s,multiElement:l,activeTool:c,isResizing:m,isRotating:p,isCropping:d}=this.state;this.setState(x=>({isResizing:!1,isRotating:!1,isCropping:!1,resizingElement:null,selectionElement:null,frameToHighlight:null,elementsToHighlight:null,cursorButton:"up",snapLines:Sd(x.snapLines,[]),originSnapOffset:null})),this.lassoTrail.endPath(),this.previousPointerMoveCoords=null,$o.setReferenceSnapPoints(null),$o.setVisibleGaps(null),this.savePointer(n.clientX,n.clientY,"up");let u=o.hit.allHitElements,h=ot({clientX:n.clientX,clientY:n.clientY},this.state);if(this.state.activeTool.type==="selection"&&!o.boxSelection.hasOccurred&&!o.resize.isResizing&&!u.some(x=>this.state.selectedElementIds[x.id])){let x=this.getElementAtPosition(h.x,h.y,{includeLockedElements:!0});this.store.scheduleCapture(),x?.locked?this.setState({activeLockedId:x.groupIds.length>0?x.groupIds.at(-1)||"":x.id}):this.setState({activeLockedId:null})}else this.setState({activeLockedId:null});if(Ar("COMPLEX_BINDINGS")&&this.resetDelayedBindMode(),this.setState({selectedElementsAreBeingDragged:!1,bindMode:"orbit"}),o.drag.hasOccurred&&o.hit?.element?.id){let x=r.get(o.hit.element.id);Dx(x)&&x.boundElements?.filter(y=>y.type==="arrow").map(y=>r.get(y.id)).filter(y=>vo(y)).forEach(y=>{y&&this.scene.mutateElement(y,{})})}if(this.state.selectedLinearElement?.isEditing&&!this.state.newElement&&this.state.selectedLinearElement.draggedFocusPointBinding===null)if(!o.boxSelection.hasOccurred&&o.hit?.element?.id!==this.state.selectedLinearElement.elementId&&this.state.selectedLinearElement.draggedFocusPointBinding===null)this.actionManager.executeAction(to);else{let x=Me.handlePointerUp(n,this.state.selectedLinearElement,this.state,this.scene);this.actionManager.executeAction(to,"ui",{event:n,sceneCoords:h}),x!==this.state.selectedLinearElement&&this.setState({selectedLinearElement:x,suggestedBinding:null})}else if(this.state.selectedLinearElement){if(this.state.selectedLinearElement.elbowed){let x=Me.getElement(this.state.selectedLinearElement.elementId,this.scene.getNonDeletedElementsMap());x&&this.scene.mutateElement(x,{})}if(this.state.selectedLinearElement.draggedFocusPointBinding?(Wq(this.state.selectedLinearElement,this.scene),this.setState({selectedLinearElement:{...this.state.selectedLinearElement,draggedFocusPointBinding:null}})):o.hit?.element?.id!==this.state.selectedLinearElement.elementId?this.scene.getSelectedElements(this.state).length>1&&this.setState({selectedLinearElement:null}):this.state.selectedLinearElement.isDragging&&(this.setState({selectedLinearElement:{...this.state.selectedLinearElement,isDragging:!1}}),this.actionManager.executeAction(to,"ui",{event:n,sceneCoords:h})),this.state.newElement&&this.state.multiElement&&ao(this.state.newElement)&&this.state.selectedLinearElement){let{multiElement:x}=this.state;this.setState({selectedLinearElement:{...this.state.selectedLinearElement,lastCommittedPoint:x.points[x.points.length-1]}})}}if(this.missingPointerEventCleanupEmitter.clear(),window.removeEventListener(ue.POINTER_MOVE,o.eventListeners.onMove),window.removeEventListener(ue.POINTER_UP,o.eventListeners.onUp),window.removeEventListener(ue.KEYDOWN,o.eventListeners.onKeyDown),window.removeEventListener(ue.KEYUP,o.eventListeners.onKeyUp),this.props?.onPointerUp?.(c,o),this.onPointerUpEmitter.trigger(this.state.activeTool,o,n),i?.type==="freedraw"){let x=ot(n,this.state),y=i.points,v=x.x-i.x,I=x.y-i.y;v===y[0][0]&&I===y[0][1]&&(I+=1e-4,v+=1e-4);let k=i.simulatePressure?[]:[...i.pressures,n.pressure];this.scene.mutateElement(i,{points:[...y,de(v,I)],pressures:k}),this.actionManager.executeAction(to);return}if(ao(i)){i.points.length>1&&i.points[1][0]!==0&&i.points[1][1]!==0&&this.store.scheduleCapture();let x=ot(n,this.state),y=Ti(de(x.x,x.y),de(o.origin.x,o.origin.y))*this.state.zoom.value;if((!o.drag.hasOccurred||y<kj)&&i&&!l)if(this.editorInterface.isTouchScreen){let v=Math.min(this.state.width*.7/this.state.zoom.value,100);this.scene.mutateElement(i,{x:i.x-v/2,points:[de(0,0),de(v,0)]},{informMutation:!1,isDragging:!1}),this.actionManager.executeAction(to)}else{let v=x.x-i.x,I=x.y-i.y;this.scene.mutateElement(i,{points:[i.points[0],de(v,I)]},{informMutation:!1,isDragging:!1}),this.setState({multiElement:i,newElement:i})}else o.drag.hasOccurred&&!l&&(ao(i)&&this.actionManager.executeAction(to,"ui",{event:n,sceneCoords:h}),this.setState({suggestedBinding:null,startBoundElement:null}),c.locked?this.setState(v=>({newElement:null})):(So(this.interactiveCanvas),this.setState(v=>({newElement:null,activeTool:er(this.state,{type:this.state.preferredSelectionTool.type}),selectedElementIds:Oe({...v.selectedElementIds,[i.id]:!0},v),selectedLinearElement:new Me(i,this.scene.getNonDeletedElementsMap())}))),this.scene.triggerUpdate());return}if(vn(i)){let x=vq(Tx({fontSize:i.fontSize,fontFamily:i.fontFamily}),i.lineHeight);i.width<x&&this.scene.mutateElement(i,{autoResize:!0}),this.resetCursor(),this.handleTextWysiwyg(i,{isExistingElement:!0})}if(c.type!=="selection"&&i&&F6(i)){this.updateScene({elements:this.scene.getElementsIncludingDeleted().filter(x=>x.id!==i.id),appState:{newElement:null},captureUpdate:so.NEVER});return}if(jt(i)){let x=rq(this.scene.getElementsIncludingDeleted(),i,this.scene.getNonDeletedElementsMap());this.scene.replaceAllElements(zx(this.scene.getElementsMapIncludingDeleted(),x,i,this.state))}if(i&&(this.scene.mutateElement(i,Xj(i),{informMutation:!1,isDragging:!1}),this.scene.triggerUpdate()),o.drag.hasOccurred){let x=ot(n,this.state);if(this.state.selectedLinearElement&&this.state.selectedLinearElement.isDragging){let y=this.scene.getElement(this.state.selectedLinearElement.elementId);if(y?.frameId){let v=Gx(y,r);v&&y&&(iq(y,v,this.scene.getNonDeletedElementsMap())||(this.scene.mutateElement(y,{groupIds:[]}),nq([y],this.scene.getNonDeletedElementsMap()),this.scene.triggerUpdate()))}}else{let y=this.getTopLayerFrameAtSceneCoords(x),v=this.scene.getSelectedElements(this.state),I=this.scene.getElementsMapIncludingDeleted(),k=L=>{if(L.length>0){for(let S of L){let _=S.groupIds.indexOf(this.state.editingGroupId);this.scene.mutateElement(S,{groupIds:S.groupIds.slice(0,_)},{informMutation:!1,isDragging:!1})}I.forEach(S=>{S.groupIds.length&&Ca(I,S.groupIds[S.groupIds.length-1]).length<2&&this.scene.mutateElement(S,{groupIds:[]},{informMutation:!1,isDragging:!1})}),this.setState({editingGroupId:null})}};if(y&&!this.state.selectedElementIds[y.id]){let L=v.filter(S=>S.frameId!==y.id&&Y6(S,I,this.state));this.state.editingGroupId&&k(L),I=zx(I,L,y,this.state)}else if(!y&&this.state.editingGroupId){let L=v.filter(S=>S.frameId&&!Y6(S,I,this.state));k(L)}I=W6(I,this.state,this),this.scene.replaceAllElements(I)}}if(a&&this.store.scheduleCapture(),a&&F6(a)&&this.updateScene({elements:this.scene.getElementsIncludingDeleted().filter(x=>x.id!==a.id),captureUpdate:so.NEVER}),o.resize.isResizing){let x=W6(this.scene.getElementsIncludingDeleted(),this.state,this),y=this.scene.getSelectedElements(this.state).filter(v=>jt(v));for(let v of y)x=oq(x,Hx(this.scene.getElementsIncludingDeleted(),v,this.state,r),v,this);this.scene.replaceAllElements(x)}let g=o.hit.element;this.state.selectedLinearElement?.elementId!==g?.id&&ao(g)&&this.scene.getSelectedElements(this.state).length===1&&this.setState({selectedLinearElement:new Me(g,this.scene.getNonDeletedElementsMap())}),(!s||s&&(!g&&!d||g&&g.id!==s))&&this.finishImageCropping();let E=this.lastPointerDownEvent,w=this.lastPointerUpEvent||this.lastPointerMoveEvent;if(po(this.state)&&E&&w){if(this.eraserTrail.endPath(),Ti(de(E.clientX,E.clientY),de(w.clientX,w.clientY))===0){let y=ot({clientX:w.clientX,clientY:w.clientY},this.state);this.getElementsAtPosition(y.x,y.y).forEach(I=>this.elementsPendingErasure.add(I.id))}this.eraseElements();return}else this.elementsPendingErasure.size&&this.restoreReadyToEraseElements();if(g&&!o.drag.hasOccurred&&!o.hit.wasAddedToSelection&&(!this.state.selectedLinearElement?.isEditing||!o.boxSelection.hasOccurred)&&this.state.activeTool.type!=="lasso"&&(n.shiftKey&&!this.state.selectedLinearElement?.isEditing?this.state.selectedElementIds[g.id]?Sq(this.state,g)?this.setState(x=>{let y={...x.selectedElementIds};for(let v of g.groupIds.flatMap(I=>Ca(this.scene.getNonDeletedElements(),I)))delete y[v.id];return{selectedGroupIds:{...x.selectedElementIds,...g.groupIds.map(v=>({[v]:!1})).reduce((v,I)=>({...v,...I}),{})},selectedElementIds:Oe(y,x)}}):this.state.selectedLinearElement?.isDragging||this.setState(x=>{let y={...x.selectedElementIds};delete y[g.id];let v=le(this.scene.getNonDeletedElements(),{selectedElementIds:y});return{...nn({editingGroupId:x.editingGroupId,selectedElementIds:y},this.scene.getNonDeletedElements(),x,this),selectedLinearElement:v.length===1&&ao(v[0])?new Me(v[0],this.scene.getNonDeletedElementsMap()):x.selectedLinearElement}}):g.frameId&&this.state.selectedElementIds[g.frameId]?this.setState(x=>{let y={...x.selectedElementIds,[g.id]:!0};return delete y[g.frameId],(this.scene.getElement(g.frameId)?.groupIds??[]).flatMap(v=>Ca(this.scene.getNonDeletedElements(),v)).forEach(v=>{delete y[v.id]}),{...nn({editingGroupId:x.editingGroupId,selectedElementIds:y},this.scene.getNonDeletedElements(),x,this),showHyperlinkPopup:g.link||Lr(g)?"info":!1}}):this.setState(x=>({selectedElementIds:Oe({...x.selectedElementIds,[g.id]:!0},x)})):this.setState(x=>({...nn({editingGroupId:x.editingGroupId,selectedElementIds:{[g.id]:!0}},this.scene.getNonDeletedElements(),x,this),selectedLinearElement:ao(g)&&x.selectedLinearElement?.elementId!==g.id?new Me(g,this.scene.getNonDeletedElementsMap()):x.selectedLinearElement}))),this.state.activeTool.type!=="lasso"&&!(g&&vo(g))&&!o.drag.hasOccurred&&!this.state.isResizing&&(g&&dq({point:de(o.origin.x,o.origin.y),element:g,elementsMap:r,threshold:this.getElementHitThreshold(g),frameNameBound:jt(g)?this.frameNameBoundsCache.get(g):null},r)||!g&&o.hit.hasHitCommonBoundingBoxOfSelectedElements)){this.state.selectedLinearElement?.isEditing?this.actionManager.executeAction(Qs):this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null}),Re(this.interactiveCanvas,st.AUTO);return}if(!c.locked&&c.type!=="freedraw"&&i&&this.setState(x=>({selectedElementIds:Oe({...x.selectedElementIds,[i.id]:!0},x),showHyperlinkPopup:Lr(i)&&!i.link?"editor":x.showHyperlinkPopup})),(c.type!=="selection"||He(this.scene.getNonDeletedElements(),this.state)||!k6(this.state.previousSelectedElementIds,this.state.selectedElementIds))&&this.store.scheduleCapture(),o.drag.hasOccurred&&!this.state.selectedLinearElement||m||p||d){let x=this.scene.getSelectedElements(this.state).filter(Al);M6(x,this.scene,this.state)}if(c.type==="laser"){this.laserTrails.endPath();return}!c.locked&&c.type!=="freedraw"&&(c.type!=="lasso"||c.type==="lasso"&&c.fromSelection)?(So(this.interactiveCanvas),this.setState({newElement:null,suggestedBinding:null,activeTool:er(this.state,{type:this.state.preferredSelectionTool.type})})):this.setState({newElement:null,suggestedBinding:null})})}clearSelection(o){this.setState(n=>({selectedElementIds:Oe({},n),activeEmbeddable:null,selectedGroupIds:{},editingGroupId:n.editingGroupId&&o!=null&&K6(o,n.editingGroupId)?n.editingGroupId:null})),this.setState({selectedElementIds:Oe({},this.state),activeEmbeddable:null,previousSelectedElementIds:this.state.selectedElementIds,selectedLinearElement:null})}getTextWysiwygSnappedToCenterPosition(o,n,r,i){if(i){let a=i.x+i.width/2,s=i.y+i.height/2,l=Fx(i,r,this.scene.getNonDeletedElementsMap());if(l&&(a=l.x,s=l.y),Math.hypot(o-a,n-s)<sj){let{x:p,y:d}=Cg({sceneX:a,sceneY:s},r);return{viewportX:p,viewportY:d,elementCenterX:a,elementCenterY:s}}}}getCanvasOffsets(){if(this.excalidrawContainerRef?.current){let o=this.excalidrawContainerRef.current,{left:n,top:r}=o.getBoundingClientRect();return{offsetLeft:n,offsetTop:r}}return{offsetLeft:0,offsetTop:0}}async updateLanguage(){let o=Ua.find(n=>n.code===this.props.langCode)||An;await rm(o),this.setAppState({})}},Vq=()=>{(cP()||dP())&&(window.h=window.h||{},Object.defineProperties(window.h,{elements:{configurable:!0,get(){return this.app?.scene.getElementsIncludingDeleted()},set(e){return this.app?.scene.replaceAllElements(pP(e))}},scene:{configurable:!0,get(){return this.app?.scene}}}))};Vq();var hP=Jx;import{useEffect as $q,useState as Kq}from"react";import{jsx as Xq}from"react/jsx-runtime";var fP=e=>{let[t,o]=Kq(!0);return $q(()=>{let n=async()=>{await rm(r),o(!1)},r=Ua.find(i=>i.code===e.langCode)||An;n()},[e.langCode]),t?Xq(_u,{theme:e.theme}):e.children};import Zq from"clsx";import{jsx as bP}from"react/jsx-runtime";var xP=({children:e})=>{let{FooterCenterTunnel:t}=Xe(),o=ye();return bP(t.In,{children:bP("div",{className:Zq("footer-center zen-mode-transition",{"layer-ui__wrapper__footer-left--transition-bottom":o.zenModeEnabled}),children:e})})},jq=xP;xP.displayName="FooterCenter";import qq from"clsx";import{MQ_MIN_WIDTH_DESKTOP as Jq}from"@orangecatai/common";import{jsx as eJ,jsxs as tJ}from"react/jsx-runtime";var EP=({isCollaborating:e,onSelect:t,editorInterface:o,...n})=>{let r=ye(),i=o?.formFactor!=="desktop"||r.width<Jq;return tJ(ro,{...n,className:qq("collab-button",{active:e}),type:"button",onSelect:t,style:{position:"relative",width:i?void 0:"auto"},title:f("labels.liveCollaboration"),children:[i?Ay:f("labels.share"),r.collaborators.size>0&&eJ("div",{className:"CollabButton-collaborators",children:r.collaborators.size})]})},Qq=EP;EP.displayName="LiveCollaborationTrigger";import{jsx as _i,jsxs as wP}from"react/jsx-runtime";var oJ=()=>_i("svg",{viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"ExcalidrawLogo-icon",children:_i("path",{d:"M39.9 32.889a.326.326 0 0 0-.279-.056c-2.094-3.083-4.774-6-7.343-8.833l-.419-.472a.212.212 0 0 0-.056-.139.586.586 0 0 0-.167-.111l-.084-.083-.056-.056c-.084-.167-.28-.278-.475-.167-.782.39-1.507.973-2.206 1.528-.92.722-1.842 1.445-2.708 2.25a8.405 8.405 0 0 0-.977 1.028c-.14.194-.028.361.14.444-.615.611-1.23 1.223-1.843 1.861a.315.315 0 0 0-.084.223c0 .083.056.166.111.194l1.09.833v.028c1.535 1.528 4.244 3.611 7.12 5.861.418.334.865.667 1.284 1 .195.223.39.473.558.695.084.11.28.139.391.055.056.056.14.111.196.167a.398.398 0 0 0 .167.056.255.255 0 0 0 .224-.111.394.394 0 0 0 .055-.167c.029 0 .028.028.056.028a.318.318 0 0 0 .224-.084l5.082-5.528a.309.309 0 0 0 0-.444Zm-14.63-1.917a.485.485 0 0 0 .111.14c.586.5 1.2 1 1.843 1.555l-2.569-1.945-.251-.166c-.056-.028-.112-.084-.168-.111l-.195-.167.056-.056.055-.055.112-.111c.866-.861 2.346-2.306 3.1-3.028-.81.805-2.43 3.167-2.095 3.944Zm8.767 6.89-2.122-1.612a44.713 44.713 0 0 0-2.625-2.5c1.145.861 2.122 1.611 2.262 1.75 1.117.972 1.06.806 1.815 1.445l.921.666a1.06 1.06 0 0 1-.251.25Zm.558.416-.056-.028c.084-.055.168-.111.252-.194l-.196.222ZM1.089 5.75c.055.361.14.722.195 1.056.335 1.833.67 3.5 1.284 4.75l.252.944c.084.361.223.806.363.917 1.424 1.25 3.602 3.11 5.947 4.889a.295.295 0 0 0 .363 0s0 .027.028.027a.254.254 0 0 0 .196.084.318.318 0 0 0 .223-.084c2.988-3.305 5.221-6.027 6.813-8.305.112-.111.14-.278.14-.417.111-.111.195-.25.307-.333.111-.111.111-.306 0-.39l-.028-.027c0-.055-.028-.139-.084-.167-.698-.666-1.2-1.138-1.731-1.638-.922-.862-1.871-1.75-3.881-3.75l-.028-.028c-.028-.028-.056-.056-.112-.056-.558-.194-1.703-.389-3.127-.639C6.087 2.223 3.21 1.723.614.944c0 0-.168 0-.196.028l-.083.084c-.028.027-.056.055-.224.11h.056-.056c.028.167.028.278.084.473 0 .055.112.5.112.555l.782 3.556Zm15.496 3.278-.335-.334c.084.112.196.195.335.334Zm-3.546 4.666-.056.056c0-.028.028-.056.056-.056Zm-2.038-10c.168.167.866.834 1.033.973-.726-.334-2.54-1.167-3.379-1.445.838.167 1.983.334 2.346.472ZM1.424 2.306c.419.722.754 3.222 1.089 5.666-.196-.778-.335-1.555-.503-2.278-.251-1.277-.503-2.416-.838-3.416.056 0 .14 0 .252.028Zm-.168-.584c-.112 0-.223-.028-.307-.028 0-.027 0-.055-.028-.055.14 0 .223.028.335.083Zm-1.089.222c0-.027 0-.027 0 0ZM39.453 1.333c.028-.11-.558-.61-.363-.639.42-.027.42-.666 0-.666-.558.028-1.144.166-1.675.25-.977.194-1.982.389-2.96.61-2.205.473-4.383.973-6.561 1.557-.67.194-1.424.333-2.066.666-.224.111-.196.333-.084.472-.056.028-.084.028-.14.056-.195.028-.363.056-.558.083-.168.028-.252.167-.224.334 0 .027.028.083.028.11-1.173 1.556-2.485 3.195-3.909 4.945-1.396 1.611-2.876 3.306-4.356 5.056-4.719 5.5-10.052 11.75-15.943 17.25a.268.268 0 0 0 0 .389c.028.027.056.055.084.055-.084.084-.168.14-.252.222-.056.056-.084.111-.084.167a.605.605 0 0 0-.111.139c-.112.111-.112.305.028.389.111.11.307.11.39-.028.029-.028.029-.056.056-.056a.44.44 0 0 1 .615 0c.335.362.67.723.977 1.028l-.698-.583c-.112-.111-.307-.083-.39.028-.113.11-.085.305.027.389l7.427 6.194c.056.056.112.056.196.056s.14-.028.195-.084l.168-.166c.028.027.083.027.111.027.084 0 .14-.027.196-.083 10.052-10.055 18.15-17.639 27.42-24.417.083-.055.111-.166.111-.25.112 0 .196-.083.251-.194 1.704-5.194 2.039-9.806 2.15-12.083v-.028c0-.028.028-.056.028-.083.028-.056.028-.084.028-.084a1.626 1.626 0 0 0-.111-1.028ZM21.472 9.5c.446-.5.893-1.028 1.34-1.5-2.876 3.778-7.65 9.583-14.408 16.5 4.607-5.083 9.242-10.333 13.068-15ZM5.193 35.778h.084-.084Zm3.462 3.194c-.027-.028-.027-.028 0-.028v.028Zm4.16-3.583c.224-.25.448-.472.699-.722 0 0 0 .027.028.027-.252.223-.475.445-.726.695Zm1.146-1.111c.14-.14.279-.334.446-.5l.028-.028c1.648-1.694 3.351-3.389 5.082-5.111l.028-.028c.419-.333.921-.694 1.368-1.028a379.003 379.003 0 0 0-6.952 6.695ZM24.794 6.472c-.921 1.195-1.954 2.778-2.82 4.028-2.736 3.944-11.532 13.583-11.727 13.75a1976.983 1976.983 0 0 1-8.042 7.639l-.167.167c-.14-.167-.14-.417.028-.556C14.49 19.861 22.03 10.167 25.074 5.917c-.084.194-.14.36-.28.555Zm4.83 5.695c-1.116-.64-1.646-1.64-1.34-2.611l.084-.334c.028-.083.084-.194.14-.277.307-.5.754-.917 1.257-1.167.027 0 .055 0 .083-.028-.028-.056-.028-.139-.028-.222.028-.167.14-.278.335-.278.335 0 1.369.306 1.76.639.111.083.223.194.335.305.14.167.363.445.474.667.056.028.112.306.196.445.056.222.111.472.084.694-.028.028 0 .194-.028.194a2.668 2.668 0 0 1-.363 1.028c-.028.028-.028.056-.056.084l-.028.027c-.14.223-.335.417-.53.556-.643.444-1.369.583-2.095.389 0 0-.195-.084-.28-.111Zm8.154-.834a39.098 39.098 0 0 1-.893 3.167c0 .028-.028.083 0 .111-.056 0-.084.028-.14.056-2.206 1.61-4.356 3.305-6.506 5.028 1.843-1.64 3.686-3.306 5.613-4.945.558-.5.949-1.139 1.06-1.861l.28-1.667v-.055c.14-.334.67-.195.586.166Z",fill:"currentColor"})}),nJ=()=>wP("svg",{viewBox:"0 0 450 55",xmlns:"http://www.w3.org/2000/svg",fill:"none",className:"ExcalidrawLogo-text",children:[_i("path",{d:"M429.27 96.74c2.47-1.39 4.78-3.02 6.83-4.95 1.43-1.35 2.73-2.86 3.81-4.51-.66.9-1.4 1.77-2.23 2.59-2.91 2.84-5.72 5.09-8.42 6.87h.01ZM343.6 69.36c.33 3.13.58 6.27.79 9.4.09 1.37.18 2.75.25 4.12-.12-4.46-.27-8.93-.5-13.39-.11-2.08-.24-4.16-.4-6.24-.06 1.79-.11 3.85-.13 6.11h-.01ZM378.47 98.34c.01-.37.07-1.13.01-6.51-.11 1.9-.22 3.81-.31 5.71-.07 1.42-.22 2.91-.16 4.35.39.03.78.07 1.17.1-.92-.85-.76-2.01-.72-3.66l.01.01ZM344.09 86.12c-.09-2.41-.22-4.83-.39-7.24v12.21c.15-.05.32-.09.47-.14.05-1.61-.03-3.23-.09-4.83h.01ZM440.69 66.79c-.22-.34-.45-.67-.69-.99-3.71-4.87-9.91-7.14-15.65-8.55-1.05-.26-2.12-.49-3.18-.71 2.29.59 4.48 1.26 6.64 2.02 7.19 2.54 10.57 5.41 12.88 8.23ZM305.09 72.46l1.2 3.6c.84 2.53 1.67 5.06 2.46 7.61.24.78.5 1.57.73 2.36.22-.04.44-.08.67-.12a776.9 776.9 0 0 1-5.01-13.57c-.02.04-.03.09-.05.13v-.01ZM345.49 90.25v.31c1.48-.42 3.05-.83 4.66-1.2-1.56.25-3.12.52-4.66.89ZM371.02 90.22c0-.57-.04-1.14-.11-1.71-.06-.02-.12-.04-.19-.05-.21-.05-.43-.08-.65-.11.42.16.74.88.95 1.87ZM398.93 54.23c-.13 0-.27-.01-.4-.02l.03.4c.11-.15.23-.27.37-.38ZM401.57 62.28v-.15c-1.22-.24-2.86-.61-3.23-1.25-.09-.15-.18-.51-.27-.98-.09.37-.2.73-.33 1.09 1.24.56 2.52.98 3.83 1.29ZM421.73 88.68c-2.97 1.65-6.28 3.12-9.69 3.68v.18c4.72-.14 11.63-3.85 16.33-8.38-2.04 1.75-4.33 3.24-6.63 4.53l-.01-.01ZM411.28 80.92c-.05-1.2-.09-2.4-.15-3.6-.21 5.66-.46 11.38-.47 14.51.24-.02.48-.04.71-.07.15-3.61.05-7.23-.09-10.83v-.01Z",transform:"translate(-144.023 -51.76)"}),_i("path",{d:"M425.38 67.41c-3.5-1.45-7.19-2.57-14.06-3.62.09 1.97.06 4.88-.03 8.12.03.04.06.09.06.15.19 1.36.28 2.73.37 4.1.25 3.77.39 7.55.41 11.33 0 1.38-.01 2.76-.07 4.13 1.4-.25 2.78-.65 4.12-1.15 4.07-1.5 7.94-3.78 11.28-6.54 2.33-1.92 5.13-4.49 5.88-7.58.63-3.53-2.45-6.68-7.97-8.96l.01.02ZM411.35 92.53v-.06l-.34.03c.11.01.22.03.34.03ZM314.26 64.06c-.23-.59-.47-1.17-.7-1.75.57 1.62 1.11 3.25 1.6 4.9l.15.54 2.35 6.05c.32.82.66 1.64.98 2.46-1.38-4.1-2.83-8.17-4.39-12.2h.01ZM156.82 103.07c-.18.13-.38.23-.58.33 1.32-.03 2.66-.2 3.93-.34.86-.09 1.72-.22 2.58-.33-2.12.1-4.12.17-5.94.34h.01ZM210.14 68.88s.03.04.05.07c.18-.31.39-.64.58-.96-.21.3-.42.6-.64.89h.01ZM201.65 82.8c-.5.77-1.02 1.56-1.49 2.37 1.11-1.55 2.21-3.1 3.2-4.59-.23.23-.49.51-.75.79-.32.47-.65.95-.96 1.43ZM194.03 98.66c-.33-.4-.65-.84-1.05-1.17-.24-.2-.07-.49.17-.56-.23-.26-.42-.5-.63-.75 1.51-2.55 3.93-5.87 6.4-9.28-.17-.08-.29-.28-.2-.49.04-.09.09-.17.13-.26-1.21 1.78-2.42 3.55-3.61 5.33-.87 1.31-1.74 2.64-2.54 4-.29.5-.63 1.04-.87 1.61.81.65 1.63 1.27 2.47 1.88-.09-.11-.18-.21-.27-.32v.01ZM307.79 82.93c-1-3.17-2.05-6.32-3.1-9.48-1.62 4.08-3.69 9.17-6.16 15.19 3.32-1.04 6.77-1.87 10.27-2.5-.32-1.08-.67-2.15-1.01-3.21ZM149.5 80.7c.05-1.71.04-3.43 0-5.14-.1 2.26-.16 4.51-.22 6.77-.02.73-.03 1.46-.04 2.19.14-1.27.2-2.55.24-3.82h.02ZM228.98 98.3c.39 1.25.91 3.03.94 3.91.06-.03.12-.07.17-.1.08-1.29-.55-2.65-1.11-3.81ZM307.72 53.36c.81.5 1.53 1.04 2.07 1.49-.38-.8-.78-1.58-1.21-2.35-.17.03-.34.06-.51.11-.43.12-.86.26-1.29.41.35-.01.53.1.94.34ZM283.69 96.14c3.91-7.25 6.89-13.35 8.88-18.15l1.1-2.66c-1.27 2.64-2.56 5.27-3.83 7.9-1.53 3.15-3.06 6.31-4.58 9.47-.87 1.81-1.76 3.62-2.54 5.47.04.02.07.04.11.07.05.05.1.09.15.14.05-.73.27-1.48.71-2.24ZM289.92 103.23s-.04.01-.05.03c0-.02.04-.03.05-.04.05-.05.11-.1.16-.15l.21-.21c-.55 0-1.5-.27-2.55-.72.4.26.8.51 1.22.74.24.13.48.26.73.37.05.02.1.03.14.05a.27.27 0 0 1 .08-.07h.01ZM269.23 68.49c-.39-.19-.82-.48-1.33-.87-3.06-1.56-6.31-2.78-9.36-2.35-3.5.49-5.7 1.11-7.74 2.44 5.71-2.6 12.82-2.07 18.44.79l-.01-.01ZM177.87 53.69l1.06.03c-.96-.22-2-.25-2.89-.3-4.95-.26-9.99.33-14.86 1.19-2.44.43-4.88.95-7.28 1.59 9.09-1.76 15.69-2.77 23.97-2.51ZM219.85 55.51c-.18.12-.36.27-.56.45-.45.53-.86 1.11-1.26 1.66-1.91 2.61-3.71 5.31-5.57 7.95l-.12.18 8.05-10.11c-.18-.05-.36-.1-.55-.13h.01ZM510.71 54.1c.12-.15.29-.3.53-.45.69-.4 3.72-.63 5.87-.74-.36-.02-.73-.04-1.09-.05-1.84-.03-3.67.09-5.49.35.05.3.12.59.18.88v.01ZM510.76 86.02c1.37-3.07 2.49-6.27 3.57-9.46.55-1.64 1.12-3.3 1.6-4.97-1.59 4.01-3.67 9.14-6.2 15.3.24-.08.5-.14.74-.22.1-.22.19-.44.29-.65ZM566.95 75.76c.11-.02.23.03.31.11-.05-.13-.09-.26-.14-.39-.05.09-.11.18-.17.28ZM511.33 86.41c3.08-.89 6.24-1.62 9.46-2.14-1.51-3.98-2.98-7.96-4.39-11.87-.05.15-.09.31-.14.46-1.02 3.32-2.15 6.61-3.39 9.85-.48 1.25-.98 2.49-1.53 3.7h-.01ZM578.24 74.45c.11-.44.23-.87.35-1.31-.31.7-.64 1.39-.97 2.08.09.21.19.4.28.61.12-.46.23-.92.35-1.38h-.01ZM520.62 53.11c-.09 0-.18-.01-.28-.02.38.34.29 1.08.93 2.53l6.65 17.15c2.2 5.68 4.69 11.36 7.41 16.87l1.06 2.17c-2.95-7.05-5.92-14.08-8.87-21.13-1.58-3.79-3.16-7.59-4.7-11.4-.78-1.92-1.73-3.89-2.25-5.91-.03-.1 0-.19.04-.26h.01ZM578.78 77.87c1.45-5.77 3.07-10.43 3.58-13.36.05-.34.16-.88.31-1.55-.67 1.79-1.37 3.56-2.08 5.33-.12.43-.23.86-.35 1.29-.65 2.43-1.29 4.86-1.9 7.3.14.33.29.65.43 1l.01-.01ZM545.3 94.66c.02-.44.03-.83.05-1.12.02-1.01.05-2.02.11-3.02.03-6.66-.46-14.33-1.46-22.8-.13-.42-.27-1.24-.56-2.89 0-.02 0-.04-.01-.06.62 6.61.95 13.25 1.32 19.87.17 3.08.33 6.16.52 9.23.02.25.03.52.04.78l-.01.01ZM580.77 102.81c.13.2.27.38.37.49.27-.11.53-.22.8-.32-.43.09-.82.05-1.17-.16v-.01ZM530.48 104.07h.33c-.36-.13-.71-.32-1.04-.56.14.24.3.47.45.7.06-.08.14-.13.26-.13v-.01ZM542.63 58.82c.06.23.11.47.15.71.14-.33.36-.62.7-.86-.28.05-.57.11-.85.15ZM583.81 57.87c.15-.7.29-1.41.42-2.11-.14.45-.28.9-.42 1.34-.46 1.44-.89 2.89-1.31 4.34.44-1.19.88-2.37 1.31-3.57ZM523.62 91.48c-4.66 1.17-9.05 2.89-14.02 5.27 4.65-1.84 9.48-3.29 14.28-4.63-.09-.22-.17-.41-.26-.64ZM460.64 78.3c-.04-2.9-.11-5.81-.28-8.71-.1-1.68-.17-3.43-.5-5.09-.07.02-.14.03-.2.05.3 6.54.45 12.17.51 17.12.17-.07.34-.14.51-.2 0-1.06-.01-2.11-.03-3.17h-.01ZM470.63 63.24c-3.38-.26-6.81.32-10.1 1.1.41 2.01.47 4.14.57 6.18.18 3.55.25 7.11.27 10.67 3.31-1.38 6.5-3.12 9.3-5.35 1.96-1.56 3.86-3.41 5.02-5.66.73-1.41 1.19-3.22.26-4.65-1.09-1.7-3.46-2.14-5.32-2.29ZM460.29 63.68c1-.24 2.01-.46 3.04-.65-1.15.16-2.37.38-3.71.69v.13c.07-.02.15-.04.22-.05.11-.13.3-.18.45-.11v-.01ZM457.24 100.96c.43-.03.86-.07 1.29-.11.14-.49.27-.99.38-1.49-.44.7-1 1.23-1.67 1.6ZM482.88 104.98c-.18.23-.36.38-.55.47.14.09.27.19.4.28a70.76 70.76 0 0 0 4.37-4.63c.76-.89 1.52-1.81 2.19-2.77-.3-.27-.61-.53-.92-.79-.07 1.94-4.62 6.32-5.49 7.45v-.01Z",transform:"translate(-144.023 -51.76)"}),_i("path",{d:"M474.36 63.31c-.4-.16-.84-.27-1.29-.37 1.56.42 3.08 1.22 3.76 2.74.62 1.4.32 2.95-.28 4.32.7-1.22.94-2.34.74-3.47-.24-1.33-1.19-2.54-2.93-3.21v-.01ZM477.34 89.18c-1.2-.81-2.4-1.62-3.6-2.42-.14.1-.26.19-.4.29 1.4.67 2.73 1.39 4 2.13ZM465.88 93.85c.37.25.74.5 1.1.75.46.32.92.65 1.38.97-1.57-1.2-2.01-1.61-2.49-1.72h.01ZM574.92 90.06c-2.28-5.21-4.93-11.13-5.67-12.26-.1-.15-1.57-3.01-1.63-3.08 0 0-.01.02-.02.02.4 1.37 1.09 2.69 1.65 3.99 2.14 4.95 4.36 9.86 6.67 14.73.6 1.26 1.21 2.52 1.83 3.78-.75-2.01-1.64-4.45-2.83-7.18ZM448.73 65.29c.1.2.22.38.34.57.22-.02.43-.06.65-.08v-.08c-.14-.05-.25 0-.99-.41ZM460.16 94.81c-.02.31-.06.59-.1.89-.03 1.71-.33 3.43-.79 5.07.15-.02.3-.03.45-.05.01-.04.02-.08.03-.11.09-.34.15-.69.2-1.03.17-1.07.25-2.16.33-3.24.05-.69.08-1.39.12-2.08-.27.1-.27.26-.24.57v-.02Z",transform:"translate(-144.023 -51.76)"}),_i("path",{d:"m328.67 98.12-3.22-6.58c-1.29-2.63-2.53-5.29-3.72-7.97-.25-.85-.52-1.69-.79-2.53-.81-2.57-1.67-5.12-2.55-7.67-1.92-5.53-3.9-11.08-6.32-16.41-.72-1.58-1.46-3.44-2.63-4.79-.03-.17-.16-.29-.34-.36a.282.282 0 0 0-.23-.04c-.06-.01-.12 0-.18.01-.74.06-1.5.38-2.19.61-2.22.77-4.4 1.64-6.63 2.38-.03-.08-.06-.16-.09-.25-.15-.42-.82-.24-.67.19.03.09.07.19.1.28l-.18.06c-.36.11-.28.6 0 .68.18 1.18.63 2.36.98 3.49.03.09.06.17.08.26-.08.23-.17.46-.24.64-.37.98-.79 1.94-1.21 2.9-1.27 2.89-2.62 5.75-3.98 8.6-3.18 6.67-6.44 13.31-9.64 19.97-1.08 2.25-2.2 4.5-3.15 6.81-.13.32.24.5.5.37 1.34 1.33 2.84 2.5 4.4 3.57.65.44 1.31.87 2.01 1.24.4.22.86.48 1.33.5.24.01.35-.19.33-.37.11-.1.21-.21.28-.28.41-.41.81-.84 1.2-1.26.85-.92 1.69-1.87 2.5-2.84 6.31-2.34 12.6-4.31 18.71-5.84 2.14 5.3 3.43 8.43 3.97 9.58.55 1.05 1.15 1.88 1.82 2.52 1.32.56 6.96-.03 9.23-1.96.87-1.28 1.19-2.67.93-4.15-.09-.5-.22-.95-.4-1.33l-.01-.03Zm-20.09-45.61c.43.77.83 1.56 1.21 2.35-.54-.45-1.27-.99-2.07-1.49-.42-.24-.6-.35-.94-.34.43-.15.85-.29 1.29-.41.17-.05.34-.08.51-.11Zm-25.86 45.66c.78-1.85 1.67-3.66 2.54-5.47 1.51-3.16 3.05-6.31 4.58-9.47 1.28-2.63 2.56-5.26 3.83-7.9l-1.1 2.66c-1.99 4.79-4.97 10.9-8.88 18.15-.43.76-.66 1.51-.71 2.24-.05-.05-.1-.09-.15-.14a.259.259 0 0 0-.11-.07Zm6.24 4.71c-.42-.23-.82-.48-1.22-.74 1.05.45 2 .72 2.55.72l-.21.21c-.05.05-.11.1-.16.15-.01.01-.04.03-.05.04 0-.02.03-.02.05-.03a.27.27 0 0 0-.08.07c-.05-.02-.1-.03-.14-.05-.25-.1-.49-.24-.73-.37h-.01Zm15.73-29.43c1.05 3.15 2.1 6.31 3.1 9.48.34 1.06.69 2.13 1.01 3.21-3.5.63-6.95 1.46-10.27 2.5 2.48-6.03 4.54-11.11 6.16-15.19Zm4.79 12.57c-.23-.79-.49-1.58-.73-2.36-.79-2.54-1.63-5.08-2.46-7.61l-1.2-3.6c.02-.04.04-.09.05-.13 1.6 4.45 3.28 9 5.01 13.57l-.67.12v.01Zm5.83-18.27-.15-.54c-.49-1.64-1.03-3.28-1.6-4.9.23.58.47 1.17.7 1.75 1.56 4.03 3.01 8.1 4.39 12.2-.33-.82-.67-1.64-.98-2.46l-2.35-6.05h-.01ZM390.43 79.37c-.13-10.43-.22-17.5-.24-19.97-.24-1.6.21-2.88-.65-3.65-.14-.13-.32-.23-.52-.32h.03c.45 0 .45-.69 0-.7-1.75-.03-3.5-.04-5.25-.14-1.38-.08-2.76-.21-4.15-.31-.07 0-.12.01-.17.04-.21-.07-.47.03-.45.31l.03.45c-.11.14-.19.3-.22.5-.21 1.26-.32 13.67-.36 23.59-.32 5.79-.67 11.57-.97 17.36-.09 1.73-.29 3.54-.21 5.3-.39.02-.38.64.04.69v.12c.05.44.74.45.7 0v-.06c1.1.09 2.2.21 3.3.3 1.14.19 2.44.2 3.29.17 1.73-.05 2.92-.05 3.8-.37.45-.05.9-.11 1.35-.17.44-.06.25-.73-.19-.67h-.01c.24-.32.45-.72.62-1.25.66-1.84.41-6.36.34-11.33l-.13-9.9.02.01Zm-12.26 18.17c.09-1.91.2-3.81.31-5.71.06 5.38 0 6.14-.01 6.51-.05 1.65-.21 2.81.72 3.66-.39-.04-.78-.07-1.17-.1-.06-1.44.09-2.93.16-4.35l-.01-.01ZM588.97 53.85c-2.06-.25-3.17-.51-3.76-.6a.3.3 0 0 1 .04-.08c.22-.39-.39-.75-.6-.35-.56 1.02-.9 2.19-1.26 3.29-.61 1.88-1.17 3.78-1.72 5.68-.63 2.19-1.24 4.39-1.83 6.59-.81 2.03-1.67 4.05-2.61 6.03-1.7-3.64-3.11-6.04-4.03-7.57-2.26-3.74-2.85-5.48-3.57-6.08l.31-.09c.43-.12.25-.8-.19-.67-1.06.3-2.12.6-3.17.95-.93.32-1.85.69-2.76 1.07-.13.05-.19.16-.22.27-.04.02-.08.05-.11.07-.04-.06-.07-.12-.11-.18a.354.354 0 0 0-.48-.12c-.16.09-.22.32-.13.48l.33.54c0 .09.02.18.06.28.51 1.16.78 1.38.72 1.47-2.42 3.44-5.41 7.86-6.2 9.1-1.27 1.97-2.01 3.14-2.45 3.84l-.91-6.56-.43-4.1c-.19-1.85-.37-3.23-.53-4.13-.19-1.1-.3-2.15-.45-3.16-.2-1.36-.29-2.06-.47-2.42h.04c.45.02.45-.68 0-.7-3.43-.16-6.81.94-10.17 1.48-.24-.22-.73-.04-.58.32.24.59.33 1.25.43 1.87.17 1.06.29 2.13.4 3.2.32 3.09.53 6.2.74 9.3.44 6.75.77 13.51 1.17 20.26.11 1.95.13 3.96.46 5.89.05.3.37.31.55.14.74 1.71 2.87 1.27 6.13 1.27 1.34 0 2.39.04 2.99-.11.02.32.48.53.63.18 3.61-8.26 7.41-16.46 12.05-24.2.03-.05.04-.1.05-.15.3.73.64 1.45.94 2.16.97 2.26 1.97 4.52 2.98 6.76 2.26 5.03 4.54 10.07 7.09 14.96.47.9.94 1.79 1.47 2.65.2.32.4.67.66.96-.18.25 0 .68.34.54.91-.38 1.82-.75 2.76-1.07 1.04-.35 2.11-.65 3.17-.95.39-.11.28-.66-.07-.68.62-.4.95-.96.87-1.91-.3-3.34.72-7.47.86-8.52l2.14-11.43c1.75-10.74 3.13-17.51 3.23-20.86.02-.49.08-2.84.13-3.24.17-1.25.48-1-4.96-1.65l.03-.02Zm-46.19 5.67c-.04-.24-.09-.48-.15-.71l.85-.15c-.34.24-.56.53-.7.86Zm1.95 25.12c-.36-6.63-.7-13.26-1.32-19.87 0 .02 0 .04.01.06.29 1.65.44 2.47.56 2.89 1 8.46 1.5 16.14 1.46 22.8-.06.99-.1 2-.11 3.02-.01.29-.03.68-.05 1.12-.01-.26-.03-.53-.04-.78-.19-3.08-.35-6.16-.52-9.23l.01-.01Zm36.4 18.66c-.11-.11-.24-.29-.37-.49.35.21.74.26 1.17.16-.27.11-.53.22-.8.32v.01Zm-.89-33.72c.12-.43.23-.86.35-1.29.71-1.77 1.41-3.55 2.08-5.33-.15.68-.26 1.22-.31 1.55-.5 2.94-2.13 7.59-3.58 13.36-.15-.35-.29-.66-.43-1 .61-2.44 1.25-4.87 1.9-7.3l-.01.01Zm3.56-12.48c.14-.44.28-.89.42-1.34-.13.7-.27 1.41-.42 2.11-.43 1.19-.86 2.38-1.31 3.57.42-1.45.85-2.9 1.31-4.34Zm-5.22 16.05c-.11.44-.23.87-.35 1.31-.12.46-.23.92-.35 1.38-.1-.22-.19-.4-.28-.61.34-.69.66-1.38.97-2.08h.01Zm-11.64 2.62c.06-.1.12-.19.17-.28.05.13.09.26.14.39a.398.398 0 0 0-.31-.11Zm2.3 2.98c-.56-1.3-1.25-2.63-1.65-3.99 0 0 .01-.02.02-.02.06.08 1.52 2.93 1.63 3.08.73 1.13 3.38 7.04 5.67 12.26 1.2 2.73 2.08 5.17 2.83 7.18-.62-1.25-1.23-2.51-1.83-3.78-2.31-4.87-4.53-9.78-6.67-14.73ZM275.92 87.03c-1.06-2.18-1.13-3.45-2.44-2.93-1.52.57-2.94 1.3-4.5 2.1-1.4.72-2.68 1.44-3.92 2.12.01-.25-.24-.5-.51-.34-4.8 2.93-12.41 4.7-17.28 1.31-1.98-1.77-3.32-4.15-3.97-5.78-.29-.95-.49-1.94-.63-2.93-.14-3.34 1.58-6.53 3.9-9.12.8-.79 1.68-1.51 2.66-2.12 3.7-2.3 8.22-3.07 12.51-2.51 2.71.35 5.32 1.24 7.71 2.55.39.22.75-.39.35-.6-.18-.1-.37-.18-.55-.27.56.27 1.03.33 1.51.19l-.48.39c-.15.11-.23.3-.13.48.09.15.33.24.48.13 1.3-.97 2.46-2.09 3.45-3.37.37-.29.64-.6.65-.97v-.02c.08-.33-.03-.7-.21-1.08-.31-.87-.98-2.01-2.19-3.26-2.43-2.52-3.79-3.45-5.68-4.26-1.14-.49-3.12-1.06-4.42-1.23-3.28-.42-10.64-1.21-18.18 4.11-7.74 5.46-11.94 12.3-12.23 20.61-.08 2.06.04 3.98.34 5.71.74 4.18 2.57 8 5.44 11.34 4.26 4.99 9.76 7.52 16.34 7.52 4.85 0 9.69-1.77 14.89-4.62.23-.12.45-.23.68-.35 2.19-1.1 4.37-2.23 6.46-3.5.49-.3 1.03-.61 1.5-.98 1.47-.87 1.11-1.12.49-2.95-.39-1.14-.76-2.7-2.06-5.36l.02-.01Zm-17.38-21.76c3.05-.42 6.31.79 9.36 2.35.51.39.94.68 1.33.87-5.61-2.86-12.72-3.39-18.44-.79 2.05-1.33 4.24-1.95 7.74-2.44l.01.01ZM443.67 72.67c-.4-2.2-1.15-4.33-2.37-6.22-1.49-2.32-3.58-4.19-5.91-5.64-6.17-3.81-13.75-5.11-20.83-6.01-3.23-.41-6.47-.69-9.72-.92l-1.39-.12c-.85-.07-1.52-.1-2.05-.1-1.08-.06-2.17-.12-3.25-.17-.08 0-.14.02-.19.05-.1.05-.18.14-.16.3.27 2.55-.01 5.12-.92 7.52-.15.38.4.56.62.28 1.32.59 2.68 1.05 4.08 1.37 0 2.78-.14 7.58-.33 12.91 0 0 0 .02-.01.03-.61 3.66-.79 7.42-1 11.12-.23 4.01-.43 8.03-.44 12.05 0 .64 0 1.28.03 1.93.02.31 0 .68.15.96.06.11.14.16.24.17-.2.17-.21.54.11.59 3.83.67 7.78.71 11.68.25 2.3-.19 4.87-.65 7.65-1.56 1.85-.54 3.67-1.18 5.43-1.91 7.2-3.02 14.31-8.07 17.35-15.53.76-1.86 1.17-3.8 1.31-5.75.3-1.93.28-3.82-.09-5.58l.01-.02Zm-19.32-15.42c5.74 1.41 11.94 3.68 15.65 8.55.25.32.47.65.69.99-2.3-2.82-5.68-5.69-12.88-8.23-2.16-.76-4.35-1.43-6.64-2.02 1.06.21 2.13.45 3.18.71Zm-25.82-3.04c.13 0 .27.01.4.02-.14.1-.26.23-.37.38 0-.13-.02-.26-.03-.4Zm34.82 22.17c-.75 3.09-3.55 5.66-5.88 7.58-3.35 2.76-7.21 5.03-11.28 6.54-1.33.49-2.71.9-4.12 1.15.06-1.38.08-2.76.07-4.13-.02-3.78-.16-7.56-.41-11.33-.09-1.37-.18-2.74-.37-4.1 0-.06-.03-.11-.06-.15.09-3.25.12-6.16.03-8.12 6.86 1.05 10.56 2.17 14.06 3.62 5.52 2.28 8.59 5.44 7.97 8.96l-.01-.02Zm-22 16.15c-.12 0-.23-.02-.34-.03l.34-.03v.06Zm-.69-.7c0-3.13.26-8.84.47-14.51.06 1.2.11 2.41.15 3.6.15 3.6.25 7.23.09 10.83-.24.03-.48.05-.71.07v.01Zm-12.33-30.94c.37.63 2.01 1.01 3.23 1.25v.15c-1.31-.31-2.59-.73-3.83-1.29.12-.36.23-.72.33-1.09.08.48.18.84.27.98Zm13.7 31.65v-.18c3.41-.56 6.71-2.02 9.69-3.68 2.31-1.28 4.59-2.78 6.63-4.53-4.69 4.53-11.61 8.24-16.33 8.38l.01.01Zm24.07-.75c-2.05 1.93-4.37 3.56-6.83 4.95 2.7-1.78 5.52-4.03 8.42-6.87.82-.82 1.56-1.69 2.23-2.59-1.08 1.65-2.38 3.16-3.81 4.51h-.01ZM187.16 92.14c-.79-2.47-2.1-7.12-3.1-6.87-.19-.01-2.09.77-4.08 1.54-3.06 1.18-5.91 2.13-10.09 2.82-2.74.42-5.87 1.01-10.61 1.06.04-3.34.05-6.01.05-7.99 7.97-.65 12.33-2.11 16.37-3.55 1.11-.39 2.69-1.01 2.63-1.8-.08-.35-.55-1.39-1.17-2.61-.47-1.16-.98-2.31-1.61-3.38-.42-.71-1.04-1.69-1.86-2.06-.11-.08-.22-.13-.29-.12-.02 0-.04 0-.07.01-.19-.04-.39-.05-.6-.01-.17.03-.24.15-.25.28-.04.02-.09.04-.14.05-4.33 1.48-8.85 2.33-13.24 3.61a499.1 499.1 0 0 0-.31-8.19c4.51-.99 8.88-1.38 13.11-1.82 3.68-.38 6.28.12 7.47.34.59.11.9.16 1.16.18h.1c-.1.37.44.66.62.28.02-.04.03-.08.05-.13.15.2.53.22.62-.1.17-.58.19-1.21.21-1.81v-.36c.03-.15.05-.3.07-.45.52-2.47.33-5.09-.64-7.44-.11-.27-.44-.28-.6-.14-.08-.21-.15-.42-.24-.62-.19-.41-.79-.05-.6.35.03.07.05.15.09.22-.98-.42-2.15-.54-3.17-.63-2.17-.19-4.37-.14-6.54 0-5.7.35-11.4 1.3-16.91 2.79-2.08.56-4.13 1.22-6.14 2-4.54 1.05-3.79 1.51-2.17 6.07.18.51.46 1.68.54 1.94.82 2.47 1.08 2.13 3.1 2.13s0 .05 0 .08h.52c-.48 2.66-.51 5.45-.62 8.13-.15 3.48-.22 6.96-.28 10.45 0 .41-.01.82-.02 1.23-.16.29-.33.57-.51.85-.05.38-.09.77-.14 1.18-.42 3.52-.59 6.48-.52 8.8v.34c.02.47.05.76.06.87.16 1.57-.26 3.47 1.35 3.79 1.61.32 3.5.55 4.85.55.11 0 .22-.02.33-.02 1.79.24 3.67.05 5.45-.12 2.85-.28 5.69-.7 8.51-1.19 3.03-.53 6.05-1.14 9.04-1.86 2.4-.58 4.82-1.19 7.13-2.06.51-.19 1.73-.57 2.46-1.14 1.81-.68 2.18-1 1.57-2.67-.23-.62-.48-1.49-.91-2.78l-.03-.02Zm-11.12-38.71c.89.05 1.93.08 2.89.3-.33 0-.68-.02-1.06-.03-8.28-.26-14.88.75-23.97 2.51 2.41-.64 4.85-1.16 7.28-1.59 4.87-.86 9.91-1.45 14.86-1.19Zm-26.53 22.13c.03 1.71.04 3.43 0 5.14-.04 1.27-.11 2.55-.24 3.82 0-.73.02-1.46.04-2.19.05-2.26.12-4.51.22-6.77h-.02Zm6.73 27.85c.2-.1.4-.21.58-.33 1.82-.17 3.82-.24 5.94-.34-.86.11-1.72.24-2.58.33-1.27.14-2.61.31-3.93.34h-.01ZM534.48 85.44c-3.52-8.38-7.07-16.75-10.5-25.17-.63-1.54-1.25-3.09-1.86-4.65-.31-.8-.65-1.6-.87-2.43-.04-.17-.17-.24-.31-.25.1-.2 0-.51-.29-.53-1.59-.08-3.18-.22-4.78-.25-1.96-.03-3.91.13-5.84.42-.31.05-.31.38-.13.56-.03.06-.05.14-.04.22.23 1.54.63 3.06 1.16 4.53.13.35.27.7.41 1.06l-2.68 6.18c-.11.03-.2.09-.25.22-.67 1.9-1.52 3.73-2.34 5.56a536.85 536.85 0 0 1-3.9 8.45c-2.64 5.64-5.34 11.25-7.91 16.93-.44.97-.88 1.94-1.29 2.93-.2.48-.47 1-.55 1.52v.05c-.02.12.02.26.16.34 1.19.73 2.41 1.41 3.66 2.05 1.2.62 2.45 1.25 3.76 1.61.43.12.62-.55.19-.67-1.13-.31-2.2-.83-3.24-1.36 1.09.36 2.1.69 2.75.93 2.82 1.01 2.38 1.1 4.3-3.75 2.1-1.09 4.34-1.96 6.53-2.79 4.35-1.64 8.8-3.03 13.27-4.29.82 2.01 1.77 3.97 2.72 5.92.35.83.62 1.45.79 1.82.22.42.45.8.69 1.15.17.33.33.67.5 1 .42.8.84 1.63 1.4 2.35.23.29.6 0 .55-.31 1.53-.02 3.06-.07 4.58-.27.92-.12 1.82-.32 2.71-.54 1.39-.27 3.85-1.11 3.74-1.42-.67-1.96-1.55-3.87-2.34-5.78-1.57-3.78-3.16-7.56-4.75-11.33v-.01Zm-11.65-26.16c1.54 3.81 3.12 7.6 4.7 11.4 2.94 7.05 5.91 14.09 8.87 21.13l-1.06-2.17c-2.71-5.51-5.2-11.19-7.41-16.87l-6.65-17.15c-.65-1.45-.55-2.19-.93-2.53.09 0 .18.01.28.02a.29.29 0 0 0-.04.26c.52 2.02 1.47 3.98 2.25 5.91h-.01Zm-6.58 13.58c.05-.15.09-.31.14-.46 1.41 3.92 2.88 7.9 4.39 11.87-3.22.52-6.38 1.25-9.46 2.14.55-1.22 1.05-2.46 1.53-3.7 1.24-3.24 2.37-6.53 3.39-9.85h.01Zm-.23-20c.36 0 .73.03 1.09.05-2.15.1-5.18.33-5.87.74-.24.15-.41.3-.53.45-.06-.29-.13-.58-.18-.88 1.82-.26 3.65-.39 5.49-.35v-.01Zm-.09 18.72c-.49 1.67-1.05 3.33-1.6 4.97-1.07 3.19-2.19 6.38-3.57 9.46-.09.21-.19.43-.29.65-.25.07-.5.14-.74.22 2.53-6.16 4.61-11.29 6.2-15.3Zm-6.34 25.16c4.97-2.38 9.37-4.1 14.02-5.27l.26.64c-4.8 1.35-9.63 2.8-14.28 4.63Zm20.17 6.76c.33.23.68.42 1.04.56h-.33c-.12 0-.21.06-.26.13-.15-.23-.31-.45-.45-.7v.01ZM226.57 91.75c-3.55-4.74-6.68-9.11-9.31-12.99 9.2-15.25 10.05-17.81 10.35-18.38.17-.34 1.09-2.27.64-2.53-1.13-.65-1.03-.65-2.97-1.71-1.19-.65-3.04-1.61-4.53-2.12-1.71-.59-1.24-.36-3 2.77-.06.1-.11.2-.17.3-.75 1.02-1.48 2.05-2.2 3.09-1.88 2.71-3.73 5.45-5.69 8.1-3.68-4.91-6.88-8.76-9.51-11.43-.15-.15-.3-.29-.46-.42-1.27-1.28-7.24 3.53-7.93 5.58-.09.09-.19.16-.28.25-.27.26.03.64.33.58.19.65.5 1.29.94 1.91 3.85 5.06 7.19 9.76 9.94 14-1.23 2.61-3.06 5-4.67 7.38l-2.28 3.33c-.5.66-.93 1.23-1.29 1.69-.67.93-2.09 2.61-2.3 3.87-.51.85-1.16 1.84-1.29 2.83-.06.44.61.63.67.19.01-.08.04-.15.06-.22 1.36 1.08 2.76 2.11 4.19 3.11 1.3.91 2.62 1.85 4.04 2.56.21.1.4 0 .48-.17.24.07.48.14.72.2.44.1.62-.57.19-.67-2.02-.48-3.77-1.57-5.23-3.02-.47-.46-.9-.96-1.32-1.46 1.74 1.35 4.2 2.89 5.89 4.14 1.39 1.03 2.85-2.27 4.22-4.2 1.86-2.64 3.96-5.86 5.52-8.29l10.39 14.51c.67.81 1.14 1.21 1.57 1.36-.05.24.12.51.41.4 1.53-.58 3.05-1.19 4.54-1.87 1.52-.69 3.06-1.45 4.36-2.5a.28.28 0 0 0 .12-.23c1.66-1.1.81-1.74-1.41-4.91-1.13-1.58-1.71-2.36-3.7-5.01l-.03-.02Zm2.41 6.54c.56 1.15 1.19 2.52 1.11 3.81-.06.04-.12.07-.17.1-.03-.88-.55-2.66-.94-3.91Zm-16.51-32.73c1.86-2.65 3.65-5.35 5.57-7.95.4-.55.81-1.13 1.26-1.66.19-.18.38-.33.56-.45.18.03.36.08.55.13l-8.05 10.11.12-.18h-.01ZM192.7 95.48c.79-1.37 1.66-2.69 2.54-4 1.19-1.79 2.4-3.56 3.61-5.33-.04.09-.09.17-.13.26-.1.22.03.41.2.49-2.47 3.42-4.89 6.73-6.4 9.28.21.24.4.48.63.75-.24.07-.4.36-.17.56.4.33.72.77 1.05 1.17.09.11.18.21.27.32-.84-.61-1.66-1.24-2.47-1.88.24-.57.58-1.11.87-1.61v-.01Zm7.46-10.32c.47-.81.98-1.59 1.49-2.37.31-.48.64-.95.96-1.43.26-.29.52-.56.75-.79-.99 1.48-2.09 3.03-3.2 4.59Zm10.03-16.22s-.03-.05-.05-.07c.22-.29.43-.59.64-.89-.2.32-.4.65-.58.96h-.01ZM371.54 87.96c-.01-.08-.01-.16-.03-.23-.06-.38-.58-.29-.66.03-.3-.05-.6-.08-.81-.11-1.14-.15-2.29-.19-3.44-.2 1.04-.09 2.09-.18 3.14-.23.45-.02.45-.72 0-.7-6.57.35-13.14 1.23-19.65 2.11-1.53.21-3.05.42-4.57.68-.01 0-.02.01-.04.01-.04-3.33-.13-6.66-.24-9.99-.19-5.7-.4-11.41-.88-17.1-.13-1.51-.23-3.07-.49-4.58 0-.25 0-.48-.02-.68-.06-1.19-.04-2.61-.68-2.78-.16-.07-.72-.16-1.5-.24.22-.17.16-.62-.2-.63-1.19-.04-2.39.09-3.57.23-1.2.14-2.41.32-3.59.6-.16-.1-.41-.06-.5.12-.06.02-.13.03-.19.05-.35.1-.29.55-.03.66-.26.6-.19 2.27-.21 3-.02.66-.66 33.73-.9 40.3-.03.65.06 1.12.04 1.45-.16 3.05.87 4.96 6.34 3.93 1.09-.08 2.75-.77 5.36-1.43 4.13-1.04 5.78-1.52 6.2-1.65 6.43-1.69 6.78-1.97 11.72-2.43.55-.05 4.8-.38 6.03-.3.64.04 1.19.07 1.65.1.09 0 .16-.03.24-.05.1.27.56.33.66-.02.39-1.32.61-2.71.78-4.08.2-1.61.29-3.24.15-4.86.24.03.52-.23.38-.53-.09-.2-.27-.33-.49-.43v-.02Zm-.63.56c.07.57.11 1.14.11 1.71-.21-.99-.53-1.71-.95-1.87.22.03.44.06.65.11.06.01.12.04.19.05Zm-25.41 1.73c1.54-.36 3.1-.64 4.66-.89-1.61.37-3.18.77-4.66 1.2v-.31Zm-.86-7.37c-.07-1.37-.16-2.75-.25-4.12-.21-3.13-.45-6.27-.79-9.4.02-2.25.08-4.31.13-6.11.16 2.08.29 4.16.4 6.24.23 4.46.38 8.93.5 13.39h.01Zm-.94-4c.16 2.41.29 4.83.39 7.24.06 1.6.14 3.22.09 4.83-.15.05-.32.09-.47.14V78.88h-.01ZM483.72 92.83c-3.05-2.28-6.22-4.4-9.38-6.51 8.86-6.49 13.49-12.95 13.73-19.23.04-.76 0-1.5-.13-2.2-.67-3.82-3.5-6.68-8.39-8.48.13.04.27.08.4.13 3.92 1.39 7.74 4.23 8.5 8.56.34 1.95-.05 3.96-.98 5.69-.21.4.39.75.6.35 1.86-3.46 1.46-7.55-.97-10.63-3.53-4.47-9.76-5.88-15.16-6.16-2.32-.12-4.64-.04-6.95.19-6 .32-12.71 1.68-17.63 3.21-.37.11-.67.23-.92.35-.2-.17-.62.02-.57.37v.03c-.64.68-.18 1.64.48 3.21.38.91.67 1.89 1.15 2.58.32.76.68 1.51 1.13 2.19.14.21.38.19.53.07.19-.02.38-.05.57-.08v1.57c-.06.06-.1.13-.11.23-.27 4.18-.34 8.38-.48 12.57l-.3 9.03c-.24 3.91-.44 6.77-.46 7.26-.05.88-.11 1.95.07 2.81-.01.22-.02.43-.04.65 0 .11-.02.23-.03.35 0 .05-.03.27-.01.16-.05.4.5.59.64.28.05.04.12.08.2.08 1.75.13 3.5.28 5.25.3 1.69.02 3.38-.12 5.06-.32.08.23.36.39.55.15.06-.08.11-.17.16-.26.18-.09.24-.32.18-.48.05-.2.1-.4.13-.6.16-.86.25-1.74.33-2.62.11-1.17.17-2.34.23-3.51.15-.01.32-.03.52-.04.36-.03 1.73-.15 2.06-.15.39 0 .7-.02.95-.04 1.76 1.11 3.45 2.35 5.14 3.55 2.83 2.01 5.64 4.04 8.47 6.04 1.42 1 2.85 2 4.29 2.97.1.06.19.07.27.04.08 0 .17-.02.25-.1 1.61-1.56 3.15-3.18 4.6-4.88.75-.88 1.49-1.78 2.15-2.73.01.01.03.02.04.03.34.3.83-.2.49-.49-2.16-1.9-4.34-3.76-6.64-5.48l.03-.01Zm-6.38-3.65a55.72 55.72 0 0 0-4-2.13c.14-.1.26-.19.4-.29 1.2.81 2.4 1.61 3.6 2.42Zm-20.1 11.78c.67-.37 1.23-.91 1.67-1.6-.11.5-.24 1-.38 1.49-.43.04-.86.08-1.29.11Zm2.38-37.24c1.34-.31 2.56-.52 3.71-.69-1.03.19-2.04.41-3.04.65-.14-.07-.34-.02-.45.11-.07.02-.15.04-.22.05v-.13.01Zm.04.84c.07-.02.14-.03.2-.05.34 1.66.41 3.41.5 5.09.17 2.9.24 5.81.28 8.71l.03 3.17c-.17.07-.34.14-.51.2-.06-4.96-.21-10.58-.51-17.12h.01Zm16.04 5.62c-1.16 2.25-3.06 4.1-5.02 5.66-2.8 2.23-5.99 3.97-9.3 5.35-.01-3.56-.09-7.12-.27-10.67-.1-2.04-.16-4.16-.57-6.18 3.3-.78 6.72-1.36 10.1-1.1 1.85.14 4.23.59 5.32 2.29.92 1.43.46 3.24-.26 4.65Zm.85-.18c.6-1.37.9-2.92.28-4.32-.67-1.52-2.2-2.32-3.76-2.74.46.1.89.21 1.29.37 1.74.67 2.69 1.88 2.93 3.21.2 1.13-.05 2.25-.74 3.47V70Zm-27.47-4.14c-.12-.19-.23-.38-.34-.57.74.42.85.36.99.41v.08c-.22.03-.43.06-.65.08Zm11.21 30.46c-.08 1.08-.16 2.17-.33 3.24-.05.35-.11.69-.2 1.03 0 .04-.02.07-.03.11-.15.02-.3.04-.45.05.45-1.64.76-3.36.79-5.07.03-.29.08-.57.1-.89-.03-.31-.03-.47.24-.57-.04.69-.07 1.39-.12 2.08v.02Zm5.6-2.47c.48.11.92.52 2.49 1.72-.46-.32-.92-.65-1.38-.97-.37-.25-.73-.5-1.1-.75h-.01Zm21.23 7.24a70.76 70.76 0 0 1-4.37 4.63c-.14-.09-.27-.19-.4-.28.19-.09.37-.24.55-.47.87-1.14 5.43-5.51 5.49-7.45.31.26.62.53.92.79-.67.97-1.42 1.88-2.19 2.77v.01Z",fill:"currentColor",transform:"translate(-144.023 -51.76)"})]}),yP=({style:e,size:t="small",withText:o})=>wP("div",{className:`ExcalidrawLogo is-${t}`,style:e,children:[_i(oJ,{}),o&&_i(nJ,{})]});import{Fragment as TP,jsx as It,jsxs as iE}from"react/jsx-runtime";var aE=({icon:e,shortcut:t,children:o})=>{let n=we();return iE(TP,{children:[It("div",{className:"welcome-screen-menu-item__icon",children:e}),It("div",{className:"welcome-screen-menu-item__text",children:o}),t&&n.formFactor!=="phone"&&It("div",{className:"welcome-screen-menu-item__shortcut",children:t})]})};aE.displayName="WelcomeScreenMenuItemContent";var zd=({onSelect:e,children:t,icon:o,shortcut:n,className:r="",...i})=>It("button",{...i,type:"button",className:`welcome-screen-menu-item ${r}`,onClick:e,children:It(aE,{icon:o,shortcut:n,children:t})});zd.displayName="WelcomeScreenMenuItem";var vP=({children:e,href:t,icon:o,shortcut:n,className:r="",...i})=>It("a",{...i,className:`welcome-screen-menu-item ${r}`,href:t,target:"_blank",rel:"noopener",children:It(aE,{icon:o,shortcut:n,children:e})});vP.displayName="WelcomeScreenMenuItemLink";var rn=({children:e})=>{let{WelcomeScreenCenterTunnel:t}=Xe();return It(t.In,{children:It("div",{className:"welcome-screen-center",children:e||iE(TP,{children:[It(sE,{}),It(lE,{children:f("welcomeScreen.defaults.center_heading")}),iE(cE,{children:[It(mE,{}),It(dE,{})]})]})})})};rn.displayName="Center";var sE=({children:e})=>It("div",{className:"welcome-screen-center__logo excalifont welcome-screen-decor",children:e||It(yP,{withText:!0})});sE.displayName="Logo";var lE=({children:e})=>It("div",{className:"welcome-screen-center__heading welcome-screen-decor excalifont",children:e});lE.displayName="Heading";var cE=({children:e})=>It("div",{className:"welcome-screen-menu",children:e});cE.displayName="Menu";var dE=()=>{let e=nt();return It(zd,{onSelect:()=>e.executeAction(ji),shortcut:"?",icon:ja,children:f("helpDialog.title")})};dE.displayName="MenuItemHelp";var mE=()=>{let e=ye(),t=nt();return e.viewModeEnabled?null:It(zd,{onSelect:()=>t.executeAction(Cs),shortcut:Ke("loadScene"),icon:qa,children:f("buttons.load")})};mE.displayName="MenuItemLoadScene";var IP=({onSelect:e})=>{let{t}=Ge();return It(zd,{shortcut:null,onSelect:e,icon:pm,children:t("labels.liveCollaboration")})};IP.displayName="MenuItemLiveCollaborationTrigger";rn.Logo=sE;rn.Heading=lE;rn.Menu=cE;rn.MenuItem=zd;rn.MenuItemLink=vP;rn.MenuItemHelp=dE;rn.MenuItemLoadScene=mE;rn.MenuItemLiveCollaborationTrigger=IP;import{jsx as _l,jsxs as pE}from"react/jsx-runtime";var Rg=({children:e})=>{let{WelcomeScreenMenuHintTunnel:t}=Xe();return _l(t.In,{children:pE("div",{className:"excalifont welcome-screen-decor welcome-screen-decor-hint welcome-screen-decor-hint--menu",children:[gy,_l("div",{className:"welcome-screen-decor-hint__label",children:e||f("welcomeScreen.defaults.menuHint")})]})})};Rg.displayName="MenuHint";var Ng=({children:e})=>{let{WelcomeScreenToolbarHintTunnel:t}=Xe();return _l(t.In,{children:pE("div",{className:"excalifont welcome-screen-decor welcome-screen-decor-hint welcome-screen-decor-hint--toolbar",children:[_l("div",{className:"welcome-screen-decor-hint__label",children:e||f("welcomeScreen.defaults.toolbarHint")}),fy]})})};Ng.displayName="ToolbarHint";var Bg=({children:e})=>{let{WelcomeScreenHelpHintTunnel:t}=Xe();return _l(t.In,{children:pE("div",{className:"excalifont welcome-screen-decor welcome-screen-decor-hint welcome-screen-decor-hint--help",children:[_l("div",{children:e||f("welcomeScreen.defaults.helpHint")}),hy]})})};Bg.displayName="HelpHint";import{Fragment as CP,jsx as Hd,jsxs as iJ}from"react/jsx-runtime";var Fg=e=>Hd(CP,{children:e.children||iJ(CP,{children:[Hd(rn,{}),Hd(Rg,{}),Hd(Ng,{}),Hd(Bg,{})]})});Fg.displayName="WelcomeScreen";Fg.Center=rn;Fg.Hints={MenuHint:Rg,ToolbarHint:Ng,HelpHint:Bg};var rJ=Fg;var aJ=()=>{Array.prototype.at||Object.defineProperty(Array.prototype,"at",{value:function(e){if(e=Math.trunc(e)||0,e<0&&(e+=this.length),!(e<0||e>=this.length))return this[e]},writable:!0,enumerable:!1,configurable:!0}),Element.prototype.replaceChildren||(Element.prototype.replaceChildren=function(...e){this.innerHTML="",this.append(...e)})},kP=aJ;import{getSceneVersion as kje,hashElementsVersion as Sje,hashString as Mje,getNonDeletedElements as Pje}from"@orangecatai/element";import{getTextFromElements as Lje}from"@orangecatai/element";import{isInvisiblySmallElement as Dje}from"@orangecatai/element";import sJ from"lodash.throttle";import{arrayToMap as lJ,isDevEnv as SP,isTestEnv as MP}from"@orangecatai/common";import{orderByFractionalIndex as cJ,syncInvalidIndices as PP,validateFractionalIndices as dJ}from"@orangecatai/element";var mJ=(e,t,o)=>!!(t&&(t.id===e.editingTextElement?.id||t.id===e.resizingElement?.id||t.id===e.newElement?.id||t.version>o.version||t.version===o.version&&t.versionNonce<=o.versionNonce)),pJ=sJ((e,t,o)=>{if(SP()||MP()||window?.DEBUG_FRACTIONAL_INDICES){let n=PP(e.map(r=>({...r})));dJ(n,{shouldThrow:MP()||SP(),includeBoundTextValidation:!0,reconciliationContext:{localElements:t,remoteElements:o}})}},1e3*60,{leading:!0,trailing:!1}),uJ=(e,t,o)=>{let n=lJ(e),r=[],i=new Set;for(let s of t)if(!i.has(s.id)){let l=n.get(s.id),c=mJ(o,l,s);l&&c?(r.push(l),i.add(l.id)):(r.push(s),i.add(s.id))}for(let s of e)i.has(s.id)||(r.push(s),i.add(s.id));let a=cJ(r);return pJ(a,e,t),PP(a),a};import{isLinearElement as Uje}from"@orangecatai/element";import{FONT_FAMILY as Yje,THEME as US,MIME_TYPES as Vje,ROUNDNESS as bp,DEFAULT_LASER_COLOR as $je,UserIdleState as Kje,normalizeLink as Xje,sceneCoordsToViewportCoords as aT,viewportCoordsToSceneCoords as Zje,getFormFactor as jje}from"@orangecatai/common";import{mutateElement as Ep,newElementWith as Jje,bumpVersion as Ns}from"@orangecatai/element";import{CaptureUpdateAction as eqe}from"@orangecatai/element";import{jsx as uE}from"react/jsx-runtime";var AP=({children:e,icon:t})=>{let{t:o}=Ge(),{TTDDialogTriggerTunnel:n}=Xe(),r=ve();return uE(n.In,{children:uE(he.Item,{onSelect:()=>{ge("ai","dialog open","ttd"),r({openDialog:{name:"ttd",tab:"text-to-diagram"}})},icon:t??Mw,badge:uE(he.Item.Badge,{children:"AI"}),children:e??o("labels.textToDiagram")})})};AP.displayName="TTDDialogTrigger";function gJ(e){let t=e.get("X-Ratelimit-Limit"),o=e.get("X-Ratelimit-Remaining");return{rateLimit:t?parseInt(t,10):void 0,rateLimitRemaining:o?parseInt(o,10):void 0}}async function*gE(e){let t=new TextDecoder,o="";try{for(;;){let{done:n,value:r}=await e.read();if(n)break;o+=t.decode(r,{stream:!0});let i=o.split(`
217
- `);o=i.pop()||"";for(let a of i){let s=a.trim();s&&s.startsWith("data: ")&&(yield s.slice(6))}}}finally{e.releaseLock()}}async function hJ(e){let{url:t,messages:o,onChunk:n,onStreamCreated:r,extractRateLimits:i=!0,signal:a}=e;try{let s="",l={},c=null,m=await fetch(t,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify({messages:o}),signal:a});if(i&&(l=gJ(m.headers)),!m.ok){if(m.status===429)return{...l,error:new Sn({message:"Rate limit exceeded",status:429})};let d=await m.text();throw new Sn({message:d||"Generation failed...",status:m.status})}let p=m.body?.getReader();if(!p)throw new Sn({message:"Couldn't get reader from response body",status:500});r?.();try{for await(let d of gE(p)){if(d==="[DONE]")break;try{let u=JSON.parse(d);if(u===null)break;switch(u.type){case"content":{let h=u.delta;h&&(s+=h,n?.(h));break}case"error":c=new Sn({message:u.error.message,status:500});break;case"done":break}}catch(u){console.warn("Failed to parse SSE data:",d,u)}}}catch(d){d.name==="AbortError"?c=new Sn({message:"Request aborted",status:499}):c=new Sn({message:d.message||"Streaming error",status:500})}return c?{...l,error:c}:s?{generatedResponse:s,error:null,...l}:{...l,error:new Sn({message:"Generation failed...",status:m.status})}}catch(s){return s.name==="AbortError"?{error:new Sn({message:"Request aborted",status:499})}:{error:new Sn({message:s.message||"Request failed",status:500})}}}import{getCommonBounds as uqe,getVisibleSceneBounds as gqe,convertToExcalidrawElements as WS}from"@orangecatai/element";import{useLayoutEffect as fJ}from"react";var bJ=e=>{let t=Qe();return fJ(()=>{t.setPlugins({diagramToCode:{generate:e.generate}})},[t,e.generate]),null};import{isElementLink as Eqe}from"@orangecatai/element";import{setCustomTextMetricsProvider as wqe}from"@orangecatai/element";import oQ,{useCallback as Io,useEffect as CE,useImperativeHandle as nQ,useMemo as rQ,useRef as an,useState as Tt}from"react";import{ArrowUp as iQ,AtSign as lA,Check as cA,ChevronDown as aQ,ChevronRight as sQ,Copy as dA,Globe as lQ,MessageSquare as mA,Mic as cQ,MicOff as dQ,Paperclip as kE,Plus as pA,Search as mQ,Wrench as pQ,X as SE}from"lucide-react";import{nanoid as LP}from"nanoid";import{newFrameElement as xJ,newElement as zg,newTextElement as _P,newImageElement as DP,getFrameChildren as Dl,isFrameLikeElement as hE,syncMovedIndices as Rl}from"@orangecatai/element";import{FRAME_STYLE as EJ,arrayToMap as Nl}from"@orangecatai/common";var RP=[{type:"function",function:{name:"create_frame",description:"Create a new frame on the canvas. Frames act as artboards that clip their children. Default size is 512x512.",parameters:{type:"object",properties:{width:{type:"number",description:"Frame width in pixels (default 512)"},height:{type:"number",description:"Frame height in pixels (default 512)"},name:{type:"string",description:"Optional display name for the frame"}},required:[],additionalProperties:!1}}},{type:"function",function:{name:"add_rectangle",description:"Add a filled rectangle inside a frame. Commonly used for solid background fills behind images and text.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the parent frame"},x:{type:"number",description:"X position relative to canvas (use the frame's x for full coverage)"},y:{type:"number",description:"Y position relative to canvas (use the frame's y for full coverage)"},width:{type:"number",description:"Rectangle width in pixels"},height:{type:"number",description:"Rectangle height in pixels"},backgroundColor:{type:"string",description:'Fill color as hex string e.g. "#1a1a2e". Use "transparent" for no fill.'},fillStyle:{type:"string",enum:["solid","hachure","cross-hatch"],description:'Fill style (default "solid")'},strokeColor:{type:"string",description:'Stroke/border color as hex (default "transparent")'},strokeWidth:{type:"number",description:"Stroke width in pixels (default 0)"},opacity:{type:"number",description:"Opacity 0-100 (default 100)"}},required:["frameId","x","y","width","height","backgroundColor"],additionalProperties:!1}}},{type:"function",function:{name:"add_text",description:"Add a text element inside a frame. Use for headlines, subheads, body copy, CTAs etc.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the parent frame"},x:{type:"number",description:"X position (canvas coordinates)"},y:{type:"number",description:"Y position (canvas coordinates)"},text:{type:"string",description:"The text content"},fontSize:{type:"number",description:"Font size in pixels (default 20)"},fontFamily:{type:"number",enum:[1,2,3,4,5],description:"Font family: 1=Excalifont(hand), 2=Nunito(sans), 3=Comic Shanns(code), 4=Liberation Sans(clean sans), 5=Cascadia(code). Default 2."},strokeColor:{type:"string",description:'Text color as hex string (default "#000000")'},textAlign:{type:"string",enum:["left","center","right"],description:"Horizontal alignment (default left)"},width:{type:"number",description:"Optional fixed width for text wrapping"}},required:["frameId","x","y","text"],additionalProperties:!1}}},{type:"function",function:{name:"generate_image",description:"Generate an image using AI (Gemini) from a text prompt and place it inside a frame. Use for hero images, product shots, backgrounds, illustrations etc.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the parent frame to insert the image into"},prompt:{type:"string",description:"Detailed image generation prompt describing what to create"},x:{type:"number",description:"X position for the image (canvas coordinates)"},y:{type:"number",description:"Y position for the image (canvas coordinates)"},width:{type:"number",description:"Image width in pixels"},height:{type:"number",description:"Image height in pixels"}},required:["frameId","prompt","x","y","width","height"],additionalProperties:!1}}},{type:"function",function:{name:"update_element",description:"Update properties of an existing element (move, resize, recolor, change text, etc.)",parameters:{type:"object",properties:{elementId:{type:"string",description:"ID of the element to update"},x:{type:"number",description:"New X position"},y:{type:"number",description:"New Y position"},width:{type:"number",description:"New width"},height:{type:"number",description:"New height"},backgroundColor:{type:"string",description:"New background/fill color"},strokeColor:{type:"string",description:"New stroke/text color"},opacity:{type:"number",description:"New opacity 0-100"},fontSize:{type:"number",description:"New font size (text elements only)"},text:{type:"string",description:"New text content (text elements only)"},fillStyle:{type:"string",enum:["solid","hachure","cross-hatch"],description:"New fill style"}},required:["elementId"],additionalProperties:!1}}},{type:"function",function:{name:"delete_element",description:"Delete an element from the canvas",parameters:{type:"object",properties:{elementId:{type:"string",description:"ID of the element to delete"}},required:["elementId"],additionalProperties:!1}}},{type:"function",function:{name:"get_frame_elements",description:"Get all child elements inside a frame. Returns their IDs, types, positions, sizes, colors, and text content. Use this to understand the current layout before making changes.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the frame to inspect"}},required:["frameId"],additionalProperties:!1}}}];var NP=[{type:"function",function:{name:"create_frame",description:"Create a new frame on the canvas to act as the root container for your banner. Default size is 512x512. ALWAYS call this FIRST before generating images or HTML.",parameters:{type:"object",properties:{width:{type:"number",description:"Frame width in pixels (default 512)"},height:{type:"number",description:"Frame height in pixels (default 512)"},name:{type:"string",description:"Optional display name for the frame"}},required:[],additionalProperties:!1}}},{type:"function",function:{name:"generate_image",description:"Generate an image using AI (Gemini) and place it onto the canvas. Always call this for any photo or image content \u2014 even when the user has attached a reference image. The attached image is passed to Gemini as visual reference; Gemini generates the final output. Use referenceImageIndex to tell Gemini which user attachment to reference. IMPORTANT: your prompt must describe a purely visual scene \u2014 NO text, NO typography, NO words, NO captions, NO watermarks. All copy is handled by the HTML layer. A 'no text' safety suffix will be auto-appended, but you must also describe composition clearly (e.g. which side should be left open/empty for the HTML text).",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the parent frame to insert the image into"},prompt:{type:"string",description:"Detailed generation prompt. When using a reference image, describe what you want Gemini to produce \u2014 e.g. 'use this building as the subject, wide cinematic crop with open sky on the left for text overlay'."},x:{type:"number",description:"X position relative to the frame's top-left corner"},y:{type:"number",description:"Y position relative to the frame's top-left corner"},width:{type:"number",description:"Image width in pixels"},height:{type:"number",description:"Image height in pixels"},referenceImageIndex:{type:"number",description:"0-based index of the user's attached image to pass to Gemini as reference. Always use 0 when the user has attached an image."}},required:["frameId","prompt","x","y","width","height"],additionalProperties:!1}}},{type:"function",function:{name:"generate_html_banner",description:"Place HTML/CSS text and shape elements into an EXISTING frame on the canvas. Always call create_frame first to get a frameId, then generate_image, then call this with that frameId. frameId is required \u2014 this tool does NOT create frames.",parameters:{type:"object",properties:{html:{type:"string",description:"Complete self-contained HTML with inline <style>. All layer elements must use position:absolute with explicit left/top/width/height in px. Root div must have class='canvas'."},frameId:{type:"string",description:"Required. The ID of the frame created by create_frame. Adds HTML elements into this existing frame, preserving existing children like images."}},required:["html","frameId"],additionalProperties:!1}}},{type:"function",function:{name:"get_frame_elements",description:"Get all child elements inside a frame. Use when editing an existing banner to understand its current state before replacing.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the frame to inspect"}},required:["frameId"],additionalProperties:!1}}},{type:"function",function:{name:"update_element",description:"Update properties of an existing element. Use for minor targeted fixes after the banner is placed.",parameters:{type:"object",properties:{elementId:{type:"string"},x:{type:"number"},y:{type:"number"},width:{type:"number"},height:{type:"number"},backgroundColor:{type:"string"},strokeColor:{type:"string"},opacity:{type:"number"},fontSize:{type:"number"},text:{type:"string"},fillStyle:{type:"string",enum:["solid","hachure","cross-hatch"]}},required:["elementId"],additionalProperties:!1}}},{type:"function",function:{name:"delete_element",description:"Delete an element from the canvas.",parameters:{type:"object",properties:{elementId:{type:"string",description:"ID of the element to delete"}},required:["elementId"],additionalProperties:!1}}}];function fE(e){let t={id:e.id,type:e.type,x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)};if(e.backgroundColor&&e.backgroundColor!=="transparent"&&(t.backgroundColor=e.backgroundColor),e.strokeColor&&e.strokeColor!=="#1e1e1e"&&(t.strokeColor=e.strokeColor),e.opacity!==100&&(t.opacity=e.opacity),e.fillStyle&&e.fillStyle!=="solid"&&(t.fillStyle=e.fillStyle),e.type==="text"){let o=e;t.text=o.text,t.fontSize=o.fontSize,t.fontFamily=o.fontFamily,t.textAlign=o.textAlign}if(e.type==="image"&&(t.type="image"),e.type==="frame"){let o=e;o.name&&(t.name=o.name)}return t}function BP(e){return e.map(fE)}function FP(e){let t=e.getSceneElements(),o=[];for(let n of t)if(hE(n)){let r=Dl(t,n.id),i=n;o.push({id:n.id,name:i.name||`Frame ${Math.round(n.width)}\xD7${Math.round(n.height)}`,width:Math.round(n.width),height:Math.round(n.height),childCount:r.length})}return o}async function Gd(e,t){let o=e.getSceneElements(),n=o.find(s=>s.id===t);if(!n||!hE(n))return null;let r=e.getAppState(),i=e.getFiles(),a=Dl(o,t);try{return(await Ba([...a,n],r,i,{exportBackground:!0,viewBackgroundColor:r.viewBackgroundColor,exportingFrame:n,exportPadding:0})).toDataURL("image/jpeg",.7)}catch{return null}}function OP(e,t){let o=e.getSceneElements(),n=o.find(l=>l.id===t);if(!n||!hE(n))return null;let r=Dl(o,t),i=n,a={id:n.id,name:i.name||`Frame ${Math.round(n.width)}\xD7${Math.round(n.height)}`,width:Math.round(n.width),height:Math.round(n.height),childCount:r.length},s={frame:fE(n),children:BP(r)};return{serialized:JSON.stringify(s,null,2),frameInfo:a}}async function zP(e,t,o){let n;try{n=JSON.parse(t)}catch{return{success:!1,error:"Invalid JSON arguments",statusMessage:"Failed to parse tool arguments"}}switch(e){case"create_frame":return vJ(n,o);case"add_rectangle":return IJ(n,o);case"add_text":return TJ(n,o);case"generate_image":return CJ(n,o);case"update_element":return kJ(n,o);case"delete_element":return SJ(n,o);case"get_frame_elements":return MJ(n,o);case"generate_html_banner":return PJ(n,o);default:return{success:!1,error:`Unknown tool: ${e}`,statusMessage:`Unknown tool: ${e}`}}}function yJ(e){let t=e.getAppState(),o=-t.scrollX+t.width/2/t.zoom.value,n=-t.scrollY+t.height/2/t.zoom.value;return{x:o,y:n}}var Og=10;function wJ(e,t,o,n,r){return Math.abs(e-r.x)<Og&&Math.abs(t-r.y)<Og&&Math.abs(o-r.width)<Og&&Math.abs(n-r.height)<Og}function HP(e,t,o,n,r,i){return e==="text"?3:e==="image"?1:wJ(t,o,n,r,i)?0:2}function bE(e,t,o){let n=e[t],r=n.id,i=t+1;for(let a=t+1;a<e.length;a++){let s=e[a];if(s.frameId!==r)continue;if(HP(s.type,s.x,s.y,s.width,s.height,n)>o)return a;i=a+1}return i}function vJ(e,t){let o=e.width||512,n=e.height||512,r=e.name||null,i=yJ(t.excalidrawAPI),a=xJ({...EJ,x:i.x-o/2,y:i.y-n/2,width:o,height:n,opacity:100,locked:!1,name:r??void 0}),l=[...t.excalidrawAPI.getSceneElements(),a];return Rl(l,Nl([a])),t.excalidrawAPI.updateScene({elements:l}),t.excalidrawAPI.scrollToContent(a,{fitToViewport:!1}),{success:!0,data:{frameId:a.id,x:Math.round(a.x),y:Math.round(a.y),width:o,height:n},statusMessage:`Created frame "${r||"Ad Frame"}" (${o}\xD7${n})`}}function IJ(e,t){let o=e.frameId;if(!o)return{success:!1,error:"frameId is required",statusMessage:"Failed: missing frameId"};let n=zg({type:"rectangle",x:e.x,y:e.y,width:e.width,height:e.height,backgroundColor:e.backgroundColor||"transparent",fillStyle:e.fillStyle||"solid",strokeColor:e.strokeColor||"transparent",strokeWidth:e.strokeWidth??0,opacity:e.opacity??100}),r=t.excalidrawAPI.getSceneElements(),i=r.findIndex(d=>d.id===o);if(i===-1)return{success:!1,error:`Frame ${o} not found`,statusMessage:"Failed: frame not found"};let a=r[i],s=HP("rectangle",e.x,e.y,e.width,e.height,a),l={...n,frameId:o},c=[...r],m=bE(c,i,s);c.splice(m,0,l),Rl(c,Nl([l])),t.excalidrawAPI.updateScene({elements:c});let p=s===0;return{success:!0,data:{elementId:n.id,type:"rectangle",x:Math.round(n.x),y:Math.round(n.y),width:Math.round(n.width),height:Math.round(n.height),backgroundColor:n.backgroundColor,isBackground:p},statusMessage:`Added ${p?"background ":""}rectangle (${Math.round(n.width)}\xD7${Math.round(n.height)}) with fill ${n.backgroundColor}`}}function TJ(e,t){let o=e.frameId;if(!o)return{success:!1,error:"frameId is required",statusMessage:"Failed: missing frameId"};let n=_P({x:e.x,y:e.y,text:e.text,fontSize:e.fontSize||20,fontFamily:e.fontFamily||2,strokeColor:e.strokeColor||"#000000",textAlign:e.textAlign||"left",width:e.width}),r=t.excalidrawAPI.getSceneElements(),i=r.findIndex(c=>c.id===o);if(i===-1)return{success:!1,error:`Frame ${o} not found`,statusMessage:"Failed: frame not found"};let a={...n,frameId:o},s=[...r],l=bE(s,i,3);return s.splice(l,0,a),Rl(s,Nl([a])),t.excalidrawAPI.updateScene({elements:s}),{success:!0,data:{elementId:n.id,type:"text",x:Math.round(n.x),y:Math.round(n.y),text:e.text,fontSize:e.fontSize||20},statusMessage:`Added text "${e.text.slice(0,40)}${e.text.length>40?"\u2026":""}"`}}async function CJ(e,t){let o=e.frameId,n=e.prompt,r=e.x,i=e.y,a=e.width,s=e.height,l=e.referenceImageIndex,c=l!==void 0?t.fileAttachments?.[l]?.dataUrl:void 0,m=`${n} \u2014 NO text, NO typography, NO words, NO captions, NO watermarks, NO overlaid copy. Pure clean visual image only.`;if(!o||!n)return{success:!1,error:"frameId and prompt are required",statusMessage:"Failed: missing required parameters"};if(!t.geminiApiKey)return{success:!1,error:"No Gemini API key configured. Set geminiApiKey prop or VITE_APP_GEMINI_API_KEY.",statusMessage:"Failed: no Gemini API key"};let p=t.excalidrawAPI.getSceneElements(),d=p.findIndex(x=>x.id===o);if(d===-1)return{success:!1,error:`Frame ${o} not found`,statusMessage:"Failed: frame not found"};let u=p[d],h=r<u.width&&i<u.height&&Math.abs(r-u.x)>50,g=h?u.x+r:r,E=h?u.y+i:i,w=a>=s?a/s>1.3?"16:9":"1:1":"9:16";try{let x=await ua(m,t.agentImageModel||"gemini-3.1-flash-image-preview",w,"1K",!1,!1,t.geminiApiKey,c,t.signal);if(t.signal?.aborted)return{success:!1,error:"Cancelled",statusMessage:"Image generation cancelled"};let y=LP(),v=DP({type:"image",x:g,y:E,width:a,height:s,fileId:y,status:"pending",scale:[1,1]}),I=t.excalidrawAPI.getSceneElements(),k=I.findIndex(P=>P.id===o);if(k===-1)return{success:!1,error:`Frame ${o} was removed during image generation`,statusMessage:"Failed: frame no longer exists"};let L={...v,frameId:o},S=[...I],_=bE(S,k,1);return S.splice(_,0,L),Rl(S,Nl([L])),t.excalidrawAPI.updateScene({elements:S}),t.excalidrawAPI.addFiles([{id:y,dataURL:x,mimeType:Bo(x),created:Date.now(),lastRetrieved:Date.now()}]),{success:!0,data:{elementId:v.id,frameId:L.frameId,type:"image",x:Math.round(g),y:Math.round(E),width:Math.round(a),height:Math.round(s)},statusMessage:`Generated image from prompt "${n.slice(0,50)}${n.length>50?"\u2026":""}"`}}catch(x){let y=x instanceof Error?x.message:"Image generation failed";return{success:!1,error:y,statusMessage:`Image generation failed: ${y}`}}}function kJ(e,t){let o=e.elementId;if(!o)return{success:!1,error:"elementId is required",statusMessage:"Failed: missing elementId"};let r=t.excalidrawAPI.getSceneElements().find(s=>s.id===o);if(!r)return{success:!1,error:`Element ${o} not found`,statusMessage:"Failed: element not found"};let i={},a=["x","y","width","height","backgroundColor","strokeColor","opacity","fontSize","text","fillStyle"];for(let s of a)e[s]!==void 0&&(i[s]=e[s]);return Object.keys(i).length===0?{success:!1,error:"No valid properties to update",statusMessage:"Failed: nothing to update"}:i.text!==void 0&&r.type==="text"&&(i.width===void 0||i.height===void 0)?{success:!1,error:"Updating text content requires providing new width and height to avoid clipping.",statusMessage:"Failed: text update requires width and height"}:(t.excalidrawAPI.mutateElement(r,i),{success:!0,data:{elementId:o,updated:Object.keys(i)},statusMessage:`Updated element (${Object.keys(i).join(", ")})`})}function SJ(e,t){let o=e.elementId;if(!o)return{success:!1,error:"elementId is required",statusMessage:"Failed: missing elementId"};let r=t.excalidrawAPI.getSceneElements().find(i=>i.id===o);return r?(t.excalidrawAPI.mutateElement(r,{isDeleted:!0}),{success:!0,data:{elementId:o},statusMessage:`Deleted element ${o}`}):{success:!1,error:`Element ${o} not found`,statusMessage:"Failed: element not found"}}function MJ(e,t){let o=e.frameId;if(!o)return{success:!1,error:"frameId is required",statusMessage:"Failed: missing frameId"};let n=t.excalidrawAPI.getSceneElements(),r=n.find(s=>s.id===o);if(!r)return{success:!1,error:`Frame ${o} not found`,statusMessage:"Failed: frame not found"};let i=Dl(n,o),a=BP(i);return{success:!0,data:{frameId:o,frame:fE(r),children:a,childCount:a.length},statusMessage:`Found ${a.length} elements in frame`}}async function PJ(e,t){let o=e.html,n=e.frameId;if(!o||typeof o!="string")return{success:!1,error:"html is required",statusMessage:"Failed: missing html"};if(!n)return{success:!1,error:"frameId is required. Call create_frame first to get a frameId, then generate_image with that frameId, then call generate_html_banner with that frameId.",statusMessage:"Failed: frameId is required"};let r=t.excalidrawAPI.getSceneElements(),i=r.find(T=>T.id===n);if(!i)return{success:!1,error:`Frame ${n} not found`,statusMessage:"Failed: frame not found"};let a=i,s=a.x,l=a.y,c=Math.round(a.width),m=Math.round(a.height),d=Dl(r,n).filter(T=>T.customData?.generatedByHtml===!0);for(let T of d)t.excalidrawAPI.mutateElement(T,{isDeleted:!0});let u;try{u=await xu(o,s,l,c,m,t.customFontMap)}catch(T){let M=T instanceof Error?T.message:"HTML parse failed";return{success:!1,error:M,statusMessage:`HTML banner parse failed: ${M}`}}if(u.length===0){let T=o.match(/\.(?:bg|canvas)[^{]*\{[^}]*background(?:-color)?:\s*(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\))/),M=T?T[1]:null;if(M){let N=zg({type:"rectangle",x:s,y:l,width:c,height:m,backgroundColor:M.startsWith("#")?M:"#ffffff",fillStyle:"solid",strokeColor:"transparent",strokeWidth:0,opacity:100,roughness:0,customData:{generatedByHtml:!0}}),B=[...t.excalidrawAPI.getSceneElements(),N];Rl(B,Nl([N])),t.excalidrawAPI.updateScene({elements:B})}return{success:!1,error:"Parser produced no elements \u2014 check HTML structure. Try simpler HTML: fewer elements, explicit px values for all positions, no nested divs.",statusMessage:"Failed: no elements parsed from HTML"}}let h=[],g=[];for(let T of u)if(T.kind==="rectangle"){let M=zg({type:"rectangle",x:T.x,y:T.y,width:T.width,height:T.height,backgroundColor:T.backgroundColor,fillStyle:"solid",strokeColor:T.strokeColor,strokeWidth:T.strokeWidth,opacity:T.opacity,roughness:0,...T.borderRadius>0?{roundness:{type:3,value:T.borderRadius}}:{},customData:{generatedByHtml:!0}});h.push({...M,frameId:a.id})}else if(T.kind==="ellipse"){let M=zg({type:"ellipse",x:T.x,y:T.y,width:T.width,height:T.height,backgroundColor:T.backgroundColor,fillStyle:"solid",strokeColor:T.strokeColor,strokeWidth:T.strokeWidth,opacity:T.opacity,roughness:0});h.push({...M,frameId:a.id})}else if(T.kind==="text"){let M=_P({x:T.x,y:T.y,text:T.text,fontSize:T.fontSize,fontFamily:T.fontFamily,strokeColor:T.color,textAlign:T.textAlign,width:T.width,opacity:T.opacity,roughness:0,customData:{generatedByHtml:!0}});h.push({...M,frameId:a.id})}else if(T.kind==="image"){let M=LP(),N=DP({type:"image",x:T.x,y:T.y,width:T.width,height:T.height,fileId:M,status:"pending",scale:[1,1],customData:{generatedByHtml:!0}});h.push({...N,frameId:a.id}),g.push({id:M,dataURL:T.dataUrl,mimeType:Bo(T.dataUrl),created:Date.now(),lastRetrieved:Date.now()})}let E=c*m,w=[],x=[];for(let T of h)T.type==="rectangle"&&T.width*T.height>=E*.25?w.push(T):x.push(T);let y=t.excalidrawAPI.getSceneElements(),v=y.findIndex(T=>T.id===a.id),I=Dl(y,a.id),k=I.length>0?y.findIndex(T=>T.id===I[0].id):v+1,L=I.length>0?y.findIndex(T=>T.id===I[I.length-1].id)+1:v+1,S=[...y.slice(0,k),...w,...y.slice(k,L),...x,...y.slice(L)],_=[...w,...x];Rl(S,Nl(_)),t.excalidrawAPI.updateScene({elements:S}),g.length>0&&t.excalidrawAPI.addFiles(g),t.excalidrawAPI.scrollToContent(a,{fitToViewport:!1});let P=await Gd(t.excalidrawAPI,a.id);return{success:!0,data:{frameId:a.id,x:Math.round(s),y:Math.round(l),width:c,height:m,elementCount:h.length,screenshot:P??void 0},statusMessage:`Banner updated: ${h.length} elements in frame "${e.name||"Banner"}" (${c}\xD7${m})`,screenshot:P??void 0}}function AJ(e){try{let o=JSON.parse(e)?.choices?.[0];return o?{content:o.delta?.content??null,toolCalls:o.delta?.tool_calls??null,finishReason:o.finish_reason??null}:null}catch{return null}}async function*Hg(e){let t=e.body?.getReader();if(t)for await(let o of gE(t)){if(o==="[DONE]")break;let n=AJ(o);n&&(yield n)}}function GP(e,t){if(!t.toolCalls)return e;for(let o of t.toolCalls){let n=o.index;if(n>=e.length||o.id){for(;e.length<=n;)e.push({id:"",type:"function",function:{name:"",arguments:""}});e[n]={id:o.id||e[n].id,type:"function",function:{name:o.function?.name||e[n].function.name,arguments:o.function?.arguments||""}}}else o.function?.arguments&&(e[n].function.arguments+=o.function.arguments),o.function?.name&&(e[n].function.name=o.function.name)}return e}function UP(e){return e.filter(t=>t.id&&t.function.name).map(t=>({id:t.id,type:"function",function:{name:t.function.name,arguments:t.function.arguments}}))}function Gg(e){return e.body?(e.headers.get("content-type")||"").includes("text/event-stream"):!1}var LJ=`You are an expert HTML/CSS banner designer embedded inside a canvas editor. You create beautiful advertisement banners by writing clean, self-contained HTML/CSS code. Your HTML is parsed by a DOM renderer that converts each element into individually editable canvas elements \u2014 so you must follow the layout rules strictly.
216
+ `),g=h.reduce((E,w,x)=>{let y=xq(w).trim();if(y.length){let v=this.getTopLayerFrameAtSceneCoords({x:r,y:u}),I=$6(y,s,l),k=I.width>p,L=k?hq(y,s,p):y;I=k?$6(L,s,l):I;let S=r-I.width/2,_=u-I.height/2,P=_6({...a,x:S,y:_,text:L,originalText:y,lineHeight:l,autoResize:!k,frameId:v?v.id:null});E.push(P),u+=P.height+d}else h[x-1]?.trim()&&(u+=Eq(a.fontSize,l)+d);return E},[]);g.length!==0&&(this.scene.insertElements(g),this.store.scheduleCapture(),this.setState({selectedElementIds:Oe(Object.fromEntries(g.map(E=>[E.id,!0])),this.state)}),!n&&g.length>1&&sP===!1&&this.editorInterface.formFactor!=="phone"&&(this.setToast({message:f("toast.pasteAsSingleElement",{shortcut:G("CtrlOrCmd+Shift+V")}),duration:5e3}),sP=!0))}handleTextWysiwyg(o,{isExistingElement:n=!1}){let r=this.scene.getElementsMapIncludingDeleted(),i=(a,s)=>{this.scene.replaceAllElements([...this.scene.getElementsIncludingDeleted().map(l=>l.id===o.id&&vn(l)?Si(l,{originalText:a,isDeleted:s??l.isDeleted,...Wj(l,G6(l,r),r,a)}):l)])};j3({id:o.id,canvas:this.canvas,getViewportCoords:(a,s)=>{let{x:l,y:c}=Cg({sceneX:a,sceneY:s},this.state);return[l-this.state.offsetLeft,c-this.state.offsetTop]},onChange:mt(a=>{i(a,!1),Q6(o)&&Pg(o,this.scene)}),onSubmit:mt(({viaKeyboard:a,nextOriginalText:s})=>{let l=!s.trim();if(i(s,l),!l&&a){let c=o.containerId?o.containerId:o.id;wo(()=>{this.setState(m=>({selectedElementIds:Oe({...m.selectedElementIds,[c]:!0},m)}))})}l&&Bj(this.scene.getNonDeletedElements(),[o]),(!l||n)&&this.store.scheduleCapture(),wo(()=>{this.setState({newElement:null,editingTextElement:null})}),this.state.activeTool.locked&&So(this.interactiveCanvas,this.state),this.focusContainer()}),element:o,excalidrawContainer:this.excalidrawContainerRef.current,app:this,autoSelect:!this.editorInterface.isTouchScreen}),this.deselectElements(),i(o.originalText,!1)}deselectElements(){this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null})}getTextElementAtPosition(o,n){let r=this.getElementAtPosition(o,n,{includeBoundTextElement:!0});return r&&vn(r)&&!r.isDeleted?r:null}getElementAtPosition(o,n,r){let i=[];if(r&&"allHitElements"in r?i=r?.allHitElements||[]:i=this.getElementsAtPosition(o,n,{includeBoundTextElement:r?.includeBoundTextElement,includeLockedElements:r?.includeLockedElements}),i.length>1){if(r?.preferSelected){for(let s=i.length-1;s>-1;s--)if(this.state.selectedElementIds[i[s].id])return i[s]}let a=i[i.length-1];return Ad({point:de(o,n),element:a,threshold:this.getElementHitThreshold(a)/2,elementsMap:this.scene.getNonDeletedElementsMap(),frameNameBound:jt(a)?this.frameNameBoundsCache.get(a):null})?a:i[i.length-2]}return i.length===1?i[0]:null}getElementsAtPosition(o,n,r){let i=[],a=this.scene.getNonDeletedElementsMap();return(r?.includeBoundTextElement&&r?.includeLockedElements?this.scene.getNonDeletedElements():this.scene.getNonDeletedElements().filter(l=>(r?.includeLockedElements||!l.locked)&&(r?.includeBoundTextElement||!(vn(l)&&l.containerId)))).filter(l=>this.hitElement(o,n,l)).filter(l=>{let c=Gx(l,a);return c&&this.state.frameRendering.enabled&&this.state.frameRendering.clip?U6({x:o,y:n},c,a):!0}).filter(l=>Ll(l)?(i.push(l),!1):!0).concat(i)}getElementHitThreshold(o){return Math.max(o.strokeWidth/2+.1,.85*(w6/this.state.zoom.value))}hitElement(o,n,r,i=!0){return i&&this.state.selectedElementIds[r.id]&&tq([r],this.state,this.editorInterface)&&Bq(de(o,n),r,this.scene.getNonDeletedElementsMap(),this.getElementHitThreshold(r))||cq(de(o,n),r,this.scene.getNonDeletedElementsMap())?!0:Ad({point:de(o,n),element:r,threshold:this.getElementHitThreshold(r),elementsMap:this.scene.getNonDeletedElementsMap(),frameNameBound:jt(r)?this.frameNameBoundsCache.get(r):null})}getTextBindableContainerAtPosition(o,n){let r=this.scene.getNonDeletedElements(),i=this.scene.getSelectedElements(this.state);if(i.length===1)return N6(i[0],!1)?i[0]:null;let a=null;for(let s=r.length-1;s>=0;--s){if(r[s].isDeleted)continue;let[l,c,m,p]=Mg(r[s],this.scene.getNonDeletedElementsMap());if(Al(r[s])&&Ad({point:de(o,n),element:r[s],elementsMap:this.scene.getNonDeletedElementsMap(),threshold:this.getElementHitThreshold(r[s])})){a=r[s];break}else if(l<o&&o<m&&c<n&&n<p){a=r[s];break}}return N6(a,!1)?a:null}handleHoverSelectedLinearElement(o,n,r){let i=this.scene.getNonDeletedElementsMap(),a=Me.getElement(o.elementId,i);if(a)if(this.state.selectedLinearElement){let s=-1,l=null;Ad({point:de(n,r),element:a,elementsMap:i,threshold:this.getElementHitThreshold(a)})?(s=Me.getPointIndexUnderCursor(a,i,this.state.zoom,n,r),l=Me.getSegmentMidpointHitCoords(o,{x:n,y:r},this.state,this.scene.getNonDeletedElementsMap()),(vo(a)?s===0||s===a.points.length-1:s>=0)||l?Ne(this.interactiveCanvas,st.POINTER):this.hitElement(n,r,a)&&(!vo(a)||!(a.startBinding||a.endBinding))&&(this.state.activeTool.type!=="lasso"||Object.keys(this.state.selectedElementIds).length>0)&&Ne(this.interactiveCanvas,st.MOVE)):this.hitElement(n,r,a)&&(!vo(a)||!(a.startBinding||a.endBinding))&&(this.state.activeTool.type!=="lasso"||Object.keys(this.state.selectedElementIds).length>0)&&Ne(this.interactiveCanvas,st.MOVE),this.state.selectedLinearElement.hoverPointIndex!==s&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,hoverPointIndex:s}}),Me.arePointsEqual(this.state.selectedLinearElement.segmentMidPointHoveredCoords,l)||this.setState({selectedLinearElement:{...this.state.selectedLinearElement,segmentMidPointHoveredCoords:l}});let c=null,m=a;(m.startBinding||m.endBinding)&&(c=Gq(a,n,r,this.scene,this.state)),this.state.selectedLinearElement.hoveredFocusPointBinding!==c&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,isDragging:!1,hoveredFocusPointBinding:c}}),c&&Ne(this.interactiveCanvas,st.POINTER)}else Ne(this.interactiveCanvas,st.AUTO)}updateGestureOnPointerDown(o){De.pointers.set(o.pointerId,{x:o.clientX,y:o.clientY}),De.pointers.size===2&&(De.lastCenter=f0(De.pointers),De.initialScale=this.state.zoom.value,De.initialDistance=b0(Array.from(De.pointers.values())))}initialPointerDownState(o){let n=ot(o,this.state),r=this.scene.getSelectedElements(this.state),[i,a,s,l]=Pl(r),c=r.findIndex(vo)===0;return{origin:n,withCmdOrCtrl:o[oe.CTRL_OR_CMD],originInGrid:Cx(Zt(n.x,n.y,o[oe.CTRL_OR_CMD]||c?null:this.getEffectiveGridSize())),scrollbars:V0(Nd,o.clientX-this.state.offsetLeft,o.clientY-this.state.offsetTop),lastCoords:{...n},originalElements:this.scene.getNonDeletedElements().reduce((m,p)=>(m.set(p.id,D6(p)),m),new Map),resize:{handleType:!1,isResizing:!1,offset:{x:0,y:0},arrowDirection:"origin",center:{x:(s+i)/2,y:(l+a)/2}},hit:{element:null,allHitElements:[],wasAddedToSelection:!1,hasBeenDuplicated:!1,hasHitCommonBoundingBoxOfSelectedElements:this.isHittingCommonBoundingBoxOfSelectedElements(n,r)},drag:{hasOccurred:!1,offset:null,origin:{...n},blockDragging:!1},eventListeners:{onMove:null,onUp:null,onKeyUp:null,onKeyDown:null},boxSelection:{hasOccurred:!1}}}handleDraggingScrollBar(o,n){if(!(n.scrollbars.isOverEither&&!this.state.multiElement))return!1;Xx=!0,n.lastCoords.x=o.clientX,n.lastCoords.y=o.clientY;let r=Su(a=>{a.target instanceof HTMLElement&&this.handlePointerMoveOverScrollbars(a,n)}),i=mt(()=>{Fd=null,Xx=!1,So(this.interactiveCanvas,this.state),this.setState({cursorButton:"up"}),this.savePointer(o.clientX,o.clientY,"up"),window.removeEventListener(ue.POINTER_MOVE,r),window.removeEventListener(ue.POINTER_UP,i),r.flush()});return Fd=i,window.addEventListener(ue.POINTER_MOVE,r),window.addEventListener(ue.POINTER_UP,i),!0}isASelectedElement(o){return o!=null&&this.state.selectedElementIds[o.id]}isHittingCommonBoundingBoxOfSelectedElements(o,n){if(n.length<2)return!1;let r=Math.max(w6/this.state.zoom.value,1),[i,a,s,l]=Pl(n);return o.x>i-r&&o.x<s+r&&o.y>a-r&&o.y<l+r}getCurrentItemRoundness(o){return this.state.currentItemRoundness==="round"?{type:$j(o)?vg.ADAPTIVE_RADIUS:vg.PROPORTIONAL_RADIUS}:null}maybeCacheReferenceSnapPoints(o,n,r=!1){wr({event:o,app:this,selectedElements:n})&&(r||!$o.getReferenceSnapPoints())&&$o.setReferenceSnapPoints(X5(this.scene.getNonDeletedElements(),n,this.state,this.scene.getNonDeletedElementsMap()))}maybeCacheVisibleGaps(o,n,r=!1){wr({event:o,app:this,selectedElements:n})&&(r||!$o.getVisibleGaps())&&$o.setVisibleGaps(K5(this.scene.getNonDeletedElements(),n,this.state,this.scene.getNonDeletedElementsMap()))}onKeyDownFromPointerDownHandler(o){return mt(n=>{this.maybeHandleResize(o,n)||this.maybeDragNewGenericElement(o,n)})}onKeyUpFromPointerDownHandler(o){return mt(n=>{n.key===oe.ALT&&n.preventDefault(),!this.maybeHandleResize(o,n)&&this.maybeDragNewGenericElement(o,n)})}onPointerMoveFromPointerDownHandler(o){return Su(n=>{if(this.state.openDialog?.name==="elementLinkSelector")return;let r=ot(n,this.state);if(this.state.activeLockedId&&this.setState({activeLockedId:null}),this.state.selectedLinearElement&&this.state.selectedLinearElement.elbowed&&this.state.selectedLinearElement.initialState.segmentMidpoint.index){let[d,u]=Zt(r.x,r.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),h=this.state.selectedLinearElement.initialState.segmentMidpoint.index;if(h<0){let E=Me.getSegmentMidpointHitCoords({...this.state.selectedLinearElement,segmentMidPointHoveredCoords:null},{x:d,y:u},this.state,this.scene.getNonDeletedElementsMap());h=E?Me.getSegmentMidPointIndex(this.state.selectedLinearElement,this.state,E,this.scene.getNonDeletedElementsMap()):-1}let g=Me.moveFixedSegment(this.state.selectedLinearElement,h,d,u,this.scene);this.setState({selectedLinearElement:{...this.state.selectedLinearElement,isDragging:!0,segmentMidPointHoveredCoords:g.segmentMidPointHoveredCoords,initialState:g.initialState}});return}let i=this.previousPointerMoveCoords??o.origin;if(this.previousPointerMoveCoords=r,o.drag.offset===null&&(o.drag.offset=Cx(Rq(this.scene.getSelectedElements(this.state),o.origin.x,o.origin.y))),!(n.target instanceof HTMLElement)||this.handlePointerMoveOverScrollbars(n,o))return;if(po(this.state)){this.handleEraser(n,r);return}this.state.activeTool.type==="laser"&&this.laserTrails.addPointToPath(r.x,r.y);let[s,l]=Zt(r.x,r.y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize());if(o.resize.isResizing&&(o.lastCoords.x=r.x,o.lastCoords.y=r.y,this.maybeHandleCrop(o,n)||this.maybeHandleResize(o,n)))return!0;let c=this.scene.getNonDeletedElementsMap();if(this.state.selectedLinearElement){let d=this.state.selectedLinearElement;if(d.draggedFocusPointBinding){Hq(d,c,r,this.scene,this.state,this.getEffectiveGridSize(),n.altKey),this.setState({selectedLinearElement:{...d,isDragging:!1,selectedPointsIndices:[],initialState:{...d.initialState,lastClickedPoint:-1}}});return}if(Me.shouldAddMidpoint(this.state.selectedLinearElement,r,this.state,c)){let u=Me.addMidpoint(this.state.selectedLinearElement,r,this,!n[oe.CTRL_OR_CMD],this.scene);if(!u)return;wo(()=>{this.state.selectedLinearElement&&this.setState({selectedLinearElement:{...this.state.selectedLinearElement,initialState:u.pointerDownState,selectedPointsIndices:u.selectedPointsIndices,segmentMidPointHoveredCoords:null}})});return}else{if(d.initialState.segmentMidpoint.value!==null&&!d.initialState.segmentMidpoint.added)return;if(d.initialState.lastClickedPoint>-1){let u=Me.getElement(d.elementId,c);if(u?.isDeleted)return;if(or(u)){let g=wn(de(r.x,r.y),this.scene.getNonDeletedElements(),c);Ar("COMPLEX_BINDINGS")&&this.handleDelayedBindModeChange(u,g)}if(n.altKey&&!this.state.selectedLinearElement?.initialState?.arrowStartIsInside&&Ar("COMPLEX_BINDINGS")&&this.handleSkipBindMode(),d.initialState.lastClickedPoint===-1)return;let h=Me.handlePointDragging(n,this,r.x,r.y,d);if(h){o.lastCoords.x=r.x,o.lastCoords.y=r.y,o.drag.hasOccurred=!0,(h.suggestedBinding!==this.state.suggestedBinding||!k6(h.selectedLinearElement?.selectedPointsIndices??[],this.state.selectedLinearElement?.selectedPointsIndices??[])||h.selectedLinearElement?.hoverPointIndex!==this.state.selectedLinearElement?.hoverPointIndex||h.selectedLinearElement?.customLineAngle!==this.state.selectedLinearElement?.customLineAngle||this.state.selectedLinearElement.isDragging!==h.selectedLinearElement?.isDragging||this.state.selectedLinearElement?.initialState?.altFocusPoint!==h.selectedLinearElement?.initialState?.altFocusPoint)&&this.setState(h);return}}}}let m=o.hit.allHitElements.some(d=>this.isASelectedElement(d)),p=this.state.selectedLinearElement?.isEditing&&n.shiftKey&&this.state.selectedLinearElement.elementId===o.hit.element?.id;if((m||o.hit.hasHitCommonBoundingBoxOfSelectedElements)&&!p&&!o.drag.blockDragging){let d=this.scene.getSelectedElements(this.state);if(d.length>0&&d.every(E=>E.locked))return;let u=d.find(E=>jt(E)),h=this.getTopLayerFrameAtSceneCoords(r),g=h&&!u?h:null;if(this.state.frameToHighlight!==g&&wo(()=>{this.setState({frameToHighlight:g})}),o.drag.hasOccurred=!0,this.state.activeTool.type==="lasso"&&this.lassoTrail.hasCurrentTrail&&!(this.editorInterface.formFactor!=="desktop"&&o.hit.element)&&!this.state.activeTool.fromSelection)return;if(this.state.activeTool.type==="lasso"&&d.length>0&&o.drag.hasOccurred&&!this.state.activeTool.fromSelection&&this.lassoTrail.endPath(),d.length>0&&!o.withCmdOrCtrl&&!this.state.editingTextElement&&this.state.activeEmbeddable?.state!=="active"){let E={x:r.x-o.drag.origin.x,y:r.y-o.drag.origin.y},w=[...o.originalElements.values()],x=n.shiftKey;if(x){let I=Math.abs(E.x),k=Math.abs(E.y),L=x&&I<k,S=x&&I>k;L&&(E.x=0),S&&(E.y=0)}if(this.state.croppingElementId){let I=this.scene.getNonDeletedElementsMap().get(this.state.croppingElementId);if(I&&Mi(I)&&I.crop!==null&&o.hit.element===I){let k=I.crop,L=Pd(I)&&this.imageCache.get(I.fileId)?.image;if(L&&!(L instanceof Promise)){let S=Yq(I),_=d6(r.x-i.x,r.y-i.y);_[0]*=L.naturalWidth/S.width,_[1]*=L.naturalHeight/S.height;let[P,T,M,N,O,B]=Mg(I,c),U=wx(yx(de(P,T),de(O,B),I.angle)),D=wx(yx(de(M,T),de(O,B),I.angle)),F=wx(yx(de(P,N),de(O,B),I.angle)),z=u6(m6(D,U)),$=u6(m6(F,U)),V=d6(p6(_,z),p6(_,$)),Q={...k,x:c6(k.x-V[0]*Math.sign(I.scale[0]),0,L.naturalWidth-k.width),y:c6(k.y-V[1]*Math.sign(I.scale[1]),0,L.naturalHeight-k.height)};this.scene.mutateElement(I,{crop:Q});return}}}this.maybeCacheVisibleGaps(n,d),this.maybeCacheReferenceSnapPoints(n,d);let{snapOffset:y,snapLines:v}=Z5(w,E,this,n,this.scene.getNonDeletedElementsMap());if(this.setState({snapLines:v}),this.state.editingFrame||Dq(o,d,E,this.scene,y,n[oe.CTRL_OR_CMD]?null:this.getEffectiveGridSize()),this.setState({selectedElementsAreBeingDragged:!0,selectionElement:null}),n.altKey&&!o.hit.hasBeenDuplicated){o.hit.hasBeenDuplicated=!0;let I=this.scene.getElementsIncludingDeleted(),k=o.hit.element,L=this.scene.getSelectedElements({selectedElementIds:this.state.selectedElementIds,includeBoundTextElement:!0,includeElementsInFrames:!0});k&&o.hit.wasAddedToSelection&&!L.find(U=>U.id===k.id)&&L.push(k);let S=new Map(L.map(U=>[U.id,U])),{duplicatedElements:_,duplicateElementsMap:P,elementsWithDuplicates:T,origIdToDuplicateId:M}=Px({type:"in-place",elements:I,appState:this.state,randomizeSeed:!0,idsOfElementsToDuplicate:S,overrides:({duplicateElement:U,origElement:D})=>({frameId:U.frameId??D.frameId,seed:Cj()})});_.forEach(U=>{o.originalElements.set(U.id,D6(U))});let N=T.map(U=>{if(S.has(U.id)){let D=o.originalElements.get(U.id);if(D)return Si(U,{x:D.x,y:D.y})}return U}),O=this.props.onDuplicate?.(N,I),B=X6(O||N,kg(_));wo(()=>{if(o.hit.element){let U=M.get(o.hit.element.id),D=U&&P.get(U);o.hit.element=D||null}o.hit.allHitElements=o.hit.allHitElements.reduce((U,D)=>{let F=M.get(D.id),z=F&&P.get(F);return z&&U.push(z),U},[]),o.drag.origin=ot(n,this.state),this.setState(U=>({...Pq(_,this.scene.getNonDeletedElements(),U)})),this.scene.replaceAllElements(B),L.forEach(U=>{Dx(U)&&U.boundElements?.some(D=>D.type==="arrow")&&Pg(U,this.scene)}),this.maybeCacheVisibleGaps(n,L,!0),this.maybeCacheReferenceSnapPoints(n,L,!0)})}return}}if(this.state.selectionElement){if(o.lastCoords.x=r.x,o.lastCoords.y=r.y,n.altKey){this.setActiveTool({type:"lasso",fromSelection:!0},n.shiftKey),this.lassoTrail.startPath(o.origin.x,o.origin.y,n.shiftKey),this.setAppState({selectionElement:null});return}this.maybeDragNewGenericElement(o,n)}else if(this.state.activeTool.type==="lasso")!n.altKey&&this.state.activeTool.fromSelection?(this.setActiveTool({type:"selection"}),this.createGenericElementOnPointerDown("selection",o),o.lastCoords.x=r.x,o.lastCoords.y=r.y,this.maybeDragNewGenericElement(o,n),this.lassoTrail.endPath()):this.lassoTrail.addPointToPath(r.x,r.y,n.shiftKey);else{let d=this.state.newElement;if(!d)return;if(d.type==="freedraw"){let u=d.points,h=r.x-d.x,g=r.y-d.y,E=u.length>0&&u[u.length-1];if(!(E&&E[0]===h&&E[1]===g)){let x=d.simulatePressure?d.pressures:[...d.pressures,n.pressure];this.scene.mutateElement(d,{points:[...u,de(h,g)],pressures:x},{informMutation:!1,isDragging:!1}),this.setState({newElement:d})}}else if(so(d)&&!d.isDeleted){o.drag.hasOccurred=!0;let u=d.points;tr(u.length>1,"Do not create linear elements with less than 2 points");let h=this.state.selectedLinearElement;h||(h=new Me(d,this.scene.getNonDeletedElementsMap()),h={...h,selectedPointsIndices:[1],initialState:{...h.initialState,lastClickedPoint:1}}),this.setState({newElement:d,...Me.handlePointDragging(n,this,s,l,h)})}else o.lastCoords.x=r.x,o.lastCoords.y=r.y,this.maybeDragNewGenericElement(o,n,!1)}if(this.state.activeTool.type==="selection"){o.boxSelection.hasOccurred=!0;let d=this.scene.getNonDeletedElements();if(this.state.selectedLinearElement?.isEditing)Me.handleBoxSelection(n,this.state,this.setState.bind(this),this.scene.getNonDeletedElementsMap());else{let u=!0;!n.shiftKey&&He(d,this.state)&&(o.withCmdOrCtrl&&o.hit.element?this.setState(g=>nn({...g,selectedElementIds:{[o.hit.element.id]:!0}},this.scene.getNonDeletedElements(),g,this)):u=!1);let h=this.state.selectionElement?zE(d,this.state.selectionElement,this.scene.getNonDeletedElementsMap(),!1):[];this.setState(g=>{let E={...u&&g.selectedElementIds,...h.reduce((w,x)=>(w[x.id]=!0,w),{})};return o.hit.element&&(h.length?delete E[o.hit.element.id]:E[o.hit.element.id]=!0),g=u?g:{...g,selectedGroupIds:{},editingGroupId:null},{...nn({editingGroupId:g.editingGroupId,selectedElementIds:E},this.scene.getNonDeletedElements(),g,this),selectedLinearElement:h.length===1&&so(h[0])?new Me(h[0],this.scene.getNonDeletedElementsMap()):null,showHyperlinkPopup:h.length===1&&(h[0].link||Lr(h[0]))?"info":!1}})}}})}handlePointerMoveOverScrollbars(o,n){if(n.scrollbars.isOverHorizontal){let r=o.clientX,i=r-n.lastCoords.x;return this.translateCanvas({scrollX:this.state.scrollX-i*(Nd.horizontal?.deltaMultiplier||1)/this.state.zoom.value}),n.lastCoords.x=r,!0}if(n.scrollbars.isOverVertical){let r=o.clientY,i=r-n.lastCoords.y;return this.translateCanvas({scrollY:this.state.scrollY-i*(Nd.vertical?.deltaMultiplier||1)/this.state.zoom.value}),n.lastCoords.y=r,!0}return!1}onPointerUpFromPointerDownHandler(o){return mt(n=>{let r=this.scene.getNonDeletedElementsMap();this.removePointer(n),o.drag.blockDragging=!1,o.eventListeners.onMove&&o.eventListeners.onMove.flush();let{newElement:i,resizingElement:a,croppingElementId:s,multiElement:l,activeTool:c,isResizing:m,isRotating:p,isCropping:d}=this.state;this.setState(x=>({isResizing:!1,isRotating:!1,isCropping:!1,resizingElement:null,selectionElement:null,frameToHighlight:null,elementsToHighlight:null,cursorButton:"up",snapLines:Sd(x.snapLines,[]),originSnapOffset:null})),this.lassoTrail.endPath(),this.previousPointerMoveCoords=null,$o.setReferenceSnapPoints(null),$o.setVisibleGaps(null),this.savePointer(n.clientX,n.clientY,"up");let u=o.hit.allHitElements,h=ot({clientX:n.clientX,clientY:n.clientY},this.state);if(this.state.activeTool.type==="selection"&&!o.boxSelection.hasOccurred&&!o.resize.isResizing&&!u.some(x=>this.state.selectedElementIds[x.id])){let x=this.getElementAtPosition(h.x,h.y,{includeLockedElements:!0});this.store.scheduleCapture(),x?.locked?this.setState({activeLockedId:x.groupIds.length>0?x.groupIds.at(-1)||"":x.id}):this.setState({activeLockedId:null})}else this.setState({activeLockedId:null});if(Ar("COMPLEX_BINDINGS")&&this.resetDelayedBindMode(),this.setState({selectedElementsAreBeingDragged:!1,bindMode:"orbit"}),o.drag.hasOccurred&&o.hit?.element?.id){let x=r.get(o.hit.element.id);Dx(x)&&x.boundElements?.filter(y=>y.type==="arrow").map(y=>r.get(y.id)).filter(y=>vo(y)).forEach(y=>{y&&this.scene.mutateElement(y,{})})}if(this.state.selectedLinearElement?.isEditing&&!this.state.newElement&&this.state.selectedLinearElement.draggedFocusPointBinding===null)if(!o.boxSelection.hasOccurred&&o.hit?.element?.id!==this.state.selectedLinearElement.elementId&&this.state.selectedLinearElement.draggedFocusPointBinding===null)this.actionManager.executeAction(oo);else{let x=Me.handlePointerUp(n,this.state.selectedLinearElement,this.state,this.scene);this.actionManager.executeAction(oo,"ui",{event:n,sceneCoords:h}),x!==this.state.selectedLinearElement&&this.setState({selectedLinearElement:x,suggestedBinding:null})}else if(this.state.selectedLinearElement){if(this.state.selectedLinearElement.elbowed){let x=Me.getElement(this.state.selectedLinearElement.elementId,this.scene.getNonDeletedElementsMap());x&&this.scene.mutateElement(x,{})}if(this.state.selectedLinearElement.draggedFocusPointBinding?(Wq(this.state.selectedLinearElement,this.scene),this.setState({selectedLinearElement:{...this.state.selectedLinearElement,draggedFocusPointBinding:null}})):o.hit?.element?.id!==this.state.selectedLinearElement.elementId?this.scene.getSelectedElements(this.state).length>1&&this.setState({selectedLinearElement:null}):this.state.selectedLinearElement.isDragging&&(this.setState({selectedLinearElement:{...this.state.selectedLinearElement,isDragging:!1}}),this.actionManager.executeAction(oo,"ui",{event:n,sceneCoords:h})),this.state.newElement&&this.state.multiElement&&so(this.state.newElement)&&this.state.selectedLinearElement){let{multiElement:x}=this.state;this.setState({selectedLinearElement:{...this.state.selectedLinearElement,lastCommittedPoint:x.points[x.points.length-1]}})}}if(this.missingPointerEventCleanupEmitter.clear(),window.removeEventListener(ue.POINTER_MOVE,o.eventListeners.onMove),window.removeEventListener(ue.POINTER_UP,o.eventListeners.onUp),window.removeEventListener(ue.KEYDOWN,o.eventListeners.onKeyDown),window.removeEventListener(ue.KEYUP,o.eventListeners.onKeyUp),this.props?.onPointerUp?.(c,o),this.onPointerUpEmitter.trigger(this.state.activeTool,o,n),i?.type==="freedraw"){let x=ot(n,this.state),y=i.points,v=x.x-i.x,I=x.y-i.y;v===y[0][0]&&I===y[0][1]&&(I+=1e-4,v+=1e-4);let k=i.simulatePressure?[]:[...i.pressures,n.pressure];this.scene.mutateElement(i,{points:[...y,de(v,I)],pressures:k}),this.actionManager.executeAction(oo);return}if(so(i)){i.points.length>1&&i.points[1][0]!==0&&i.points[1][1]!==0&&this.store.scheduleCapture();let x=ot(n,this.state),y=Ti(de(x.x,x.y),de(o.origin.x,o.origin.y))*this.state.zoom.value;if((!o.drag.hasOccurred||y<kj)&&i&&!l)if(this.editorInterface.isTouchScreen){let v=Math.min(this.state.width*.7/this.state.zoom.value,100);this.scene.mutateElement(i,{x:i.x-v/2,points:[de(0,0),de(v,0)]},{informMutation:!1,isDragging:!1}),this.actionManager.executeAction(oo)}else{let v=x.x-i.x,I=x.y-i.y;this.scene.mutateElement(i,{points:[i.points[0],de(v,I)]},{informMutation:!1,isDragging:!1}),this.setState({multiElement:i,newElement:i})}else o.drag.hasOccurred&&!l&&(so(i)&&this.actionManager.executeAction(oo,"ui",{event:n,sceneCoords:h}),this.setState({suggestedBinding:null,startBoundElement:null}),c.locked?this.setState(v=>({newElement:null})):(ko(this.interactiveCanvas),this.setState(v=>({newElement:null,activeTool:er(this.state,{type:this.state.preferredSelectionTool.type}),selectedElementIds:Oe({...v.selectedElementIds,[i.id]:!0},v),selectedLinearElement:new Me(i,this.scene.getNonDeletedElementsMap())}))),this.scene.triggerUpdate());return}if(vn(i)){let x=vq(Tx({fontSize:i.fontSize,fontFamily:i.fontFamily}),i.lineHeight);i.width<x&&this.scene.mutateElement(i,{autoResize:!0}),this.resetCursor(),this.handleTextWysiwyg(i,{isExistingElement:!0})}if(c.type!=="selection"&&i&&F6(i)){this.updateScene({elements:this.scene.getElementsIncludingDeleted().filter(x=>x.id!==i.id),appState:{newElement:null},captureUpdate:lo.NEVER});return}if(jt(i)){let x=rq(this.scene.getElementsIncludingDeleted(),i,this.scene.getNonDeletedElementsMap());this.scene.replaceAllElements(zx(this.scene.getElementsMapIncludingDeleted(),x,i,this.state))}if(i&&(this.scene.mutateElement(i,Xj(i),{informMutation:!1,isDragging:!1}),this.scene.triggerUpdate()),o.drag.hasOccurred){let x=ot(n,this.state);if(this.state.selectedLinearElement&&this.state.selectedLinearElement.isDragging){let y=this.scene.getElement(this.state.selectedLinearElement.elementId);if(y?.frameId){let v=Gx(y,r);v&&y&&(iq(y,v,this.scene.getNonDeletedElementsMap())||(this.scene.mutateElement(y,{groupIds:[]}),nq([y],this.scene.getNonDeletedElementsMap()),this.scene.triggerUpdate()))}}else{let y=this.getTopLayerFrameAtSceneCoords(x),v=this.scene.getSelectedElements(this.state),I=this.scene.getElementsMapIncludingDeleted(),k=L=>{if(L.length>0){for(let S of L){let _=S.groupIds.indexOf(this.state.editingGroupId);this.scene.mutateElement(S,{groupIds:S.groupIds.slice(0,_)},{informMutation:!1,isDragging:!1})}I.forEach(S=>{S.groupIds.length&&Ca(I,S.groupIds[S.groupIds.length-1]).length<2&&this.scene.mutateElement(S,{groupIds:[]},{informMutation:!1,isDragging:!1})}),this.setState({editingGroupId:null})}};if(y&&!this.state.selectedElementIds[y.id]){let L=v.filter(S=>S.frameId!==y.id&&Y6(S,I,this.state));this.state.editingGroupId&&k(L),I=zx(I,L,y,this.state)}else if(!y&&this.state.editingGroupId){let L=v.filter(S=>S.frameId&&!Y6(S,I,this.state));k(L)}I=W6(I,this.state,this),this.scene.replaceAllElements(I)}}if(a&&this.store.scheduleCapture(),a&&F6(a)&&this.updateScene({elements:this.scene.getElementsIncludingDeleted().filter(x=>x.id!==a.id),captureUpdate:lo.NEVER}),o.resize.isResizing){let x=W6(this.scene.getElementsIncludingDeleted(),this.state,this),y=this.scene.getSelectedElements(this.state).filter(v=>jt(v));for(let v of y)x=oq(x,Hx(this.scene.getElementsIncludingDeleted(),v,this.state,r),v,this);this.scene.replaceAllElements(x)}let g=o.hit.element;this.state.selectedLinearElement?.elementId!==g?.id&&so(g)&&this.scene.getSelectedElements(this.state).length===1&&this.setState({selectedLinearElement:new Me(g,this.scene.getNonDeletedElementsMap())}),(!s||s&&(!g&&!d||g&&g.id!==s))&&this.finishImageCropping();let E=this.lastPointerDownEvent,w=this.lastPointerUpEvent||this.lastPointerMoveEvent;if(po(this.state)&&E&&w){if(this.eraserTrail.endPath(),Ti(de(E.clientX,E.clientY),de(w.clientX,w.clientY))===0){let y=ot({clientX:w.clientX,clientY:w.clientY},this.state);this.getElementsAtPosition(y.x,y.y).forEach(I=>this.elementsPendingErasure.add(I.id))}this.eraseElements();return}else this.elementsPendingErasure.size&&this.restoreReadyToEraseElements();if(g&&!o.drag.hasOccurred&&!o.hit.wasAddedToSelection&&(!this.state.selectedLinearElement?.isEditing||!o.boxSelection.hasOccurred)&&this.state.activeTool.type!=="lasso"&&(n.shiftKey&&!this.state.selectedLinearElement?.isEditing?this.state.selectedElementIds[g.id]?Sq(this.state,g)?this.setState(x=>{let y={...x.selectedElementIds};for(let v of g.groupIds.flatMap(I=>Ca(this.scene.getNonDeletedElements(),I)))delete y[v.id];return{selectedGroupIds:{...x.selectedElementIds,...g.groupIds.map(v=>({[v]:!1})).reduce((v,I)=>({...v,...I}),{})},selectedElementIds:Oe(y,x)}}):this.state.selectedLinearElement?.isDragging||this.setState(x=>{let y={...x.selectedElementIds};delete y[g.id];let v=le(this.scene.getNonDeletedElements(),{selectedElementIds:y});return{...nn({editingGroupId:x.editingGroupId,selectedElementIds:y},this.scene.getNonDeletedElements(),x,this),selectedLinearElement:v.length===1&&so(v[0])?new Me(v[0],this.scene.getNonDeletedElementsMap()):x.selectedLinearElement}}):g.frameId&&this.state.selectedElementIds[g.frameId]?this.setState(x=>{let y={...x.selectedElementIds,[g.id]:!0};return delete y[g.frameId],(this.scene.getElement(g.frameId)?.groupIds??[]).flatMap(v=>Ca(this.scene.getNonDeletedElements(),v)).forEach(v=>{delete y[v.id]}),{...nn({editingGroupId:x.editingGroupId,selectedElementIds:y},this.scene.getNonDeletedElements(),x,this),showHyperlinkPopup:g.link||Lr(g)?"info":!1}}):this.setState(x=>({selectedElementIds:Oe({...x.selectedElementIds,[g.id]:!0},x)})):this.setState(x=>({...nn({editingGroupId:x.editingGroupId,selectedElementIds:{[g.id]:!0}},this.scene.getNonDeletedElements(),x,this),selectedLinearElement:so(g)&&x.selectedLinearElement?.elementId!==g.id?new Me(g,this.scene.getNonDeletedElementsMap()):x.selectedLinearElement}))),this.state.activeTool.type!=="lasso"&&!(g&&vo(g))&&!o.drag.hasOccurred&&!this.state.isResizing&&(g&&dq({point:de(o.origin.x,o.origin.y),element:g,elementsMap:r,threshold:this.getElementHitThreshold(g),frameNameBound:jt(g)?this.frameNameBoundsCache.get(g):null},r)||!g&&o.hit.hasHitCommonBoundingBoxOfSelectedElements)){this.state.selectedLinearElement?.isEditing?this.actionManager.executeAction(Qs):this.setState({selectedElementIds:Oe({},this.state),selectedGroupIds:{},editingGroupId:null,activeEmbeddable:null}),Ne(this.interactiveCanvas,st.AUTO);return}if(!c.locked&&c.type!=="freedraw"&&i&&this.setState(x=>({selectedElementIds:Oe({...x.selectedElementIds,[i.id]:!0},x),showHyperlinkPopup:Lr(i)&&!i.link?"editor":x.showHyperlinkPopup})),(c.type!=="selection"||He(this.scene.getNonDeletedElements(),this.state)||!k6(this.state.previousSelectedElementIds,this.state.selectedElementIds))&&this.store.scheduleCapture(),o.drag.hasOccurred&&!this.state.selectedLinearElement||m||p||d){let x=this.scene.getSelectedElements(this.state).filter(Al);M6(x,this.scene,this.state)}if(c.type==="laser"){this.laserTrails.endPath();return}!c.locked&&c.type!=="freedraw"&&(c.type!=="lasso"||c.type==="lasso"&&c.fromSelection)?(ko(this.interactiveCanvas),this.setState({newElement:null,suggestedBinding:null,activeTool:er(this.state,{type:this.state.preferredSelectionTool.type})})):this.setState({newElement:null,suggestedBinding:null})})}clearSelection(o){this.setState(n=>({selectedElementIds:Oe({},n),activeEmbeddable:null,selectedGroupIds:{},editingGroupId:n.editingGroupId&&o!=null&&K6(o,n.editingGroupId)?n.editingGroupId:null})),this.setState({selectedElementIds:Oe({},this.state),activeEmbeddable:null,previousSelectedElementIds:this.state.selectedElementIds,selectedLinearElement:null})}getTextWysiwygSnappedToCenterPosition(o,n,r,i){if(i){let a=i.x+i.width/2,s=i.y+i.height/2,l=Fx(i,r,this.scene.getNonDeletedElementsMap());if(l&&(a=l.x,s=l.y),Math.hypot(o-a,n-s)<sj){let{x:p,y:d}=Cg({sceneX:a,sceneY:s},r);return{viewportX:p,viewportY:d,elementCenterX:a,elementCenterY:s}}}}getCanvasOffsets(){if(this.excalidrawContainerRef?.current){let o=this.excalidrawContainerRef.current,{left:n,top:r}=o.getBoundingClientRect();return{offsetLeft:n,offsetTop:r}}return{offsetLeft:0,offsetTop:0}}async updateLanguage(){let o=Ua.find(n=>n.code===this.props.langCode)||An;await rm(o),this.setAppState({})}},Vq=()=>{(cP()||dP())&&(window.h=window.h||{},Object.defineProperties(window.h,{elements:{configurable:!0,get(){return this.app?.scene.getElementsIncludingDeleted()},set(e){return this.app?.scene.replaceAllElements(pP(e))}},scene:{configurable:!0,get(){return this.app?.scene}}}))};Vq();var hP=Jx;import{useEffect as $q,useState as Kq}from"react";import{jsx as Xq}from"react/jsx-runtime";var fP=e=>{let[t,o]=Kq(!0);return $q(()=>{let n=async()=>{await rm(r),o(!1)},r=Ua.find(i=>i.code===e.langCode)||An;n()},[e.langCode]),t?Xq(_u,{theme:e.theme}):e.children};import Zq from"clsx";import{jsx as bP}from"react/jsx-runtime";var xP=({children:e})=>{let{FooterCenterTunnel:t}=Xe(),o=ye();return bP(t.In,{children:bP("div",{className:Zq("footer-center zen-mode-transition",{"layer-ui__wrapper__footer-left--transition-bottom":o.zenModeEnabled}),children:e})})},jq=xP;xP.displayName="FooterCenter";import qq from"clsx";import{MQ_MIN_WIDTH_DESKTOP as Jq}from"@orangecatai/common";import{jsx as eJ,jsxs as tJ}from"react/jsx-runtime";var EP=({isCollaborating:e,onSelect:t,editorInterface:o,...n})=>{let r=ye(),i=o?.formFactor!=="desktop"||r.width<Jq;return tJ(io,{...n,className:qq("collab-button",{active:e}),type:"button",onSelect:t,style:{position:"relative",width:i?void 0:"auto"},title:f("labels.liveCollaboration"),children:[i?Ay:f("labels.share"),r.collaborators.size>0&&eJ("div",{className:"CollabButton-collaborators",children:r.collaborators.size})]})},Qq=EP;EP.displayName="LiveCollaborationTrigger";import{jsx as _i,jsxs as wP}from"react/jsx-runtime";var oJ=()=>_i("svg",{viewBox:"0 0 40 40",fill:"none",xmlns:"http://www.w3.org/2000/svg",className:"ExcalidrawLogo-icon",children:_i("path",{d:"M39.9 32.889a.326.326 0 0 0-.279-.056c-2.094-3.083-4.774-6-7.343-8.833l-.419-.472a.212.212 0 0 0-.056-.139.586.586 0 0 0-.167-.111l-.084-.083-.056-.056c-.084-.167-.28-.278-.475-.167-.782.39-1.507.973-2.206 1.528-.92.722-1.842 1.445-2.708 2.25a8.405 8.405 0 0 0-.977 1.028c-.14.194-.028.361.14.444-.615.611-1.23 1.223-1.843 1.861a.315.315 0 0 0-.084.223c0 .083.056.166.111.194l1.09.833v.028c1.535 1.528 4.244 3.611 7.12 5.861.418.334.865.667 1.284 1 .195.223.39.473.558.695.084.11.28.139.391.055.056.056.14.111.196.167a.398.398 0 0 0 .167.056.255.255 0 0 0 .224-.111.394.394 0 0 0 .055-.167c.029 0 .028.028.056.028a.318.318 0 0 0 .224-.084l5.082-5.528a.309.309 0 0 0 0-.444Zm-14.63-1.917a.485.485 0 0 0 .111.14c.586.5 1.2 1 1.843 1.555l-2.569-1.945-.251-.166c-.056-.028-.112-.084-.168-.111l-.195-.167.056-.056.055-.055.112-.111c.866-.861 2.346-2.306 3.1-3.028-.81.805-2.43 3.167-2.095 3.944Zm8.767 6.89-2.122-1.612a44.713 44.713 0 0 0-2.625-2.5c1.145.861 2.122 1.611 2.262 1.75 1.117.972 1.06.806 1.815 1.445l.921.666a1.06 1.06 0 0 1-.251.25Zm.558.416-.056-.028c.084-.055.168-.111.252-.194l-.196.222ZM1.089 5.75c.055.361.14.722.195 1.056.335 1.833.67 3.5 1.284 4.75l.252.944c.084.361.223.806.363.917 1.424 1.25 3.602 3.11 5.947 4.889a.295.295 0 0 0 .363 0s0 .027.028.027a.254.254 0 0 0 .196.084.318.318 0 0 0 .223-.084c2.988-3.305 5.221-6.027 6.813-8.305.112-.111.14-.278.14-.417.111-.111.195-.25.307-.333.111-.111.111-.306 0-.39l-.028-.027c0-.055-.028-.139-.084-.167-.698-.666-1.2-1.138-1.731-1.638-.922-.862-1.871-1.75-3.881-3.75l-.028-.028c-.028-.028-.056-.056-.112-.056-.558-.194-1.703-.389-3.127-.639C6.087 2.223 3.21 1.723.614.944c0 0-.168 0-.196.028l-.083.084c-.028.027-.056.055-.224.11h.056-.056c.028.167.028.278.084.473 0 .055.112.5.112.555l.782 3.556Zm15.496 3.278-.335-.334c.084.112.196.195.335.334Zm-3.546 4.666-.056.056c0-.028.028-.056.056-.056Zm-2.038-10c.168.167.866.834 1.033.973-.726-.334-2.54-1.167-3.379-1.445.838.167 1.983.334 2.346.472ZM1.424 2.306c.419.722.754 3.222 1.089 5.666-.196-.778-.335-1.555-.503-2.278-.251-1.277-.503-2.416-.838-3.416.056 0 .14 0 .252.028Zm-.168-.584c-.112 0-.223-.028-.307-.028 0-.027 0-.055-.028-.055.14 0 .223.028.335.083Zm-1.089.222c0-.027 0-.027 0 0ZM39.453 1.333c.028-.11-.558-.61-.363-.639.42-.027.42-.666 0-.666-.558.028-1.144.166-1.675.25-.977.194-1.982.389-2.96.61-2.205.473-4.383.973-6.561 1.557-.67.194-1.424.333-2.066.666-.224.111-.196.333-.084.472-.056.028-.084.028-.14.056-.195.028-.363.056-.558.083-.168.028-.252.167-.224.334 0 .027.028.083.028.11-1.173 1.556-2.485 3.195-3.909 4.945-1.396 1.611-2.876 3.306-4.356 5.056-4.719 5.5-10.052 11.75-15.943 17.25a.268.268 0 0 0 0 .389c.028.027.056.055.084.055-.084.084-.168.14-.252.222-.056.056-.084.111-.084.167a.605.605 0 0 0-.111.139c-.112.111-.112.305.028.389.111.11.307.11.39-.028.029-.028.029-.056.056-.056a.44.44 0 0 1 .615 0c.335.362.67.723.977 1.028l-.698-.583c-.112-.111-.307-.083-.39.028-.113.11-.085.305.027.389l7.427 6.194c.056.056.112.056.196.056s.14-.028.195-.084l.168-.166c.028.027.083.027.111.027.084 0 .14-.027.196-.083 10.052-10.055 18.15-17.639 27.42-24.417.083-.055.111-.166.111-.25.112 0 .196-.083.251-.194 1.704-5.194 2.039-9.806 2.15-12.083v-.028c0-.028.028-.056.028-.083.028-.056.028-.084.028-.084a1.626 1.626 0 0 0-.111-1.028ZM21.472 9.5c.446-.5.893-1.028 1.34-1.5-2.876 3.778-7.65 9.583-14.408 16.5 4.607-5.083 9.242-10.333 13.068-15ZM5.193 35.778h.084-.084Zm3.462 3.194c-.027-.028-.027-.028 0-.028v.028Zm4.16-3.583c.224-.25.448-.472.699-.722 0 0 0 .027.028.027-.252.223-.475.445-.726.695Zm1.146-1.111c.14-.14.279-.334.446-.5l.028-.028c1.648-1.694 3.351-3.389 5.082-5.111l.028-.028c.419-.333.921-.694 1.368-1.028a379.003 379.003 0 0 0-6.952 6.695ZM24.794 6.472c-.921 1.195-1.954 2.778-2.82 4.028-2.736 3.944-11.532 13.583-11.727 13.75a1976.983 1976.983 0 0 1-8.042 7.639l-.167.167c-.14-.167-.14-.417.028-.556C14.49 19.861 22.03 10.167 25.074 5.917c-.084.194-.14.36-.28.555Zm4.83 5.695c-1.116-.64-1.646-1.64-1.34-2.611l.084-.334c.028-.083.084-.194.14-.277.307-.5.754-.917 1.257-1.167.027 0 .055 0 .083-.028-.028-.056-.028-.139-.028-.222.028-.167.14-.278.335-.278.335 0 1.369.306 1.76.639.111.083.223.194.335.305.14.167.363.445.474.667.056.028.112.306.196.445.056.222.111.472.084.694-.028.028 0 .194-.028.194a2.668 2.668 0 0 1-.363 1.028c-.028.028-.028.056-.056.084l-.028.027c-.14.223-.335.417-.53.556-.643.444-1.369.583-2.095.389 0 0-.195-.084-.28-.111Zm8.154-.834a39.098 39.098 0 0 1-.893 3.167c0 .028-.028.083 0 .111-.056 0-.084.028-.14.056-2.206 1.61-4.356 3.305-6.506 5.028 1.843-1.64 3.686-3.306 5.613-4.945.558-.5.949-1.139 1.06-1.861l.28-1.667v-.055c.14-.334.67-.195.586.166Z",fill:"currentColor"})}),nJ=()=>wP("svg",{viewBox:"0 0 450 55",xmlns:"http://www.w3.org/2000/svg",fill:"none",className:"ExcalidrawLogo-text",children:[_i("path",{d:"M429.27 96.74c2.47-1.39 4.78-3.02 6.83-4.95 1.43-1.35 2.73-2.86 3.81-4.51-.66.9-1.4 1.77-2.23 2.59-2.91 2.84-5.72 5.09-8.42 6.87h.01ZM343.6 69.36c.33 3.13.58 6.27.79 9.4.09 1.37.18 2.75.25 4.12-.12-4.46-.27-8.93-.5-13.39-.11-2.08-.24-4.16-.4-6.24-.06 1.79-.11 3.85-.13 6.11h-.01ZM378.47 98.34c.01-.37.07-1.13.01-6.51-.11 1.9-.22 3.81-.31 5.71-.07 1.42-.22 2.91-.16 4.35.39.03.78.07 1.17.1-.92-.85-.76-2.01-.72-3.66l.01.01ZM344.09 86.12c-.09-2.41-.22-4.83-.39-7.24v12.21c.15-.05.32-.09.47-.14.05-1.61-.03-3.23-.09-4.83h.01ZM440.69 66.79c-.22-.34-.45-.67-.69-.99-3.71-4.87-9.91-7.14-15.65-8.55-1.05-.26-2.12-.49-3.18-.71 2.29.59 4.48 1.26 6.64 2.02 7.19 2.54 10.57 5.41 12.88 8.23ZM305.09 72.46l1.2 3.6c.84 2.53 1.67 5.06 2.46 7.61.24.78.5 1.57.73 2.36.22-.04.44-.08.67-.12a776.9 776.9 0 0 1-5.01-13.57c-.02.04-.03.09-.05.13v-.01ZM345.49 90.25v.31c1.48-.42 3.05-.83 4.66-1.2-1.56.25-3.12.52-4.66.89ZM371.02 90.22c0-.57-.04-1.14-.11-1.71-.06-.02-.12-.04-.19-.05-.21-.05-.43-.08-.65-.11.42.16.74.88.95 1.87ZM398.93 54.23c-.13 0-.27-.01-.4-.02l.03.4c.11-.15.23-.27.37-.38ZM401.57 62.28v-.15c-1.22-.24-2.86-.61-3.23-1.25-.09-.15-.18-.51-.27-.98-.09.37-.2.73-.33 1.09 1.24.56 2.52.98 3.83 1.29ZM421.73 88.68c-2.97 1.65-6.28 3.12-9.69 3.68v.18c4.72-.14 11.63-3.85 16.33-8.38-2.04 1.75-4.33 3.24-6.63 4.53l-.01-.01ZM411.28 80.92c-.05-1.2-.09-2.4-.15-3.6-.21 5.66-.46 11.38-.47 14.51.24-.02.48-.04.71-.07.15-3.61.05-7.23-.09-10.83v-.01Z",transform:"translate(-144.023 -51.76)"}),_i("path",{d:"M425.38 67.41c-3.5-1.45-7.19-2.57-14.06-3.62.09 1.97.06 4.88-.03 8.12.03.04.06.09.06.15.19 1.36.28 2.73.37 4.1.25 3.77.39 7.55.41 11.33 0 1.38-.01 2.76-.07 4.13 1.4-.25 2.78-.65 4.12-1.15 4.07-1.5 7.94-3.78 11.28-6.54 2.33-1.92 5.13-4.49 5.88-7.58.63-3.53-2.45-6.68-7.97-8.96l.01.02ZM411.35 92.53v-.06l-.34.03c.11.01.22.03.34.03ZM314.26 64.06c-.23-.59-.47-1.17-.7-1.75.57 1.62 1.11 3.25 1.6 4.9l.15.54 2.35 6.05c.32.82.66 1.64.98 2.46-1.38-4.1-2.83-8.17-4.39-12.2h.01ZM156.82 103.07c-.18.13-.38.23-.58.33 1.32-.03 2.66-.2 3.93-.34.86-.09 1.72-.22 2.58-.33-2.12.1-4.12.17-5.94.34h.01ZM210.14 68.88s.03.04.05.07c.18-.31.39-.64.58-.96-.21.3-.42.6-.64.89h.01ZM201.65 82.8c-.5.77-1.02 1.56-1.49 2.37 1.11-1.55 2.21-3.1 3.2-4.59-.23.23-.49.51-.75.79-.32.47-.65.95-.96 1.43ZM194.03 98.66c-.33-.4-.65-.84-1.05-1.17-.24-.2-.07-.49.17-.56-.23-.26-.42-.5-.63-.75 1.51-2.55 3.93-5.87 6.4-9.28-.17-.08-.29-.28-.2-.49.04-.09.09-.17.13-.26-1.21 1.78-2.42 3.55-3.61 5.33-.87 1.31-1.74 2.64-2.54 4-.29.5-.63 1.04-.87 1.61.81.65 1.63 1.27 2.47 1.88-.09-.11-.18-.21-.27-.32v.01ZM307.79 82.93c-1-3.17-2.05-6.32-3.1-9.48-1.62 4.08-3.69 9.17-6.16 15.19 3.32-1.04 6.77-1.87 10.27-2.5-.32-1.08-.67-2.15-1.01-3.21ZM149.5 80.7c.05-1.71.04-3.43 0-5.14-.1 2.26-.16 4.51-.22 6.77-.02.73-.03 1.46-.04 2.19.14-1.27.2-2.55.24-3.82h.02ZM228.98 98.3c.39 1.25.91 3.03.94 3.91.06-.03.12-.07.17-.1.08-1.29-.55-2.65-1.11-3.81ZM307.72 53.36c.81.5 1.53 1.04 2.07 1.49-.38-.8-.78-1.58-1.21-2.35-.17.03-.34.06-.51.11-.43.12-.86.26-1.29.41.35-.01.53.1.94.34ZM283.69 96.14c3.91-7.25 6.89-13.35 8.88-18.15l1.1-2.66c-1.27 2.64-2.56 5.27-3.83 7.9-1.53 3.15-3.06 6.31-4.58 9.47-.87 1.81-1.76 3.62-2.54 5.47.04.02.07.04.11.07.05.05.1.09.15.14.05-.73.27-1.48.71-2.24ZM289.92 103.23s-.04.01-.05.03c0-.02.04-.03.05-.04.05-.05.11-.1.16-.15l.21-.21c-.55 0-1.5-.27-2.55-.72.4.26.8.51 1.22.74.24.13.48.26.73.37.05.02.1.03.14.05a.27.27 0 0 1 .08-.07h.01ZM269.23 68.49c-.39-.19-.82-.48-1.33-.87-3.06-1.56-6.31-2.78-9.36-2.35-3.5.49-5.7 1.11-7.74 2.44 5.71-2.6 12.82-2.07 18.44.79l-.01-.01ZM177.87 53.69l1.06.03c-.96-.22-2-.25-2.89-.3-4.95-.26-9.99.33-14.86 1.19-2.44.43-4.88.95-7.28 1.59 9.09-1.76 15.69-2.77 23.97-2.51ZM219.85 55.51c-.18.12-.36.27-.56.45-.45.53-.86 1.11-1.26 1.66-1.91 2.61-3.71 5.31-5.57 7.95l-.12.18 8.05-10.11c-.18-.05-.36-.1-.55-.13h.01ZM510.71 54.1c.12-.15.29-.3.53-.45.69-.4 3.72-.63 5.87-.74-.36-.02-.73-.04-1.09-.05-1.84-.03-3.67.09-5.49.35.05.3.12.59.18.88v.01ZM510.76 86.02c1.37-3.07 2.49-6.27 3.57-9.46.55-1.64 1.12-3.3 1.6-4.97-1.59 4.01-3.67 9.14-6.2 15.3.24-.08.5-.14.74-.22.1-.22.19-.44.29-.65ZM566.95 75.76c.11-.02.23.03.31.11-.05-.13-.09-.26-.14-.39-.05.09-.11.18-.17.28ZM511.33 86.41c3.08-.89 6.24-1.62 9.46-2.14-1.51-3.98-2.98-7.96-4.39-11.87-.05.15-.09.31-.14.46-1.02 3.32-2.15 6.61-3.39 9.85-.48 1.25-.98 2.49-1.53 3.7h-.01ZM578.24 74.45c.11-.44.23-.87.35-1.31-.31.7-.64 1.39-.97 2.08.09.21.19.4.28.61.12-.46.23-.92.35-1.38h-.01ZM520.62 53.11c-.09 0-.18-.01-.28-.02.38.34.29 1.08.93 2.53l6.65 17.15c2.2 5.68 4.69 11.36 7.41 16.87l1.06 2.17c-2.95-7.05-5.92-14.08-8.87-21.13-1.58-3.79-3.16-7.59-4.7-11.4-.78-1.92-1.73-3.89-2.25-5.91-.03-.1 0-.19.04-.26h.01ZM578.78 77.87c1.45-5.77 3.07-10.43 3.58-13.36.05-.34.16-.88.31-1.55-.67 1.79-1.37 3.56-2.08 5.33-.12.43-.23.86-.35 1.29-.65 2.43-1.29 4.86-1.9 7.3.14.33.29.65.43 1l.01-.01ZM545.3 94.66c.02-.44.03-.83.05-1.12.02-1.01.05-2.02.11-3.02.03-6.66-.46-14.33-1.46-22.8-.13-.42-.27-1.24-.56-2.89 0-.02 0-.04-.01-.06.62 6.61.95 13.25 1.32 19.87.17 3.08.33 6.16.52 9.23.02.25.03.52.04.78l-.01.01ZM580.77 102.81c.13.2.27.38.37.49.27-.11.53-.22.8-.32-.43.09-.82.05-1.17-.16v-.01ZM530.48 104.07h.33c-.36-.13-.71-.32-1.04-.56.14.24.3.47.45.7.06-.08.14-.13.26-.13v-.01ZM542.63 58.82c.06.23.11.47.15.71.14-.33.36-.62.7-.86-.28.05-.57.11-.85.15ZM583.81 57.87c.15-.7.29-1.41.42-2.11-.14.45-.28.9-.42 1.34-.46 1.44-.89 2.89-1.31 4.34.44-1.19.88-2.37 1.31-3.57ZM523.62 91.48c-4.66 1.17-9.05 2.89-14.02 5.27 4.65-1.84 9.48-3.29 14.28-4.63-.09-.22-.17-.41-.26-.64ZM460.64 78.3c-.04-2.9-.11-5.81-.28-8.71-.1-1.68-.17-3.43-.5-5.09-.07.02-.14.03-.2.05.3 6.54.45 12.17.51 17.12.17-.07.34-.14.51-.2 0-1.06-.01-2.11-.03-3.17h-.01ZM470.63 63.24c-3.38-.26-6.81.32-10.1 1.1.41 2.01.47 4.14.57 6.18.18 3.55.25 7.11.27 10.67 3.31-1.38 6.5-3.12 9.3-5.35 1.96-1.56 3.86-3.41 5.02-5.66.73-1.41 1.19-3.22.26-4.65-1.09-1.7-3.46-2.14-5.32-2.29ZM460.29 63.68c1-.24 2.01-.46 3.04-.65-1.15.16-2.37.38-3.71.69v.13c.07-.02.15-.04.22-.05.11-.13.3-.18.45-.11v-.01ZM457.24 100.96c.43-.03.86-.07 1.29-.11.14-.49.27-.99.38-1.49-.44.7-1 1.23-1.67 1.6ZM482.88 104.98c-.18.23-.36.38-.55.47.14.09.27.19.4.28a70.76 70.76 0 0 0 4.37-4.63c.76-.89 1.52-1.81 2.19-2.77-.3-.27-.61-.53-.92-.79-.07 1.94-4.62 6.32-5.49 7.45v-.01Z",transform:"translate(-144.023 -51.76)"}),_i("path",{d:"M474.36 63.31c-.4-.16-.84-.27-1.29-.37 1.56.42 3.08 1.22 3.76 2.74.62 1.4.32 2.95-.28 4.32.7-1.22.94-2.34.74-3.47-.24-1.33-1.19-2.54-2.93-3.21v-.01ZM477.34 89.18c-1.2-.81-2.4-1.62-3.6-2.42-.14.1-.26.19-.4.29 1.4.67 2.73 1.39 4 2.13ZM465.88 93.85c.37.25.74.5 1.1.75.46.32.92.65 1.38.97-1.57-1.2-2.01-1.61-2.49-1.72h.01ZM574.92 90.06c-2.28-5.21-4.93-11.13-5.67-12.26-.1-.15-1.57-3.01-1.63-3.08 0 0-.01.02-.02.02.4 1.37 1.09 2.69 1.65 3.99 2.14 4.95 4.36 9.86 6.67 14.73.6 1.26 1.21 2.52 1.83 3.78-.75-2.01-1.64-4.45-2.83-7.18ZM448.73 65.29c.1.2.22.38.34.57.22-.02.43-.06.65-.08v-.08c-.14-.05-.25 0-.99-.41ZM460.16 94.81c-.02.31-.06.59-.1.89-.03 1.71-.33 3.43-.79 5.07.15-.02.3-.03.45-.05.01-.04.02-.08.03-.11.09-.34.15-.69.2-1.03.17-1.07.25-2.16.33-3.24.05-.69.08-1.39.12-2.08-.27.1-.27.26-.24.57v-.02Z",transform:"translate(-144.023 -51.76)"}),_i("path",{d:"m328.67 98.12-3.22-6.58c-1.29-2.63-2.53-5.29-3.72-7.97-.25-.85-.52-1.69-.79-2.53-.81-2.57-1.67-5.12-2.55-7.67-1.92-5.53-3.9-11.08-6.32-16.41-.72-1.58-1.46-3.44-2.63-4.79-.03-.17-.16-.29-.34-.36a.282.282 0 0 0-.23-.04c-.06-.01-.12 0-.18.01-.74.06-1.5.38-2.19.61-2.22.77-4.4 1.64-6.63 2.38-.03-.08-.06-.16-.09-.25-.15-.42-.82-.24-.67.19.03.09.07.19.1.28l-.18.06c-.36.11-.28.6 0 .68.18 1.18.63 2.36.98 3.49.03.09.06.17.08.26-.08.23-.17.46-.24.64-.37.98-.79 1.94-1.21 2.9-1.27 2.89-2.62 5.75-3.98 8.6-3.18 6.67-6.44 13.31-9.64 19.97-1.08 2.25-2.2 4.5-3.15 6.81-.13.32.24.5.5.37 1.34 1.33 2.84 2.5 4.4 3.57.65.44 1.31.87 2.01 1.24.4.22.86.48 1.33.5.24.01.35-.19.33-.37.11-.1.21-.21.28-.28.41-.41.81-.84 1.2-1.26.85-.92 1.69-1.87 2.5-2.84 6.31-2.34 12.6-4.31 18.71-5.84 2.14 5.3 3.43 8.43 3.97 9.58.55 1.05 1.15 1.88 1.82 2.52 1.32.56 6.96-.03 9.23-1.96.87-1.28 1.19-2.67.93-4.15-.09-.5-.22-.95-.4-1.33l-.01-.03Zm-20.09-45.61c.43.77.83 1.56 1.21 2.35-.54-.45-1.27-.99-2.07-1.49-.42-.24-.6-.35-.94-.34.43-.15.85-.29 1.29-.41.17-.05.34-.08.51-.11Zm-25.86 45.66c.78-1.85 1.67-3.66 2.54-5.47 1.51-3.16 3.05-6.31 4.58-9.47 1.28-2.63 2.56-5.26 3.83-7.9l-1.1 2.66c-1.99 4.79-4.97 10.9-8.88 18.15-.43.76-.66 1.51-.71 2.24-.05-.05-.1-.09-.15-.14a.259.259 0 0 0-.11-.07Zm6.24 4.71c-.42-.23-.82-.48-1.22-.74 1.05.45 2 .72 2.55.72l-.21.21c-.05.05-.11.1-.16.15-.01.01-.04.03-.05.04 0-.02.03-.02.05-.03a.27.27 0 0 0-.08.07c-.05-.02-.1-.03-.14-.05-.25-.1-.49-.24-.73-.37h-.01Zm15.73-29.43c1.05 3.15 2.1 6.31 3.1 9.48.34 1.06.69 2.13 1.01 3.21-3.5.63-6.95 1.46-10.27 2.5 2.48-6.03 4.54-11.11 6.16-15.19Zm4.79 12.57c-.23-.79-.49-1.58-.73-2.36-.79-2.54-1.63-5.08-2.46-7.61l-1.2-3.6c.02-.04.04-.09.05-.13 1.6 4.45 3.28 9 5.01 13.57l-.67.12v.01Zm5.83-18.27-.15-.54c-.49-1.64-1.03-3.28-1.6-4.9.23.58.47 1.17.7 1.75 1.56 4.03 3.01 8.1 4.39 12.2-.33-.82-.67-1.64-.98-2.46l-2.35-6.05h-.01ZM390.43 79.37c-.13-10.43-.22-17.5-.24-19.97-.24-1.6.21-2.88-.65-3.65-.14-.13-.32-.23-.52-.32h.03c.45 0 .45-.69 0-.7-1.75-.03-3.5-.04-5.25-.14-1.38-.08-2.76-.21-4.15-.31-.07 0-.12.01-.17.04-.21-.07-.47.03-.45.31l.03.45c-.11.14-.19.3-.22.5-.21 1.26-.32 13.67-.36 23.59-.32 5.79-.67 11.57-.97 17.36-.09 1.73-.29 3.54-.21 5.3-.39.02-.38.64.04.69v.12c.05.44.74.45.7 0v-.06c1.1.09 2.2.21 3.3.3 1.14.19 2.44.2 3.29.17 1.73-.05 2.92-.05 3.8-.37.45-.05.9-.11 1.35-.17.44-.06.25-.73-.19-.67h-.01c.24-.32.45-.72.62-1.25.66-1.84.41-6.36.34-11.33l-.13-9.9.02.01Zm-12.26 18.17c.09-1.91.2-3.81.31-5.71.06 5.38 0 6.14-.01 6.51-.05 1.65-.21 2.81.72 3.66-.39-.04-.78-.07-1.17-.1-.06-1.44.09-2.93.16-4.35l-.01-.01ZM588.97 53.85c-2.06-.25-3.17-.51-3.76-.6a.3.3 0 0 1 .04-.08c.22-.39-.39-.75-.6-.35-.56 1.02-.9 2.19-1.26 3.29-.61 1.88-1.17 3.78-1.72 5.68-.63 2.19-1.24 4.39-1.83 6.59-.81 2.03-1.67 4.05-2.61 6.03-1.7-3.64-3.11-6.04-4.03-7.57-2.26-3.74-2.85-5.48-3.57-6.08l.31-.09c.43-.12.25-.8-.19-.67-1.06.3-2.12.6-3.17.95-.93.32-1.85.69-2.76 1.07-.13.05-.19.16-.22.27-.04.02-.08.05-.11.07-.04-.06-.07-.12-.11-.18a.354.354 0 0 0-.48-.12c-.16.09-.22.32-.13.48l.33.54c0 .09.02.18.06.28.51 1.16.78 1.38.72 1.47-2.42 3.44-5.41 7.86-6.2 9.1-1.27 1.97-2.01 3.14-2.45 3.84l-.91-6.56-.43-4.1c-.19-1.85-.37-3.23-.53-4.13-.19-1.1-.3-2.15-.45-3.16-.2-1.36-.29-2.06-.47-2.42h.04c.45.02.45-.68 0-.7-3.43-.16-6.81.94-10.17 1.48-.24-.22-.73-.04-.58.32.24.59.33 1.25.43 1.87.17 1.06.29 2.13.4 3.2.32 3.09.53 6.2.74 9.3.44 6.75.77 13.51 1.17 20.26.11 1.95.13 3.96.46 5.89.05.3.37.31.55.14.74 1.71 2.87 1.27 6.13 1.27 1.34 0 2.39.04 2.99-.11.02.32.48.53.63.18 3.61-8.26 7.41-16.46 12.05-24.2.03-.05.04-.1.05-.15.3.73.64 1.45.94 2.16.97 2.26 1.97 4.52 2.98 6.76 2.26 5.03 4.54 10.07 7.09 14.96.47.9.94 1.79 1.47 2.65.2.32.4.67.66.96-.18.25 0 .68.34.54.91-.38 1.82-.75 2.76-1.07 1.04-.35 2.11-.65 3.17-.95.39-.11.28-.66-.07-.68.62-.4.95-.96.87-1.91-.3-3.34.72-7.47.86-8.52l2.14-11.43c1.75-10.74 3.13-17.51 3.23-20.86.02-.49.08-2.84.13-3.24.17-1.25.48-1-4.96-1.65l.03-.02Zm-46.19 5.67c-.04-.24-.09-.48-.15-.71l.85-.15c-.34.24-.56.53-.7.86Zm1.95 25.12c-.36-6.63-.7-13.26-1.32-19.87 0 .02 0 .04.01.06.29 1.65.44 2.47.56 2.89 1 8.46 1.5 16.14 1.46 22.8-.06.99-.1 2-.11 3.02-.01.29-.03.68-.05 1.12-.01-.26-.03-.53-.04-.78-.19-3.08-.35-6.16-.52-9.23l.01-.01Zm36.4 18.66c-.11-.11-.24-.29-.37-.49.35.21.74.26 1.17.16-.27.11-.53.22-.8.32v.01Zm-.89-33.72c.12-.43.23-.86.35-1.29.71-1.77 1.41-3.55 2.08-5.33-.15.68-.26 1.22-.31 1.55-.5 2.94-2.13 7.59-3.58 13.36-.15-.35-.29-.66-.43-1 .61-2.44 1.25-4.87 1.9-7.3l-.01.01Zm3.56-12.48c.14-.44.28-.89.42-1.34-.13.7-.27 1.41-.42 2.11-.43 1.19-.86 2.38-1.31 3.57.42-1.45.85-2.9 1.31-4.34Zm-5.22 16.05c-.11.44-.23.87-.35 1.31-.12.46-.23.92-.35 1.38-.1-.22-.19-.4-.28-.61.34-.69.66-1.38.97-2.08h.01Zm-11.64 2.62c.06-.1.12-.19.17-.28.05.13.09.26.14.39a.398.398 0 0 0-.31-.11Zm2.3 2.98c-.56-1.3-1.25-2.63-1.65-3.99 0 0 .01-.02.02-.02.06.08 1.52 2.93 1.63 3.08.73 1.13 3.38 7.04 5.67 12.26 1.2 2.73 2.08 5.17 2.83 7.18-.62-1.25-1.23-2.51-1.83-3.78-2.31-4.87-4.53-9.78-6.67-14.73ZM275.92 87.03c-1.06-2.18-1.13-3.45-2.44-2.93-1.52.57-2.94 1.3-4.5 2.1-1.4.72-2.68 1.44-3.92 2.12.01-.25-.24-.5-.51-.34-4.8 2.93-12.41 4.7-17.28 1.31-1.98-1.77-3.32-4.15-3.97-5.78-.29-.95-.49-1.94-.63-2.93-.14-3.34 1.58-6.53 3.9-9.12.8-.79 1.68-1.51 2.66-2.12 3.7-2.3 8.22-3.07 12.51-2.51 2.71.35 5.32 1.24 7.71 2.55.39.22.75-.39.35-.6-.18-.1-.37-.18-.55-.27.56.27 1.03.33 1.51.19l-.48.39c-.15.11-.23.3-.13.48.09.15.33.24.48.13 1.3-.97 2.46-2.09 3.45-3.37.37-.29.64-.6.65-.97v-.02c.08-.33-.03-.7-.21-1.08-.31-.87-.98-2.01-2.19-3.26-2.43-2.52-3.79-3.45-5.68-4.26-1.14-.49-3.12-1.06-4.42-1.23-3.28-.42-10.64-1.21-18.18 4.11-7.74 5.46-11.94 12.3-12.23 20.61-.08 2.06.04 3.98.34 5.71.74 4.18 2.57 8 5.44 11.34 4.26 4.99 9.76 7.52 16.34 7.52 4.85 0 9.69-1.77 14.89-4.62.23-.12.45-.23.68-.35 2.19-1.1 4.37-2.23 6.46-3.5.49-.3 1.03-.61 1.5-.98 1.47-.87 1.11-1.12.49-2.95-.39-1.14-.76-2.7-2.06-5.36l.02-.01Zm-17.38-21.76c3.05-.42 6.31.79 9.36 2.35.51.39.94.68 1.33.87-5.61-2.86-12.72-3.39-18.44-.79 2.05-1.33 4.24-1.95 7.74-2.44l.01.01ZM443.67 72.67c-.4-2.2-1.15-4.33-2.37-6.22-1.49-2.32-3.58-4.19-5.91-5.64-6.17-3.81-13.75-5.11-20.83-6.01-3.23-.41-6.47-.69-9.72-.92l-1.39-.12c-.85-.07-1.52-.1-2.05-.1-1.08-.06-2.17-.12-3.25-.17-.08 0-.14.02-.19.05-.1.05-.18.14-.16.3.27 2.55-.01 5.12-.92 7.52-.15.38.4.56.62.28 1.32.59 2.68 1.05 4.08 1.37 0 2.78-.14 7.58-.33 12.91 0 0 0 .02-.01.03-.61 3.66-.79 7.42-1 11.12-.23 4.01-.43 8.03-.44 12.05 0 .64 0 1.28.03 1.93.02.31 0 .68.15.96.06.11.14.16.24.17-.2.17-.21.54.11.59 3.83.67 7.78.71 11.68.25 2.3-.19 4.87-.65 7.65-1.56 1.85-.54 3.67-1.18 5.43-1.91 7.2-3.02 14.31-8.07 17.35-15.53.76-1.86 1.17-3.8 1.31-5.75.3-1.93.28-3.82-.09-5.58l.01-.02Zm-19.32-15.42c5.74 1.41 11.94 3.68 15.65 8.55.25.32.47.65.69.99-2.3-2.82-5.68-5.69-12.88-8.23-2.16-.76-4.35-1.43-6.64-2.02 1.06.21 2.13.45 3.18.71Zm-25.82-3.04c.13 0 .27.01.4.02-.14.1-.26.23-.37.38 0-.13-.02-.26-.03-.4Zm34.82 22.17c-.75 3.09-3.55 5.66-5.88 7.58-3.35 2.76-7.21 5.03-11.28 6.54-1.33.49-2.71.9-4.12 1.15.06-1.38.08-2.76.07-4.13-.02-3.78-.16-7.56-.41-11.33-.09-1.37-.18-2.74-.37-4.1 0-.06-.03-.11-.06-.15.09-3.25.12-6.16.03-8.12 6.86 1.05 10.56 2.17 14.06 3.62 5.52 2.28 8.59 5.44 7.97 8.96l-.01-.02Zm-22 16.15c-.12 0-.23-.02-.34-.03l.34-.03v.06Zm-.69-.7c0-3.13.26-8.84.47-14.51.06 1.2.11 2.41.15 3.6.15 3.6.25 7.23.09 10.83-.24.03-.48.05-.71.07v.01Zm-12.33-30.94c.37.63 2.01 1.01 3.23 1.25v.15c-1.31-.31-2.59-.73-3.83-1.29.12-.36.23-.72.33-1.09.08.48.18.84.27.98Zm13.7 31.65v-.18c3.41-.56 6.71-2.02 9.69-3.68 2.31-1.28 4.59-2.78 6.63-4.53-4.69 4.53-11.61 8.24-16.33 8.38l.01.01Zm24.07-.75c-2.05 1.93-4.37 3.56-6.83 4.95 2.7-1.78 5.52-4.03 8.42-6.87.82-.82 1.56-1.69 2.23-2.59-1.08 1.65-2.38 3.16-3.81 4.51h-.01ZM187.16 92.14c-.79-2.47-2.1-7.12-3.1-6.87-.19-.01-2.09.77-4.08 1.54-3.06 1.18-5.91 2.13-10.09 2.82-2.74.42-5.87 1.01-10.61 1.06.04-3.34.05-6.01.05-7.99 7.97-.65 12.33-2.11 16.37-3.55 1.11-.39 2.69-1.01 2.63-1.8-.08-.35-.55-1.39-1.17-2.61-.47-1.16-.98-2.31-1.61-3.38-.42-.71-1.04-1.69-1.86-2.06-.11-.08-.22-.13-.29-.12-.02 0-.04 0-.07.01-.19-.04-.39-.05-.6-.01-.17.03-.24.15-.25.28-.04.02-.09.04-.14.05-4.33 1.48-8.85 2.33-13.24 3.61a499.1 499.1 0 0 0-.31-8.19c4.51-.99 8.88-1.38 13.11-1.82 3.68-.38 6.28.12 7.47.34.59.11.9.16 1.16.18h.1c-.1.37.44.66.62.28.02-.04.03-.08.05-.13.15.2.53.22.62-.1.17-.58.19-1.21.21-1.81v-.36c.03-.15.05-.3.07-.45.52-2.47.33-5.09-.64-7.44-.11-.27-.44-.28-.6-.14-.08-.21-.15-.42-.24-.62-.19-.41-.79-.05-.6.35.03.07.05.15.09.22-.98-.42-2.15-.54-3.17-.63-2.17-.19-4.37-.14-6.54 0-5.7.35-11.4 1.3-16.91 2.79-2.08.56-4.13 1.22-6.14 2-4.54 1.05-3.79 1.51-2.17 6.07.18.51.46 1.68.54 1.94.82 2.47 1.08 2.13 3.1 2.13s0 .05 0 .08h.52c-.48 2.66-.51 5.45-.62 8.13-.15 3.48-.22 6.96-.28 10.45 0 .41-.01.82-.02 1.23-.16.29-.33.57-.51.85-.05.38-.09.77-.14 1.18-.42 3.52-.59 6.48-.52 8.8v.34c.02.47.05.76.06.87.16 1.57-.26 3.47 1.35 3.79 1.61.32 3.5.55 4.85.55.11 0 .22-.02.33-.02 1.79.24 3.67.05 5.45-.12 2.85-.28 5.69-.7 8.51-1.19 3.03-.53 6.05-1.14 9.04-1.86 2.4-.58 4.82-1.19 7.13-2.06.51-.19 1.73-.57 2.46-1.14 1.81-.68 2.18-1 1.57-2.67-.23-.62-.48-1.49-.91-2.78l-.03-.02Zm-11.12-38.71c.89.05 1.93.08 2.89.3-.33 0-.68-.02-1.06-.03-8.28-.26-14.88.75-23.97 2.51 2.41-.64 4.85-1.16 7.28-1.59 4.87-.86 9.91-1.45 14.86-1.19Zm-26.53 22.13c.03 1.71.04 3.43 0 5.14-.04 1.27-.11 2.55-.24 3.82 0-.73.02-1.46.04-2.19.05-2.26.12-4.51.22-6.77h-.02Zm6.73 27.85c.2-.1.4-.21.58-.33 1.82-.17 3.82-.24 5.94-.34-.86.11-1.72.24-2.58.33-1.27.14-2.61.31-3.93.34h-.01ZM534.48 85.44c-3.52-8.38-7.07-16.75-10.5-25.17-.63-1.54-1.25-3.09-1.86-4.65-.31-.8-.65-1.6-.87-2.43-.04-.17-.17-.24-.31-.25.1-.2 0-.51-.29-.53-1.59-.08-3.18-.22-4.78-.25-1.96-.03-3.91.13-5.84.42-.31.05-.31.38-.13.56-.03.06-.05.14-.04.22.23 1.54.63 3.06 1.16 4.53.13.35.27.7.41 1.06l-2.68 6.18c-.11.03-.2.09-.25.22-.67 1.9-1.52 3.73-2.34 5.56a536.85 536.85 0 0 1-3.9 8.45c-2.64 5.64-5.34 11.25-7.91 16.93-.44.97-.88 1.94-1.29 2.93-.2.48-.47 1-.55 1.52v.05c-.02.12.02.26.16.34 1.19.73 2.41 1.41 3.66 2.05 1.2.62 2.45 1.25 3.76 1.61.43.12.62-.55.19-.67-1.13-.31-2.2-.83-3.24-1.36 1.09.36 2.1.69 2.75.93 2.82 1.01 2.38 1.1 4.3-3.75 2.1-1.09 4.34-1.96 6.53-2.79 4.35-1.64 8.8-3.03 13.27-4.29.82 2.01 1.77 3.97 2.72 5.92.35.83.62 1.45.79 1.82.22.42.45.8.69 1.15.17.33.33.67.5 1 .42.8.84 1.63 1.4 2.35.23.29.6 0 .55-.31 1.53-.02 3.06-.07 4.58-.27.92-.12 1.82-.32 2.71-.54 1.39-.27 3.85-1.11 3.74-1.42-.67-1.96-1.55-3.87-2.34-5.78-1.57-3.78-3.16-7.56-4.75-11.33v-.01Zm-11.65-26.16c1.54 3.81 3.12 7.6 4.7 11.4 2.94 7.05 5.91 14.09 8.87 21.13l-1.06-2.17c-2.71-5.51-5.2-11.19-7.41-16.87l-6.65-17.15c-.65-1.45-.55-2.19-.93-2.53.09 0 .18.01.28.02a.29.29 0 0 0-.04.26c.52 2.02 1.47 3.98 2.25 5.91h-.01Zm-6.58 13.58c.05-.15.09-.31.14-.46 1.41 3.92 2.88 7.9 4.39 11.87-3.22.52-6.38 1.25-9.46 2.14.55-1.22 1.05-2.46 1.53-3.7 1.24-3.24 2.37-6.53 3.39-9.85h.01Zm-.23-20c.36 0 .73.03 1.09.05-2.15.1-5.18.33-5.87.74-.24.15-.41.3-.53.45-.06-.29-.13-.58-.18-.88 1.82-.26 3.65-.39 5.49-.35v-.01Zm-.09 18.72c-.49 1.67-1.05 3.33-1.6 4.97-1.07 3.19-2.19 6.38-3.57 9.46-.09.21-.19.43-.29.65-.25.07-.5.14-.74.22 2.53-6.16 4.61-11.29 6.2-15.3Zm-6.34 25.16c4.97-2.38 9.37-4.1 14.02-5.27l.26.64c-4.8 1.35-9.63 2.8-14.28 4.63Zm20.17 6.76c.33.23.68.42 1.04.56h-.33c-.12 0-.21.06-.26.13-.15-.23-.31-.45-.45-.7v.01ZM226.57 91.75c-3.55-4.74-6.68-9.11-9.31-12.99 9.2-15.25 10.05-17.81 10.35-18.38.17-.34 1.09-2.27.64-2.53-1.13-.65-1.03-.65-2.97-1.71-1.19-.65-3.04-1.61-4.53-2.12-1.71-.59-1.24-.36-3 2.77-.06.1-.11.2-.17.3-.75 1.02-1.48 2.05-2.2 3.09-1.88 2.71-3.73 5.45-5.69 8.1-3.68-4.91-6.88-8.76-9.51-11.43-.15-.15-.3-.29-.46-.42-1.27-1.28-7.24 3.53-7.93 5.58-.09.09-.19.16-.28.25-.27.26.03.64.33.58.19.65.5 1.29.94 1.91 3.85 5.06 7.19 9.76 9.94 14-1.23 2.61-3.06 5-4.67 7.38l-2.28 3.33c-.5.66-.93 1.23-1.29 1.69-.67.93-2.09 2.61-2.3 3.87-.51.85-1.16 1.84-1.29 2.83-.06.44.61.63.67.19.01-.08.04-.15.06-.22 1.36 1.08 2.76 2.11 4.19 3.11 1.3.91 2.62 1.85 4.04 2.56.21.1.4 0 .48-.17.24.07.48.14.72.2.44.1.62-.57.19-.67-2.02-.48-3.77-1.57-5.23-3.02-.47-.46-.9-.96-1.32-1.46 1.74 1.35 4.2 2.89 5.89 4.14 1.39 1.03 2.85-2.27 4.22-4.2 1.86-2.64 3.96-5.86 5.52-8.29l10.39 14.51c.67.81 1.14 1.21 1.57 1.36-.05.24.12.51.41.4 1.53-.58 3.05-1.19 4.54-1.87 1.52-.69 3.06-1.45 4.36-2.5a.28.28 0 0 0 .12-.23c1.66-1.1.81-1.74-1.41-4.91-1.13-1.58-1.71-2.36-3.7-5.01l-.03-.02Zm2.41 6.54c.56 1.15 1.19 2.52 1.11 3.81-.06.04-.12.07-.17.1-.03-.88-.55-2.66-.94-3.91Zm-16.51-32.73c1.86-2.65 3.65-5.35 5.57-7.95.4-.55.81-1.13 1.26-1.66.19-.18.38-.33.56-.45.18.03.36.08.55.13l-8.05 10.11.12-.18h-.01ZM192.7 95.48c.79-1.37 1.66-2.69 2.54-4 1.19-1.79 2.4-3.56 3.61-5.33-.04.09-.09.17-.13.26-.1.22.03.41.2.49-2.47 3.42-4.89 6.73-6.4 9.28.21.24.4.48.63.75-.24.07-.4.36-.17.56.4.33.72.77 1.05 1.17.09.11.18.21.27.32-.84-.61-1.66-1.24-2.47-1.88.24-.57.58-1.11.87-1.61v-.01Zm7.46-10.32c.47-.81.98-1.59 1.49-2.37.31-.48.64-.95.96-1.43.26-.29.52-.56.75-.79-.99 1.48-2.09 3.03-3.2 4.59Zm10.03-16.22s-.03-.05-.05-.07c.22-.29.43-.59.64-.89-.2.32-.4.65-.58.96h-.01ZM371.54 87.96c-.01-.08-.01-.16-.03-.23-.06-.38-.58-.29-.66.03-.3-.05-.6-.08-.81-.11-1.14-.15-2.29-.19-3.44-.2 1.04-.09 2.09-.18 3.14-.23.45-.02.45-.72 0-.7-6.57.35-13.14 1.23-19.65 2.11-1.53.21-3.05.42-4.57.68-.01 0-.02.01-.04.01-.04-3.33-.13-6.66-.24-9.99-.19-5.7-.4-11.41-.88-17.1-.13-1.51-.23-3.07-.49-4.58 0-.25 0-.48-.02-.68-.06-1.19-.04-2.61-.68-2.78-.16-.07-.72-.16-1.5-.24.22-.17.16-.62-.2-.63-1.19-.04-2.39.09-3.57.23-1.2.14-2.41.32-3.59.6-.16-.1-.41-.06-.5.12-.06.02-.13.03-.19.05-.35.1-.29.55-.03.66-.26.6-.19 2.27-.21 3-.02.66-.66 33.73-.9 40.3-.03.65.06 1.12.04 1.45-.16 3.05.87 4.96 6.34 3.93 1.09-.08 2.75-.77 5.36-1.43 4.13-1.04 5.78-1.52 6.2-1.65 6.43-1.69 6.78-1.97 11.72-2.43.55-.05 4.8-.38 6.03-.3.64.04 1.19.07 1.65.1.09 0 .16-.03.24-.05.1.27.56.33.66-.02.39-1.32.61-2.71.78-4.08.2-1.61.29-3.24.15-4.86.24.03.52-.23.38-.53-.09-.2-.27-.33-.49-.43v-.02Zm-.63.56c.07.57.11 1.14.11 1.71-.21-.99-.53-1.71-.95-1.87.22.03.44.06.65.11.06.01.12.04.19.05Zm-25.41 1.73c1.54-.36 3.1-.64 4.66-.89-1.61.37-3.18.77-4.66 1.2v-.31Zm-.86-7.37c-.07-1.37-.16-2.75-.25-4.12-.21-3.13-.45-6.27-.79-9.4.02-2.25.08-4.31.13-6.11.16 2.08.29 4.16.4 6.24.23 4.46.38 8.93.5 13.39h.01Zm-.94-4c.16 2.41.29 4.83.39 7.24.06 1.6.14 3.22.09 4.83-.15.05-.32.09-.47.14V78.88h-.01ZM483.72 92.83c-3.05-2.28-6.22-4.4-9.38-6.51 8.86-6.49 13.49-12.95 13.73-19.23.04-.76 0-1.5-.13-2.2-.67-3.82-3.5-6.68-8.39-8.48.13.04.27.08.4.13 3.92 1.39 7.74 4.23 8.5 8.56.34 1.95-.05 3.96-.98 5.69-.21.4.39.75.6.35 1.86-3.46 1.46-7.55-.97-10.63-3.53-4.47-9.76-5.88-15.16-6.16-2.32-.12-4.64-.04-6.95.19-6 .32-12.71 1.68-17.63 3.21-.37.11-.67.23-.92.35-.2-.17-.62.02-.57.37v.03c-.64.68-.18 1.64.48 3.21.38.91.67 1.89 1.15 2.58.32.76.68 1.51 1.13 2.19.14.21.38.19.53.07.19-.02.38-.05.57-.08v1.57c-.06.06-.1.13-.11.23-.27 4.18-.34 8.38-.48 12.57l-.3 9.03c-.24 3.91-.44 6.77-.46 7.26-.05.88-.11 1.95.07 2.81-.01.22-.02.43-.04.65 0 .11-.02.23-.03.35 0 .05-.03.27-.01.16-.05.4.5.59.64.28.05.04.12.08.2.08 1.75.13 3.5.28 5.25.3 1.69.02 3.38-.12 5.06-.32.08.23.36.39.55.15.06-.08.11-.17.16-.26.18-.09.24-.32.18-.48.05-.2.1-.4.13-.6.16-.86.25-1.74.33-2.62.11-1.17.17-2.34.23-3.51.15-.01.32-.03.52-.04.36-.03 1.73-.15 2.06-.15.39 0 .7-.02.95-.04 1.76 1.11 3.45 2.35 5.14 3.55 2.83 2.01 5.64 4.04 8.47 6.04 1.42 1 2.85 2 4.29 2.97.1.06.19.07.27.04.08 0 .17-.02.25-.1 1.61-1.56 3.15-3.18 4.6-4.88.75-.88 1.49-1.78 2.15-2.73.01.01.03.02.04.03.34.3.83-.2.49-.49-2.16-1.9-4.34-3.76-6.64-5.48l.03-.01Zm-6.38-3.65a55.72 55.72 0 0 0-4-2.13c.14-.1.26-.19.4-.29 1.2.81 2.4 1.61 3.6 2.42Zm-20.1 11.78c.67-.37 1.23-.91 1.67-1.6-.11.5-.24 1-.38 1.49-.43.04-.86.08-1.29.11Zm2.38-37.24c1.34-.31 2.56-.52 3.71-.69-1.03.19-2.04.41-3.04.65-.14-.07-.34-.02-.45.11-.07.02-.15.04-.22.05v-.13.01Zm.04.84c.07-.02.14-.03.2-.05.34 1.66.41 3.41.5 5.09.17 2.9.24 5.81.28 8.71l.03 3.17c-.17.07-.34.14-.51.2-.06-4.96-.21-10.58-.51-17.12h.01Zm16.04 5.62c-1.16 2.25-3.06 4.1-5.02 5.66-2.8 2.23-5.99 3.97-9.3 5.35-.01-3.56-.09-7.12-.27-10.67-.1-2.04-.16-4.16-.57-6.18 3.3-.78 6.72-1.36 10.1-1.1 1.85.14 4.23.59 5.32 2.29.92 1.43.46 3.24-.26 4.65Zm.85-.18c.6-1.37.9-2.92.28-4.32-.67-1.52-2.2-2.32-3.76-2.74.46.1.89.21 1.29.37 1.74.67 2.69 1.88 2.93 3.21.2 1.13-.05 2.25-.74 3.47V70Zm-27.47-4.14c-.12-.19-.23-.38-.34-.57.74.42.85.36.99.41v.08c-.22.03-.43.06-.65.08Zm11.21 30.46c-.08 1.08-.16 2.17-.33 3.24-.05.35-.11.69-.2 1.03 0 .04-.02.07-.03.11-.15.02-.3.04-.45.05.45-1.64.76-3.36.79-5.07.03-.29.08-.57.1-.89-.03-.31-.03-.47.24-.57-.04.69-.07 1.39-.12 2.08v.02Zm5.6-2.47c.48.11.92.52 2.49 1.72-.46-.32-.92-.65-1.38-.97-.37-.25-.73-.5-1.1-.75h-.01Zm21.23 7.24a70.76 70.76 0 0 1-4.37 4.63c-.14-.09-.27-.19-.4-.28.19-.09.37-.24.55-.47.87-1.14 5.43-5.51 5.49-7.45.31.26.62.53.92.79-.67.97-1.42 1.88-2.19 2.77v.01Z",fill:"currentColor",transform:"translate(-144.023 -51.76)"})]}),yP=({style:e,size:t="small",withText:o})=>wP("div",{className:`ExcalidrawLogo is-${t}`,style:e,children:[_i(oJ,{}),o&&_i(nJ,{})]});import{Fragment as TP,jsx as vt,jsxs as iE}from"react/jsx-runtime";var aE=({icon:e,shortcut:t,children:o})=>{let n=we();return iE(TP,{children:[vt("div",{className:"welcome-screen-menu-item__icon",children:e}),vt("div",{className:"welcome-screen-menu-item__text",children:o}),t&&n.formFactor!=="phone"&&vt("div",{className:"welcome-screen-menu-item__shortcut",children:t})]})};aE.displayName="WelcomeScreenMenuItemContent";var zd=({onSelect:e,children:t,icon:o,shortcut:n,className:r="",...i})=>vt("button",{...i,type:"button",className:`welcome-screen-menu-item ${r}`,onClick:e,children:vt(aE,{icon:o,shortcut:n,children:t})});zd.displayName="WelcomeScreenMenuItem";var vP=({children:e,href:t,icon:o,shortcut:n,className:r="",...i})=>vt("a",{...i,className:`welcome-screen-menu-item ${r}`,href:t,target:"_blank",rel:"noopener",children:vt(aE,{icon:o,shortcut:n,children:e})});vP.displayName="WelcomeScreenMenuItemLink";var rn=({children:e})=>{let{WelcomeScreenCenterTunnel:t}=Xe();return vt(t.In,{children:vt("div",{className:"welcome-screen-center",children:e||iE(TP,{children:[vt(sE,{}),vt(lE,{children:f("welcomeScreen.defaults.center_heading")}),iE(cE,{children:[vt(mE,{}),vt(dE,{})]})]})})})};rn.displayName="Center";var sE=({children:e})=>vt("div",{className:"welcome-screen-center__logo excalifont welcome-screen-decor",children:e||vt(yP,{withText:!0})});sE.displayName="Logo";var lE=({children:e})=>vt("div",{className:"welcome-screen-center__heading welcome-screen-decor excalifont",children:e});lE.displayName="Heading";var cE=({children:e})=>vt("div",{className:"welcome-screen-menu",children:e});cE.displayName="Menu";var dE=()=>{let e=nt();return vt(zd,{onSelect:()=>e.executeAction(ji),shortcut:"?",icon:ja,children:f("helpDialog.title")})};dE.displayName="MenuItemHelp";var mE=()=>{let e=ye(),t=nt();return e.viewModeEnabled?null:vt(zd,{onSelect:()=>t.executeAction(Cs),shortcut:Ke("loadScene"),icon:qa,children:f("buttons.load")})};mE.displayName="MenuItemLoadScene";var IP=({onSelect:e})=>{let{t}=Ge();return vt(zd,{shortcut:null,onSelect:e,icon:pm,children:t("labels.liveCollaboration")})};IP.displayName="MenuItemLiveCollaborationTrigger";rn.Logo=sE;rn.Heading=lE;rn.Menu=cE;rn.MenuItem=zd;rn.MenuItemLink=vP;rn.MenuItemHelp=dE;rn.MenuItemLoadScene=mE;rn.MenuItemLiveCollaborationTrigger=IP;import{jsx as _l,jsxs as pE}from"react/jsx-runtime";var Rg=({children:e})=>{let{WelcomeScreenMenuHintTunnel:t}=Xe();return _l(t.In,{children:pE("div",{className:"excalifont welcome-screen-decor welcome-screen-decor-hint welcome-screen-decor-hint--menu",children:[gy,_l("div",{className:"welcome-screen-decor-hint__label",children:e||f("welcomeScreen.defaults.menuHint")})]})})};Rg.displayName="MenuHint";var Ng=({children:e})=>{let{WelcomeScreenToolbarHintTunnel:t}=Xe();return _l(t.In,{children:pE("div",{className:"excalifont welcome-screen-decor welcome-screen-decor-hint welcome-screen-decor-hint--toolbar",children:[_l("div",{className:"welcome-screen-decor-hint__label",children:e||f("welcomeScreen.defaults.toolbarHint")}),fy]})})};Ng.displayName="ToolbarHint";var Bg=({children:e})=>{let{WelcomeScreenHelpHintTunnel:t}=Xe();return _l(t.In,{children:pE("div",{className:"excalifont welcome-screen-decor welcome-screen-decor-hint welcome-screen-decor-hint--help",children:[_l("div",{children:e||f("welcomeScreen.defaults.helpHint")}),hy]})})};Bg.displayName="HelpHint";import{Fragment as CP,jsx as Hd,jsxs as iJ}from"react/jsx-runtime";var Fg=e=>Hd(CP,{children:e.children||iJ(CP,{children:[Hd(rn,{}),Hd(Rg,{}),Hd(Ng,{}),Hd(Bg,{})]})});Fg.displayName="WelcomeScreen";Fg.Center=rn;Fg.Hints={MenuHint:Rg,ToolbarHint:Ng,HelpHint:Bg};var rJ=Fg;var aJ=()=>{Array.prototype.at||Object.defineProperty(Array.prototype,"at",{value:function(e){if(e=Math.trunc(e)||0,e<0&&(e+=this.length),!(e<0||e>=this.length))return this[e]},writable:!0,enumerable:!1,configurable:!0}),Element.prototype.replaceChildren||(Element.prototype.replaceChildren=function(...e){this.innerHTML="",this.append(...e)})},kP=aJ;import{getSceneVersion as kje,hashElementsVersion as Sje,hashString as Mje,getNonDeletedElements as Pje}from"@orangecatai/element";import{getTextFromElements as Lje}from"@orangecatai/element";import{isInvisiblySmallElement as Dje}from"@orangecatai/element";import sJ from"lodash.throttle";import{arrayToMap as lJ,isDevEnv as SP,isTestEnv as MP}from"@orangecatai/common";import{orderByFractionalIndex as cJ,syncInvalidIndices as PP,validateFractionalIndices as dJ}from"@orangecatai/element";var mJ=(e,t,o)=>!!(t&&(t.id===e.editingTextElement?.id||t.id===e.resizingElement?.id||t.id===e.newElement?.id||t.version>o.version||t.version===o.version&&t.versionNonce<=o.versionNonce)),pJ=sJ((e,t,o)=>{if(SP()||MP()||window?.DEBUG_FRACTIONAL_INDICES){let n=PP(e.map(r=>({...r})));dJ(n,{shouldThrow:MP()||SP(),includeBoundTextValidation:!0,reconciliationContext:{localElements:t,remoteElements:o}})}},1e3*60,{leading:!0,trailing:!1}),uJ=(e,t,o)=>{let n=lJ(e),r=[],i=new Set;for(let s of t)if(!i.has(s.id)){let l=n.get(s.id),c=mJ(o,l,s);l&&c?(r.push(l),i.add(l.id)):(r.push(s),i.add(s.id))}for(let s of e)i.has(s.id)||(r.push(s),i.add(s.id));let a=cJ(r);return pJ(a,e,t),PP(a),a};import{isLinearElement as Uje}from"@orangecatai/element";import{FONT_FAMILY as Yje,THEME as US,MIME_TYPES as Vje,ROUNDNESS as bp,DEFAULT_LASER_COLOR as $je,UserIdleState as Kje,normalizeLink as Xje,sceneCoordsToViewportCoords as aT,viewportCoordsToSceneCoords as Zje,getFormFactor as jje}from"@orangecatai/common";import{mutateElement as Ep,newElementWith as Jje,bumpVersion as Ns}from"@orangecatai/element";import{CaptureUpdateAction as eqe}from"@orangecatai/element";import{jsx as uE}from"react/jsx-runtime";var AP=({children:e,icon:t})=>{let{t:o}=Ge(),{TTDDialogTriggerTunnel:n}=Xe(),r=ve();return uE(n.In,{children:uE(he.Item,{onSelect:()=>{ge("ai","dialog open","ttd"),r({openDialog:{name:"ttd",tab:"text-to-diagram"}})},icon:t??Mw,badge:uE(he.Item.Badge,{children:"AI"}),children:e??o("labels.textToDiagram")})})};AP.displayName="TTDDialogTrigger";function gJ(e){let t=e.get("X-Ratelimit-Limit"),o=e.get("X-Ratelimit-Remaining");return{rateLimit:t?parseInt(t,10):void 0,rateLimitRemaining:o?parseInt(o,10):void 0}}async function*gE(e){let t=new TextDecoder,o="";try{for(;;){let{done:n,value:r}=await e.read();if(n)break;o+=t.decode(r,{stream:!0});let i=o.split(`
217
+ `);o=i.pop()||"";for(let a of i){let s=a.trim();s&&s.startsWith("data: ")&&(yield s.slice(6))}}}finally{e.releaseLock()}}async function hJ(e){let{url:t,messages:o,onChunk:n,onStreamCreated:r,extractRateLimits:i=!0,signal:a}=e;try{let s="",l={},c=null,m=await fetch(t,{method:"POST",headers:{Accept:"text/event-stream","Content-Type":"application/json"},body:JSON.stringify({messages:o}),signal:a});if(i&&(l=gJ(m.headers)),!m.ok){if(m.status===429)return{...l,error:new Sn({message:"Rate limit exceeded",status:429})};let d=await m.text();throw new Sn({message:d||"Generation failed...",status:m.status})}let p=m.body?.getReader();if(!p)throw new Sn({message:"Couldn't get reader from response body",status:500});r?.();try{for await(let d of gE(p)){if(d==="[DONE]")break;try{let u=JSON.parse(d);if(u===null)break;switch(u.type){case"content":{let h=u.delta;h&&(s+=h,n?.(h));break}case"error":c=new Sn({message:u.error.message,status:500});break;case"done":break}}catch(u){console.warn("Failed to parse SSE data:",d,u)}}}catch(d){d.name==="AbortError"?c=new Sn({message:"Request aborted",status:499}):c=new Sn({message:d.message||"Streaming error",status:500})}return c?{...l,error:c}:s?{generatedResponse:s,error:null,...l}:{...l,error:new Sn({message:"Generation failed...",status:m.status})}}catch(s){return s.name==="AbortError"?{error:new Sn({message:"Request aborted",status:499})}:{error:new Sn({message:s.message||"Request failed",status:500})}}}import{getCommonBounds as uqe,getVisibleSceneBounds as gqe,convertToExcalidrawElements as WS}from"@orangecatai/element";import{useLayoutEffect as fJ}from"react";var bJ=e=>{let t=Qe();return fJ(()=>{t.setPlugins({diagramToCode:{generate:e.generate}})},[t,e.generate]),null};import{isElementLink as Eqe}from"@orangecatai/element";import{setCustomTextMetricsProvider as wqe}from"@orangecatai/element";import oQ,{useCallback as Io,useEffect as CE,useImperativeHandle as nQ,useMemo as rQ,useRef as an,useState as It}from"react";import{ArrowUp as iQ,AtSign as lA,Check as cA,ChevronDown as aQ,ChevronRight as sQ,Copy as dA,Globe as lQ,MessageSquare as mA,Mic as cQ,MicOff as dQ,Paperclip as kE,Plus as pA,Search as mQ,Wrench as pQ,X as SE}from"lucide-react";import{nanoid as LP}from"nanoid";import{newFrameElement as xJ,newElement as zg,newTextElement as _P,newImageElement as DP,getFrameChildren as Dl,isFrameLikeElement as hE,syncMovedIndices as Rl}from"@orangecatai/element";import{FRAME_STYLE as EJ,arrayToMap as Nl}from"@orangecatai/common";var RP=[{type:"function",function:{name:"create_frame",description:"Create a new frame on the canvas. Frames act as artboards that clip their children. Default size is 512x512.",parameters:{type:"object",properties:{width:{type:"number",description:"Frame width in pixels (default 512)"},height:{type:"number",description:"Frame height in pixels (default 512)"},name:{type:"string",description:"Optional display name for the frame"}},required:[],additionalProperties:!1}}},{type:"function",function:{name:"add_rectangle",description:"Add a filled rectangle inside a frame. Commonly used for solid background fills behind images and text.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the parent frame"},x:{type:"number",description:"X position relative to canvas (use the frame's x for full coverage)"},y:{type:"number",description:"Y position relative to canvas (use the frame's y for full coverage)"},width:{type:"number",description:"Rectangle width in pixels"},height:{type:"number",description:"Rectangle height in pixels"},backgroundColor:{type:"string",description:'Fill color as hex string e.g. "#1a1a2e". Use "transparent" for no fill.'},fillStyle:{type:"string",enum:["solid","hachure","cross-hatch"],description:'Fill style (default "solid")'},strokeColor:{type:"string",description:'Stroke/border color as hex (default "transparent")'},strokeWidth:{type:"number",description:"Stroke width in pixels (default 0)"},opacity:{type:"number",description:"Opacity 0-100 (default 100)"}},required:["frameId","x","y","width","height","backgroundColor"],additionalProperties:!1}}},{type:"function",function:{name:"add_text",description:"Add a text element inside a frame. Use for headlines, subheads, body copy, CTAs etc.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the parent frame"},x:{type:"number",description:"X position (canvas coordinates)"},y:{type:"number",description:"Y position (canvas coordinates)"},text:{type:"string",description:"The text content"},fontSize:{type:"number",description:"Font size in pixels (default 20)"},fontFamily:{type:"number",enum:[1,2,3,4,5],description:"Font family: 1=Excalifont(hand), 2=Nunito(sans), 3=Comic Shanns(code), 4=Liberation Sans(clean sans), 5=Cascadia(code). Default 2."},strokeColor:{type:"string",description:'Text color as hex string (default "#000000")'},textAlign:{type:"string",enum:["left","center","right"],description:"Horizontal alignment (default left)"},width:{type:"number",description:"Optional fixed width for text wrapping"}},required:["frameId","x","y","text"],additionalProperties:!1}}},{type:"function",function:{name:"generate_image",description:"Generate an image using AI (Gemini) from a text prompt and place it inside a frame. Use for hero images, product shots, backgrounds, illustrations etc.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the parent frame to insert the image into"},prompt:{type:"string",description:"Detailed image generation prompt describing what to create"},x:{type:"number",description:"X position for the image (canvas coordinates)"},y:{type:"number",description:"Y position for the image (canvas coordinates)"},width:{type:"number",description:"Image width in pixels"},height:{type:"number",description:"Image height in pixels"}},required:["frameId","prompt","x","y","width","height"],additionalProperties:!1}}},{type:"function",function:{name:"update_element",description:"Update properties of an existing element (move, resize, recolor, change text, etc.)",parameters:{type:"object",properties:{elementId:{type:"string",description:"ID of the element to update"},x:{type:"number",description:"New X position"},y:{type:"number",description:"New Y position"},width:{type:"number",description:"New width"},height:{type:"number",description:"New height"},backgroundColor:{type:"string",description:"New background/fill color"},strokeColor:{type:"string",description:"New stroke/text color"},opacity:{type:"number",description:"New opacity 0-100"},fontSize:{type:"number",description:"New font size (text elements only)"},text:{type:"string",description:"New text content (text elements only)"},fillStyle:{type:"string",enum:["solid","hachure","cross-hatch"],description:"New fill style"}},required:["elementId"],additionalProperties:!1}}},{type:"function",function:{name:"delete_element",description:"Delete an element from the canvas",parameters:{type:"object",properties:{elementId:{type:"string",description:"ID of the element to delete"}},required:["elementId"],additionalProperties:!1}}},{type:"function",function:{name:"get_frame_elements",description:"Get all child elements inside a frame. Returns their IDs, types, positions, sizes, colors, and text content. Use this to understand the current layout before making changes.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the frame to inspect"}},required:["frameId"],additionalProperties:!1}}}];var NP=[{type:"function",function:{name:"create_frame",description:"Create a new frame on the canvas to act as the root container for your banner. Default size is 512x512. ALWAYS call this FIRST before generating images or HTML.",parameters:{type:"object",properties:{width:{type:"number",description:"Frame width in pixels (default 512)"},height:{type:"number",description:"Frame height in pixels (default 512)"},name:{type:"string",description:"Optional display name for the frame"}},required:[],additionalProperties:!1}}},{type:"function",function:{name:"generate_image",description:"Generate an image using AI (Gemini) and place it onto the canvas. Always call this for any photo or image content \u2014 even when the user has attached a reference image. The attached image is passed to Gemini as visual reference; Gemini generates the final output. Use referenceImageIndex to tell Gemini which user attachment to reference. IMPORTANT: your prompt must describe a purely visual scene \u2014 NO text, NO typography, NO words, NO captions, NO watermarks. All copy is handled by the HTML layer. A 'no text' safety suffix will be auto-appended, but you must also describe composition clearly (e.g. which side should be left open/empty for the HTML text).",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the parent frame to insert the image into"},prompt:{type:"string",description:"Detailed generation prompt. When using a reference image, describe what you want Gemini to produce \u2014 e.g. 'use this building as the subject, wide cinematic crop with open sky on the left for text overlay'."},x:{type:"number",description:"X position relative to the frame's top-left corner"},y:{type:"number",description:"Y position relative to the frame's top-left corner"},width:{type:"number",description:"Image width in pixels"},height:{type:"number",description:"Image height in pixels"},referenceImageIndex:{type:"number",description:"0-based index of the user's attached image to pass to Gemini as reference. Always use 0 when the user has attached an image."}},required:["frameId","prompt","x","y","width","height"],additionalProperties:!1}}},{type:"function",function:{name:"generate_html_banner",description:"Place HTML/CSS text and shape elements into an EXISTING frame on the canvas. Always call create_frame first to get a frameId, then generate_image, then call this with that frameId. frameId is required \u2014 this tool does NOT create frames.",parameters:{type:"object",properties:{html:{type:"string",description:"Complete self-contained HTML with inline <style>. All layer elements must use position:absolute with explicit left/top/width/height in px. Root div must have class='canvas'."},frameId:{type:"string",description:"Required. The ID of the frame created by create_frame. Adds HTML elements into this existing frame, preserving existing children like images."}},required:["html","frameId"],additionalProperties:!1}}},{type:"function",function:{name:"get_frame_elements",description:"Get all child elements inside a frame. Use when editing an existing banner to understand its current state before replacing.",parameters:{type:"object",properties:{frameId:{type:"string",description:"ID of the frame to inspect"}},required:["frameId"],additionalProperties:!1}}},{type:"function",function:{name:"update_element",description:"Update properties of an existing element. Use for minor targeted fixes after the banner is placed.",parameters:{type:"object",properties:{elementId:{type:"string"},x:{type:"number"},y:{type:"number"},width:{type:"number"},height:{type:"number"},backgroundColor:{type:"string"},strokeColor:{type:"string"},opacity:{type:"number"},fontSize:{type:"number"},text:{type:"string"},fillStyle:{type:"string",enum:["solid","hachure","cross-hatch"]}},required:["elementId"],additionalProperties:!1}}},{type:"function",function:{name:"delete_element",description:"Delete an element from the canvas.",parameters:{type:"object",properties:{elementId:{type:"string",description:"ID of the element to delete"}},required:["elementId"],additionalProperties:!1}}}];function fE(e){let t={id:e.id,type:e.type,x:Math.round(e.x),y:Math.round(e.y),width:Math.round(e.width),height:Math.round(e.height)};if(e.backgroundColor&&e.backgroundColor!=="transparent"&&(t.backgroundColor=e.backgroundColor),e.strokeColor&&e.strokeColor!=="#1e1e1e"&&(t.strokeColor=e.strokeColor),e.opacity!==100&&(t.opacity=e.opacity),e.fillStyle&&e.fillStyle!=="solid"&&(t.fillStyle=e.fillStyle),e.type==="text"){let o=e;t.text=o.text,t.fontSize=o.fontSize,t.fontFamily=o.fontFamily,t.textAlign=o.textAlign}if(e.type==="image"&&(t.type="image"),e.type==="frame"){let o=e;o.name&&(t.name=o.name)}return t}function BP(e){return e.map(fE)}function FP(e){let t=e.getSceneElements(),o=[];for(let n of t)if(hE(n)){let r=Dl(t,n.id),i=n;o.push({id:n.id,name:i.name||`Frame ${Math.round(n.width)}\xD7${Math.round(n.height)}`,width:Math.round(n.width),height:Math.round(n.height),childCount:r.length})}return o}async function Gd(e,t){let o=e.getSceneElements(),n=o.find(s=>s.id===t);if(!n||!hE(n))return null;let r=e.getAppState(),i=e.getFiles(),a=Dl(o,t);try{return(await Ba([...a,n],r,i,{exportBackground:!0,viewBackgroundColor:r.viewBackgroundColor,exportingFrame:n,exportPadding:0})).toDataURL("image/jpeg",.7)}catch{return null}}function OP(e,t){let o=e.getSceneElements(),n=o.find(l=>l.id===t);if(!n||!hE(n))return null;let r=Dl(o,t),i=n,a={id:n.id,name:i.name||`Frame ${Math.round(n.width)}\xD7${Math.round(n.height)}`,width:Math.round(n.width),height:Math.round(n.height),childCount:r.length},s={frame:fE(n),children:BP(r)};return{serialized:JSON.stringify(s,null,2),frameInfo:a}}async function zP(e,t,o){let n;try{n=JSON.parse(t)}catch{return{success:!1,error:"Invalid JSON arguments",statusMessage:"Failed to parse tool arguments"}}switch(e){case"create_frame":return vJ(n,o);case"add_rectangle":return IJ(n,o);case"add_text":return TJ(n,o);case"generate_image":return CJ(n,o);case"update_element":return kJ(n,o);case"delete_element":return SJ(n,o);case"get_frame_elements":return MJ(n,o);case"generate_html_banner":return PJ(n,o);default:return{success:!1,error:`Unknown tool: ${e}`,statusMessage:`Unknown tool: ${e}`}}}function yJ(e){let t=e.getAppState(),o=-t.scrollX+t.width/2/t.zoom.value,n=-t.scrollY+t.height/2/t.zoom.value;return{x:o,y:n}}var Og=10;function wJ(e,t,o,n,r){return Math.abs(e-r.x)<Og&&Math.abs(t-r.y)<Og&&Math.abs(o-r.width)<Og&&Math.abs(n-r.height)<Og}function HP(e,t,o,n,r,i){return e==="text"?3:e==="image"?1:wJ(t,o,n,r,i)?0:2}function bE(e,t,o){let n=e[t],r=n.id,i=t+1;for(let a=t+1;a<e.length;a++){let s=e[a];if(s.frameId!==r)continue;if(HP(s.type,s.x,s.y,s.width,s.height,n)>o)return a;i=a+1}return i}function vJ(e,t){let o=e.width||512,n=e.height||512,r=e.name||null,i=yJ(t.excalidrawAPI),a=xJ({...EJ,x:i.x-o/2,y:i.y-n/2,width:o,height:n,opacity:100,locked:!1,name:r??void 0}),l=[...t.excalidrawAPI.getSceneElements(),a];return Rl(l,Nl([a])),t.excalidrawAPI.updateScene({elements:l}),t.excalidrawAPI.scrollToContent(a,{fitToViewport:!1}),{success:!0,data:{frameId:a.id,x:Math.round(a.x),y:Math.round(a.y),width:o,height:n},statusMessage:`Created frame "${r||"Ad Frame"}" (${o}\xD7${n})`}}function IJ(e,t){let o=e.frameId;if(!o)return{success:!1,error:"frameId is required",statusMessage:"Failed: missing frameId"};let n=zg({type:"rectangle",x:e.x,y:e.y,width:e.width,height:e.height,backgroundColor:e.backgroundColor||"transparent",fillStyle:e.fillStyle||"solid",strokeColor:e.strokeColor||"transparent",strokeWidth:e.strokeWidth??0,opacity:e.opacity??100}),r=t.excalidrawAPI.getSceneElements(),i=r.findIndex(d=>d.id===o);if(i===-1)return{success:!1,error:`Frame ${o} not found`,statusMessage:"Failed: frame not found"};let a=r[i],s=HP("rectangle",e.x,e.y,e.width,e.height,a),l={...n,frameId:o},c=[...r],m=bE(c,i,s);c.splice(m,0,l),Rl(c,Nl([l])),t.excalidrawAPI.updateScene({elements:c});let p=s===0;return{success:!0,data:{elementId:n.id,type:"rectangle",x:Math.round(n.x),y:Math.round(n.y),width:Math.round(n.width),height:Math.round(n.height),backgroundColor:n.backgroundColor,isBackground:p},statusMessage:`Added ${p?"background ":""}rectangle (${Math.round(n.width)}\xD7${Math.round(n.height)}) with fill ${n.backgroundColor}`}}function TJ(e,t){let o=e.frameId;if(!o)return{success:!1,error:"frameId is required",statusMessage:"Failed: missing frameId"};let n=_P({x:e.x,y:e.y,text:e.text,fontSize:e.fontSize||20,fontFamily:e.fontFamily||2,strokeColor:e.strokeColor||"#000000",textAlign:e.textAlign||"left",width:e.width}),r=t.excalidrawAPI.getSceneElements(),i=r.findIndex(c=>c.id===o);if(i===-1)return{success:!1,error:`Frame ${o} not found`,statusMessage:"Failed: frame not found"};let a={...n,frameId:o},s=[...r],l=bE(s,i,3);return s.splice(l,0,a),Rl(s,Nl([a])),t.excalidrawAPI.updateScene({elements:s}),{success:!0,data:{elementId:n.id,type:"text",x:Math.round(n.x),y:Math.round(n.y),text:e.text,fontSize:e.fontSize||20},statusMessage:`Added text "${e.text.slice(0,40)}${e.text.length>40?"\u2026":""}"`}}async function CJ(e,t){let o=e.frameId,n=e.prompt,r=e.x,i=e.y,a=e.width,s=e.height,l=e.referenceImageIndex,c=l!==void 0?t.fileAttachments?.[l]?.dataUrl:void 0,m=`${n} \u2014 NO text, NO typography, NO words, NO captions, NO watermarks, NO overlaid copy. Pure clean visual image only.`;if(!o||!n)return{success:!1,error:"frameId and prompt are required",statusMessage:"Failed: missing required parameters"};if(!t.geminiApiKey)return{success:!1,error:"No Gemini API key configured. Set geminiApiKey prop or VITE_APP_GEMINI_API_KEY.",statusMessage:"Failed: no Gemini API key"};let p=t.excalidrawAPI.getSceneElements(),d=p.findIndex(x=>x.id===o);if(d===-1)return{success:!1,error:`Frame ${o} not found`,statusMessage:"Failed: frame not found"};let u=p[d],h=r<u.width&&i<u.height&&Math.abs(r-u.x)>50,g=h?u.x+r:r,E=h?u.y+i:i,w=a>=s?a/s>1.3?"16:9":"1:1":"9:16";try{let x=await ua(m,t.agentImageModel||"gemini-3.1-flash-image-preview",w,"1K",!1,!1,t.geminiApiKey,c,t.signal);if(t.signal?.aborted)return{success:!1,error:"Cancelled",statusMessage:"Image generation cancelled"};let y=LP(),v=DP({type:"image",x:g,y:E,width:a,height:s,fileId:y,status:"pending",scale:[1,1]}),I=t.excalidrawAPI.getSceneElements(),k=I.findIndex(P=>P.id===o);if(k===-1)return{success:!1,error:`Frame ${o} was removed during image generation`,statusMessage:"Failed: frame no longer exists"};let L={...v,frameId:o},S=[...I],_=bE(S,k,1);return S.splice(_,0,L),Rl(S,Nl([L])),t.excalidrawAPI.updateScene({elements:S}),t.excalidrawAPI.addFiles([{id:y,dataURL:x,mimeType:Bo(x),created:Date.now(),lastRetrieved:Date.now()}]),{success:!0,data:{elementId:v.id,frameId:L.frameId,type:"image",x:Math.round(g),y:Math.round(E),width:Math.round(a),height:Math.round(s)},statusMessage:`Generated image from prompt "${n.slice(0,50)}${n.length>50?"\u2026":""}"`}}catch(x){let y=x instanceof Error?x.message:"Image generation failed";return{success:!1,error:y,statusMessage:`Image generation failed: ${y}`}}}function kJ(e,t){let o=e.elementId;if(!o)return{success:!1,error:"elementId is required",statusMessage:"Failed: missing elementId"};let r=t.excalidrawAPI.getSceneElements().find(s=>s.id===o);if(!r)return{success:!1,error:`Element ${o} not found`,statusMessage:"Failed: element not found"};let i={},a=["x","y","width","height","backgroundColor","strokeColor","opacity","fontSize","text","fillStyle"];for(let s of a)e[s]!==void 0&&(i[s]=e[s]);return Object.keys(i).length===0?{success:!1,error:"No valid properties to update",statusMessage:"Failed: nothing to update"}:i.text!==void 0&&r.type==="text"&&(i.width===void 0||i.height===void 0)?{success:!1,error:"Updating text content requires providing new width and height to avoid clipping.",statusMessage:"Failed: text update requires width and height"}:(t.excalidrawAPI.mutateElement(r,i),{success:!0,data:{elementId:o,updated:Object.keys(i)},statusMessage:`Updated element (${Object.keys(i).join(", ")})`})}function SJ(e,t){let o=e.elementId;if(!o)return{success:!1,error:"elementId is required",statusMessage:"Failed: missing elementId"};let r=t.excalidrawAPI.getSceneElements().find(i=>i.id===o);return r?(t.excalidrawAPI.mutateElement(r,{isDeleted:!0}),{success:!0,data:{elementId:o},statusMessage:`Deleted element ${o}`}):{success:!1,error:`Element ${o} not found`,statusMessage:"Failed: element not found"}}function MJ(e,t){let o=e.frameId;if(!o)return{success:!1,error:"frameId is required",statusMessage:"Failed: missing frameId"};let n=t.excalidrawAPI.getSceneElements(),r=n.find(s=>s.id===o);if(!r)return{success:!1,error:`Frame ${o} not found`,statusMessage:"Failed: frame not found"};let i=Dl(n,o),a=BP(i);return{success:!0,data:{frameId:o,frame:fE(r),children:a,childCount:a.length},statusMessage:`Found ${a.length} elements in frame`}}async function PJ(e,t){let o=e.html,n=e.frameId;if(!o||typeof o!="string")return{success:!1,error:"html is required",statusMessage:"Failed: missing html"};if(!n)return{success:!1,error:"frameId is required. Call create_frame first to get a frameId, then generate_image with that frameId, then call generate_html_banner with that frameId.",statusMessage:"Failed: frameId is required"};let r=t.excalidrawAPI.getSceneElements(),i=r.find(T=>T.id===n);if(!i)return{success:!1,error:`Frame ${n} not found`,statusMessage:"Failed: frame not found"};let a=i,s=a.x,l=a.y,c=Math.round(a.width),m=Math.round(a.height),d=Dl(r,n).filter(T=>T.customData?.generatedByHtml===!0);for(let T of d)t.excalidrawAPI.mutateElement(T,{isDeleted:!0});let u;try{u=await xu(o,s,l,c,m,t.customFontMap)}catch(T){let M=T instanceof Error?T.message:"HTML parse failed";return{success:!1,error:M,statusMessage:`HTML banner parse failed: ${M}`}}if(u.length===0){let T=o.match(/\.(?:bg|canvas)[^{]*\{[^}]*background(?:-color)?:\s*(#[0-9a-fA-F]{3,8}|rgba?\([^)]+\))/),M=T?T[1]:null;if(M){let N=zg({type:"rectangle",x:s,y:l,width:c,height:m,backgroundColor:M.startsWith("#")?M:"#ffffff",fillStyle:"solid",strokeColor:"transparent",strokeWidth:0,opacity:100,roughness:0,customData:{generatedByHtml:!0}}),B=[...t.excalidrawAPI.getSceneElements(),N];Rl(B,Nl([N])),t.excalidrawAPI.updateScene({elements:B})}return{success:!1,error:"Parser produced no elements \u2014 check HTML structure. Try simpler HTML: fewer elements, explicit px values for all positions, no nested divs.",statusMessage:"Failed: no elements parsed from HTML"}}let h=[],g=[];for(let T of u)if(T.kind==="rectangle"){let M=zg({type:"rectangle",x:T.x,y:T.y,width:T.width,height:T.height,backgroundColor:T.backgroundColor,fillStyle:"solid",strokeColor:T.strokeColor,strokeWidth:T.strokeWidth,opacity:T.opacity,roughness:0,...T.borderRadius>0?{roundness:{type:3,value:T.borderRadius}}:{},customData:{generatedByHtml:!0}});h.push({...M,frameId:a.id})}else if(T.kind==="ellipse"){let M=zg({type:"ellipse",x:T.x,y:T.y,width:T.width,height:T.height,backgroundColor:T.backgroundColor,fillStyle:"solid",strokeColor:T.strokeColor,strokeWidth:T.strokeWidth,opacity:T.opacity,roughness:0});h.push({...M,frameId:a.id})}else if(T.kind==="text"){let M=_P({x:T.x,y:T.y,text:T.text,fontSize:T.fontSize,fontFamily:T.fontFamily,strokeColor:T.color,textAlign:T.textAlign,width:T.width,opacity:T.opacity,roughness:0,customData:{generatedByHtml:!0}});h.push({...M,frameId:a.id})}else if(T.kind==="image"){let M=LP(),N=DP({type:"image",x:T.x,y:T.y,width:T.width,height:T.height,fileId:M,status:"pending",scale:[1,1],customData:{generatedByHtml:!0}});h.push({...N,frameId:a.id}),g.push({id:M,dataURL:T.dataUrl,mimeType:Bo(T.dataUrl),created:Date.now(),lastRetrieved:Date.now()})}let E=c*m,w=[],x=[];for(let T of h)T.type==="rectangle"&&T.width*T.height>=E*.25?w.push(T):x.push(T);let y=t.excalidrawAPI.getSceneElements(),v=y.findIndex(T=>T.id===a.id),I=Dl(y,a.id),k=I.length>0?y.findIndex(T=>T.id===I[0].id):v+1,L=I.length>0?y.findIndex(T=>T.id===I[I.length-1].id)+1:v+1,S=[...y.slice(0,k),...w,...y.slice(k,L),...x,...y.slice(L)],_=[...w,...x];Rl(S,Nl(_)),t.excalidrawAPI.updateScene({elements:S}),g.length>0&&t.excalidrawAPI.addFiles(g),t.excalidrawAPI.scrollToContent(a,{fitToViewport:!1});let P=await Gd(t.excalidrawAPI,a.id);return{success:!0,data:{frameId:a.id,x:Math.round(s),y:Math.round(l),width:c,height:m,elementCount:h.length,screenshot:P??void 0},statusMessage:`Banner updated: ${h.length} elements in frame "${e.name||"Banner"}" (${c}\xD7${m})`,screenshot:P??void 0}}function AJ(e){try{let o=JSON.parse(e)?.choices?.[0];return o?{content:o.delta?.content??null,toolCalls:o.delta?.tool_calls??null,finishReason:o.finish_reason??null}:null}catch{return null}}async function*Hg(e){let t=e.body?.getReader();if(t)for await(let o of gE(t)){if(o==="[DONE]")break;let n=AJ(o);n&&(yield n)}}function GP(e,t){if(!t.toolCalls)return e;for(let o of t.toolCalls){let n=o.index;if(n>=e.length||o.id){for(;e.length<=n;)e.push({id:"",type:"function",function:{name:"",arguments:""}});e[n]={id:o.id||e[n].id,type:"function",function:{name:o.function?.name||e[n].function.name,arguments:o.function?.arguments||""}}}else o.function?.arguments&&(e[n].function.arguments+=o.function.arguments),o.function?.name&&(e[n].function.name=o.function.name)}return e}function UP(e){return e.filter(t=>t.id&&t.function.name).map(t=>({id:t.id,type:"function",function:{name:t.function.name,arguments:t.function.arguments}}))}function Gg(e){return e.body?(e.headers.get("content-type")||"").includes("text/event-stream"):!1}var LJ=`You are an expert HTML/CSS banner designer embedded inside a canvas editor. You create beautiful advertisement banners by writing clean, self-contained HTML/CSS code. Your HTML is parsed by a DOM renderer that converts each element into individually editable canvas elements \u2014 so you must follow the layout rules strictly.
218
218
 
219
219
  ## Your Workflow
220
220
 
@@ -430,10 +430,10 @@ Call generate_html_banner NOW with frameId="${_.frameId}". Your HTML must place
430
430
  - If image fills full frame (x=0, y=0): text floats on top \u2014 use the composition to place text in the open/clear zone described in your image prompt. Do NOT add a background div.
431
431
  - A full-frame background rectangle IS allowed only for Pattern A (solid color zone behind text). Never for Pattern B.
432
432
 
433
- **ZONE-FILL REMINDER:** For structured layouts (Pattern A), the image must completely fill its designated zone with no accidental gaps. If the image is in a split layout (occupying a half or side of the frame), it should span the full height and width of that zone \u2014 no random thin strips of empty space. If it's a centered/inset product shot, deliberate padding is fine but the dimensions should be intentional.`}),I.push({role:"user",content:V})}}}let T="I've completed the available operations. Let me know if you'd like any adjustments!";return m({type:"final",message:T}),{reply:T,toolActions:k}}function NJ(e,t){switch(e){case"generate_html_banner":{let o=t.width||512,n=t.height||512;return`Generating HTML banner (${o}\xD7${n}) and placing on canvas\u2026`}case"create_frame":return`Creating frame (${t.width||512}\xD7${t.height||512})\u2026`;case"add_rectangle":return"Adding background rectangle\u2026";case"add_text":return`Adding text "${String(t.text||"").slice(0,30)}"\u2026`;case"generate_image":return"Generating image \u2014 this may take a moment\u2026";case"update_element":return"Updating element\u2026";case"delete_element":return"Deleting element\u2026";case"get_frame_elements":return"Inspecting frame contents\u2026";default:return`Running ${e}\u2026`}}async function VP(e){let t=await e.arrayBuffer(),o=new AudioContext,n=await o.decodeAudioData(t);await o.close();let r=n.numberOfChannels,i=n.sampleRate,a=n.length,s=2,l=a*r*s,c=44+l,m=new ArrayBuffer(c),p=new DataView(m),d=(w,x)=>{for(let y=0;y<x.length;y++)p.setUint8(w+y,x.charCodeAt(y))};d(0,"RIFF"),p.setUint32(4,36+l,!0),d(8,"WAVE"),d(12,"fmt "),p.setUint32(16,16,!0),p.setUint16(20,1,!0),p.setUint16(22,r,!0),p.setUint32(24,i,!0),p.setUint32(28,i*r*s,!0),p.setUint16(32,r*s,!0),p.setUint16(34,16,!0),d(36,"data"),p.setUint32(40,l,!0);let u=44;for(let w=0;w<a;w++)for(let x=0;x<r;x++){let y=n.getChannelData(x)[w],v=Math.max(-1,Math.min(1,y)),I=v<0?v*32768:v*32767;p.setInt16(u,I,!0),u+=2}let h=new Uint8Array(m),g=8192,E="";for(let w=0;w<h.length;w+=g)E+=String.fromCharCode(...h.subarray(w,w+g));return btoa(E)}async function $P(e,t,o,n){let r=n||"mistralai/voxtral-small-24b-2507",i=await fetch("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({model:r,messages:[{role:"user",content:[{type:"text",text:"Transcribe this audio. Return only the transcription text, nothing else."},{type:"input_audio",input_audio:{data:e,format:t}}]}]})});if(!i.ok){let s=`Transcription error ${i.status}`;try{let l=await i.json();l?.error?.message&&(s=l.error.message)}catch{}throw new Error(s)}return(await i.json())?.choices?.[0]?.message?.content||""}import{StickToBottom as KP}from"use-stick-to-bottom";import{jsx as jP}from"react/jsx-runtime";function XP({children:e,className:t,...o}){return jP(KP,{className:Ze("flex overflow-y-auto",t),resize:"smooth",initial:"instant",role:"log",...o,children:e})}function ZP({children:e,className:t,...o}){return jP(KP.Content,{className:Ze("flex w-full flex-col",t),...o,children:e})}import{marked as zJ}from"marked";import{memo as QP,useId as HJ,useMemo as GJ}from"react";import UJ from"react-markdown";import WJ from"remark-breaks";import YJ from"remark-gfm";import{useEffect as BJ,useState as FJ}from"react";import{codeToHtml as OJ}from"shiki";import{jsx as Ud}from"react/jsx-runtime";function qP({children:e,className:t,...o}){return Ud("div",{className:Ze("not-prose flex w-full flex-col overflow-clip border","border-zinc-200 bg-white text-zinc-950 rounded-xl dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50",t),...o,children:e})}function JP({code:e,language:t="tsx",theme:o="github-light",className:n,...r}){let[i,a]=FJ(null);BJ(()=>{async function l(){if(!e){a("<pre><code></code></pre>");return}let c=await OJ(e,{lang:t,theme:o});a(c)}l()},[e,t,o]);let s=Ze("w-full overflow-x-auto text-[13px] [&>pre]:px-4 [&>pre]:py-4",n);return i?Ud("div",{className:s,dangerouslySetInnerHTML:{__html:i},...r}):Ud("div",{className:s,...r,children:Ud("pre",{children:Ud("code",{children:e})})})}import{Fragment as XJ,jsx as ka}from"react/jsx-runtime";function VJ(e){return zJ.lexer(e).map(o=>o.raw)}function $J(e){if(!e)return"plaintext";let t=e.match(/language-(\w+)/);return t?t[1]:"plaintext"}var eA={code:function({className:t,children:o,...n}){if(!n.node?.position?.start.line||n.node?.position?.start.line===n.node?.position?.end.line)return ka("span",{className:Ze("bg-zinc-50 rounded-sm px-1 font-mono text-sm dark:bg-zinc-900",t),...n,children:o});let i=$J(t);return ka(qP,{className:t,children:ka(JP,{code:o,language:i})})},pre:function({children:t}){return ka(XJ,{children:t})}},tA=QP(({content:e,components:t=eA})=>ka(UJ,{remarkPlugins:[YJ,WJ],components:t,children:e}),(e,t)=>e.content===t.content);tA.displayName="MemoizedMarkdownBlock";function KJ({children:e,id:t,className:o,components:n=eA}){let r=HJ(),i=t??r,a=GJ(()=>VJ(e),[e]);return ka("div",{className:o,children:a.map((s,l)=>ka(tA,{content:s,components:n},`${i}-block-${l}`))})}var xE=QP(KJ);xE.displayName="Markdown";import*as Ug from"react";import*as _r from"@radix-ui/react-avatar";import{jsx as EE}from"react/jsx-runtime";var oA=Ug.forwardRef(({className:e,...t},o)=>EE(_r.Root,{ref:o,className:Ze("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));oA.displayName=_r.Root.displayName;var nA=Ug.forwardRef(({className:e,...t},o)=>EE(_r.Image,{ref:o,className:Ze("aspect-square h-full w-full",e),...t}));nA.displayName=_r.Image.displayName;var rA=Ug.forwardRef(({className:e,...t},o)=>EE(_r.Fallback,{ref:o,className:Ze("flex h-full w-full items-center justify-center rounded-full bg-zinc-100 dark:bg-zinc-800",e),...t}));rA.displayName=_r.Fallback.displayName;import{jsx as Sa,jsxs as ZJ}from"react/jsx-runtime";var yE=({children:e,className:t,...o})=>Sa("div",{className:Ze("flex gap-3",t),...o,children:e});var wE=({children:e,markdown:t=!1,className:o,...n})=>{let r=Ze("rounded-lg p-2 text-zinc-950 bg-zinc-100 prose break-words whitespace-normal dark:text-zinc-50 dark:bg-zinc-800",o);return t?Sa(xE,{className:r,...n,children:e}):Sa("div",{className:r,...n,children:e})},vE=({children:e,className:t,...o})=>Sa("div",{className:Ze("text-zinc-500 flex items-center gap-2 dark:text-zinc-400",t),...o,children:e}),IE=({tooltip:e,children:t,className:o,side:n="top",...r})=>Sa(hu,{children:ZJ(fu,{...r,children:[Sa(bu,{asChild:!0,children:t}),Sa(td,{side:n,className:o,children:e})]})});import{ChevronDown as eQ}from"lucide-react";import{useStickToBottomContext as tQ}from"use-stick-to-bottom";import*as iA from"react";import{Slot as jJ}from"@radix-ui/react-slot";import{cva as qJ}from"class-variance-authority";import{jsx as QJ}from"react/jsx-runtime";var JJ=qJ("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-950 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 dark:focus-visible:ring-zinc-300",{variants:{variant:{default:"bg-zinc-900 text-zinc-50 shadow hover:bg-zinc-900/90 dark:bg-zinc-50 dark:text-zinc-900 dark:hover:bg-zinc-50/90",destructive:"bg-red-500 text-zinc-50 shadow-sm hover:bg-red-500/90 dark:bg-red-900 dark:text-zinc-50 dark:hover:bg-red-900/90",outline:"border border-zinc-200 bg-white shadow-sm hover:bg-zinc-100 hover:text-zinc-900 dark:border-zinc-800 dark:bg-zinc-950 dark:hover:bg-zinc-800 dark:hover:text-zinc-50",secondary:"bg-zinc-100 text-zinc-900 shadow-sm hover:bg-zinc-100/80 dark:bg-zinc-800 dark:text-zinc-50 dark:hover:bg-zinc-800/80",ghost:"hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-50",link:"text-zinc-900 underline-offset-4 hover:underline dark:text-zinc-50"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),TE=iA.forwardRef(({className:e,variant:t,size:o,asChild:n=!1,...r},i)=>QJ(n?jJ:"button",{className:Ze(JJ({variant:t,size:o,className:e})),ref:i,...r}));TE.displayName="Button";import{jsx as aA}from"react/jsx-runtime";function sA({className:e,variant:t="outline",size:o="sm",...n}){let{isAtBottom:r,scrollToBottom:i}=tQ();return aA(TE,{variant:t,size:o,className:Ze("h-10 w-10 rounded-full transition-all duration-150 ease-out",r?"pointer-events-none translate-y-4 scale-95 opacity-0":"translate-y-0 scale-100 opacity-100",e),onClick:()=>i(),...n,children:aA(eQ,{className:"h-5 w-5"})})}import{jsx as j,jsxs as Ae}from"react/jsx-runtime";function Bl(){return Math.random().toString(36).slice(2,10)}var Wg=3,uQ=10*1024*1024,gQ=["Create a pasta ad","Design a sale banner","Make a product showcase","Help me design"],uA=oQ.forwardRef(({isOpen:e,onClose:t,apiKey:o,excalidrawAPI:n,geminiApiKey:r,initialMessages:i,initialSessionId:a,initialSessions:s,onMessagesChange:l,onSessionCreate:c,onSessionSwitch:m,onBeforeSend:p,onAfterSend:d,onBeforeImageGen:u,onAfterImageGen:h,chatModel:g,voiceModel:E,agentImageModel:w,brandContext:x},y)=>{let[v,I]=Tt(""),[k,L]=Tt(!1),[S,_]=Tt(""),[P,T]=Tt(i??[]),[M,N]=Tt(s??[]),[O,B]=Tt(a??Bl),[U,D]=Tt(!1),[F,z]=Tt(""),[$,V]=Tt(null),[Q,ee]=Tt(null),[ie,Ee]=Tt(!1),[Le,De]=Tt([]),[We,lt]=Tt([]),[qt,rr]=Tt(!1),[In,lo]=Tt(!1),[Ct,xt]=Tt(!1),[To,Y]=Tt(!1),[te,Fe]=Tt(null),ft=an(null),Co=an(null),Dr=an(null),ir=an(null),Fl=an(null),Yg=an([]),Tn=an(""),Ma=an(!1),Vg=an(O),[fA,Pa]=Tt(!1),ar=an(!1),No=an(""),je=an(null),bA=rQ(()=>{let X=[];return x?.typography?.headline?.fontFamilyId&&X.push(x.typography.headline.fontFamilyId),x?.typography?.body?.fontFamilyId&&X.push(x.typography.body.fontFamilyId),X},[x]);CE(()=>{Vg.current=O},[O]),CE(()=>{let X=Pe=>{ft.current&&!ft.current.contains(Pe.target)&&D(!1),Dr.current&&!Dr.current.contains(Pe.target)&&Ee(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[]),CE(()=>{e||(Co.current?.abort(),je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="",ar.current=!1,Pa(!1))},[e]);let xA=(()=>{let X=M.find(Pe=>Pe.id===O)?.title;return X||(P.length>0?P[0].content.slice(0,30)+(P[0].content.length>30?"\u2026":""):"New chat")})(),Wd=Io(()=>{if(P.length===0)return;let X=P[0].content.slice(0,40)+(P[0].content.length>40?"\u2026":"");N(Pe=>{let Ye=Pe.findIndex(ze=>ze.id===O),Je={id:O,title:X,messages:P};if(Ye>=0){let ze=[...Pe];return ze[Ye]=Je,ze}return[Je,...Pe]})},[P,O]),PE=Io(()=>{Wd();let X=Bl();T([]),B(X),lo(!1),D(!1),V(null),I(""),ee(null),lt([]),_("")},[Wd]),EA=Io(X=>{Wd(),B(X.id),D(!1),V(null),X.messages.length>0?(T(X.messages),lo(!1)):(T([]),lo(!0),m&&m(X.id))},[Wd,m]),yA=Io(X=>{let Pe=Tn.current;I(X),Tn.current=X,n&&X.length>Pe.length&&X.endsWith("@")&&(De(FP(n)),Ee(!0))},[n]),wA=Io(async X=>{if(!n)return;Ee(!1),I(ze=>{let Ve=ze.lastIndexOf("@");return Ve>=0?ze.slice(0,Ve):ze});let Pe=Tn.current.lastIndexOf("@");Tn.current=Pe>=0?Tn.current.slice(0,Pe):Tn.current;let Ye=OP(n,X.id);if(!Ye)return;let Je=await Gd(n,X.id);ee({frameId:X.id,label:Ye.frameInfo.name,serialized:Ye.serialized,screenshot:Je??void 0})},[n]),vA=Io(()=>{ee(null)},[]),IA=Io(X=>{let Pe=X.target.files;if(!Pe)return;let Ye=Wg-We.length;if(Ye<=0)return;let Je=Array.from(Pe).slice(0,Ye);for(let ze of Je){if(ze.size>uQ){V(`"${ze.name}" is too large (max 10 MB).`);continue}let Ve=Bl(),co=ze.type.startsWith("image/"),mo=new FileReader;co?(mo.onload=()=>{lt(sn=>sn.length<Wg?[...sn,{id:Ve,file:ze,name:ze.name,type:"image",dataUrl:mo.result}]:sn)},mo.readAsDataURL(ze)):(mo.onload=()=>{lt(sn=>sn.length<Wg?[...sn,{id:Ve,file:ze,name:ze.name,type:"text",textContent:mo.result}]:sn)},mo.readAsText(ze))}ir.current&&(ir.current.value="")},[We.length]),TA=Io(X=>{lt(Pe=>Pe.filter(Ye=>Ye.id!==X))},[]),CA=Io(()=>{rr(X=>!X)},[]),kA=Io(async()=>{if(Ct){Fl.current?.stop(),xt(!1),Ma.current=!0;return}let X=null;try{X=await navigator.mediaDevices.getUserMedia({audio:!0});let Pe=MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4",Ye=new MediaRecorder(X,{mimeType:Pe});Fl.current=Ye,Yg.current=[],Ye.ondataavailable=Je=>{Je.data.size>0&&Yg.current.push(Je.data)},Ye.onstop=async()=>{X?.getTracks().forEach(Ve=>Ve.stop());let Je=new Blob(Yg.current,{type:Ye.mimeType}),ze=nd(o);if(!ze){V("No API key for voice transcription.");return}Y(!0),_("Transcribing\u2026");try{let Ve=await VP(Je),co=await $P(Ve,"wav",ze,E),mo=(Tn.current?`${Tn.current} `:"")+co;Tn.current=mo,I(mo)}catch(Ve){Ma.current=!1,V(Ve instanceof Error?Ve.message:"Transcription failed")}finally{Y(!1),_("")}},Ye.start(),xt(!0)}catch{X?.getTracks().forEach(Pe=>Pe.stop()),V("Could not access microphone. Check browser permissions.")}},[Ct,o]),AE=Io((X,Pe)=>{navigator.clipboard.writeText(Pe).then(()=>{Fe(X),setTimeout(()=>Fe(null),2e3)},()=>{V("Copy failed \u2014 please grant clipboard permission.")})},[]),Yd=Io(async X=>{let Pe=(X??v).trim(),Ye=nd(o);if(!Pe||k){Ma.current=!1;return}if(!Ye){Ma.current=!1,V("No OpenRouter API key. Set VITE_APP_OPENROUTER_API_KEY in .env or pass the key via the `apiKey` prop.");return}let Je=[...We],ze=qt,Ve=Q,co={id:Bl(),role:"user",content:Pe,timestamp:new Date,attachments:Je.length>0?Je.map(Wt=>({name:Wt.name,type:Wt.type,dataUrl:Wt.dataUrl})):void 0},mo=P.length===0,sn=P,Aa=[...P,co];T(Aa),I(""),Tn.current="",lt([]),ee(null),V(null);let Vd=new AbortController;Co.current=Vd,L(!0),_("Thinking\u2026");let $g=Ma.current;if(Ma.current=!1,p){let{allowed:Wt,error:Ol}=await p({hasVoice:$g});if(!Wt){T(sn),V(Ol||"Insufficient credits"),L(!1),_("");return}}if(!n){let Wt=Bl(),Ol={id:Wt,role:"assistant",content:"",timestamp:new Date},$d=[...Aa,Ol];T($d);try{let bt=await fQ(Aa,Ye,Vd.signal,{webSearchEnabled:ze,attachments:Je,chatModel:g,brandContext:x,onChunk:Di=>{ar.current||(ar.current=!0,Pa(!0),_("")),No.current+=Di,je.current||(je.current=requestAnimationFrame(()=>{let Kd=No.current;No.current="",je.current=null,T(PA=>{let zl=[...PA],DE=zl[zl.length-1];return zl[zl.length-1]={...DE,content:DE.content+Kd},zl})}))}});je.current&&(cancelAnimationFrame(je.current),je.current=null);let ln={id:Wt,role:"assistant",content:bt,timestamp:new Date},La=[...Aa,ln];T(La),d&&d({hasVoice:$g}),mo&&c&&c({id:O,title:Pe.slice(0,40)}),l&&l(La,O)}catch(bt){bt instanceof Error&&bt.name!=="AbortError"&&V(bt.message)}finally{je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="",ar.current=!1,Pa(!1),Co.current=null,L(!1),_("")}return}let _E=Bl(),Kg=!1;try{let Wt=await YP({userMessages:Aa.map(bt=>({role:bt.role,content:bt.content,imageAttachments:bt.attachments?.filter(ln=>ln.type==="image"&&ln.dataUrl).map(ln=>({name:ln.name,dataUrl:ln.dataUrl}))})),elementContext:Ve?.serialized,frameScreenshot:Ve?.screenshot,fileAttachments:Je.length>0?Je.map(bt=>({name:bt.name,type:bt.type,dataUrl:bt.dataUrl,textContent:bt.textContent})):void 0,webSearchEnabled:ze,apiKey:Ye,chatModel:g,agentImageModel:w,brandContext:x,customFontIds:bA,toolCtx:{excalidrawAPI:n,geminiApiKey:r||"",signal:Vd.signal,agentImageModel:w},onUpdate:bt=>{if(bt.type==="content_delta"){if(!Kg){Kg=!0;let ln={id:_E,role:"assistant",content:"",timestamp:new Date};T(La=>[...La,ln]),ar.current||(ar.current=!0,Pa(!0),_(""))}No.current+=bt.message,je.current||(je.current=requestAnimationFrame(()=>{let ln=No.current;No.current="",je.current=null,T(La=>{let Di=[...La],Kd=Di[Di.length-1];return Di[Di.length-1]={...Kd,content:Kd.content+ln},Di})}))}else(bt.type==="status"||bt.type==="tool_start"||bt.type==="tool_done")&&(ar.current&&(je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="",ar.current=!1,Pa(!1),Kg=!1),_(bt.message))},signal:Vd.signal,onBeforeImageGen:u,onAfterImageGen:h});je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="";let Ol={id:_E,role:"assistant",content:Wt.reply,timestamp:new Date,toolActions:Wt.toolActions.length>0?Wt.toolActions:void 0},$d=[...Aa,Ol];T($d),d&&d({hasVoice:$g}),mo&&c&&c({id:O,title:Pe.slice(0,40)}),l&&l($d,O)}catch(Wt){Wt instanceof Error&&Wt.name!=="AbortError"&&V(Wt.message)}finally{je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="",ar.current=!1,Pa(!1),Co.current=null,L(!1),_("")}},[v,k,P,o,n,r,Q,We,qt,O,p,d,l,c,u,h]);nQ(y,()=>({setMessages:(X,Pe)=>{let Ye=Pe??Vg.current;N(Je=>{let ze=Je.findIndex(Ve=>Ve.id===Ye);if(ze>=0){let Ve=[...Je],co=Ve[ze],mo=!co.title||co.title==="New chat",sn=X.length>0?X[0].content.slice(0,40)+(X[0].content.length>40?"\u2026":""):co.title;return Ve[ze]={...co,messages:X,title:mo?sn:co.title},Ve}return Je}),Ye===Vg.current&&(T(X),lo(!1))},send:X=>Yd(X)}),[Yd]);let SA=Io(()=>{Co.current?.abort(),je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current=""},[]),MA=Io(X=>{I(X)},[]),LE=M.filter(X=>F?X.title.toLowerCase().includes(F.toLowerCase()):!0);return e?j("div",{className:"acp",onPointerDown:X=>X.stopPropagation(),onClick:X=>X.stopPropagation(),children:Ae("div",{className:"acp-panel",children:[Ae("div",{className:"acp-header",ref:ft,children:[Ae("button",{className:"acp-title-btn",onClick:()=>D(X=>!X),title:"Chat history",children:[j("span",{children:xA}),j(aQ,{size:13})]}),Ae("div",{className:"acp-header-right",children:[j("button",{className:"acp-icon-btn",onClick:PE,title:"New chat",children:j(pA,{size:15})}),j("button",{className:"acp-icon-btn",onClick:t,title:"Close",children:j(SE,{size:15})})]}),U&&Ae("div",{className:"acp-history-dropdown",children:[Ae("div",{className:"acp-history-search",children:[j(mQ,{size:13}),j("input",{type:"search",placeholder:"Search chats\u2026",value:F,onChange:X=>z(X.target.value),autoFocus:!0})]}),Ae("div",{className:"acp-history-list",children:[Ae("button",{className:"acp-history-item acp-history-item--new",onClick:PE,children:[j(pA,{size:13}),j("span",{children:"New chat"})]}),LE.map(X=>Ae("button",{className:"acp-history-item",onClick:()=>EA(X),children:[j(mA,{size:13}),j("span",{children:X.title})]},X.id)),LE.length===0&&F&&j("div",{className:"acp-history-empty",children:"No matching chats"})]})]})]}),j("div",{className:"acp-messages-wrap",children:In?j("div",{className:"acp-empty",children:Ae("div",{className:"acp-loading-session",children:[Ae("div",{className:"acp-loading-dots",children:[j("span",{}),j("span",{}),j("span",{})]}),j("span",{className:"acp-status-text",children:"Loading chat\u2026"})]})}):P.length===0&&!k?Ae("div",{className:"acp-empty",children:[j("div",{className:"acp-empty-icon",children:j(mA,{size:22})}),Ae("div",{children:[j("div",{className:"acp-empty-title",children:"AI Ad Designer"}),j("div",{className:"acp-empty-sub",children:"Describe an ad and I'll create it on the canvas. Type @ to reference frames."})]}),j("div",{className:"acp-chips",children:gQ.map(X=>j("button",{className:"acp-chip",onClick:()=>MA(X),children:X},X))})]}):Ae(XP,{className:"acp-chat-root",children:[Ae(ZP,{className:"acp-chat-content",children:[P.filter((X,Pe,Ye)=>Ye.findIndex(Je=>Je.id===X.id)===Pe).map((X,Pe,Ye)=>{let Je=X.role==="assistant",ze=Pe===Ye.length-1;return j(yE,{className:`acp-msg ${Je?"acp-msg--assistant":"acp-msg--user"}`,children:Je?Ae("div",{className:"acp-msg-inner",children:[X.toolActions&&X.toolActions.length>0&&j(hQ,{actions:X.toolActions}),j(wE,{markdown:!0,className:"acp-content-assistant",children:X.content}),j(vE,{className:`acp-msg-actions${ze?" acp-msg-actions--visible":""}`,children:j(IE,{tooltip:"Copy",delayDuration:100,children:j("button",{className:"acp-action-btn",onClick:()=>AE(X.id,X.content),children:te===X.id?j(cA,{size:14}):j(dA,{size:14})})})})]}):Ae("div",{className:"acp-msg-inner",children:[X.attachments&&X.attachments.length>0&&j("div",{className:"acp-msg-attachments",children:X.attachments.map((Ve,co)=>Ve.type==="image"&&Ve.dataUrl?j("img",{src:Ve.dataUrl,alt:Ve.name,className:"acp-msg-att-thumb",title:Ve.name},co):Ae("span",{className:"acp-msg-att-pill",children:[j(kE,{size:11}),Ve.name]},co))}),j(wE,{className:"acp-content-user",children:X.content}),j(vE,{className:"acp-msg-actions",children:j(IE,{tooltip:"Copy",delayDuration:100,children:j("button",{className:"acp-action-btn",onClick:()=>AE(X.id,X.content),children:te===X.id?j(cA,{size:14}):j(dA,{size:14})})})})]})},X.id)}),k&&j(yE,{className:"acp-msg acp-msg--assistant",children:j("div",{className:"acp-msg-inner",children:Ae("div",{className:"acp-status-indicator",children:[Ae("div",{className:"acp-loading-dots",children:[j("span",{}),j("span",{}),j("span",{})]}),!fA&&S&&j("span",{className:"acp-status-text",children:S})]})})})]}),j("div",{className:"acp-scroll-anchor",children:j(sA,{className:"acp-scroll-btn"})})]})}),$&&j("div",{className:"acp-error",children:$}),Q&&j("div",{className:"acp-ref-area",children:Ae("div",{className:"acp-ref-pill",children:[j(lA,{size:12}),j("span",{children:Q.label}),j("button",{className:"acp-ref-remove",onClick:vA,title:"Remove reference",children:j(SE,{size:10})})]})}),We.length>0&&j("div",{className:"acp-attachments-area",children:We.map(X=>Ae("div",{className:"acp-attachment-pill",children:[X.type==="image"&&X.dataUrl?j("img",{src:X.dataUrl,alt:X.name,className:"acp-attachment-thumb"}):j(kE,{size:12}),j("span",{children:X.name}),j("button",{className:"acp-attachment-remove",onClick:()=>TA(X.id),title:"Remove file",children:j(SE,{size:10})})]},X.id))}),j("div",{className:"acp-input-area",children:Ae("div",{className:"acp-input-wrapper",ref:Dr,children:[ie&&j("div",{className:"acp-mention-menu",children:Le.length>0?Le.map(X=>Ae("button",{className:"acp-mention-item",onClick:()=>wA(X),children:[j(lA,{size:14}),Ae("span",{children:[X.name," ",Ae("span",{className:"acp-mention-dim",children:["(",X.width,"x",X.height,", ",X.childCount," items)"]})]})]},X.id)):j("div",{className:"acp-mention-empty",children:"No frames on the canvas. Create a frame first, then type @ to reference it."})}),j("input",{ref:ir,type:"file",multiple:!0,accept:"image/*,.txt,.json,.csv,.md,.html,.css,.js,.ts,.tsx,.jsx,.py,.xml",onChange:IA,style:{display:"none"}}),Ae(nl,{isLoading:k,value:v,onValueChange:yA,onSubmit:()=>Yd(),className:"acp-prompt-input",children:[j(rl,{placeholder:n?"Describe an ad to create\u2026 (@ for frames)":"Ask anything",className:"acp-textarea"}),Ae(il,{className:"acp-actions-bar",children:[Ae("div",{className:"acp-actions-left",children:[j(Tr,{tooltip:"Attach files (max 3)",children:j("button",{className:"acp-pill-btn acp-pill-btn--icon",onClick:()=>ir.current?.click(),disabled:We.length>=Wg,children:j(kE,{size:16})})}),j(Tr,{tooltip:qt?"Web search enabled":"Enable web search",children:Ae("button",{className:`acp-pill-btn${qt?" acp-pill-btn--active":""}`,onClick:CA,children:[j(lQ,{size:15}),j("span",{children:"Search"})]})})]}),Ae("div",{className:"acp-actions-right",children:[j(Tr,{tooltip:To?"Transcribing\u2026":Ct?"Stop recording":"Voice input",children:j("button",{className:`acp-pill-btn acp-pill-btn--icon${Ct?" acp-pill-btn--recording":""}${To?" acp-pill-btn--transcribing":""}`,onClick:kA,disabled:To,children:To?j("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"acp-mic-spinner",children:j("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}):Ct?j(dQ,{size:16}):j(cQ,{size:16})})}),j("button",{className:"acp-send-btn",onClick:k?SA:()=>Yd(),disabled:!k&&!v.trim(),title:k?"Stop":"Send",children:k?j("span",{className:"acp-stop-square"}):j(iQ,{size:16})})]})]})]})]})})]})}):null});uA.displayName="AIChatPanel";function hQ({actions:e}){let[t,o]=Tt(!1);return Ae("div",{className:"acp-tool-actions",children:[Ae("button",{className:"acp-tool-actions-toggle",onClick:()=>o(n=>!n),children:[j(pQ,{size:13}),Ae("span",{children:[e.length," action",e.length!==1?"s":""," performed"]}),j(sQ,{size:12,className:`acp-tool-chevron ${t?"acp-tool-chevron--open":""}`})]}),t&&j("div",{className:"acp-tool-actions-list",children:e.map((n,r)=>Ae("div",{className:`acp-tool-action-item ${n.result.success?"acp-tool-action-item--ok":"acp-tool-action-item--err"}`,children:[j("span",{className:"acp-tool-action-dot"}),j("span",{children:n.result.statusMessage})]},r))})]})}async function fQ(e,t,o,n){let r=n?.chatModel||"google/gemini-3.1-flash-lite-preview",i=n?.webSearchEnabled?`${r}:online`:r,a=[];n?.brandContext&&a.push({role:"system",content:bQ(n.brandContext)});let s=[...a,...e.map((d,u)=>{if(u===e.length-1&&d.role==="user"&&n?.attachments?.length){let g=[];for(let x of n.attachments)x.type==="image"&&x.dataUrl&&g.push({type:"image_url",image_url:{url:x.dataUrl}});let E=d.content,w=n.attachments.filter(x=>x.type==="text");return w.length>0&&(E+=`
433
+ **ZONE-FILL REMINDER:** For structured layouts (Pattern A), the image must completely fill its designated zone with no accidental gaps. If the image is in a split layout (occupying a half or side of the frame), it should span the full height and width of that zone \u2014 no random thin strips of empty space. If it's a centered/inset product shot, deliberate padding is fine but the dimensions should be intentional.`}),I.push({role:"user",content:V})}}}let T="I've completed the available operations. Let me know if you'd like any adjustments!";return m({type:"final",message:T}),{reply:T,toolActions:k}}function NJ(e,t){switch(e){case"generate_html_banner":{let o=t.width||512,n=t.height||512;return`Generating HTML banner (${o}\xD7${n}) and placing on canvas\u2026`}case"create_frame":return`Creating frame (${t.width||512}\xD7${t.height||512})\u2026`;case"add_rectangle":return"Adding background rectangle\u2026";case"add_text":return`Adding text "${String(t.text||"").slice(0,30)}"\u2026`;case"generate_image":return"Generating image \u2014 this may take a moment\u2026";case"update_element":return"Updating element\u2026";case"delete_element":return"Deleting element\u2026";case"get_frame_elements":return"Inspecting frame contents\u2026";default:return`Running ${e}\u2026`}}async function VP(e){let t=await e.arrayBuffer(),o=new AudioContext,n=await o.decodeAudioData(t);await o.close();let r=n.numberOfChannels,i=n.sampleRate,a=n.length,s=2,l=a*r*s,c=44+l,m=new ArrayBuffer(c),p=new DataView(m),d=(w,x)=>{for(let y=0;y<x.length;y++)p.setUint8(w+y,x.charCodeAt(y))};d(0,"RIFF"),p.setUint32(4,36+l,!0),d(8,"WAVE"),d(12,"fmt "),p.setUint32(16,16,!0),p.setUint16(20,1,!0),p.setUint16(22,r,!0),p.setUint32(24,i,!0),p.setUint32(28,i*r*s,!0),p.setUint16(32,r*s,!0),p.setUint16(34,16,!0),d(36,"data"),p.setUint32(40,l,!0);let u=44;for(let w=0;w<a;w++)for(let x=0;x<r;x++){let y=n.getChannelData(x)[w],v=Math.max(-1,Math.min(1,y)),I=v<0?v*32768:v*32767;p.setInt16(u,I,!0),u+=2}let h=new Uint8Array(m),g=8192,E="";for(let w=0;w<h.length;w+=g)E+=String.fromCharCode(...h.subarray(w,w+g));return btoa(E)}async function $P(e,t,o,n){let r=n||"mistralai/voxtral-small-24b-2507",i=await fetch("https://openrouter.ai/api/v1/chat/completions",{method:"POST",headers:{Authorization:`Bearer ${o}`,"Content-Type":"application/json"},body:JSON.stringify({model:r,messages:[{role:"user",content:[{type:"text",text:"Transcribe this audio. Return only the transcription text, nothing else."},{type:"input_audio",input_audio:{data:e,format:t}}]}]})});if(!i.ok){let s=`Transcription error ${i.status}`;try{let l=await i.json();l?.error?.message&&(s=l.error.message)}catch{}throw new Error(s)}return(await i.json())?.choices?.[0]?.message?.content||""}import{StickToBottom as KP}from"use-stick-to-bottom";import{jsx as jP}from"react/jsx-runtime";function XP({children:e,className:t,...o}){return jP(KP,{className:Ze("flex overflow-y-auto",t),resize:"smooth",initial:"instant",role:"log",...o,children:e})}function ZP({children:e,className:t,...o}){return jP(KP.Content,{className:Ze("flex w-full flex-col",t),...o,children:e})}import{marked as zJ}from"marked";import{memo as QP,useId as HJ,useMemo as GJ}from"react";import UJ from"react-markdown";import WJ from"remark-breaks";import YJ from"remark-gfm";import{useEffect as BJ,useState as FJ}from"react";import{codeToHtml as OJ}from"shiki";import{jsx as Ud}from"react/jsx-runtime";function qP({children:e,className:t,...o}){return Ud("div",{className:Ze("not-prose flex w-full flex-col overflow-clip border","border-zinc-200 bg-white text-zinc-950 rounded-xl dark:border-zinc-800 dark:bg-zinc-950 dark:text-zinc-50",t),...o,children:e})}function JP({code:e,language:t="tsx",theme:o="github-light",className:n,...r}){let[i,a]=FJ(null);BJ(()=>{async function l(){if(!e){a("<pre><code></code></pre>");return}let c=await OJ(e,{lang:t,theme:o});a(c)}l()},[e,t,o]);let s=Ze("w-full overflow-x-auto text-[13px] [&>pre]:px-4 [&>pre]:py-4",n);return i?Ud("div",{className:s,dangerouslySetInnerHTML:{__html:i},...r}):Ud("div",{className:s,...r,children:Ud("pre",{children:Ud("code",{children:e})})})}import{Fragment as XJ,jsx as ka}from"react/jsx-runtime";function VJ(e){return zJ.lexer(e).map(o=>o.raw)}function $J(e){if(!e)return"plaintext";let t=e.match(/language-(\w+)/);return t?t[1]:"plaintext"}var eA={code:function({className:t,children:o,...n}){if(!n.node?.position?.start.line||n.node?.position?.start.line===n.node?.position?.end.line)return ka("span",{className:Ze("bg-zinc-50 rounded-sm px-1 font-mono text-sm dark:bg-zinc-900",t),...n,children:o});let i=$J(t);return ka(qP,{className:t,children:ka(JP,{code:o,language:i})})},pre:function({children:t}){return ka(XJ,{children:t})}},tA=QP(({content:e,components:t=eA})=>ka(UJ,{remarkPlugins:[YJ,WJ],components:t,children:e}),(e,t)=>e.content===t.content);tA.displayName="MemoizedMarkdownBlock";function KJ({children:e,id:t,className:o,components:n=eA}){let r=HJ(),i=t??r,a=GJ(()=>VJ(e),[e]);return ka("div",{className:o,children:a.map((s,l)=>ka(tA,{content:s,components:n},`${i}-block-${l}`))})}var xE=QP(KJ);xE.displayName="Markdown";import*as Ug from"react";import*as _r from"@radix-ui/react-avatar";import{jsx as EE}from"react/jsx-runtime";var oA=Ug.forwardRef(({className:e,...t},o)=>EE(_r.Root,{ref:o,className:Ze("relative flex h-10 w-10 shrink-0 overflow-hidden rounded-full",e),...t}));oA.displayName=_r.Root.displayName;var nA=Ug.forwardRef(({className:e,...t},o)=>EE(_r.Image,{ref:o,className:Ze("aspect-square h-full w-full",e),...t}));nA.displayName=_r.Image.displayName;var rA=Ug.forwardRef(({className:e,...t},o)=>EE(_r.Fallback,{ref:o,className:Ze("flex h-full w-full items-center justify-center rounded-full bg-zinc-100 dark:bg-zinc-800",e),...t}));rA.displayName=_r.Fallback.displayName;import{jsx as Sa,jsxs as ZJ}from"react/jsx-runtime";var yE=({children:e,className:t,...o})=>Sa("div",{className:Ze("flex gap-3",t),...o,children:e});var wE=({children:e,markdown:t=!1,className:o,...n})=>{let r=Ze("rounded-lg p-2 text-zinc-950 bg-zinc-100 prose break-words whitespace-normal dark:text-zinc-50 dark:bg-zinc-800",o);return t?Sa(xE,{className:r,...n,children:e}):Sa("div",{className:r,...n,children:e})},vE=({children:e,className:t,...o})=>Sa("div",{className:Ze("text-zinc-500 flex items-center gap-2 dark:text-zinc-400",t),...o,children:e}),IE=({tooltip:e,children:t,className:o,side:n="top",...r})=>Sa(hu,{children:ZJ(fu,{...r,children:[Sa(bu,{asChild:!0,children:t}),Sa(td,{side:n,className:o,children:e})]})});import{ChevronDown as eQ}from"lucide-react";import{useStickToBottomContext as tQ}from"use-stick-to-bottom";import*as iA from"react";import{Slot as jJ}from"@radix-ui/react-slot";import{cva as qJ}from"class-variance-authority";import{jsx as QJ}from"react/jsx-runtime";var JJ=qJ("inline-flex items-center justify-center gap-2 whitespace-nowrap rounded-md text-sm font-medium transition-colors focus-visible:outline-none focus-visible:ring-1 focus-visible:ring-zinc-950 disabled:pointer-events-none disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:size-4 [&_svg]:shrink-0 dark:focus-visible:ring-zinc-300",{variants:{variant:{default:"bg-zinc-900 text-zinc-50 shadow hover:bg-zinc-900/90 dark:bg-zinc-50 dark:text-zinc-900 dark:hover:bg-zinc-50/90",destructive:"bg-red-500 text-zinc-50 shadow-sm hover:bg-red-500/90 dark:bg-red-900 dark:text-zinc-50 dark:hover:bg-red-900/90",outline:"border border-zinc-200 bg-white shadow-sm hover:bg-zinc-100 hover:text-zinc-900 dark:border-zinc-800 dark:bg-zinc-950 dark:hover:bg-zinc-800 dark:hover:text-zinc-50",secondary:"bg-zinc-100 text-zinc-900 shadow-sm hover:bg-zinc-100/80 dark:bg-zinc-800 dark:text-zinc-50 dark:hover:bg-zinc-800/80",ghost:"hover:bg-zinc-100 hover:text-zinc-900 dark:hover:bg-zinc-800 dark:hover:text-zinc-50",link:"text-zinc-900 underline-offset-4 hover:underline dark:text-zinc-50"},size:{default:"h-9 px-4 py-2",sm:"h-8 rounded-md px-3 text-xs",lg:"h-10 rounded-md px-8",icon:"h-9 w-9"}},defaultVariants:{variant:"default",size:"default"}}),TE=iA.forwardRef(({className:e,variant:t,size:o,asChild:n=!1,...r},i)=>QJ(n?jJ:"button",{className:Ze(JJ({variant:t,size:o,className:e})),ref:i,...r}));TE.displayName="Button";import{jsx as aA}from"react/jsx-runtime";function sA({className:e,variant:t="outline",size:o="sm",...n}){let{isAtBottom:r,scrollToBottom:i}=tQ();return aA(TE,{variant:t,size:o,className:Ze("h-10 w-10 rounded-full transition-all duration-150 ease-out",r?"pointer-events-none translate-y-4 scale-95 opacity-0":"translate-y-0 scale-100 opacity-100",e),onClick:()=>i(),...n,children:aA(eQ,{className:"h-5 w-5"})})}import{jsx as j,jsxs as Le}from"react/jsx-runtime";function Bl(){return Math.random().toString(36).slice(2,10)}var Wg=3,uQ=10*1024*1024,gQ=["Create a pasta ad","Design a sale banner","Make a product showcase","Help me design"],uA=oQ.forwardRef(({isOpen:e,onClose:t,apiKey:o,excalidrawAPI:n,geminiApiKey:r,initialMessages:i,initialSessionId:a,initialSessions:s,onMessagesChange:l,onSessionCreate:c,onSessionSwitch:m,onBeforeSend:p,onAfterSend:d,onBeforeImageGen:u,onAfterImageGen:h,chatModel:g,voiceModel:E,agentImageModel:w,brandContext:x},y)=>{let[v,I]=It(""),[k,L]=It(!1),[S,_]=It(""),[P,T]=It(i??[]),[M,N]=It(s??[]),[O,B]=It(a??Bl),[U,D]=It(!1),[F,z]=It(""),[$,V]=It(null),[Q,ee]=It(null),[ie,Ee]=It(!1),[_e,Re]=It([]),[We,lt]=It([]),[qt,rr]=It(!1),[In,Ro]=It(!1),[Tt,Ct]=It(!1),[Jt,Y]=It(!1),[te,Pe]=It(null),ft=an(null),To=an(null),Dr=an(null),ir=an(null),Fl=an(null),Yg=an([]),Tn=an(""),Ma=an(!1),Vg=an(O),[fA,Pa]=It(!1),ar=an(!1),No=an(""),je=an(null),bA=rQ(()=>{let X=[];return x?.typography?.headline?.fontFamilyId&&X.push(x.typography.headline.fontFamilyId),x?.typography?.body?.fontFamilyId&&X.push(x.typography.body.fontFamilyId),X},[x]);CE(()=>{Vg.current=O},[O]),CE(()=>{let X=Ae=>{ft.current&&!ft.current.contains(Ae.target)&&D(!1),Dr.current&&!Dr.current.contains(Ae.target)&&Ee(!1)};return document.addEventListener("mousedown",X),()=>document.removeEventListener("mousedown",X)},[]),CE(()=>{e||(To.current?.abort(),je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="",ar.current=!1,Pa(!1))},[e]);let xA=(()=>{let X=M.find(Ae=>Ae.id===O)?.title;return X||(P.length>0?P[0].content.slice(0,30)+(P[0].content.length>30?"\u2026":""):"New chat")})(),Wd=Io(()=>{if(P.length===0)return;let X=P[0].content.slice(0,40)+(P[0].content.length>40?"\u2026":"");N(Ae=>{let Ye=Ae.findIndex(ze=>ze.id===O),Je={id:O,title:X,messages:P};if(Ye>=0){let ze=[...Ae];return ze[Ye]=Je,ze}return[Je,...Ae]})},[P,O]),PE=Io(()=>{Wd();let X=Bl();T([]),B(X),Ro(!1),D(!1),V(null),I(""),ee(null),lt([]),_("")},[Wd]),EA=Io(X=>{Wd(),B(X.id),D(!1),V(null),X.messages.length>0?(T(X.messages),Ro(!1)):(T([]),Ro(!0),m&&m(X.id))},[Wd,m]),yA=Io(X=>{let Ae=Tn.current;I(X),Tn.current=X,n&&X.length>Ae.length&&X.endsWith("@")&&(Re(FP(n)),Ee(!0))},[n]),wA=Io(async X=>{if(!n)return;Ee(!1),I(ze=>{let Ve=ze.lastIndexOf("@");return Ve>=0?ze.slice(0,Ve):ze});let Ae=Tn.current.lastIndexOf("@");Tn.current=Ae>=0?Tn.current.slice(0,Ae):Tn.current;let Ye=OP(n,X.id);if(!Ye)return;let Je=await Gd(n,X.id);ee({frameId:X.id,label:Ye.frameInfo.name,serialized:Ye.serialized,screenshot:Je??void 0})},[n]),vA=Io(()=>{ee(null)},[]),IA=Io(X=>{let Ae=X.target.files;if(!Ae)return;let Ye=Wg-We.length;if(Ye<=0)return;let Je=Array.from(Ae).slice(0,Ye);for(let ze of Je){if(ze.size>uQ){V(`"${ze.name}" is too large (max 10 MB).`);continue}let Ve=Bl(),co=ze.type.startsWith("image/"),mo=new FileReader;co?(mo.onload=()=>{lt(sn=>sn.length<Wg?[...sn,{id:Ve,file:ze,name:ze.name,type:"image",dataUrl:mo.result}]:sn)},mo.readAsDataURL(ze)):(mo.onload=()=>{lt(sn=>sn.length<Wg?[...sn,{id:Ve,file:ze,name:ze.name,type:"text",textContent:mo.result}]:sn)},mo.readAsText(ze))}ir.current&&(ir.current.value="")},[We.length]),TA=Io(X=>{lt(Ae=>Ae.filter(Ye=>Ye.id!==X))},[]),CA=Io(()=>{rr(X=>!X)},[]),kA=Io(async()=>{if(Tt){Fl.current?.stop(),Ct(!1),Ma.current=!0;return}let X=null;try{X=await navigator.mediaDevices.getUserMedia({audio:!0});let Ae=MediaRecorder.isTypeSupported("audio/webm")?"audio/webm":"audio/mp4",Ye=new MediaRecorder(X,{mimeType:Ae});Fl.current=Ye,Yg.current=[],Ye.ondataavailable=Je=>{Je.data.size>0&&Yg.current.push(Je.data)},Ye.onstop=async()=>{X?.getTracks().forEach(Ve=>Ve.stop());let Je=new Blob(Yg.current,{type:Ye.mimeType}),ze=nd(o);if(!ze){V("No API key for voice transcription.");return}Y(!0),_("Transcribing\u2026");try{let Ve=await VP(Je),co=await $P(Ve,"wav",ze,E),mo=(Tn.current?`${Tn.current} `:"")+co;Tn.current=mo,I(mo)}catch(Ve){Ma.current=!1,V(Ve instanceof Error?Ve.message:"Transcription failed")}finally{Y(!1),_("")}},Ye.start(),Ct(!0)}catch{X?.getTracks().forEach(Ae=>Ae.stop()),V("Could not access microphone. Check browser permissions.")}},[Tt,o]),AE=Io((X,Ae)=>{navigator.clipboard.writeText(Ae).then(()=>{Pe(X),setTimeout(()=>Pe(null),2e3)},()=>{V("Copy failed \u2014 please grant clipboard permission.")})},[]),Yd=Io(async X=>{let Ae=(X??v).trim(),Ye=nd(o);if(!Ae||k){Ma.current=!1;return}if(!Ye){Ma.current=!1,V("No OpenRouter API key. Set VITE_APP_OPENROUTER_API_KEY in .env or pass the key via the `apiKey` prop.");return}let Je=[...We],ze=qt,Ve=Q,co={id:Bl(),role:"user",content:Ae,timestamp:new Date,attachments:Je.length>0?Je.map(Wt=>({name:Wt.name,type:Wt.type,dataUrl:Wt.dataUrl})):void 0},mo=P.length===0,sn=P,Aa=[...P,co];T(Aa),I(""),Tn.current="",lt([]),ee(null),V(null);let Vd=new AbortController;To.current=Vd,L(!0),_("Thinking\u2026");let $g=Ma.current;if(Ma.current=!1,p){let{allowed:Wt,error:Ol}=await p({hasVoice:$g});if(!Wt){T(sn),V(Ol||"Insufficient credits"),L(!1),_("");return}}if(!n){let Wt=Bl(),Ol={id:Wt,role:"assistant",content:"",timestamp:new Date},$d=[...Aa,Ol];T($d);try{let bt=await fQ(Aa,Ye,Vd.signal,{webSearchEnabled:ze,attachments:Je,chatModel:g,brandContext:x,onChunk:Di=>{ar.current||(ar.current=!0,Pa(!0),_("")),No.current+=Di,je.current||(je.current=requestAnimationFrame(()=>{let Kd=No.current;No.current="",je.current=null,T(PA=>{let zl=[...PA],DE=zl[zl.length-1];return zl[zl.length-1]={...DE,content:DE.content+Kd},zl})}))}});je.current&&(cancelAnimationFrame(je.current),je.current=null);let ln={id:Wt,role:"assistant",content:bt,timestamp:new Date},La=[...Aa,ln];T(La),d&&d({hasVoice:$g}),mo&&c&&c({id:O,title:Ae.slice(0,40)}),l&&l(La,O)}catch(bt){bt instanceof Error&&bt.name!=="AbortError"&&V(bt.message)}finally{je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="",ar.current=!1,Pa(!1),To.current=null,L(!1),_("")}return}let _E=Bl(),Kg=!1;try{let Wt=await YP({userMessages:Aa.map(bt=>({role:bt.role,content:bt.content,imageAttachments:bt.attachments?.filter(ln=>ln.type==="image"&&ln.dataUrl).map(ln=>({name:ln.name,dataUrl:ln.dataUrl}))})),elementContext:Ve?.serialized,frameScreenshot:Ve?.screenshot,fileAttachments:Je.length>0?Je.map(bt=>({name:bt.name,type:bt.type,dataUrl:bt.dataUrl,textContent:bt.textContent})):void 0,webSearchEnabled:ze,apiKey:Ye,chatModel:g,agentImageModel:w,brandContext:x,customFontIds:bA,toolCtx:{excalidrawAPI:n,geminiApiKey:r||"",signal:Vd.signal,agentImageModel:w},onUpdate:bt=>{if(bt.type==="content_delta"){if(!Kg){Kg=!0;let ln={id:_E,role:"assistant",content:"",timestamp:new Date};T(La=>[...La,ln]),ar.current||(ar.current=!0,Pa(!0),_(""))}No.current+=bt.message,je.current||(je.current=requestAnimationFrame(()=>{let ln=No.current;No.current="",je.current=null,T(La=>{let Di=[...La],Kd=Di[Di.length-1];return Di[Di.length-1]={...Kd,content:Kd.content+ln},Di})}))}else(bt.type==="status"||bt.type==="tool_start"||bt.type==="tool_done")&&(ar.current&&(je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="",ar.current=!1,Pa(!1),Kg=!1),_(bt.message))},signal:Vd.signal,onBeforeImageGen:u,onAfterImageGen:h});je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="";let Ol={id:_E,role:"assistant",content:Wt.reply,timestamp:new Date,toolActions:Wt.toolActions.length>0?Wt.toolActions:void 0},$d=[...Aa,Ol];T($d),d&&d({hasVoice:$g}),mo&&c&&c({id:O,title:Ae.slice(0,40)}),l&&l($d,O)}catch(Wt){Wt instanceof Error&&Wt.name!=="AbortError"&&V(Wt.message)}finally{je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current="",ar.current=!1,Pa(!1),To.current=null,L(!1),_("")}},[v,k,P,o,n,r,Q,We,qt,O,p,d,l,c,u,h]);nQ(y,()=>({setMessages:(X,Ae)=>{let Ye=Ae??Vg.current;N(Je=>{let ze=Je.findIndex(Ve=>Ve.id===Ye);if(ze>=0){let Ve=[...Je],co=Ve[ze],mo=!co.title||co.title==="New chat",sn=X.length>0?X[0].content.slice(0,40)+(X[0].content.length>40?"\u2026":""):co.title;return Ve[ze]={...co,messages:X,title:mo?sn:co.title},Ve}return Je}),Ye===Vg.current&&(T(X),Ro(!1))},send:X=>Yd(X)}),[Yd]);let SA=Io(()=>{To.current?.abort(),je.current&&(cancelAnimationFrame(je.current),je.current=null),No.current=""},[]),MA=Io(X=>{I(X)},[]),LE=M.filter(X=>F?X.title.toLowerCase().includes(F.toLowerCase()):!0);return e?j("div",{className:"acp",onPointerDown:X=>X.stopPropagation(),onClick:X=>X.stopPropagation(),children:Le("div",{className:"acp-panel",children:[Le("div",{className:"acp-header",ref:ft,children:[Le("button",{className:"acp-title-btn",onClick:()=>D(X=>!X),title:"Chat history",children:[j("span",{children:xA}),j(aQ,{size:13})]}),Le("div",{className:"acp-header-right",children:[j("button",{className:"acp-icon-btn",onClick:PE,title:"New chat",children:j(pA,{size:15})}),j("button",{className:"acp-icon-btn",onClick:t,title:"Close",children:j(SE,{size:15})})]}),U&&Le("div",{className:"acp-history-dropdown",children:[Le("div",{className:"acp-history-search",children:[j(mQ,{size:13}),j("input",{type:"search",placeholder:"Search chats\u2026",value:F,onChange:X=>z(X.target.value),autoFocus:!0})]}),Le("div",{className:"acp-history-list",children:[Le("button",{className:"acp-history-item acp-history-item--new",onClick:PE,children:[j(pA,{size:13}),j("span",{children:"New chat"})]}),LE.map(X=>Le("button",{className:"acp-history-item",onClick:()=>EA(X),children:[j(mA,{size:13}),j("span",{children:X.title})]},X.id)),LE.length===0&&F&&j("div",{className:"acp-history-empty",children:"No matching chats"})]})]})]}),j("div",{className:"acp-messages-wrap",children:In?j("div",{className:"acp-empty",children:Le("div",{className:"acp-loading-session",children:[Le("div",{className:"acp-loading-dots",children:[j("span",{}),j("span",{}),j("span",{})]}),j("span",{className:"acp-status-text",children:"Loading chat\u2026"})]})}):P.length===0&&!k?Le("div",{className:"acp-empty",children:[j("div",{className:"acp-empty-icon",children:j(mA,{size:22})}),Le("div",{children:[j("div",{className:"acp-empty-title",children:"AI Ad Designer"}),j("div",{className:"acp-empty-sub",children:"Describe an ad and I'll create it on the canvas. Type @ to reference frames."})]}),j("div",{className:"acp-chips",children:gQ.map(X=>j("button",{className:"acp-chip",onClick:()=>MA(X),children:X},X))})]}):Le(XP,{className:"acp-chat-root",children:[Le(ZP,{className:"acp-chat-content",children:[P.filter((X,Ae,Ye)=>Ye.findIndex(Je=>Je.id===X.id)===Ae).map((X,Ae,Ye)=>{let Je=X.role==="assistant",ze=Ae===Ye.length-1;return j(yE,{className:`acp-msg ${Je?"acp-msg--assistant":"acp-msg--user"}`,children:Je?Le("div",{className:"acp-msg-inner",children:[X.toolActions&&X.toolActions.length>0&&j(hQ,{actions:X.toolActions}),j(wE,{markdown:!0,className:"acp-content-assistant",children:X.content}),j(vE,{className:`acp-msg-actions${ze?" acp-msg-actions--visible":""}`,children:j(IE,{tooltip:"Copy",delayDuration:100,children:j("button",{className:"acp-action-btn",onClick:()=>AE(X.id,X.content),children:te===X.id?j(cA,{size:14}):j(dA,{size:14})})})})]}):Le("div",{className:"acp-msg-inner",children:[X.attachments&&X.attachments.length>0&&j("div",{className:"acp-msg-attachments",children:X.attachments.map((Ve,co)=>Ve.type==="image"&&Ve.dataUrl?j("img",{src:Ve.dataUrl,alt:Ve.name,className:"acp-msg-att-thumb",title:Ve.name},co):Le("span",{className:"acp-msg-att-pill",children:[j(kE,{size:11}),Ve.name]},co))}),j(wE,{className:"acp-content-user",children:X.content}),j(vE,{className:"acp-msg-actions",children:j(IE,{tooltip:"Copy",delayDuration:100,children:j("button",{className:"acp-action-btn",onClick:()=>AE(X.id,X.content),children:te===X.id?j(cA,{size:14}):j(dA,{size:14})})})})]})},X.id)}),k&&j(yE,{className:"acp-msg acp-msg--assistant",children:j("div",{className:"acp-msg-inner",children:Le("div",{className:"acp-status-indicator",children:[Le("div",{className:"acp-loading-dots",children:[j("span",{}),j("span",{}),j("span",{})]}),!fA&&S&&j("span",{className:"acp-status-text",children:S})]})})})]}),j("div",{className:"acp-scroll-anchor",children:j(sA,{className:"acp-scroll-btn"})})]})}),$&&j("div",{className:"acp-error",children:$}),Q&&j("div",{className:"acp-ref-area",children:Le("div",{className:"acp-ref-pill",children:[j(lA,{size:12}),j("span",{children:Q.label}),j("button",{className:"acp-ref-remove",onClick:vA,title:"Remove reference",children:j(SE,{size:10})})]})}),We.length>0&&j("div",{className:"acp-attachments-area",children:We.map(X=>Le("div",{className:"acp-attachment-pill",children:[X.type==="image"&&X.dataUrl?j("img",{src:X.dataUrl,alt:X.name,className:"acp-attachment-thumb"}):j(kE,{size:12}),j("span",{children:X.name}),j("button",{className:"acp-attachment-remove",onClick:()=>TA(X.id),title:"Remove file",children:j(SE,{size:10})})]},X.id))}),j("div",{className:"acp-input-area",children:Le("div",{className:"acp-input-wrapper",ref:Dr,children:[ie&&j("div",{className:"acp-mention-menu",children:_e.length>0?_e.map(X=>Le("button",{className:"acp-mention-item",onClick:()=>wA(X),children:[j(lA,{size:14}),Le("span",{children:[X.name," ",Le("span",{className:"acp-mention-dim",children:["(",X.width,"x",X.height,", ",X.childCount," items)"]})]})]},X.id)):j("div",{className:"acp-mention-empty",children:"No frames on the canvas. Create a frame first, then type @ to reference it."})}),j("input",{ref:ir,type:"file",multiple:!0,accept:"image/*,.txt,.json,.csv,.md,.html,.css,.js,.ts,.tsx,.jsx,.py,.xml",onChange:IA,style:{display:"none"}}),Le(nl,{isLoading:k,value:v,onValueChange:yA,onSubmit:()=>Yd(),className:"acp-prompt-input",children:[j(rl,{placeholder:n?"Describe an ad to create\u2026 (@ for frames)":"Ask anything",className:"acp-textarea"}),Le(il,{className:"acp-actions-bar",children:[Le("div",{className:"acp-actions-left",children:[j(Tr,{tooltip:"Attach files (max 3)",children:j("button",{className:"acp-pill-btn acp-pill-btn--icon",onClick:()=>ir.current?.click(),disabled:We.length>=Wg,children:j(kE,{size:16})})}),j(Tr,{tooltip:qt?"Web search enabled":"Enable web search",children:Le("button",{className:`acp-pill-btn${qt?" acp-pill-btn--active":""}`,onClick:CA,children:[j(lQ,{size:15}),j("span",{children:"Search"})]})})]}),Le("div",{className:"acp-actions-right",children:[j(Tr,{tooltip:Jt?"Transcribing\u2026":Tt?"Stop recording":"Voice input",children:j("button",{className:`acp-pill-btn acp-pill-btn--icon${Tt?" acp-pill-btn--recording":""}${Jt?" acp-pill-btn--transcribing":""}`,onClick:kA,disabled:Jt,children:Jt?j("svg",{width:"16",height:"16",viewBox:"0 0 24 24",fill:"none",stroke:"currentColor",strokeWidth:"2",strokeLinecap:"round",strokeLinejoin:"round",className:"acp-mic-spinner",children:j("path",{d:"M21 12a9 9 0 1 1-6.219-8.56"})}):Tt?j(dQ,{size:16}):j(cQ,{size:16})})}),j("button",{className:"acp-send-btn",onClick:k?SA:()=>Yd(),disabled:!k&&!v.trim(),title:k?"Stop":"Send",children:k?j("span",{className:"acp-stop-square"}):j(iQ,{size:16})})]})]})]})]})})]})}):null});uA.displayName="AIChatPanel";function hQ({actions:e}){let[t,o]=It(!1);return Le("div",{className:"acp-tool-actions",children:[Le("button",{className:"acp-tool-actions-toggle",onClick:()=>o(n=>!n),children:[j(pQ,{size:13}),Le("span",{children:[e.length," action",e.length!==1?"s":""," performed"]}),j(sQ,{size:12,className:`acp-tool-chevron ${t?"acp-tool-chevron--open":""}`})]}),t&&j("div",{className:"acp-tool-actions-list",children:e.map((n,r)=>Le("div",{className:`acp-tool-action-item ${n.result.success?"acp-tool-action-item--ok":"acp-tool-action-item--err"}`,children:[j("span",{className:"acp-tool-action-dot"}),j("span",{children:n.result.statusMessage})]},r))})]})}async function fQ(e,t,o,n){let r=n?.chatModel||"google/gemini-3.1-flash-lite-preview",i=n?.webSearchEnabled?`${r}:online`:r,a=[];n?.brandContext&&a.push({role:"system",content:bQ(n.brandContext)});let s=[...a,...e.map((d,u)=>{if(u===e.length-1&&d.role==="user"&&n?.attachments?.length){let g=[];for(let x of n.attachments)x.type==="image"&&x.dataUrl&&g.push({type:"image_url",image_url:{url:x.dataUrl}});let E=d.content,w=n.attachments.filter(x=>x.type==="text");return w.length>0&&(E+=`
434
434
 
435
435
  ${w.map(x=>`[File: ${x.name}]
436
436
  ${x.textContent}`).join(`
437
437
 
438
438
  `)}`),g.push({type:"text",text:E}),{role:d.role,content:g}}return{role:d.role,content:d.content}})],l={model:i,messages:s};n?.webSearchEnabled&&(l.plugins=[{id:"web",max_results:5}]),n?.onChunk&&(l.stream=!0);let c=await fetch("https://openrouter.ai/api/v1/chat/completions",{method:"POST",signal:o,headers:{Authorization:`Bearer ${t}`,"Content-Type":"application/json"},body:JSON.stringify(l)});if(!c.ok){let d=`OpenRouter error ${c.status}`;try{let u=await c.json();u?.error?.message&&(d=u.error.message)}catch{}throw new Error(d)}if(n?.onChunk&&Gg(c)){let d="";try{for await(let u of Hg(c))u.content&&(d+=u.content,n.onChunk(u.content))}catch(u){if(u.name==="AbortError")throw u;if(d)return d;throw u}if(!d)throw new Error("No response returned by the API.");return d}let p=(await c.json())?.choices?.[0]?.message?.content;if(!p)throw new Error("No response returned by the API.");return p}function bQ(e){let t=["## Brand Identity \u2014 use these guidelines for copywriting and design suggestions"];if(e.colors){let{primary:o,secondary:n,accent:r,background:i}=e.colors,a=[o&&`Primary: ${o}`,n&&`Secondary: ${n}`,r&&`Accent/CTA: ${r}`,i&&`Background: ${i}`].filter(Boolean);a.length&&t.push(`**Colors**: ${a.join(", ")}`)}if(e.typography){let{headline:o,body:n}=e.typography;o?.family&&t.push(`**Headline font**: ${o.family}${o.weight?` weight ${o.weight}`:""}`),n?.family&&t.push(`**Body font**: ${n.family}${n.weight?` weight ${n.weight}`:""}`)}if(e.visualStyle&&t.push(`**Visual style**: ${e.visualStyle}`),e.layoutPattern&&t.push(`**Layout pattern**: ${e.layoutPattern}`),e.toneOfVoice){let{register:o,vocabulary:n,ctaStyle:r}=e.toneOfVoice,i=[o&&`register: ${o}`,n&&`vocabulary: ${n}`,r&&`CTA style: ${r}`].filter(Boolean);i.length&&t.push(`**Tone of voice**: ${i.join(", ")}`)}if(e.imagery){let{type:o,lighting:n,composition:r}=e.imagery,i=[o&&`type: ${o}`,n&&`lighting: ${n}`,r&&`composition: ${r}`].filter(Boolean);i.length&&t.push(`**Imagery direction**: ${i.join(", ")}`)}return t.join(`
439
- `)}import{jsx as ME}from"react/jsx-runtime";kP();var yQ=e=>{let{onChange:t,onIncrement:o,initialData:n,excalidrawAPI:r,isCollaborating:i=!1,onPointerUpdate:a,renderTopLeftUI:s,renderTopRightUI:l,langCode:c=An.code,viewModeEnabled:m,zenModeEnabled:p,gridModeEnabled:d,libraryReturnUrl:u,theme:h,name:g,renderCustomStats:E,onPaste:w,detectScroll:x=!0,handleKeyboardGlobally:y=!1,onLibraryChange:v,autoFocus:I=!1,generateIdForFile:k,onLinkOpen:L,generateLinkForSelection:S,onPointerDown:_,onPointerUp:P,onScrollChange:T,onDuplicate:M,children:N,validateEmbeddable:O,renderEmbeddable:B,aiEnabled:U,showDeprecatedFonts:D,geminiApiKey:F,leonardoApiKey:z,removeBgApiKey:$,renderScrollbars:V,onBeforeImageGen:Q,onAfterImageGen:ee,onBeforeUpscale:ie,onAfterUpscale:Ee,onBeforeRemoveBg:Le,onAfterRemoveBg:De,onBeforeAutoResize:We,onAfterAutoResize:lt,agentImageModel:qt,showLibraryButton:rr,imageEditToolbarCallbacks:In,customFonts:lo}=e,Ct=e.UIOptions?.canvasActions,xt={...e.UIOptions,canvasActions:{...hA.canvasActions,...Ct},tools:{image:e.UIOptions?.tools?.image??!0}};return Ct?.export&&(xt.canvasActions.export.saveFileToDisk=Ct.export?.saveFileToDisk??hA.canvasActions.export.saveFileToDisk),xt.canvasActions.toggleTheme===null&&typeof h>"u"&&(xt.canvasActions.toggleTheme=!0),gA(()=>{(async()=>{await import("canvas-roundrect-polyfill")})();let Y=te=>{typeof te.scale=="number"&&te.scale!==1&&te.preventDefault()};return document.addEventListener("touchmove",Y,{passive:!1}),()=>{document.removeEventListener("touchmove",Y)}},[]),gA(()=>{if(lo?.length)for(let To of lo)Mn.registerCustomFont(To)},[lo]),ME(iy,{store:Et,children:ME(fP,{langCode:c,theme:h,children:ME(hP,{onChange:t,onIncrement:o,initialData:n,excalidrawAPI:r,isCollaborating:i,onPointerUpdate:a,renderTopLeftUI:s,renderTopRightUI:l,langCode:c,viewModeEnabled:m,zenModeEnabled:p,gridModeEnabled:d,libraryReturnUrl:u,theme:h,name:g,renderCustomStats:E,UIOptions:xt,onPaste:w,detectScroll:x,handleKeyboardGlobally:y,onLibraryChange:v,autoFocus:I,generateIdForFile:k,onLinkOpen:L,generateLinkForSelection:S,onPointerDown:_,onPointerUp:P,onScrollChange:T,onDuplicate:M,validateEmbeddable:O,renderEmbeddable:B,aiEnabled:U!==!1,showDeprecatedFonts:D,geminiApiKey:F,leonardoApiKey:z,removeBgApiKey:$,renderScrollbars:V,onBeforeImageGen:Q,onAfterImageGen:ee,onBeforeUpscale:ie,onAfterUpscale:Ee,onBeforeRemoveBg:Le,onAfterRemoveBg:De,onBeforeAutoResize:We,onAfterAutoResize:lt,agentImageModel:qt,showLibraryButton:rr,imageEditToolbarCallbacks:In,children:N})})})},wQ=(e,t)=>{if(e.children!==t.children)return!1;let{initialData:o,UIOptions:n={},...r}=e,{initialData:i,UIOptions:a={},...s}=t,l=Object.keys(n),c=Object.keys(a);return l.length!==c.length?!1:l.every(p=>p==="getFormFactor"?!0:p==="canvasActions"?Object.keys(n.canvasActions).every(u=>u==="export"&&n?.canvasActions?.export&&a?.canvasActions?.export?n.canvasActions.export.saveFileToDisk===a.canvasActions.export.saveFileToDisk:n?.canvasActions?.[u]===a?.canvasActions?.[u]):n[p]===a[p])&&EQ(r,s)},vQ=xQ.memo(yQ,wQ);vQ.displayName="Excalidraw";export{uA as AIChatPanel,ro as Button,eqe as CaptureUpdateAction,sO as CommandPalette,$je as DEFAULT_LASER_COLOR,ju as DefaultSidebar,bJ as DiagramToCodePlugin,mc as Ellipsify,vQ as Excalidraw,Yje as FONT_FAMILY,jq as Footer,Qq as LiveCollaborationTrigger,Vje as MIME_TYPES,Kt as MainMenu,bp as ROUNDNESS,jo as Sidebar,yd as Stats,US as THEME,ig as TTDDialog,AP as TTDDialogTrigger,hJ as TTDStreamFetch,Kje as UserIdleState,rJ as WelcomeScreen,Ns as bumpVersion,WS as convertToExcalidrawElements,An as defaultLang,l5 as elementPartiallyOverlapsWithOrContainsBBox,c5 as elementsOverlappingBBox,mT as exportToBlob,Jr as exportToCanvas,v9 as exportToClipboard,zs as exportToSvg,uqe as getCommonBounds,za as getDataURL,jje as getFormFactor,Tp as getLibraryItemsHash,Pje as getNonDeletedElements,kje as getSceneVersion,Lje as getTextFromElements,gqe as getVisibleSceneBounds,Sje as hashElementsVersion,Mje as hashString,a0 as isElementInsideBBox,Eqe as isElementLink,Dje as isInvisiblySmallElement,Uje as isLinearElement,Ua as languages,em as loadFromBlob,eh as loadLibraryFromBlob,Qg as loadSceneOrLibraryFromBlob,yT as mergeLibraryItems,Ep as mutateElement,Jje as newElementWith,Xje as normalizeLink,yb as parseLibraryTokensFromUrl,uJ as reconcileElements,Oa as restoreAppState,LA as restoreElement,Ni as restoreElements,$l as restoreLibraryItems,aT as sceneCoordsToViewportCoords,Wl as serializeAsJSON,AA as serializeLibraryAsJSON,wqe as setCustomTextMetricsProvider,we as useEditorInterface,O9 as useHandleLibrary,Ge as useI18n,_t as useStylesPanelMode,Zje as viewportCoordsToSceneCoords,b2 as zoomToFitBounds};
439
+ `)}import{jsx as ME}from"react/jsx-runtime";kP();var yQ=e=>{let{onChange:t,onIncrement:o,initialData:n,excalidrawAPI:r,isCollaborating:i=!1,onPointerUpdate:a,renderTopLeftUI:s,renderTopRightUI:l,langCode:c=An.code,viewModeEnabled:m,zenModeEnabled:p,gridModeEnabled:d,libraryReturnUrl:u,theme:h,name:g,renderCustomStats:E,onPaste:w,detectScroll:x=!0,handleKeyboardGlobally:y=!1,onLibraryChange:v,autoFocus:I=!1,generateIdForFile:k,onLinkOpen:L,generateLinkForSelection:S,onPointerDown:_,onPointerUp:P,onScrollChange:T,onDuplicate:M,children:N,validateEmbeddable:O,renderEmbeddable:B,aiEnabled:U,showDeprecatedFonts:D,geminiApiKey:F,leonardoApiKey:z,removeBgApiKey:$,renderScrollbars:V,onBeforeImageGen:Q,onAfterImageGen:ee,onBeforeUpscale:ie,onAfterUpscale:Ee,onBeforeRemoveBg:_e,onAfterRemoveBg:Re,onBeforeAutoResize:We,onAfterAutoResize:lt,agentImageModel:qt,chatModel:rr,showLibraryButton:In,imageEditToolbarCallbacks:Ro,customFonts:Tt}=e,Ct=e.UIOptions?.canvasActions,Jt={...e.UIOptions,canvasActions:{...hA.canvasActions,...Ct},tools:{image:e.UIOptions?.tools?.image??!0}};return Ct?.export&&(Jt.canvasActions.export.saveFileToDisk=Ct.export?.saveFileToDisk??hA.canvasActions.export.saveFileToDisk),Jt.canvasActions.toggleTheme===null&&typeof h>"u"&&(Jt.canvasActions.toggleTheme=!0),gA(()=>{(async()=>{await import("canvas-roundrect-polyfill")})();let te=Pe=>{typeof Pe.scale=="number"&&Pe.scale!==1&&Pe.preventDefault()};return document.addEventListener("touchmove",te,{passive:!1}),()=>{document.removeEventListener("touchmove",te)}},[]),gA(()=>{if(Tt?.length)for(let Y of Tt)Mn.registerCustomFont(Y)},[Tt]),ME(iy,{store:xt,children:ME(fP,{langCode:c,theme:h,children:ME(hP,{onChange:t,onIncrement:o,initialData:n,excalidrawAPI:r,isCollaborating:i,onPointerUpdate:a,renderTopLeftUI:s,renderTopRightUI:l,langCode:c,viewModeEnabled:m,zenModeEnabled:p,gridModeEnabled:d,libraryReturnUrl:u,theme:h,name:g,renderCustomStats:E,UIOptions:Jt,onPaste:w,detectScroll:x,handleKeyboardGlobally:y,onLibraryChange:v,autoFocus:I,generateIdForFile:k,onLinkOpen:L,generateLinkForSelection:S,onPointerDown:_,onPointerUp:P,onScrollChange:T,onDuplicate:M,validateEmbeddable:O,renderEmbeddable:B,aiEnabled:U!==!1,showDeprecatedFonts:D,geminiApiKey:F,leonardoApiKey:z,removeBgApiKey:$,renderScrollbars:V,onBeforeImageGen:Q,onAfterImageGen:ee,onBeforeUpscale:ie,onAfterUpscale:Ee,onBeforeRemoveBg:_e,onAfterRemoveBg:Re,onBeforeAutoResize:We,onAfterAutoResize:lt,agentImageModel:qt,chatModel:rr,showLibraryButton:In,imageEditToolbarCallbacks:Ro,children:N})})})},wQ=(e,t)=>{if(e.children!==t.children)return!1;let{initialData:o,UIOptions:n={},...r}=e,{initialData:i,UIOptions:a={},...s}=t,l=Object.keys(n),c=Object.keys(a);return l.length!==c.length?!1:l.every(p=>p==="getFormFactor"?!0:p==="canvasActions"?Object.keys(n.canvasActions).every(u=>u==="export"&&n?.canvasActions?.export&&a?.canvasActions?.export?n.canvasActions.export.saveFileToDisk===a.canvasActions.export.saveFileToDisk:n?.canvasActions?.[u]===a?.canvasActions?.[u]):n[p]===a[p])&&EQ(r,s)},vQ=xQ.memo(yQ,wQ);vQ.displayName="Excalidraw";export{uA as AIChatPanel,io as Button,eqe as CaptureUpdateAction,sO as CommandPalette,$je as DEFAULT_LASER_COLOR,ju as DefaultSidebar,bJ as DiagramToCodePlugin,mc as Ellipsify,vQ as Excalidraw,Yje as FONT_FAMILY,jq as Footer,Qq as LiveCollaborationTrigger,Vje as MIME_TYPES,Kt as MainMenu,bp as ROUNDNESS,jo as Sidebar,yd as Stats,US as THEME,ig as TTDDialog,AP as TTDDialogTrigger,hJ as TTDStreamFetch,Kje as UserIdleState,rJ as WelcomeScreen,Ns as bumpVersion,WS as convertToExcalidrawElements,An as defaultLang,l5 as elementPartiallyOverlapsWithOrContainsBBox,c5 as elementsOverlappingBBox,mT as exportToBlob,Jr as exportToCanvas,v9 as exportToClipboard,zs as exportToSvg,uqe as getCommonBounds,za as getDataURL,jje as getFormFactor,Tp as getLibraryItemsHash,Pje as getNonDeletedElements,kje as getSceneVersion,Lje as getTextFromElements,gqe as getVisibleSceneBounds,Sje as hashElementsVersion,Mje as hashString,a0 as isElementInsideBBox,Eqe as isElementLink,Dje as isInvisiblySmallElement,Uje as isLinearElement,Ua as languages,em as loadFromBlob,eh as loadLibraryFromBlob,Qg as loadSceneOrLibraryFromBlob,yT as mergeLibraryItems,Ep as mutateElement,Jje as newElementWith,Xje as normalizeLink,yb as parseLibraryTokensFromUrl,uJ as reconcileElements,Oa as restoreAppState,LA as restoreElement,Ni as restoreElements,$l as restoreLibraryItems,aT as sceneCoordsToViewportCoords,Wl as serializeAsJSON,AA as serializeLibraryAsJSON,wqe as setCustomTextMetricsProvider,we as useEditorInterface,O9 as useHandleLibrary,Ge as useI18n,_t as useStylesPanelMode,Zje as viewportCoordsToSceneCoords,b2 as zoomToFitBounds};