App.tsx 346 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202
  1. import clsx from "clsx";
  2. import throttle from "lodash.throttle";
  3. import React, { useContext } from "react";
  4. import { flushSync } from "react-dom";
  5. import rough from "roughjs/bin/rough";
  6. import { nanoid } from "nanoid";
  7. import {
  8. clamp,
  9. pointFrom,
  10. pointDistance,
  11. vector,
  12. pointRotateRads,
  13. vectorScale,
  14. vectorFromPoint,
  15. vectorSubtract,
  16. vectorDot,
  17. vectorNormalize,
  18. } from "@excalidraw/math";
  19. import {
  20. COLOR_PALETTE,
  21. CODES,
  22. shouldResizeFromCenter,
  23. shouldMaintainAspectRatio,
  24. shouldRotateWithDiscreteAngle,
  25. isArrowKey,
  26. KEYS,
  27. APP_NAME,
  28. CURSOR_TYPE,
  29. DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
  30. DEFAULT_VERTICAL_ALIGN,
  31. DRAGGING_THRESHOLD,
  32. ELEMENT_SHIFT_TRANSLATE_AMOUNT,
  33. ELEMENT_TRANSLATE_AMOUNT,
  34. EVENT,
  35. FRAME_STYLE,
  36. IMAGE_MIME_TYPES,
  37. IMAGE_RENDER_TIMEOUT,
  38. isBrave,
  39. LINE_CONFIRM_THRESHOLD,
  40. MAX_ALLOWED_FILE_BYTES,
  41. MIME_TYPES,
  42. MQ_MAX_HEIGHT_LANDSCAPE,
  43. MQ_MAX_WIDTH_LANDSCAPE,
  44. MQ_MAX_WIDTH_PORTRAIT,
  45. MQ_RIGHT_SIDEBAR_MIN_WIDTH,
  46. POINTER_BUTTON,
  47. ROUNDNESS,
  48. SCROLL_TIMEOUT,
  49. TAP_TWICE_TIMEOUT,
  50. TEXT_TO_CENTER_SNAP_THRESHOLD,
  51. THEME,
  52. THEME_FILTER,
  53. TOUCH_CTX_MENU_TIMEOUT,
  54. VERTICAL_ALIGN,
  55. YOUTUBE_STATES,
  56. ZOOM_STEP,
  57. POINTER_EVENTS,
  58. TOOL_TYPE,
  59. isIOS,
  60. supportsResizeObserver,
  61. DEFAULT_COLLISION_THRESHOLD,
  62. DEFAULT_TEXT_ALIGN,
  63. ARROW_TYPE,
  64. DEFAULT_REDUCED_GLOBAL_ALPHA,
  65. isSafari,
  66. isLocalLink,
  67. normalizeLink,
  68. toValidURL,
  69. getGridPoint,
  70. getLineHeight,
  71. debounce,
  72. distance,
  73. getFontString,
  74. getNearestScrollableContainer,
  75. isInputLike,
  76. isToolIcon,
  77. isWritableElement,
  78. sceneCoordsToViewportCoords,
  79. tupleToCoors,
  80. viewportCoordsToSceneCoords,
  81. wrapEvent,
  82. updateObject,
  83. updateActiveTool,
  84. getShortcutKey,
  85. isTransparent,
  86. easeToValuesRAF,
  87. muteFSAbortError,
  88. isTestEnv,
  89. isDevEnv,
  90. easeOut,
  91. updateStable,
  92. addEventListener,
  93. normalizeEOL,
  94. getDateTime,
  95. isShallowEqual,
  96. arrayToMap,
  97. type EXPORT_IMAGE_TYPES,
  98. randomInteger,
  99. CLASSES,
  100. Emitter,
  101. MINIMUM_ARROW_SIZE,
  102. } from "@excalidraw/common";
  103. import {
  104. getObservedAppState,
  105. getCommonBounds,
  106. maybeSuggestBindingsForLinearElementAtCoords,
  107. getElementAbsoluteCoords,
  108. bindOrUnbindLinearElements,
  109. fixBindingsAfterDeletion,
  110. getHoveredElementForBinding,
  111. isBindingEnabled,
  112. shouldEnableBindingForPointerEvent,
  113. updateBoundElements,
  114. getSuggestedBindingsForArrows,
  115. LinearElementEditor,
  116. newElementWith,
  117. newFrameElement,
  118. newFreeDrawElement,
  119. newEmbeddableElement,
  120. newMagicFrameElement,
  121. newIframeElement,
  122. newArrowElement,
  123. newElement,
  124. newImageElement,
  125. newLinearElement,
  126. newTextElement,
  127. refreshTextDimensions,
  128. deepCopyElement,
  129. duplicateElements,
  130. hasBoundTextElement,
  131. isArrowElement,
  132. isBindingElement,
  133. isBindingElementType,
  134. isBoundToContainer,
  135. isFrameLikeElement,
  136. isImageElement,
  137. isEmbeddableElement,
  138. isInitializedImageElement,
  139. isLinearElement,
  140. isLinearElementType,
  141. isUsingAdaptiveRadius,
  142. isIframeElement,
  143. isIframeLikeElement,
  144. isMagicFrameElement,
  145. isTextBindableContainer,
  146. isElbowArrow,
  147. isFlowchartNodeElement,
  148. isBindableElement,
  149. isTextElement,
  150. getLockedLinearCursorAlignSize,
  151. getNormalizedDimensions,
  152. isElementCompletelyInViewport,
  153. isElementInViewport,
  154. isInvisiblySmallElement,
  155. getCornerRadius,
  156. isPathALoop,
  157. createSrcDoc,
  158. embeddableURLValidator,
  159. maybeParseEmbedSrc,
  160. getEmbedLink,
  161. getInitializedImageElements,
  162. normalizeSVG,
  163. updateImageCache as _updateImageCache,
  164. getBoundTextElement,
  165. getContainerCenter,
  166. getContainerElement,
  167. isValidTextContainer,
  168. redrawTextBoundingBox,
  169. shouldShowBoundingBox,
  170. getFrameChildren,
  171. isCursorInFrame,
  172. addElementsToFrame,
  173. replaceAllElementsInFrame,
  174. removeElementsFromFrame,
  175. getElementsInResizingFrame,
  176. getElementsInNewFrame,
  177. getContainingFrame,
  178. elementOverlapsWithFrame,
  179. updateFrameMembershipOfSelectedElements,
  180. isElementInFrame,
  181. getFrameLikeTitle,
  182. getElementsOverlappingFrame,
  183. filterElementsEligibleAsFrameChildren,
  184. hitElementBoundText,
  185. hitElementBoundingBoxOnly,
  186. hitElementItself,
  187. getVisibleSceneBounds,
  188. FlowChartCreator,
  189. FlowChartNavigator,
  190. getLinkDirectionFromKey,
  191. cropElement,
  192. wrapText,
  193. isElementLink,
  194. parseElementLinkFromURL,
  195. isMeasureTextSupported,
  196. normalizeText,
  197. measureText,
  198. getLineHeightInPx,
  199. getApproxMinLineWidth,
  200. getApproxMinLineHeight,
  201. getMinTextElementWidth,
  202. ShapeCache,
  203. getRenderOpacity,
  204. editGroupForSelectedElement,
  205. getElementsInGroup,
  206. getSelectedGroupIdForElement,
  207. getSelectedGroupIds,
  208. isElementInGroup,
  209. isSelectedViaGroup,
  210. selectGroupsForSelectedElements,
  211. syncInvalidIndices,
  212. syncMovedIndices,
  213. excludeElementsInFramesFromSelection,
  214. getSelectionStateForElements,
  215. makeNextSelectedElementIds,
  216. getResizeOffsetXY,
  217. getResizeArrowDirection,
  218. transformElements,
  219. getCursorForResizingElement,
  220. getElementWithTransformHandleType,
  221. getTransformHandleTypeFromCoords,
  222. dragNewElement,
  223. dragSelectedElements,
  224. getDragOffsetXY,
  225. isNonDeletedElement,
  226. Scene,
  227. Store,
  228. CaptureUpdateAction,
  229. type ElementUpdate,
  230. hitElementBoundingBox,
  231. isLineElement,
  232. isSimpleArrow,
  233. } from "@excalidraw/element";
  234. import type { LocalPoint, Radians } from "@excalidraw/math";
  235. import type {
  236. ExcalidrawElement,
  237. ExcalidrawFreeDrawElement,
  238. ExcalidrawGenericElement,
  239. ExcalidrawLinearElement,
  240. ExcalidrawTextElement,
  241. NonDeleted,
  242. InitializedExcalidrawImageElement,
  243. ExcalidrawImageElement,
  244. FileId,
  245. NonDeletedExcalidrawElement,
  246. ExcalidrawTextContainer,
  247. ExcalidrawFrameLikeElement,
  248. ExcalidrawMagicFrameElement,
  249. ExcalidrawIframeLikeElement,
  250. IframeData,
  251. ExcalidrawIframeElement,
  252. ExcalidrawEmbeddableElement,
  253. Ordered,
  254. MagicGenerationData,
  255. ExcalidrawArrowElement,
  256. ExcalidrawElbowArrowElement,
  257. } from "@excalidraw/element/types";
  258. import type { Mutable, ValueOf } from "@excalidraw/common/utility-types";
  259. import {
  260. actionAddToLibrary,
  261. actionBringForward,
  262. actionBringToFront,
  263. actionCopy,
  264. actionCopyAsPng,
  265. actionCopyAsSvg,
  266. copyText,
  267. actionCopyStyles,
  268. actionCut,
  269. actionDeleteSelected,
  270. actionDuplicateSelection,
  271. actionFinalize,
  272. actionFlipHorizontal,
  273. actionFlipVertical,
  274. actionGroup,
  275. actionPasteStyles,
  276. actionSelectAll,
  277. actionSendBackward,
  278. actionSendToBack,
  279. actionToggleGridMode,
  280. actionToggleStats,
  281. actionToggleZenMode,
  282. actionUnbindText,
  283. actionBindText,
  284. actionUngroup,
  285. actionLink,
  286. actionToggleElementLock,
  287. actionToggleLinearEditor,
  288. actionToggleObjectsSnapMode,
  289. actionToggleCropEditor,
  290. } from "../actions";
  291. import { actionWrapTextInContainer } from "../actions/actionBoundText";
  292. import { actionToggleHandTool, zoomToFit } from "../actions/actionCanvas";
  293. import { actionPaste } from "../actions/actionClipboard";
  294. import { actionCopyElementLink } from "../actions/actionElementLink";
  295. import { actionUnlockAllElements } from "../actions/actionElementLock";
  296. import {
  297. actionRemoveAllElementsFromFrame,
  298. actionSelectAllElementsInFrame,
  299. actionWrapSelectionInFrame,
  300. } from "../actions/actionFrame";
  301. import { createRedoAction, createUndoAction } from "../actions/actionHistory";
  302. import { actionTextAutoResize } from "../actions/actionTextAutoResize";
  303. import { actionToggleViewMode } from "../actions/actionToggleViewMode";
  304. import { ActionManager } from "../actions/manager";
  305. import { actions } from "../actions/register";
  306. import { getShortcutFromShortcutName } from "../actions/shortcuts";
  307. import { trackEvent } from "../analytics";
  308. import { AnimationFrameHandler } from "../animation-frame-handler";
  309. import {
  310. getDefaultAppState,
  311. isEraserActive,
  312. isHandToolActive,
  313. } from "../appState";
  314. import { copyTextToSystemClipboard, parseClipboard } from "../clipboard";
  315. import { exportCanvas, loadFromBlob } from "../data";
  316. import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
  317. import { restore, restoreElements } from "../data/restore";
  318. import { getCenter, getDistance } from "../gesture";
  319. import { History } from "../history";
  320. import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
  321. import {
  322. calculateScrollCenter,
  323. getElementsWithinSelection,
  324. getNormalizedZoom,
  325. getSelectedElements,
  326. hasBackground,
  327. isSomeElementSelected,
  328. } from "../scene";
  329. import { getStateForZoom } from "../scene/zoom";
  330. import {
  331. dataURLToString,
  332. generateIdFromFile,
  333. getDataURL,
  334. getDataURL_sync,
  335. getFileFromEvent,
  336. ImageURLToFile,
  337. isImageFileHandle,
  338. isSupportedImageFile,
  339. loadSceneOrLibraryFromBlob,
  340. normalizeFile,
  341. parseLibraryJSON,
  342. resizeImageFile,
  343. SVGStringToFile,
  344. } from "../data/blob";
  345. import { fileOpen } from "../data/filesystem";
  346. import {
  347. showHyperlinkTooltip,
  348. hideHyperlinkToolip,
  349. Hyperlink,
  350. } from "../components/hyperlink/Hyperlink";
  351. import { Fonts } from "../fonts";
  352. import { editorJotaiStore, type WritableAtom } from "../editor-jotai";
  353. import { ImageSceneDataError } from "../errors";
  354. import {
  355. getSnapLinesAtPointer,
  356. snapDraggedElements,
  357. isActiveToolNonLinearSnappable,
  358. snapNewElement,
  359. snapResizingElements,
  360. isSnappingEnabled,
  361. getVisibleGaps,
  362. getReferenceSnapPoints,
  363. SnapCache,
  364. isGridModeEnabled,
  365. } from "../snapping";
  366. import { convertToExcalidrawElements } from "../data/transform";
  367. import { Renderer } from "../scene/Renderer";
  368. import {
  369. setEraserCursor,
  370. setCursor,
  371. resetCursor,
  372. setCursorForShape,
  373. } from "../cursor";
  374. import { ElementCanvasButtons } from "../components/ElementCanvasButtons";
  375. import { LaserTrails } from "../laser-trails";
  376. import { withBatchedUpdates, withBatchedUpdatesThrottled } from "../reactUtils";
  377. import { textWysiwyg } from "../wysiwyg/textWysiwyg";
  378. import { isOverScrollBars } from "../scene/scrollbars";
  379. import { isMaybeMermaidDefinition } from "../mermaid";
  380. import { LassoTrail } from "../lasso";
  381. import { EraserTrail } from "../eraser";
  382. import ConvertElementTypePopup, {
  383. getConversionTypeFromElements,
  384. convertElementTypePopupAtom,
  385. convertElementTypes,
  386. } from "./ConvertElementTypePopup";
  387. import { activeConfirmDialogAtom } from "./ActiveConfirmDialog";
  388. import BraveMeasureTextError from "./BraveMeasureTextError";
  389. import { ContextMenu, CONTEXT_MENU_SEPARATOR } from "./ContextMenu";
  390. import { activeEyeDropperAtom } from "./EyeDropper";
  391. import FollowMode from "./FollowMode/FollowMode";
  392. import LayerUI from "./LayerUI";
  393. import { ElementCanvasButton } from "./MagicButton";
  394. import { SVGLayer } from "./SVGLayer";
  395. import { searchItemInFocusAtom } from "./SearchMenu";
  396. import { isSidebarDockedAtom } from "./Sidebar/Sidebar";
  397. import { StaticCanvas, InteractiveCanvas } from "./canvases";
  398. import NewElementCanvas from "./canvases/NewElementCanvas";
  399. import {
  400. isPointHittingLink,
  401. isPointHittingLinkIcon,
  402. } from "./hyperlink/helpers";
  403. import { MagicIcon, copyIcon, fullscreenIcon } from "./icons";
  404. import { Toast } from "./Toast";
  405. import { findShapeByKey } from "./shapes";
  406. import UnlockPopup from "./UnlockPopup";
  407. import type {
  408. RenderInteractiveSceneCallback,
  409. ScrollBars,
  410. } from "../scene/types";
  411. import type { PastedMixedContent } from "../clipboard";
  412. import type { ExportedElements } from "../data";
  413. import type { ContextMenuItems } from "./ContextMenu";
  414. import type { FileSystemHandle } from "../data/filesystem";
  415. import type { ExcalidrawElementSkeleton } from "../data/transform";
  416. import type {
  417. AppClassProperties,
  418. AppProps,
  419. AppState,
  420. BinaryFileData,
  421. ExcalidrawImperativeAPI,
  422. BinaryFiles,
  423. Gesture,
  424. GestureEvent,
  425. LibraryItems,
  426. PointerDownState,
  427. SceneData,
  428. Device,
  429. FrameNameBoundsCache,
  430. SidebarName,
  431. SidebarTabName,
  432. KeyboardModifiersObject,
  433. CollaboratorPointer,
  434. ToolType,
  435. OnUserFollowedPayload,
  436. UnsubscribeCallback,
  437. EmbedsValidationStatus,
  438. ElementsPendingErasure,
  439. GenerateDiagramToCode,
  440. NullableGridSize,
  441. Offsets,
  442. } from "../types";
  443. import type { RoughCanvas } from "roughjs/bin/canvas";
  444. import type { Action, ActionResult } from "../actions/types";
  445. const AppContext = React.createContext<AppClassProperties>(null!);
  446. const AppPropsContext = React.createContext<AppProps>(null!);
  447. const deviceContextInitialValue = {
  448. viewport: {
  449. isMobile: false,
  450. isLandscape: false,
  451. },
  452. editor: {
  453. isMobile: false,
  454. canFitSidebar: false,
  455. },
  456. isTouchScreen: false,
  457. };
  458. const DeviceContext = React.createContext<Device>(deviceContextInitialValue);
  459. DeviceContext.displayName = "DeviceContext";
  460. export const ExcalidrawContainerContext = React.createContext<{
  461. container: HTMLDivElement | null;
  462. id: string | null;
  463. }>({ container: null, id: null });
  464. ExcalidrawContainerContext.displayName = "ExcalidrawContainerContext";
  465. const ExcalidrawElementsContext = React.createContext<
  466. readonly NonDeletedExcalidrawElement[]
  467. >([]);
  468. ExcalidrawElementsContext.displayName = "ExcalidrawElementsContext";
  469. const ExcalidrawAppStateContext = React.createContext<AppState>({
  470. ...getDefaultAppState(),
  471. width: 0,
  472. height: 0,
  473. offsetLeft: 0,
  474. offsetTop: 0,
  475. });
  476. ExcalidrawAppStateContext.displayName = "ExcalidrawAppStateContext";
  477. const ExcalidrawSetAppStateContext = React.createContext<
  478. React.Component<any, AppState>["setState"]
  479. >(() => {
  480. console.warn("Uninitialized ExcalidrawSetAppStateContext context!");
  481. });
  482. ExcalidrawSetAppStateContext.displayName = "ExcalidrawSetAppStateContext";
  483. const ExcalidrawActionManagerContext = React.createContext<ActionManager>(
  484. null!,
  485. );
  486. ExcalidrawActionManagerContext.displayName = "ExcalidrawActionManagerContext";
  487. export const useApp = () => useContext(AppContext);
  488. export const useAppProps = () => useContext(AppPropsContext);
  489. export const useDevice = () => useContext<Device>(DeviceContext);
  490. export const useExcalidrawContainer = () =>
  491. useContext(ExcalidrawContainerContext);
  492. export const useExcalidrawElements = () =>
  493. useContext(ExcalidrawElementsContext);
  494. export const useExcalidrawAppState = () =>
  495. useContext(ExcalidrawAppStateContext);
  496. export const useExcalidrawSetAppState = () =>
  497. useContext(ExcalidrawSetAppStateContext);
  498. export const useExcalidrawActionManager = () =>
  499. useContext(ExcalidrawActionManagerContext);
  500. let didTapTwice: boolean = false;
  501. let tappedTwiceTimer = 0;
  502. let isHoldingSpace: boolean = false;
  503. let isPanning: boolean = false;
  504. let isDraggingScrollBar: boolean = false;
  505. let currentScrollBars: ScrollBars = { horizontal: null, vertical: null };
  506. let touchTimeout = 0;
  507. let invalidateContextMenu = false;
  508. /**
  509. * Map of youtube embed video states
  510. */
  511. const YOUTUBE_VIDEO_STATES = new Map<
  512. ExcalidrawElement["id"],
  513. ValueOf<typeof YOUTUBE_STATES>
  514. >();
  515. let IS_PLAIN_PASTE = false;
  516. let IS_PLAIN_PASTE_TIMER = 0;
  517. let PLAIN_PASTE_TOAST_SHOWN = false;
  518. let lastPointerUp: (() => void) | null = null;
  519. const gesture: Gesture = {
  520. pointers: new Map(),
  521. lastCenter: null,
  522. initialDistance: null,
  523. initialScale: null,
  524. };
  525. class App extends React.Component<AppProps, AppState> {
  526. canvas: AppClassProperties["canvas"];
  527. interactiveCanvas: AppClassProperties["interactiveCanvas"] = null;
  528. rc: RoughCanvas;
  529. unmounted: boolean = false;
  530. actionManager: ActionManager;
  531. device: Device = deviceContextInitialValue;
  532. private excalidrawContainerRef = React.createRef<HTMLDivElement>();
  533. public scene: Scene;
  534. public fonts: Fonts;
  535. public renderer: Renderer;
  536. public visibleElements: readonly NonDeletedExcalidrawElement[];
  537. private resizeObserver: ResizeObserver | undefined;
  538. private nearestScrollableContainer: HTMLElement | Document | undefined;
  539. public library: AppClassProperties["library"];
  540. public libraryItemsFromStorage: LibraryItems | undefined;
  541. public id: string;
  542. private store: Store;
  543. private history: History;
  544. public excalidrawContainerValue: {
  545. container: HTMLDivElement | null;
  546. id: string;
  547. };
  548. public files: BinaryFiles = {};
  549. public imageCache: AppClassProperties["imageCache"] = new Map();
  550. private iFrameRefs = new Map<ExcalidrawElement["id"], HTMLIFrameElement>();
  551. /**
  552. * Indicates whether the embeddable's url has been validated for rendering.
  553. * If value not set, indicates that the validation is pending.
  554. * Initially or on url change the flag is not reset so that we can guarantee
  555. * the validation came from a trusted source (the editor).
  556. **/
  557. private embedsValidationStatus: EmbedsValidationStatus = new Map();
  558. /** embeds that have been inserted to DOM (as a perf optim, we don't want to
  559. * insert to DOM before user initially scrolls to them) */
  560. private initializedEmbeds = new Set<ExcalidrawIframeLikeElement["id"]>();
  561. private handleToastClose = () => {
  562. this.setToast(null);
  563. };
  564. private elementsPendingErasure: ElementsPendingErasure = new Set();
  565. public flowChartCreator: FlowChartCreator = new FlowChartCreator();
  566. private flowChartNavigator: FlowChartNavigator = new FlowChartNavigator();
  567. hitLinkElement?: NonDeletedExcalidrawElement;
  568. lastPointerDownEvent: React.PointerEvent<HTMLElement> | null = null;
  569. lastPointerUpEvent: React.PointerEvent<HTMLElement> | PointerEvent | null =
  570. null;
  571. lastPointerMoveEvent: PointerEvent | null = null;
  572. lastPointerMoveCoords: { x: number; y: number } | null = null;
  573. lastViewportPosition = { x: 0, y: 0 };
  574. animationFrameHandler = new AnimationFrameHandler();
  575. laserTrails = new LaserTrails(this.animationFrameHandler, this);
  576. eraserTrail = new EraserTrail(this.animationFrameHandler, this);
  577. lassoTrail = new LassoTrail(this.animationFrameHandler, this);
  578. onChangeEmitter = new Emitter<
  579. [
  580. elements: readonly ExcalidrawElement[],
  581. appState: AppState,
  582. files: BinaryFiles,
  583. ]
  584. >();
  585. onPointerDownEmitter = new Emitter<
  586. [
  587. activeTool: AppState["activeTool"],
  588. pointerDownState: PointerDownState,
  589. event: React.PointerEvent<HTMLElement>,
  590. ]
  591. >();
  592. onPointerUpEmitter = new Emitter<
  593. [
  594. activeTool: AppState["activeTool"],
  595. pointerDownState: PointerDownState,
  596. event: PointerEvent,
  597. ]
  598. >();
  599. onUserFollowEmitter = new Emitter<[payload: OnUserFollowedPayload]>();
  600. onScrollChangeEmitter = new Emitter<
  601. [scrollX: number, scrollY: number, zoom: AppState["zoom"]]
  602. >();
  603. missingPointerEventCleanupEmitter = new Emitter<
  604. [event: PointerEvent | null]
  605. >();
  606. onRemoveEventListenersEmitter = new Emitter<[]>();
  607. constructor(props: AppProps) {
  608. super(props);
  609. const defaultAppState = getDefaultAppState();
  610. const {
  611. excalidrawAPI,
  612. viewModeEnabled = false,
  613. zenModeEnabled = false,
  614. gridModeEnabled = false,
  615. objectsSnapModeEnabled = false,
  616. theme = defaultAppState.theme,
  617. name = `${t("labels.untitled")}-${getDateTime()}`,
  618. } = props;
  619. this.state = {
  620. ...defaultAppState,
  621. theme,
  622. isLoading: true,
  623. ...this.getCanvasOffsets(),
  624. viewModeEnabled,
  625. zenModeEnabled,
  626. objectsSnapModeEnabled,
  627. gridModeEnabled: gridModeEnabled ?? defaultAppState.gridModeEnabled,
  628. name,
  629. width: window.innerWidth,
  630. height: window.innerHeight,
  631. };
  632. this.id = nanoid();
  633. this.library = new Library(this);
  634. this.actionManager = new ActionManager(
  635. this.syncActionResult,
  636. () => this.state,
  637. () => this.scene.getElementsIncludingDeleted(),
  638. this,
  639. );
  640. this.scene = new Scene();
  641. this.canvas = document.createElement("canvas");
  642. this.rc = rough.canvas(this.canvas);
  643. this.renderer = new Renderer(this.scene);
  644. this.visibleElements = [];
  645. this.store = new Store(this);
  646. this.history = new History(this.store);
  647. if (excalidrawAPI) {
  648. const api: ExcalidrawImperativeAPI = {
  649. updateScene: this.updateScene,
  650. mutateElement: this.mutateElement,
  651. updateLibrary: this.library.updateLibrary,
  652. addFiles: this.addFiles,
  653. resetScene: this.resetScene,
  654. getSceneElementsIncludingDeleted: this.getSceneElementsIncludingDeleted,
  655. getSceneElementsMapIncludingDeleted:
  656. this.getSceneElementsMapIncludingDeleted,
  657. history: {
  658. clear: this.resetHistory,
  659. },
  660. scrollToContent: this.scrollToContent,
  661. getSceneElements: this.getSceneElements,
  662. getAppState: () => this.state,
  663. getFiles: () => this.files,
  664. getName: this.getName,
  665. registerAction: (action: Action) => {
  666. this.actionManager.registerAction(action);
  667. },
  668. refresh: this.refresh,
  669. setToast: this.setToast,
  670. id: this.id,
  671. setActiveTool: this.setActiveTool,
  672. setCursor: this.setCursor,
  673. resetCursor: this.resetCursor,
  674. updateFrameRendering: this.updateFrameRendering,
  675. toggleSidebar: this.toggleSidebar,
  676. onChange: (cb) => this.onChangeEmitter.on(cb),
  677. onIncrement: (cb) => this.store.onStoreIncrementEmitter.on(cb),
  678. onPointerDown: (cb) => this.onPointerDownEmitter.on(cb),
  679. onPointerUp: (cb) => this.onPointerUpEmitter.on(cb),
  680. onScrollChange: (cb) => this.onScrollChangeEmitter.on(cb),
  681. onUserFollow: (cb) => this.onUserFollowEmitter.on(cb),
  682. } as const;
  683. if (typeof excalidrawAPI === "function") {
  684. excalidrawAPI(api);
  685. } else {
  686. console.error("excalidrawAPI should be a function!");
  687. }
  688. }
  689. this.excalidrawContainerValue = {
  690. container: this.excalidrawContainerRef.current,
  691. id: this.id,
  692. };
  693. this.fonts = new Fonts(this.scene);
  694. this.history = new History(this.store);
  695. this.actionManager.registerAll(actions);
  696. this.actionManager.registerAction(createUndoAction(this.history));
  697. this.actionManager.registerAction(createRedoAction(this.history));
  698. }
  699. updateEditorAtom = <Value, Args extends unknown[], Result>(
  700. atom: WritableAtom<Value, Args, Result>,
  701. ...args: Args
  702. ): Result => {
  703. const result = editorJotaiStore.set(atom, ...args);
  704. this.triggerRender();
  705. return result;
  706. };
  707. private onWindowMessage(event: MessageEvent) {
  708. if (
  709. event.origin !== "https://player.vimeo.com" &&
  710. event.origin !== "https://www.youtube.com"
  711. ) {
  712. return;
  713. }
  714. let data = null;
  715. try {
  716. data = JSON.parse(event.data);
  717. } catch (e) {}
  718. if (!data) {
  719. return;
  720. }
  721. switch (event.origin) {
  722. case "https://player.vimeo.com":
  723. //Allowing for multiple instances of Excalidraw running in the window
  724. if (data.method === "paused") {
  725. let source: Window | null = null;
  726. const iframes = document.body.querySelectorAll(
  727. "iframe.excalidraw__embeddable",
  728. );
  729. if (!iframes) {
  730. break;
  731. }
  732. for (const iframe of iframes as NodeListOf<HTMLIFrameElement>) {
  733. if (iframe.contentWindow === event.source) {
  734. source = iframe.contentWindow;
  735. }
  736. }
  737. source?.postMessage(
  738. JSON.stringify({
  739. method: data.value ? "play" : "pause",
  740. value: true,
  741. }),
  742. "*",
  743. );
  744. }
  745. break;
  746. case "https://www.youtube.com":
  747. if (
  748. data.event === "infoDelivery" &&
  749. data.info &&
  750. data.id &&
  751. typeof data.info.playerState === "number"
  752. ) {
  753. const id = data.id;
  754. const playerState = data.info.playerState as number;
  755. if (
  756. (Object.values(YOUTUBE_STATES) as number[]).includes(playerState)
  757. ) {
  758. YOUTUBE_VIDEO_STATES.set(
  759. id,
  760. playerState as ValueOf<typeof YOUTUBE_STATES>,
  761. );
  762. }
  763. }
  764. break;
  765. }
  766. }
  767. private cacheEmbeddableRef(
  768. element: ExcalidrawIframeLikeElement,
  769. ref: HTMLIFrameElement | null,
  770. ) {
  771. if (ref) {
  772. this.iFrameRefs.set(element.id, ref);
  773. }
  774. }
  775. /**
  776. * Returns gridSize taking into account `gridModeEnabled`.
  777. * If disabled, returns null.
  778. */
  779. public getEffectiveGridSize = () => {
  780. return (
  781. isGridModeEnabled(this) ? this.state.gridSize : null
  782. ) as NullableGridSize;
  783. };
  784. private getHTMLIFrameElement(
  785. element: ExcalidrawIframeLikeElement,
  786. ): HTMLIFrameElement | undefined {
  787. return this.iFrameRefs.get(element.id);
  788. }
  789. private handleEmbeddableCenterClick(element: ExcalidrawIframeLikeElement) {
  790. if (
  791. this.state.activeEmbeddable?.element === element &&
  792. this.state.activeEmbeddable?.state === "active"
  793. ) {
  794. return;
  795. }
  796. // The delay serves two purposes
  797. // 1. To prevent first click propagating to iframe on mobile,
  798. // else the click will immediately start and stop the video
  799. // 2. If the user double clicks the frame center to activate it
  800. // without the delay youtube will immediately open the video
  801. // in fullscreen mode
  802. setTimeout(() => {
  803. this.setState({
  804. activeEmbeddable: { element, state: "active" },
  805. selectedElementIds: { [element.id]: true },
  806. newElement: null,
  807. selectionElement: null,
  808. });
  809. }, 100);
  810. if (isIframeElement(element)) {
  811. return;
  812. }
  813. const iframe = this.getHTMLIFrameElement(element);
  814. if (!iframe?.contentWindow) {
  815. return;
  816. }
  817. if (iframe.src.includes("youtube")) {
  818. const state = YOUTUBE_VIDEO_STATES.get(element.id);
  819. if (!state) {
  820. YOUTUBE_VIDEO_STATES.set(element.id, YOUTUBE_STATES.UNSTARTED);
  821. iframe.contentWindow.postMessage(
  822. JSON.stringify({
  823. event: "listening",
  824. id: element.id,
  825. }),
  826. "*",
  827. );
  828. }
  829. switch (state) {
  830. case YOUTUBE_STATES.PLAYING:
  831. case YOUTUBE_STATES.BUFFERING:
  832. iframe.contentWindow?.postMessage(
  833. JSON.stringify({
  834. event: "command",
  835. func: "pauseVideo",
  836. args: "",
  837. }),
  838. "*",
  839. );
  840. break;
  841. default:
  842. iframe.contentWindow?.postMessage(
  843. JSON.stringify({
  844. event: "command",
  845. func: "playVideo",
  846. args: "",
  847. }),
  848. "*",
  849. );
  850. }
  851. }
  852. if (iframe.src.includes("player.vimeo.com")) {
  853. iframe.contentWindow.postMessage(
  854. JSON.stringify({
  855. method: "paused", //video play/pause in onWindowMessage handler
  856. }),
  857. "*",
  858. );
  859. }
  860. }
  861. private isIframeLikeElementCenter(
  862. el: ExcalidrawIframeLikeElement | null,
  863. event: React.PointerEvent<HTMLElement> | PointerEvent,
  864. sceneX: number,
  865. sceneY: number,
  866. ) {
  867. return (
  868. el &&
  869. !event.altKey &&
  870. !event.shiftKey &&
  871. !event.metaKey &&
  872. !event.ctrlKey &&
  873. (this.state.activeEmbeddable?.element !== el ||
  874. this.state.activeEmbeddable?.state === "hover" ||
  875. !this.state.activeEmbeddable) &&
  876. sceneX >= el.x + el.width / 3 &&
  877. sceneX <= el.x + (2 * el.width) / 3 &&
  878. sceneY >= el.y + el.height / 3 &&
  879. sceneY <= el.y + (2 * el.height) / 3
  880. );
  881. }
  882. private updateEmbedValidationStatus = (
  883. element: ExcalidrawEmbeddableElement,
  884. status: boolean,
  885. ) => {
  886. this.embedsValidationStatus.set(element.id, status);
  887. ShapeCache.delete(element);
  888. };
  889. private updateEmbeddables = () => {
  890. const iframeLikes = new Set<ExcalidrawIframeLikeElement["id"]>();
  891. let updated = false;
  892. this.scene.getNonDeletedElements().filter((element) => {
  893. if (isEmbeddableElement(element)) {
  894. iframeLikes.add(element.id);
  895. if (!this.embedsValidationStatus.has(element.id)) {
  896. updated = true;
  897. const validated = embeddableURLValidator(
  898. element.link,
  899. this.props.validateEmbeddable,
  900. );
  901. this.updateEmbedValidationStatus(element, validated);
  902. }
  903. } else if (isIframeElement(element)) {
  904. iframeLikes.add(element.id);
  905. }
  906. return false;
  907. });
  908. if (updated) {
  909. this.scene.triggerUpdate();
  910. }
  911. // GC
  912. this.iFrameRefs.forEach((ref, id) => {
  913. if (!iframeLikes.has(id)) {
  914. this.iFrameRefs.delete(id);
  915. }
  916. });
  917. };
  918. private renderEmbeddables() {
  919. const scale = this.state.zoom.value;
  920. const normalizedWidth = this.state.width;
  921. const normalizedHeight = this.state.height;
  922. const embeddableElements = this.scene
  923. .getNonDeletedElements()
  924. .filter(
  925. (el): el is Ordered<NonDeleted<ExcalidrawIframeLikeElement>> =>
  926. (isEmbeddableElement(el) &&
  927. this.embedsValidationStatus.get(el.id) === true) ||
  928. isIframeElement(el),
  929. );
  930. return (
  931. <>
  932. {embeddableElements.map((el) => {
  933. const { x, y } = sceneCoordsToViewportCoords(
  934. { sceneX: el.x, sceneY: el.y },
  935. this.state,
  936. );
  937. const isVisible = isElementInViewport(
  938. el,
  939. normalizedWidth,
  940. normalizedHeight,
  941. this.state,
  942. this.scene.getNonDeletedElementsMap(),
  943. );
  944. const hasBeenInitialized = this.initializedEmbeds.has(el.id);
  945. if (isVisible && !hasBeenInitialized) {
  946. this.initializedEmbeds.add(el.id);
  947. }
  948. const shouldRender = isVisible || hasBeenInitialized;
  949. if (!shouldRender) {
  950. return null;
  951. }
  952. let src: IframeData | null;
  953. if (isIframeElement(el)) {
  954. src = null;
  955. const data: MagicGenerationData = (el.customData?.generationData ??
  956. this.magicGenerations.get(el.id)) || {
  957. status: "error",
  958. message: "No generation data",
  959. code: "ERR_NO_GENERATION_DATA",
  960. };
  961. if (data.status === "done") {
  962. const html = data.html;
  963. src = {
  964. intrinsicSize: { w: el.width, h: el.height },
  965. type: "document",
  966. srcdoc: () => {
  967. return html;
  968. },
  969. } as const;
  970. } else if (data.status === "pending") {
  971. src = {
  972. intrinsicSize: { w: el.width, h: el.height },
  973. type: "document",
  974. srcdoc: () => {
  975. return createSrcDoc(`
  976. <style>
  977. html, body {
  978. width: 100%;
  979. height: 100%;
  980. color: ${
  981. this.state.theme === THEME.DARK ? "white" : "black"
  982. };
  983. }
  984. body {
  985. display: flex;
  986. align-items: center;
  987. justify-content: center;
  988. flex-direction: column;
  989. gap: 1rem;
  990. }
  991. .Spinner {
  992. display: flex;
  993. align-items: center;
  994. justify-content: center;
  995. margin-left: auto;
  996. margin-right: auto;
  997. }
  998. .Spinner svg {
  999. animation: rotate 1.6s linear infinite;
  1000. transform-origin: center center;
  1001. width: 40px;
  1002. height: 40px;
  1003. }
  1004. .Spinner circle {
  1005. stroke: currentColor;
  1006. animation: dash 1.6s linear 0s infinite;
  1007. stroke-linecap: round;
  1008. }
  1009. @keyframes rotate {
  1010. 100% {
  1011. transform: rotate(360deg);
  1012. }
  1013. }
  1014. @keyframes dash {
  1015. 0% {
  1016. stroke-dasharray: 1, 300;
  1017. stroke-dashoffset: 0;
  1018. }
  1019. 50% {
  1020. stroke-dasharray: 150, 300;
  1021. stroke-dashoffset: -200;
  1022. }
  1023. 100% {
  1024. stroke-dasharray: 1, 300;
  1025. stroke-dashoffset: -280;
  1026. }
  1027. }
  1028. </style>
  1029. <div class="Spinner">
  1030. <svg
  1031. viewBox="0 0 100 100"
  1032. >
  1033. <circle
  1034. cx="50"
  1035. cy="50"
  1036. r="46"
  1037. stroke-width="8"
  1038. fill="none"
  1039. stroke-miter-limit="10"
  1040. />
  1041. </svg>
  1042. </div>
  1043. <div>Generating...</div>
  1044. `);
  1045. },
  1046. } as const;
  1047. } else {
  1048. let message: string;
  1049. if (data.code === "ERR_GENERATION_INTERRUPTED") {
  1050. message = "Generation was interrupted...";
  1051. } else {
  1052. message = data.message || "Generation failed";
  1053. }
  1054. src = {
  1055. intrinsicSize: { w: el.width, h: el.height },
  1056. type: "document",
  1057. srcdoc: () => {
  1058. return createSrcDoc(`
  1059. <style>
  1060. html, body {
  1061. height: 100%;
  1062. }
  1063. body {
  1064. display: flex;
  1065. flex-direction: column;
  1066. align-items: center;
  1067. justify-content: center;
  1068. color: ${COLOR_PALETTE.red[3]};
  1069. }
  1070. h1, h3 {
  1071. margin-top: 0;
  1072. margin-bottom: 0.5rem;
  1073. }
  1074. </style>
  1075. <h1>Error!</h1>
  1076. <h3>${message}</h3>
  1077. `);
  1078. },
  1079. } as const;
  1080. }
  1081. } else {
  1082. src = getEmbedLink(toValidURL(el.link || ""));
  1083. }
  1084. const isActive =
  1085. this.state.activeEmbeddable?.element === el &&
  1086. this.state.activeEmbeddable?.state === "active";
  1087. const isHovered =
  1088. this.state.activeEmbeddable?.element === el &&
  1089. this.state.activeEmbeddable?.state === "hover";
  1090. return (
  1091. <div
  1092. key={el.id}
  1093. className={clsx("excalidraw__embeddable-container", {
  1094. "is-hovered": isHovered,
  1095. })}
  1096. style={{
  1097. transform: isVisible
  1098. ? `translate(${x - this.state.offsetLeft}px, ${
  1099. y - this.state.offsetTop
  1100. }px) scale(${scale})`
  1101. : "none",
  1102. display: isVisible ? "block" : "none",
  1103. opacity: getRenderOpacity(
  1104. el,
  1105. getContainingFrame(el, this.scene.getNonDeletedElementsMap()),
  1106. this.elementsPendingErasure,
  1107. null,
  1108. this.state.openDialog?.name === "elementLinkSelector"
  1109. ? DEFAULT_REDUCED_GLOBAL_ALPHA
  1110. : 1,
  1111. ),
  1112. ["--embeddable-radius" as string]: `${getCornerRadius(
  1113. Math.min(el.width, el.height),
  1114. el,
  1115. )}px`,
  1116. }}
  1117. >
  1118. <div
  1119. //this is a hack that addresses isse with embedded excalidraw.com embeddable
  1120. //https://github.com/excalidraw/excalidraw/pull/6691#issuecomment-1607383938
  1121. /*ref={(ref) => {
  1122. if (!this.excalidrawContainerRef.current) {
  1123. return;
  1124. }
  1125. const container = this.excalidrawContainerRef.current;
  1126. const sh = container.scrollHeight;
  1127. const ch = container.clientHeight;
  1128. if (sh !== ch) {
  1129. container.style.height = `${sh}px`;
  1130. setTimeout(() => {
  1131. container.style.height = `100%`;
  1132. });
  1133. }
  1134. }}*/
  1135. className="excalidraw__embeddable-container__inner"
  1136. style={{
  1137. width: isVisible ? `${el.width}px` : 0,
  1138. height: isVisible ? `${el.height}px` : 0,
  1139. transform: isVisible ? `rotate(${el.angle}rad)` : "none",
  1140. pointerEvents: isActive
  1141. ? POINTER_EVENTS.enabled
  1142. : POINTER_EVENTS.disabled,
  1143. }}
  1144. >
  1145. {isHovered && (
  1146. <div className="excalidraw__embeddable-hint">
  1147. {t("buttons.embeddableInteractionButton")}
  1148. </div>
  1149. )}
  1150. <div
  1151. className="excalidraw__embeddable__outer"
  1152. style={{
  1153. padding: `${el.strokeWidth}px`,
  1154. }}
  1155. >
  1156. {(isEmbeddableElement(el)
  1157. ? this.props.renderEmbeddable?.(el, this.state)
  1158. : null) ?? (
  1159. <iframe
  1160. ref={(ref) => this.cacheEmbeddableRef(el, ref)}
  1161. className="excalidraw__embeddable"
  1162. srcDoc={
  1163. src?.type === "document"
  1164. ? src.srcdoc(this.state.theme)
  1165. : undefined
  1166. }
  1167. src={
  1168. src?.type !== "document" ? src?.link ?? "" : undefined
  1169. }
  1170. // https://stackoverflow.com/q/18470015
  1171. scrolling="no"
  1172. referrerPolicy="no-referrer-when-downgrade"
  1173. title="Excalidraw Embedded Content"
  1174. allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
  1175. allowFullScreen={true}
  1176. sandbox={`${
  1177. src?.sandbox?.allowSameOrigin ? "allow-same-origin" : ""
  1178. } allow-scripts allow-forms allow-popups allow-popups-to-escape-sandbox allow-presentation allow-downloads`}
  1179. />
  1180. )}
  1181. </div>
  1182. </div>
  1183. </div>
  1184. );
  1185. })}
  1186. </>
  1187. );
  1188. }
  1189. private getFrameNameDOMId = (frameElement: ExcalidrawElement) => {
  1190. return `${this.id}-frame-name-${frameElement.id}`;
  1191. };
  1192. frameNameBoundsCache: FrameNameBoundsCache = {
  1193. get: (frameElement) => {
  1194. let bounds = this.frameNameBoundsCache._cache.get(frameElement.id);
  1195. if (
  1196. !bounds ||
  1197. bounds.zoom !== this.state.zoom.value ||
  1198. bounds.versionNonce !== frameElement.versionNonce
  1199. ) {
  1200. const frameNameDiv = document.getElementById(
  1201. this.getFrameNameDOMId(frameElement),
  1202. );
  1203. if (frameNameDiv) {
  1204. const box = frameNameDiv.getBoundingClientRect();
  1205. const boxSceneTopLeft = viewportCoordsToSceneCoords(
  1206. { clientX: box.x, clientY: box.y },
  1207. this.state,
  1208. );
  1209. const boxSceneBottomRight = viewportCoordsToSceneCoords(
  1210. { clientX: box.right, clientY: box.bottom },
  1211. this.state,
  1212. );
  1213. bounds = {
  1214. x: boxSceneTopLeft.x,
  1215. y: boxSceneTopLeft.y,
  1216. width: boxSceneBottomRight.x - boxSceneTopLeft.x,
  1217. height: boxSceneBottomRight.y - boxSceneTopLeft.y,
  1218. angle: 0,
  1219. zoom: this.state.zoom.value,
  1220. versionNonce: frameElement.versionNonce,
  1221. };
  1222. this.frameNameBoundsCache._cache.set(frameElement.id, bounds);
  1223. return bounds;
  1224. }
  1225. return null;
  1226. }
  1227. return bounds;
  1228. },
  1229. /**
  1230. * @private
  1231. */
  1232. _cache: new Map(),
  1233. };
  1234. private resetEditingFrame = (frame: ExcalidrawFrameLikeElement | null) => {
  1235. if (frame) {
  1236. this.scene.mutateElement(frame, { name: frame.name?.trim() || null });
  1237. }
  1238. this.setState({ editingFrame: null });
  1239. };
  1240. private renderFrameNames = () => {
  1241. if (!this.state.frameRendering.enabled || !this.state.frameRendering.name) {
  1242. if (this.state.editingFrame) {
  1243. this.resetEditingFrame(null);
  1244. }
  1245. return null;
  1246. }
  1247. const isDarkTheme = this.state.theme === THEME.DARK;
  1248. const nonDeletedFramesLikes = this.scene.getNonDeletedFramesLikes();
  1249. const focusedSearchMatch =
  1250. nonDeletedFramesLikes.length > 0
  1251. ? this.state.searchMatches?.focusedId &&
  1252. isFrameLikeElement(
  1253. this.scene.getElement(this.state.searchMatches.focusedId),
  1254. )
  1255. ? this.state.searchMatches.matches.find((sm) => sm.focus)
  1256. : null
  1257. : null;
  1258. return nonDeletedFramesLikes.map((f) => {
  1259. if (
  1260. !isElementInViewport(
  1261. f,
  1262. this.canvas.width / window.devicePixelRatio,
  1263. this.canvas.height / window.devicePixelRatio,
  1264. {
  1265. offsetLeft: this.state.offsetLeft,
  1266. offsetTop: this.state.offsetTop,
  1267. scrollX: this.state.scrollX,
  1268. scrollY: this.state.scrollY,
  1269. zoom: this.state.zoom,
  1270. },
  1271. this.scene.getNonDeletedElementsMap(),
  1272. )
  1273. ) {
  1274. if (this.state.editingFrame === f.id) {
  1275. this.resetEditingFrame(f);
  1276. }
  1277. // if frame not visible, don't render its name
  1278. return null;
  1279. }
  1280. const { x: x1, y: y1 } = sceneCoordsToViewportCoords(
  1281. { sceneX: f.x, sceneY: f.y },
  1282. this.state,
  1283. );
  1284. const FRAME_NAME_EDIT_PADDING = 6;
  1285. let frameNameJSX;
  1286. const frameName = getFrameLikeTitle(f);
  1287. if (f.id === this.state.editingFrame) {
  1288. const frameNameInEdit = frameName;
  1289. frameNameJSX = (
  1290. <input
  1291. autoFocus
  1292. value={frameNameInEdit}
  1293. onChange={(e) => {
  1294. this.scene.mutateElement(f, {
  1295. name: e.target.value,
  1296. });
  1297. }}
  1298. onFocus={(e) => e.target.select()}
  1299. onBlur={() => this.resetEditingFrame(f)}
  1300. onKeyDown={(event) => {
  1301. // for some inexplicable reason, `onBlur` triggered on ESC
  1302. // does not reset `state.editingFrame` despite being called,
  1303. // and we need to reset it here as well
  1304. if (event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) {
  1305. this.resetEditingFrame(f);
  1306. }
  1307. }}
  1308. style={{
  1309. background: this.state.viewBackgroundColor,
  1310. filter: isDarkTheme ? THEME_FILTER : "none",
  1311. zIndex: 2,
  1312. border: "none",
  1313. display: "block",
  1314. padding: `${FRAME_NAME_EDIT_PADDING}px`,
  1315. borderRadius: 4,
  1316. boxShadow: "inset 0 0 0 1px var(--color-primary)",
  1317. fontFamily: "Assistant",
  1318. fontSize: `${FRAME_STYLE.nameFontSize}px`,
  1319. transform: `translate(-${FRAME_NAME_EDIT_PADDING}px, ${FRAME_NAME_EDIT_PADDING}px)`,
  1320. color: "var(--color-gray-80)",
  1321. overflow: "hidden",
  1322. maxWidth: `${
  1323. document.body.clientWidth - x1 - FRAME_NAME_EDIT_PADDING
  1324. }px`,
  1325. }}
  1326. size={frameNameInEdit.length + 1 || 1}
  1327. dir="auto"
  1328. autoComplete="off"
  1329. autoCapitalize="off"
  1330. autoCorrect="off"
  1331. />
  1332. );
  1333. } else {
  1334. frameNameJSX = frameName;
  1335. }
  1336. return (
  1337. <div
  1338. id={this.getFrameNameDOMId(f)}
  1339. key={f.id}
  1340. style={{
  1341. position: "absolute",
  1342. // Positioning from bottom so that we don't to either
  1343. // calculate text height or adjust using transform (which)
  1344. // messes up input position when editing the frame name.
  1345. // This makes the positioning deterministic and we can calculate
  1346. // the same position when rendering to canvas / svg.
  1347. bottom: `${
  1348. this.state.height +
  1349. FRAME_STYLE.nameOffsetY -
  1350. y1 +
  1351. this.state.offsetTop
  1352. }px`,
  1353. left: `${x1 - this.state.offsetLeft}px`,
  1354. zIndex: 2,
  1355. fontSize: FRAME_STYLE.nameFontSize,
  1356. color: isDarkTheme
  1357. ? FRAME_STYLE.nameColorDarkTheme
  1358. : FRAME_STYLE.nameColorLightTheme,
  1359. lineHeight: FRAME_STYLE.nameLineHeight,
  1360. width: "max-content",
  1361. maxWidth:
  1362. focusedSearchMatch?.id === f.id && focusedSearchMatch?.focus
  1363. ? "none"
  1364. : `${f.width * this.state.zoom.value}px`,
  1365. overflow: f.id === this.state.editingFrame ? "visible" : "hidden",
  1366. whiteSpace: "nowrap",
  1367. textOverflow: "ellipsis",
  1368. cursor: CURSOR_TYPE.MOVE,
  1369. pointerEvents: this.state.viewModeEnabled
  1370. ? POINTER_EVENTS.disabled
  1371. : POINTER_EVENTS.enabled,
  1372. }}
  1373. onPointerDown={(event) => this.handleCanvasPointerDown(event)}
  1374. onWheel={(event) => this.handleWheel(event)}
  1375. onContextMenu={this.handleCanvasContextMenu}
  1376. onDoubleClick={() => {
  1377. this.setState({
  1378. editingFrame: f.id,
  1379. });
  1380. }}
  1381. >
  1382. {frameNameJSX}
  1383. </div>
  1384. );
  1385. });
  1386. };
  1387. private toggleOverscrollBehavior(event: React.PointerEvent) {
  1388. // when pointer inside editor, disable overscroll behavior to prevent
  1389. // panning to trigger history back/forward on MacOS Chrome
  1390. document.documentElement.style.overscrollBehaviorX =
  1391. event.type === "pointerenter" ? "none" : "auto";
  1392. }
  1393. public render() {
  1394. const selectedElements = this.scene.getSelectedElements(this.state);
  1395. const { renderTopRightUI, renderCustomStats } = this.props;
  1396. const sceneNonce = this.scene.getSceneNonce();
  1397. const { elementsMap, visibleElements } =
  1398. this.renderer.getRenderableElements({
  1399. sceneNonce,
  1400. zoom: this.state.zoom,
  1401. offsetLeft: this.state.offsetLeft,
  1402. offsetTop: this.state.offsetTop,
  1403. scrollX: this.state.scrollX,
  1404. scrollY: this.state.scrollY,
  1405. height: this.state.height,
  1406. width: this.state.width,
  1407. editingTextElement: this.state.editingTextElement,
  1408. newElementId: this.state.newElement?.id,
  1409. });
  1410. this.visibleElements = visibleElements;
  1411. const allElementsMap = this.scene.getNonDeletedElementsMap();
  1412. const shouldBlockPointerEvents =
  1413. // default back to `--ui-pointerEvents` flow if setPointerCapture
  1414. // not supported
  1415. "setPointerCapture" in HTMLElement.prototype
  1416. ? false
  1417. : this.state.selectionElement ||
  1418. this.state.newElement ||
  1419. this.state.selectedElementsAreBeingDragged ||
  1420. this.state.resizingElement ||
  1421. (this.state.activeTool.type === "laser" &&
  1422. // technically we can just test on this once we make it more safe
  1423. this.state.cursorButton === "down");
  1424. const firstSelectedElement = selectedElements[0];
  1425. const showShapeSwitchPanel =
  1426. editorJotaiStore.get(convertElementTypePopupAtom)?.type === "panel";
  1427. return (
  1428. <div
  1429. className={clsx("excalidraw excalidraw-container", {
  1430. "excalidraw--view-mode":
  1431. this.state.viewModeEnabled ||
  1432. this.state.openDialog?.name === "elementLinkSelector",
  1433. "excalidraw--mobile": this.device.editor.isMobile,
  1434. })}
  1435. style={{
  1436. ["--ui-pointerEvents" as any]: shouldBlockPointerEvents
  1437. ? POINTER_EVENTS.disabled
  1438. : POINTER_EVENTS.enabled,
  1439. ["--right-sidebar-width" as any]: "302px",
  1440. }}
  1441. ref={this.excalidrawContainerRef}
  1442. onDrop={this.handleAppOnDrop}
  1443. tabIndex={0}
  1444. onKeyDown={
  1445. this.props.handleKeyboardGlobally ? undefined : this.onKeyDown
  1446. }
  1447. onPointerEnter={this.toggleOverscrollBehavior}
  1448. onPointerLeave={this.toggleOverscrollBehavior}
  1449. >
  1450. <AppContext.Provider value={this}>
  1451. <AppPropsContext.Provider value={this.props}>
  1452. <ExcalidrawContainerContext.Provider
  1453. value={this.excalidrawContainerValue}
  1454. >
  1455. <DeviceContext.Provider value={this.device}>
  1456. <ExcalidrawSetAppStateContext.Provider value={this.setAppState}>
  1457. <ExcalidrawAppStateContext.Provider value={this.state}>
  1458. <ExcalidrawElementsContext.Provider
  1459. value={this.scene.getNonDeletedElements()}
  1460. >
  1461. <ExcalidrawActionManagerContext.Provider
  1462. value={this.actionManager}
  1463. >
  1464. <LayerUI
  1465. canvas={this.canvas}
  1466. appState={this.state}
  1467. files={this.files}
  1468. setAppState={this.setAppState}
  1469. actionManager={this.actionManager}
  1470. elements={this.scene.getNonDeletedElements()}
  1471. onLockToggle={this.toggleLock}
  1472. onPenModeToggle={this.togglePenMode}
  1473. onHandToolToggle={this.onHandToolToggle}
  1474. langCode={getLanguage().code}
  1475. renderTopRightUI={renderTopRightUI}
  1476. renderCustomStats={renderCustomStats}
  1477. showExitZenModeBtn={
  1478. typeof this.props?.zenModeEnabled === "undefined" &&
  1479. this.state.zenModeEnabled
  1480. }
  1481. UIOptions={this.props.UIOptions}
  1482. onExportImage={this.onExportImage}
  1483. renderWelcomeScreen={
  1484. !this.state.isLoading &&
  1485. this.state.showWelcomeScreen &&
  1486. this.state.activeTool.type === "selection" &&
  1487. !this.state.zenModeEnabled &&
  1488. !this.scene.getElementsIncludingDeleted().length
  1489. }
  1490. app={this}
  1491. isCollaborating={this.props.isCollaborating}
  1492. generateLinkForSelection={
  1493. this.props.generateLinkForSelection
  1494. }
  1495. >
  1496. {this.props.children}
  1497. </LayerUI>
  1498. <div className="excalidraw-textEditorContainer" />
  1499. <div className="excalidraw-contextMenuContainer" />
  1500. <div className="excalidraw-eye-dropper-container" />
  1501. <SVGLayer
  1502. trails={[
  1503. this.laserTrails,
  1504. this.lassoTrail,
  1505. this.eraserTrail,
  1506. ]}
  1507. />
  1508. {selectedElements.length === 1 &&
  1509. this.state.openDialog?.name !==
  1510. "elementLinkSelector" &&
  1511. this.state.showHyperlinkPopup && (
  1512. <Hyperlink
  1513. key={firstSelectedElement.id}
  1514. element={firstSelectedElement}
  1515. scene={this.scene}
  1516. setAppState={this.setAppState}
  1517. onLinkOpen={this.props.onLinkOpen}
  1518. setToast={this.setToast}
  1519. updateEmbedValidationStatus={
  1520. this.updateEmbedValidationStatus
  1521. }
  1522. />
  1523. )}
  1524. {this.props.aiEnabled !== false &&
  1525. selectedElements.length === 1 &&
  1526. isMagicFrameElement(firstSelectedElement) && (
  1527. <ElementCanvasButtons
  1528. element={firstSelectedElement}
  1529. elementsMap={elementsMap}
  1530. >
  1531. <ElementCanvasButton
  1532. title={t("labels.convertToCode")}
  1533. icon={MagicIcon}
  1534. checked={false}
  1535. onChange={() =>
  1536. this.onMagicFrameGenerate(
  1537. firstSelectedElement,
  1538. "button",
  1539. )
  1540. }
  1541. />
  1542. </ElementCanvasButtons>
  1543. )}
  1544. {selectedElements.length === 1 &&
  1545. isIframeElement(firstSelectedElement) &&
  1546. firstSelectedElement.customData?.generationData
  1547. ?.status === "done" && (
  1548. <ElementCanvasButtons
  1549. element={firstSelectedElement}
  1550. elementsMap={elementsMap}
  1551. >
  1552. <ElementCanvasButton
  1553. title={t("labels.copySource")}
  1554. icon={copyIcon}
  1555. checked={false}
  1556. onChange={() =>
  1557. this.onIframeSrcCopy(firstSelectedElement)
  1558. }
  1559. />
  1560. <ElementCanvasButton
  1561. title="Enter fullscreen"
  1562. icon={fullscreenIcon}
  1563. checked={false}
  1564. onChange={() => {
  1565. const iframe =
  1566. this.getHTMLIFrameElement(
  1567. firstSelectedElement,
  1568. );
  1569. if (iframe) {
  1570. try {
  1571. iframe.requestFullscreen();
  1572. this.setState({
  1573. activeEmbeddable: {
  1574. element: firstSelectedElement,
  1575. state: "active",
  1576. },
  1577. selectedElementIds: {
  1578. [firstSelectedElement.id]: true,
  1579. },
  1580. newElement: null,
  1581. selectionElement: null,
  1582. });
  1583. } catch (err: any) {
  1584. console.warn(err);
  1585. this.setState({
  1586. errorMessage:
  1587. "Couldn't enter fullscreen",
  1588. });
  1589. }
  1590. }
  1591. }}
  1592. />
  1593. </ElementCanvasButtons>
  1594. )}
  1595. {this.state.toast !== null && (
  1596. <Toast
  1597. message={this.state.toast.message}
  1598. onClose={this.handleToastClose}
  1599. duration={this.state.toast.duration}
  1600. closable={this.state.toast.closable}
  1601. />
  1602. )}
  1603. {this.state.contextMenu && (
  1604. <ContextMenu
  1605. items={this.state.contextMenu.items}
  1606. top={this.state.contextMenu.top}
  1607. left={this.state.contextMenu.left}
  1608. actionManager={this.actionManager}
  1609. onClose={(callback) => {
  1610. this.setState({ contextMenu: null }, () => {
  1611. this.focusContainer();
  1612. callback?.();
  1613. });
  1614. }}
  1615. />
  1616. )}
  1617. <StaticCanvas
  1618. canvas={this.canvas}
  1619. rc={this.rc}
  1620. elementsMap={elementsMap}
  1621. allElementsMap={allElementsMap}
  1622. visibleElements={visibleElements}
  1623. sceneNonce={sceneNonce}
  1624. selectionNonce={
  1625. this.state.selectionElement?.versionNonce
  1626. }
  1627. scale={window.devicePixelRatio}
  1628. appState={this.state}
  1629. renderConfig={{
  1630. imageCache: this.imageCache,
  1631. isExporting: false,
  1632. renderGrid: isGridModeEnabled(this),
  1633. canvasBackgroundColor:
  1634. this.state.viewBackgroundColor,
  1635. embedsValidationStatus: this.embedsValidationStatus,
  1636. elementsPendingErasure: this.elementsPendingErasure,
  1637. pendingFlowchartNodes:
  1638. this.flowChartCreator.pendingNodes,
  1639. }}
  1640. />
  1641. {this.state.newElement && (
  1642. <NewElementCanvas
  1643. appState={this.state}
  1644. scale={window.devicePixelRatio}
  1645. rc={this.rc}
  1646. elementsMap={elementsMap}
  1647. allElementsMap={allElementsMap}
  1648. renderConfig={{
  1649. imageCache: this.imageCache,
  1650. isExporting: false,
  1651. renderGrid: false,
  1652. canvasBackgroundColor:
  1653. this.state.viewBackgroundColor,
  1654. embedsValidationStatus:
  1655. this.embedsValidationStatus,
  1656. elementsPendingErasure:
  1657. this.elementsPendingErasure,
  1658. pendingFlowchartNodes: null,
  1659. }}
  1660. />
  1661. )}
  1662. <InteractiveCanvas
  1663. containerRef={this.excalidrawContainerRef}
  1664. canvas={this.interactiveCanvas}
  1665. elementsMap={elementsMap}
  1666. visibleElements={visibleElements}
  1667. allElementsMap={allElementsMap}
  1668. selectedElements={selectedElements}
  1669. sceneNonce={sceneNonce}
  1670. selectionNonce={
  1671. this.state.selectionElement?.versionNonce
  1672. }
  1673. scale={window.devicePixelRatio}
  1674. appState={this.state}
  1675. renderScrollbars={
  1676. this.props.renderScrollbars === true
  1677. }
  1678. device={this.device}
  1679. renderInteractiveSceneCallback={
  1680. this.renderInteractiveSceneCallback
  1681. }
  1682. handleCanvasRef={this.handleInteractiveCanvasRef}
  1683. onContextMenu={this.handleCanvasContextMenu}
  1684. onPointerMove={this.handleCanvasPointerMove}
  1685. onPointerUp={this.handleCanvasPointerUp}
  1686. onPointerCancel={this.removePointer}
  1687. onTouchMove={this.handleTouchMove}
  1688. onPointerDown={this.handleCanvasPointerDown}
  1689. onDoubleClick={this.handleCanvasDoubleClick}
  1690. />
  1691. {this.state.userToFollow && (
  1692. <FollowMode
  1693. width={this.state.width}
  1694. height={this.state.height}
  1695. userToFollow={this.state.userToFollow}
  1696. onDisconnect={this.maybeUnfollowRemoteUser}
  1697. />
  1698. )}
  1699. {this.renderFrameNames()}
  1700. {this.state.activeLockedId && (
  1701. <UnlockPopup
  1702. app={this}
  1703. activeLockedId={this.state.activeLockedId}
  1704. />
  1705. )}
  1706. {showShapeSwitchPanel && (
  1707. <ConvertElementTypePopup app={this} />
  1708. )}
  1709. </ExcalidrawActionManagerContext.Provider>
  1710. {this.renderEmbeddables()}
  1711. </ExcalidrawElementsContext.Provider>
  1712. </ExcalidrawAppStateContext.Provider>
  1713. </ExcalidrawSetAppStateContext.Provider>
  1714. </DeviceContext.Provider>
  1715. </ExcalidrawContainerContext.Provider>
  1716. </AppPropsContext.Provider>
  1717. </AppContext.Provider>
  1718. </div>
  1719. );
  1720. }
  1721. public focusContainer: AppClassProperties["focusContainer"] = () => {
  1722. this.excalidrawContainerRef.current?.focus();
  1723. };
  1724. public getSceneElementsIncludingDeleted = () => {
  1725. return this.scene.getElementsIncludingDeleted();
  1726. };
  1727. public getSceneElementsMapIncludingDeleted = () => {
  1728. return this.scene.getElementsMapIncludingDeleted();
  1729. };
  1730. public getSceneElements = () => {
  1731. return this.scene.getNonDeletedElements();
  1732. };
  1733. public onInsertElements = (elements: readonly ExcalidrawElement[]) => {
  1734. this.addElementsFromPasteOrLibrary({
  1735. elements,
  1736. position: "center",
  1737. files: null,
  1738. });
  1739. };
  1740. public onExportImage = async (
  1741. type: keyof typeof EXPORT_IMAGE_TYPES,
  1742. elements: ExportedElements,
  1743. opts: { exportingFrame: ExcalidrawFrameLikeElement | null },
  1744. ) => {
  1745. trackEvent("export", type, "ui");
  1746. const fileHandle = await exportCanvas(
  1747. type,
  1748. elements,
  1749. this.state,
  1750. this.files,
  1751. {
  1752. exportBackground: this.state.exportBackground,
  1753. name: this.getName(),
  1754. viewBackgroundColor: this.state.viewBackgroundColor,
  1755. exportingFrame: opts.exportingFrame,
  1756. },
  1757. )
  1758. .catch(muteFSAbortError)
  1759. .catch((error) => {
  1760. console.error(error);
  1761. this.setState({ errorMessage: error.message });
  1762. });
  1763. if (
  1764. this.state.exportEmbedScene &&
  1765. fileHandle &&
  1766. isImageFileHandle(fileHandle)
  1767. ) {
  1768. this.setState({ fileHandle });
  1769. }
  1770. };
  1771. private magicGenerations = new Map<
  1772. ExcalidrawIframeElement["id"],
  1773. MagicGenerationData
  1774. >();
  1775. private updateMagicGeneration = ({
  1776. frameElement,
  1777. data,
  1778. }: {
  1779. frameElement: ExcalidrawIframeElement;
  1780. data: MagicGenerationData;
  1781. }) => {
  1782. if (data.status === "pending") {
  1783. // We don't wanna persist pending state to storage. It should be in-app
  1784. // state only.
  1785. // Thus reset so that we prefer local cache (if there was some
  1786. // generationData set previously)
  1787. this.scene.mutateElement(
  1788. frameElement,
  1789. {
  1790. customData: { generationData: undefined },
  1791. },
  1792. { informMutation: false, isDragging: false },
  1793. );
  1794. } else {
  1795. this.scene.mutateElement(
  1796. frameElement,
  1797. {
  1798. customData: { generationData: data },
  1799. },
  1800. { informMutation: false, isDragging: false },
  1801. );
  1802. }
  1803. this.magicGenerations.set(frameElement.id, data);
  1804. this.triggerRender();
  1805. };
  1806. public plugins: {
  1807. diagramToCode?: {
  1808. generate: GenerateDiagramToCode;
  1809. };
  1810. } = {};
  1811. public setPlugins(plugins: Partial<App["plugins"]>) {
  1812. Object.assign(this.plugins, plugins);
  1813. }
  1814. private async onMagicFrameGenerate(
  1815. magicFrame: ExcalidrawMagicFrameElement,
  1816. source: "button" | "upstream",
  1817. ) {
  1818. const generateDiagramToCode = this.plugins.diagramToCode?.generate;
  1819. if (!generateDiagramToCode) {
  1820. this.setState({
  1821. errorMessage: "No diagram to code plugin found",
  1822. });
  1823. return;
  1824. }
  1825. const magicFrameChildren = getElementsOverlappingFrame(
  1826. this.scene.getNonDeletedElements(),
  1827. magicFrame,
  1828. ).filter((el) => !isMagicFrameElement(el));
  1829. if (!magicFrameChildren.length) {
  1830. if (source === "button") {
  1831. this.setState({ errorMessage: "Cannot generate from an empty frame" });
  1832. trackEvent("ai", "generate (no-children)", "d2c");
  1833. } else {
  1834. this.setActiveTool({ type: "magicframe" });
  1835. }
  1836. return;
  1837. }
  1838. const frameElement = this.insertIframeElement({
  1839. sceneX: magicFrame.x + magicFrame.width + 30,
  1840. sceneY: magicFrame.y,
  1841. width: magicFrame.width,
  1842. height: magicFrame.height,
  1843. });
  1844. if (!frameElement) {
  1845. return;
  1846. }
  1847. this.updateMagicGeneration({
  1848. frameElement,
  1849. data: { status: "pending" },
  1850. });
  1851. this.setState({
  1852. selectedElementIds: { [frameElement.id]: true },
  1853. });
  1854. trackEvent("ai", "generate (start)", "d2c");
  1855. try {
  1856. const { html } = await generateDiagramToCode({
  1857. frame: magicFrame,
  1858. children: magicFrameChildren,
  1859. });
  1860. trackEvent("ai", "generate (success)", "d2c");
  1861. if (!html.trim()) {
  1862. this.updateMagicGeneration({
  1863. frameElement,
  1864. data: {
  1865. status: "error",
  1866. code: "ERR_OAI",
  1867. message: "Nothing genereated :(",
  1868. },
  1869. });
  1870. return;
  1871. }
  1872. const parsedHtml =
  1873. html.includes("<!DOCTYPE html>") && html.includes("</html>")
  1874. ? html.slice(
  1875. html.indexOf("<!DOCTYPE html>"),
  1876. html.indexOf("</html>") + "</html>".length,
  1877. )
  1878. : html;
  1879. this.updateMagicGeneration({
  1880. frameElement,
  1881. data: { status: "done", html: parsedHtml },
  1882. });
  1883. } catch (error: any) {
  1884. trackEvent("ai", "generate (failed)", "d2c");
  1885. this.updateMagicGeneration({
  1886. frameElement,
  1887. data: {
  1888. status: "error",
  1889. code: "ERR_OAI",
  1890. message: error.message || "Unknown error during generation",
  1891. },
  1892. });
  1893. }
  1894. }
  1895. private onIframeSrcCopy(element: ExcalidrawIframeElement) {
  1896. if (element.customData?.generationData?.status === "done") {
  1897. copyTextToSystemClipboard(element.customData.generationData.html);
  1898. this.setToast({
  1899. message: "copied to clipboard",
  1900. closable: false,
  1901. duration: 1500,
  1902. });
  1903. }
  1904. }
  1905. public onMagicframeToolSelect = () => {
  1906. const selectedElements = this.scene.getSelectedElements({
  1907. selectedElementIds: this.state.selectedElementIds,
  1908. });
  1909. if (selectedElements.length === 0) {
  1910. this.setActiveTool({ type: TOOL_TYPE.magicframe });
  1911. trackEvent("ai", "tool-select (empty-selection)", "d2c");
  1912. } else {
  1913. const selectedMagicFrame: ExcalidrawMagicFrameElement | false =
  1914. selectedElements.length === 1 &&
  1915. isMagicFrameElement(selectedElements[0]) &&
  1916. selectedElements[0];
  1917. // case: user selected elements containing frame-like(s) or are frame
  1918. // members, we don't want to wrap into another magicframe
  1919. // (unless the only selected element is a magic frame which we reuse)
  1920. if (
  1921. !selectedMagicFrame &&
  1922. selectedElements.some((el) => isFrameLikeElement(el) || el.frameId)
  1923. ) {
  1924. this.setActiveTool({ type: TOOL_TYPE.magicframe });
  1925. return;
  1926. }
  1927. trackEvent("ai", "tool-select (existing selection)", "d2c");
  1928. let frame: ExcalidrawMagicFrameElement;
  1929. if (selectedMagicFrame) {
  1930. // a single magicframe already selected -> use it
  1931. frame = selectedMagicFrame;
  1932. } else {
  1933. // selected elements aren't wrapped in magic frame yet -> wrap now
  1934. const [minX, minY, maxX, maxY] = getCommonBounds(selectedElements);
  1935. const padding = 50;
  1936. frame = newMagicFrameElement({
  1937. ...FRAME_STYLE,
  1938. x: minX - padding,
  1939. y: minY - padding,
  1940. width: maxX - minX + padding * 2,
  1941. height: maxY - minY + padding * 2,
  1942. opacity: 100,
  1943. locked: false,
  1944. });
  1945. this.scene.insertElement(frame);
  1946. for (const child of selectedElements) {
  1947. this.scene.mutateElement(child, { frameId: frame.id });
  1948. }
  1949. this.setState({
  1950. selectedElementIds: { [frame.id]: true },
  1951. });
  1952. }
  1953. this.onMagicFrameGenerate(frame, "upstream");
  1954. }
  1955. };
  1956. private openEyeDropper = ({ type }: { type: "stroke" | "background" }) => {
  1957. this.updateEditorAtom(activeEyeDropperAtom, {
  1958. swapPreviewOnAlt: true,
  1959. colorPickerType:
  1960. type === "stroke" ? "elementStroke" : "elementBackground",
  1961. onSelect: (color, event) => {
  1962. const shouldUpdateStrokeColor =
  1963. (type === "background" && event.altKey) ||
  1964. (type === "stroke" && !event.altKey);
  1965. const selectedElements = this.scene.getSelectedElements(this.state);
  1966. if (
  1967. !selectedElements.length ||
  1968. this.state.activeTool.type !== "selection"
  1969. ) {
  1970. if (shouldUpdateStrokeColor) {
  1971. this.syncActionResult({
  1972. appState: { ...this.state, currentItemStrokeColor: color },
  1973. captureUpdate: CaptureUpdateAction.IMMEDIATELY,
  1974. });
  1975. } else {
  1976. this.syncActionResult({
  1977. appState: { ...this.state, currentItemBackgroundColor: color },
  1978. captureUpdate: CaptureUpdateAction.IMMEDIATELY,
  1979. });
  1980. }
  1981. } else {
  1982. this.updateScene({
  1983. elements: this.scene.getElementsIncludingDeleted().map((el) => {
  1984. if (this.state.selectedElementIds[el.id]) {
  1985. return newElementWith(el, {
  1986. [shouldUpdateStrokeColor ? "strokeColor" : "backgroundColor"]:
  1987. color,
  1988. });
  1989. }
  1990. return el;
  1991. }),
  1992. captureUpdate: CaptureUpdateAction.IMMEDIATELY,
  1993. });
  1994. }
  1995. },
  1996. keepOpenOnAlt: false,
  1997. });
  1998. };
  1999. public dismissLinearEditor = () => {
  2000. setTimeout(() => {
  2001. if (this.state.selectedLinearElement?.isEditing) {
  2002. this.setState({
  2003. selectedLinearElement: {
  2004. ...this.state.selectedLinearElement,
  2005. isEditing: false,
  2006. },
  2007. });
  2008. }
  2009. });
  2010. };
  2011. public syncActionResult = withBatchedUpdates((actionResult: ActionResult) => {
  2012. if (this.unmounted || actionResult === false) {
  2013. return;
  2014. }
  2015. this.store.scheduleAction(actionResult.captureUpdate);
  2016. let didUpdate = false;
  2017. let editingTextElement: AppState["editingTextElement"] | null = null;
  2018. if (actionResult.elements) {
  2019. this.scene.replaceAllElements(actionResult.elements);
  2020. didUpdate = true;
  2021. }
  2022. if (actionResult.files) {
  2023. this.addMissingFiles(actionResult.files, actionResult.replaceFiles);
  2024. this.addNewImagesToImageCache();
  2025. }
  2026. if (actionResult.appState || editingTextElement || this.state.contextMenu) {
  2027. let viewModeEnabled = actionResult?.appState?.viewModeEnabled || false;
  2028. let zenModeEnabled = actionResult?.appState?.zenModeEnabled || false;
  2029. const theme =
  2030. actionResult?.appState?.theme || this.props.theme || THEME.LIGHT;
  2031. const name = actionResult?.appState?.name ?? this.state.name;
  2032. const errorMessage =
  2033. actionResult?.appState?.errorMessage ?? this.state.errorMessage;
  2034. if (typeof this.props.viewModeEnabled !== "undefined") {
  2035. viewModeEnabled = this.props.viewModeEnabled;
  2036. }
  2037. if (typeof this.props.zenModeEnabled !== "undefined") {
  2038. zenModeEnabled = this.props.zenModeEnabled;
  2039. }
  2040. editingTextElement = actionResult.appState?.editingTextElement || null;
  2041. // make sure editingTextElement points to latest element reference
  2042. if (actionResult.elements && editingTextElement) {
  2043. actionResult.elements.forEach((element) => {
  2044. if (
  2045. editingTextElement?.id === element.id &&
  2046. editingTextElement !== element &&
  2047. isNonDeletedElement(element) &&
  2048. isTextElement(element)
  2049. ) {
  2050. editingTextElement = element;
  2051. }
  2052. });
  2053. }
  2054. if (editingTextElement?.isDeleted) {
  2055. editingTextElement = null;
  2056. }
  2057. this.setState((prevAppState) => {
  2058. const actionAppState = actionResult.appState || {};
  2059. return {
  2060. ...prevAppState,
  2061. ...actionAppState,
  2062. // NOTE this will prevent opening context menu using an action
  2063. // or programmatically from the host, so it will need to be
  2064. // rewritten later
  2065. contextMenu: null,
  2066. editingTextElement,
  2067. viewModeEnabled,
  2068. zenModeEnabled,
  2069. theme,
  2070. name,
  2071. errorMessage,
  2072. };
  2073. });
  2074. didUpdate = true;
  2075. }
  2076. if (!didUpdate) {
  2077. this.scene.triggerUpdate();
  2078. }
  2079. });
  2080. // Lifecycle
  2081. private onBlur = withBatchedUpdates(() => {
  2082. isHoldingSpace = false;
  2083. this.setState({ isBindingEnabled: true });
  2084. });
  2085. private onUnload = () => {
  2086. this.onBlur();
  2087. };
  2088. private disableEvent: EventListener = (event) => {
  2089. event.preventDefault();
  2090. };
  2091. private resetHistory = () => {
  2092. this.history.clear();
  2093. };
  2094. private resetStore = () => {
  2095. this.store.clear();
  2096. };
  2097. /**
  2098. * Resets scene & history.
  2099. * ! Do not use to clear scene user action !
  2100. */
  2101. private resetScene = withBatchedUpdates(
  2102. (opts?: { resetLoadingState: boolean }) => {
  2103. this.scene.replaceAllElements([]);
  2104. this.setState((state) => ({
  2105. ...getDefaultAppState(),
  2106. isLoading: opts?.resetLoadingState ? false : state.isLoading,
  2107. theme: this.state.theme,
  2108. }));
  2109. this.resetStore();
  2110. this.resetHistory();
  2111. },
  2112. );
  2113. private initializeScene = async () => {
  2114. if ("launchQueue" in window && "LaunchParams" in window) {
  2115. (window as any).launchQueue.setConsumer(
  2116. async (launchParams: { files: any[] }) => {
  2117. if (!launchParams.files.length) {
  2118. return;
  2119. }
  2120. const fileHandle = launchParams.files[0];
  2121. const blob: Blob = await fileHandle.getFile();
  2122. this.loadFileToCanvas(
  2123. new File([blob], blob.name || "", { type: blob.type }),
  2124. fileHandle,
  2125. );
  2126. },
  2127. );
  2128. }
  2129. if (this.props.theme) {
  2130. this.setState({ theme: this.props.theme });
  2131. }
  2132. if (!this.state.isLoading) {
  2133. this.setState({ isLoading: true });
  2134. }
  2135. let initialData = null;
  2136. try {
  2137. if (typeof this.props.initialData === "function") {
  2138. initialData = (await this.props.initialData()) || null;
  2139. } else {
  2140. initialData = (await this.props.initialData) || null;
  2141. }
  2142. if (initialData?.libraryItems) {
  2143. this.library
  2144. .updateLibrary({
  2145. libraryItems: initialData.libraryItems,
  2146. merge: true,
  2147. })
  2148. .catch((error) => {
  2149. console.error(error);
  2150. });
  2151. }
  2152. } catch (error: any) {
  2153. console.error(error);
  2154. initialData = {
  2155. appState: {
  2156. errorMessage:
  2157. error.message ||
  2158. "Encountered an error during importing or restoring scene data",
  2159. },
  2160. };
  2161. }
  2162. const scene = restore(initialData, null, null, { repairBindings: true });
  2163. scene.appState = {
  2164. ...scene.appState,
  2165. theme: this.props.theme || scene.appState.theme,
  2166. // we're falling back to current (pre-init) state when deciding
  2167. // whether to open the library, to handle a case where we
  2168. // update the state outside of initialData (e.g. when loading the app
  2169. // with a library install link, which should auto-open the library)
  2170. openSidebar: scene.appState?.openSidebar || this.state.openSidebar,
  2171. activeTool:
  2172. scene.appState.activeTool.type === "image"
  2173. ? { ...scene.appState.activeTool, type: "selection" }
  2174. : scene.appState.activeTool,
  2175. isLoading: false,
  2176. toast: this.state.toast,
  2177. };
  2178. if (initialData?.scrollToContent) {
  2179. scene.appState = {
  2180. ...scene.appState,
  2181. ...calculateScrollCenter(scene.elements, {
  2182. ...scene.appState,
  2183. width: this.state.width,
  2184. height: this.state.height,
  2185. offsetTop: this.state.offsetTop,
  2186. offsetLeft: this.state.offsetLeft,
  2187. }),
  2188. };
  2189. }
  2190. this.resetStore();
  2191. this.resetHistory();
  2192. this.syncActionResult({
  2193. ...scene,
  2194. captureUpdate: CaptureUpdateAction.NEVER,
  2195. });
  2196. // clear the shape and image cache so that any images in initialData
  2197. // can be loaded fresh
  2198. this.clearImageShapeCache();
  2199. // manually loading the font faces seems faster even in browsers that do fire the loadingdone event
  2200. this.fonts.loadSceneFonts().then((fontFaces) => {
  2201. this.fonts.onLoaded(fontFaces);
  2202. });
  2203. if (isElementLink(window.location.href)) {
  2204. this.scrollToContent(window.location.href, { animate: false });
  2205. }
  2206. };
  2207. private isMobileBreakpoint = (width: number, height: number) => {
  2208. return (
  2209. width < MQ_MAX_WIDTH_PORTRAIT ||
  2210. (height < MQ_MAX_HEIGHT_LANDSCAPE && width < MQ_MAX_WIDTH_LANDSCAPE)
  2211. );
  2212. };
  2213. private refreshViewportBreakpoints = () => {
  2214. const container = this.excalidrawContainerRef.current;
  2215. if (!container) {
  2216. return;
  2217. }
  2218. const { clientWidth: viewportWidth, clientHeight: viewportHeight } =
  2219. document.body;
  2220. const prevViewportState = this.device.viewport;
  2221. const nextViewportState = updateObject(prevViewportState, {
  2222. isLandscape: viewportWidth > viewportHeight,
  2223. isMobile: this.isMobileBreakpoint(viewportWidth, viewportHeight),
  2224. });
  2225. if (prevViewportState !== nextViewportState) {
  2226. this.device = { ...this.device, viewport: nextViewportState };
  2227. return true;
  2228. }
  2229. return false;
  2230. };
  2231. private refreshEditorBreakpoints = () => {
  2232. const container = this.excalidrawContainerRef.current;
  2233. if (!container) {
  2234. return;
  2235. }
  2236. const { width: editorWidth, height: editorHeight } =
  2237. container.getBoundingClientRect();
  2238. const sidebarBreakpoint =
  2239. this.props.UIOptions.dockedSidebarBreakpoint != null
  2240. ? this.props.UIOptions.dockedSidebarBreakpoint
  2241. : MQ_RIGHT_SIDEBAR_MIN_WIDTH;
  2242. const prevEditorState = this.device.editor;
  2243. const nextEditorState = updateObject(prevEditorState, {
  2244. isMobile: this.isMobileBreakpoint(editorWidth, editorHeight),
  2245. canFitSidebar: editorWidth > sidebarBreakpoint,
  2246. });
  2247. if (prevEditorState !== nextEditorState) {
  2248. this.device = { ...this.device, editor: nextEditorState };
  2249. return true;
  2250. }
  2251. return false;
  2252. };
  2253. private clearImageShapeCache(filesMap?: BinaryFiles) {
  2254. const files = filesMap ?? this.files;
  2255. this.scene.getNonDeletedElements().forEach((element) => {
  2256. if (isInitializedImageElement(element) && files[element.fileId]) {
  2257. this.imageCache.delete(element.fileId);
  2258. ShapeCache.delete(element);
  2259. }
  2260. });
  2261. }
  2262. public async componentDidMount() {
  2263. this.unmounted = false;
  2264. this.excalidrawContainerValue.container =
  2265. this.excalidrawContainerRef.current;
  2266. if (isTestEnv() || isDevEnv()) {
  2267. const setState = this.setState.bind(this);
  2268. Object.defineProperties(window.h, {
  2269. state: {
  2270. configurable: true,
  2271. get: () => {
  2272. return this.state;
  2273. },
  2274. },
  2275. setState: {
  2276. configurable: true,
  2277. value: (...args: Parameters<typeof setState>) => {
  2278. return this.setState(...args);
  2279. },
  2280. },
  2281. app: {
  2282. configurable: true,
  2283. value: this,
  2284. },
  2285. history: {
  2286. configurable: true,
  2287. value: this.history,
  2288. },
  2289. store: {
  2290. configurable: true,
  2291. value: this.store,
  2292. },
  2293. fonts: {
  2294. configurable: true,
  2295. value: this.fonts,
  2296. },
  2297. });
  2298. }
  2299. this.store.onDurableIncrementEmitter.on((increment) => {
  2300. this.history.record(increment.delta);
  2301. });
  2302. const { onIncrement } = this.props;
  2303. // per. optimmisation, only subscribe if there is the `onIncrement` prop registered, to avoid unnecessary computation
  2304. if (onIncrement) {
  2305. this.store.onStoreIncrementEmitter.on((increment) => {
  2306. onIncrement(increment);
  2307. });
  2308. }
  2309. this.scene.onUpdate(this.triggerRender);
  2310. this.addEventListeners();
  2311. if (this.props.autoFocus && this.excalidrawContainerRef.current) {
  2312. this.focusContainer();
  2313. }
  2314. if (
  2315. // bounding rects don't work in tests so updating
  2316. // the state on init would result in making the test enviro run
  2317. // in mobile breakpoint (0 width/height), making everything fail
  2318. !isTestEnv()
  2319. ) {
  2320. this.refreshViewportBreakpoints();
  2321. this.refreshEditorBreakpoints();
  2322. }
  2323. if (supportsResizeObserver && this.excalidrawContainerRef.current) {
  2324. this.resizeObserver = new ResizeObserver(() => {
  2325. this.refreshEditorBreakpoints();
  2326. this.updateDOMRect();
  2327. });
  2328. this.resizeObserver?.observe(this.excalidrawContainerRef.current);
  2329. }
  2330. const searchParams = new URLSearchParams(window.location.search.slice(1));
  2331. if (searchParams.has("web-share-target")) {
  2332. // Obtain a file that was shared via the Web Share Target API.
  2333. this.restoreFileFromShare();
  2334. } else {
  2335. this.updateDOMRect(this.initializeScene);
  2336. }
  2337. // note that this check seems to always pass in localhost
  2338. if (isBrave() && !isMeasureTextSupported()) {
  2339. this.setState({
  2340. errorMessage: <BraveMeasureTextError />,
  2341. });
  2342. }
  2343. }
  2344. public componentWillUnmount() {
  2345. (window as any).launchQueue?.setConsumer(() => {});
  2346. this.renderer.destroy();
  2347. this.scene.destroy();
  2348. this.scene = new Scene();
  2349. this.fonts = new Fonts(this.scene);
  2350. this.renderer = new Renderer(this.scene);
  2351. this.files = {};
  2352. this.imageCache.clear();
  2353. this.resizeObserver?.disconnect();
  2354. this.unmounted = true;
  2355. this.removeEventListeners();
  2356. this.library.destroy();
  2357. this.laserTrails.stop();
  2358. this.eraserTrail.stop();
  2359. this.onChangeEmitter.clear();
  2360. this.store.onStoreIncrementEmitter.clear();
  2361. this.store.onDurableIncrementEmitter.clear();
  2362. ShapeCache.destroy();
  2363. SnapCache.destroy();
  2364. clearTimeout(touchTimeout);
  2365. isSomeElementSelected.clearCache();
  2366. selectGroupsForSelectedElements.clearCache();
  2367. touchTimeout = 0;
  2368. document.documentElement.style.overscrollBehaviorX = "";
  2369. }
  2370. private onResize = withBatchedUpdates(() => {
  2371. this.scene
  2372. .getElementsIncludingDeleted()
  2373. .forEach((element) => ShapeCache.delete(element));
  2374. this.refreshViewportBreakpoints();
  2375. this.updateDOMRect();
  2376. if (!supportsResizeObserver) {
  2377. this.refreshEditorBreakpoints();
  2378. }
  2379. this.setState({});
  2380. });
  2381. /** generally invoked only if fullscreen was invoked programmatically */
  2382. private onFullscreenChange = () => {
  2383. if (
  2384. // points to the iframe element we fullscreened
  2385. !document.fullscreenElement &&
  2386. this.state.activeEmbeddable?.state === "active"
  2387. ) {
  2388. this.setState({
  2389. activeEmbeddable: null,
  2390. });
  2391. }
  2392. };
  2393. private removeEventListeners() {
  2394. this.onRemoveEventListenersEmitter.trigger();
  2395. }
  2396. private addEventListeners() {
  2397. // remove first as we can add event listeners multiple times
  2398. this.removeEventListeners();
  2399. // -------------------------------------------------------------------------
  2400. // view+edit mode listeners
  2401. // -------------------------------------------------------------------------
  2402. if (this.props.handleKeyboardGlobally) {
  2403. this.onRemoveEventListenersEmitter.once(
  2404. addEventListener(document, EVENT.KEYDOWN, this.onKeyDown, false),
  2405. );
  2406. }
  2407. this.onRemoveEventListenersEmitter.once(
  2408. addEventListener(
  2409. this.excalidrawContainerRef.current,
  2410. EVENT.WHEEL,
  2411. this.handleWheel,
  2412. { passive: false },
  2413. ),
  2414. addEventListener(window, EVENT.MESSAGE, this.onWindowMessage, false),
  2415. addEventListener(document, EVENT.POINTER_UP, this.removePointer, {
  2416. passive: false,
  2417. }), // #3553
  2418. addEventListener(document, EVENT.COPY, this.onCopy, { passive: false }),
  2419. addEventListener(document, EVENT.KEYUP, this.onKeyUp, { passive: true }),
  2420. addEventListener(
  2421. document,
  2422. EVENT.POINTER_MOVE,
  2423. this.updateCurrentCursorPosition,
  2424. { passive: false },
  2425. ),
  2426. // rerender text elements on font load to fix #637 && #1553
  2427. addEventListener(
  2428. document.fonts,
  2429. "loadingdone",
  2430. (event) => {
  2431. const fontFaces = (event as FontFaceSetLoadEvent).fontfaces;
  2432. this.fonts.onLoaded(fontFaces);
  2433. },
  2434. { passive: false },
  2435. ),
  2436. // Safari-only desktop pinch zoom
  2437. addEventListener(
  2438. document,
  2439. EVENT.GESTURE_START,
  2440. this.onGestureStart as any,
  2441. false,
  2442. ),
  2443. addEventListener(
  2444. document,
  2445. EVENT.GESTURE_CHANGE,
  2446. this.onGestureChange as any,
  2447. false,
  2448. ),
  2449. addEventListener(
  2450. document,
  2451. EVENT.GESTURE_END,
  2452. this.onGestureEnd as any,
  2453. false,
  2454. ),
  2455. addEventListener(
  2456. window,
  2457. EVENT.FOCUS,
  2458. () => {
  2459. this.maybeCleanupAfterMissingPointerUp(null);
  2460. // browsers (chrome?) tend to free up memory a lot, which results
  2461. // in canvas context being cleared. Thus re-render on focus.
  2462. this.triggerRender(true);
  2463. },
  2464. { passive: false },
  2465. ),
  2466. );
  2467. if (this.state.viewModeEnabled) {
  2468. return;
  2469. }
  2470. // -------------------------------------------------------------------------
  2471. // edit-mode listeners only
  2472. // -------------------------------------------------------------------------
  2473. this.onRemoveEventListenersEmitter.once(
  2474. addEventListener(
  2475. document,
  2476. EVENT.FULLSCREENCHANGE,
  2477. this.onFullscreenChange,
  2478. { passive: false },
  2479. ),
  2480. addEventListener(document, EVENT.PASTE, this.pasteFromClipboard, {
  2481. passive: false,
  2482. }),
  2483. addEventListener(document, EVENT.CUT, this.onCut, { passive: false }),
  2484. addEventListener(window, EVENT.RESIZE, this.onResize, false),
  2485. addEventListener(window, EVENT.UNLOAD, this.onUnload, false),
  2486. addEventListener(window, EVENT.BLUR, this.onBlur, false),
  2487. addEventListener(
  2488. this.excalidrawContainerRef.current,
  2489. EVENT.WHEEL,
  2490. this.handleWheel,
  2491. { passive: false },
  2492. ),
  2493. addEventListener(
  2494. this.excalidrawContainerRef.current,
  2495. EVENT.DRAG_OVER,
  2496. this.disableEvent,
  2497. false,
  2498. ),
  2499. addEventListener(
  2500. this.excalidrawContainerRef.current,
  2501. EVENT.DROP,
  2502. this.disableEvent,
  2503. false,
  2504. ),
  2505. );
  2506. if (this.props.detectScroll) {
  2507. this.onRemoveEventListenersEmitter.once(
  2508. addEventListener(
  2509. getNearestScrollableContainer(this.excalidrawContainerRef.current!),
  2510. EVENT.SCROLL,
  2511. this.onScroll,
  2512. { passive: false },
  2513. ),
  2514. );
  2515. }
  2516. }
  2517. componentDidUpdate(prevProps: AppProps, prevState: AppState) {
  2518. this.updateEmbeddables();
  2519. const elements = this.scene.getElementsIncludingDeleted();
  2520. const elementsMap = this.scene.getElementsMapIncludingDeleted();
  2521. if (!this.state.showWelcomeScreen && !elements.length) {
  2522. this.setState({ showWelcomeScreen: true });
  2523. }
  2524. if (
  2525. prevProps.UIOptions.dockedSidebarBreakpoint !==
  2526. this.props.UIOptions.dockedSidebarBreakpoint
  2527. ) {
  2528. this.refreshEditorBreakpoints();
  2529. }
  2530. const hasFollowedPersonLeft =
  2531. prevState.userToFollow &&
  2532. !this.state.collaborators.has(prevState.userToFollow.socketId);
  2533. if (hasFollowedPersonLeft) {
  2534. this.maybeUnfollowRemoteUser();
  2535. }
  2536. if (
  2537. prevState.zoom.value !== this.state.zoom.value ||
  2538. prevState.scrollX !== this.state.scrollX ||
  2539. prevState.scrollY !== this.state.scrollY
  2540. ) {
  2541. this.props?.onScrollChange?.(
  2542. this.state.scrollX,
  2543. this.state.scrollY,
  2544. this.state.zoom,
  2545. );
  2546. this.onScrollChangeEmitter.trigger(
  2547. this.state.scrollX,
  2548. this.state.scrollY,
  2549. this.state.zoom,
  2550. );
  2551. }
  2552. if (prevState.userToFollow !== this.state.userToFollow) {
  2553. if (prevState.userToFollow) {
  2554. this.onUserFollowEmitter.trigger({
  2555. userToFollow: prevState.userToFollow,
  2556. action: "UNFOLLOW",
  2557. });
  2558. }
  2559. if (this.state.userToFollow) {
  2560. this.onUserFollowEmitter.trigger({
  2561. userToFollow: this.state.userToFollow,
  2562. action: "FOLLOW",
  2563. });
  2564. }
  2565. }
  2566. if (
  2567. Object.keys(this.state.selectedElementIds).length &&
  2568. isEraserActive(this.state)
  2569. ) {
  2570. this.setState({
  2571. activeTool: updateActiveTool(this.state, { type: "selection" }),
  2572. });
  2573. }
  2574. if (
  2575. this.state.activeTool.type === "eraser" &&
  2576. prevState.theme !== this.state.theme
  2577. ) {
  2578. setEraserCursor(this.interactiveCanvas, this.state.theme);
  2579. }
  2580. // Hide hyperlink popup if shown when element type is not selection
  2581. if (
  2582. prevState.activeTool.type === "selection" &&
  2583. this.state.activeTool.type !== "selection" &&
  2584. this.state.showHyperlinkPopup
  2585. ) {
  2586. this.setState({ showHyperlinkPopup: false });
  2587. }
  2588. if (prevProps.langCode !== this.props.langCode) {
  2589. this.updateLanguage();
  2590. }
  2591. if (isEraserActive(prevState) && !isEraserActive(this.state)) {
  2592. this.eraserTrail.endPath();
  2593. }
  2594. if (prevProps.viewModeEnabled !== this.props.viewModeEnabled) {
  2595. this.setState({ viewModeEnabled: !!this.props.viewModeEnabled });
  2596. }
  2597. if (prevState.viewModeEnabled !== this.state.viewModeEnabled) {
  2598. this.addEventListeners();
  2599. this.deselectElements();
  2600. }
  2601. // cleanup
  2602. if (
  2603. (prevState.openDialog?.name === "elementLinkSelector" ||
  2604. this.state.openDialog?.name === "elementLinkSelector") &&
  2605. prevState.openDialog?.name !== this.state.openDialog?.name
  2606. ) {
  2607. this.deselectElements();
  2608. this.setState({
  2609. hoveredElementIds: {},
  2610. });
  2611. }
  2612. if (prevProps.zenModeEnabled !== this.props.zenModeEnabled) {
  2613. this.setState({ zenModeEnabled: !!this.props.zenModeEnabled });
  2614. }
  2615. if (prevProps.theme !== this.props.theme && this.props.theme) {
  2616. this.setState({ theme: this.props.theme });
  2617. }
  2618. this.excalidrawContainerRef.current?.classList.toggle(
  2619. "theme--dark",
  2620. this.state.theme === THEME.DARK,
  2621. );
  2622. if (
  2623. this.state.selectedLinearElement?.isEditing &&
  2624. !this.state.selectedElementIds[this.state.selectedLinearElement.elementId]
  2625. ) {
  2626. // defer so that the scheduleCapture flag isn't reset via current update
  2627. setTimeout(() => {
  2628. // execute only if the condition still holds when the deferred callback
  2629. // executes (it can be scheduled multiple times depending on how
  2630. // many times the component renders)
  2631. this.state.selectedLinearElement?.isEditing &&
  2632. this.actionManager.executeAction(actionFinalize);
  2633. });
  2634. }
  2635. // failsafe in case the state is being updated in incorrect order resulting
  2636. // in the editingTextElement being now a deleted element
  2637. if (this.state.editingTextElement?.isDeleted) {
  2638. this.setState({ editingTextElement: null });
  2639. }
  2640. if (
  2641. this.state.selectedLinearElement &&
  2642. !this.state.selectedElementIds[this.state.selectedLinearElement.elementId]
  2643. ) {
  2644. // To make sure `selectedLinearElement` is in sync with `selectedElementIds`, however this shouldn't be needed once
  2645. // we have a single API to update `selectedElementIds`
  2646. this.setState({ selectedLinearElement: null });
  2647. }
  2648. this.store.commit(elementsMap, this.state);
  2649. // Do not notify consumers if we're still loading the scene. Among other
  2650. // potential issues, this fixes a case where the tab isn't focused during
  2651. // init, which would trigger onChange with empty elements, which would then
  2652. // override whatever is in localStorage currently.
  2653. if (!this.state.isLoading) {
  2654. this.props.onChange?.(elements, this.state, this.files);
  2655. this.onChangeEmitter.trigger(elements, this.state, this.files);
  2656. }
  2657. }
  2658. private renderInteractiveSceneCallback = ({
  2659. atLeastOneVisibleElement,
  2660. scrollBars,
  2661. elementsMap,
  2662. }: RenderInteractiveSceneCallback) => {
  2663. if (scrollBars) {
  2664. currentScrollBars = scrollBars;
  2665. }
  2666. const scrolledOutside =
  2667. // hide when editing text
  2668. this.state.editingTextElement
  2669. ? false
  2670. : !atLeastOneVisibleElement && elementsMap.size > 0;
  2671. if (this.state.scrolledOutside !== scrolledOutside) {
  2672. this.setState({ scrolledOutside });
  2673. }
  2674. this.scheduleImageRefresh();
  2675. };
  2676. private onScroll = debounce(() => {
  2677. const { offsetTop, offsetLeft } = this.getCanvasOffsets();
  2678. this.setState((state) => {
  2679. if (state.offsetLeft === offsetLeft && state.offsetTop === offsetTop) {
  2680. return null;
  2681. }
  2682. return { offsetTop, offsetLeft };
  2683. });
  2684. }, SCROLL_TIMEOUT);
  2685. // Copy/paste
  2686. private onCut = withBatchedUpdates((event: ClipboardEvent) => {
  2687. const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
  2688. document.activeElement,
  2689. );
  2690. if (!isExcalidrawActive || isWritableElement(event.target)) {
  2691. return;
  2692. }
  2693. this.actionManager.executeAction(actionCut, "keyboard", event);
  2694. event.preventDefault();
  2695. event.stopPropagation();
  2696. });
  2697. private onCopy = withBatchedUpdates((event: ClipboardEvent) => {
  2698. const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
  2699. document.activeElement,
  2700. );
  2701. if (!isExcalidrawActive || isWritableElement(event.target)) {
  2702. return;
  2703. }
  2704. this.actionManager.executeAction(actionCopy, "keyboard", event);
  2705. event.preventDefault();
  2706. event.stopPropagation();
  2707. });
  2708. private static resetTapTwice() {
  2709. didTapTwice = false;
  2710. }
  2711. private onTouchStart = (event: TouchEvent) => {
  2712. // fix for Apple Pencil Scribble (do not prevent for other devices)
  2713. if (isIOS) {
  2714. event.preventDefault();
  2715. }
  2716. if (!didTapTwice) {
  2717. didTapTwice = true;
  2718. clearTimeout(tappedTwiceTimer);
  2719. tappedTwiceTimer = window.setTimeout(
  2720. App.resetTapTwice,
  2721. TAP_TWICE_TIMEOUT,
  2722. );
  2723. return;
  2724. }
  2725. // insert text only if we tapped twice with a single finger
  2726. // event.touches.length === 1 will also prevent inserting text when user's zooming
  2727. if (didTapTwice && event.touches.length === 1) {
  2728. const touch = event.touches[0];
  2729. // @ts-ignore
  2730. this.handleCanvasDoubleClick({
  2731. clientX: touch.clientX,
  2732. clientY: touch.clientY,
  2733. });
  2734. didTapTwice = false;
  2735. clearTimeout(tappedTwiceTimer);
  2736. }
  2737. if (event.touches.length === 2) {
  2738. this.setState({
  2739. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  2740. activeEmbeddable: null,
  2741. });
  2742. }
  2743. };
  2744. private onTouchEnd = (event: TouchEvent) => {
  2745. this.resetContextMenuTimer();
  2746. if (event.touches.length > 0) {
  2747. this.setState({
  2748. previousSelectedElementIds: {},
  2749. selectedElementIds: makeNextSelectedElementIds(
  2750. this.state.previousSelectedElementIds,
  2751. this.state,
  2752. ),
  2753. });
  2754. } else {
  2755. gesture.pointers.clear();
  2756. }
  2757. };
  2758. // TODO: this is so spaghetti, we should refactor it and cover it with tests
  2759. public pasteFromClipboard = withBatchedUpdates(
  2760. async (event: ClipboardEvent) => {
  2761. const isPlainPaste = !!IS_PLAIN_PASTE;
  2762. // #686
  2763. const target = document.activeElement;
  2764. const isExcalidrawActive =
  2765. this.excalidrawContainerRef.current?.contains(target);
  2766. if (event && !isExcalidrawActive) {
  2767. return;
  2768. }
  2769. const elementUnderCursor = document.elementFromPoint(
  2770. this.lastViewportPosition.x,
  2771. this.lastViewportPosition.y,
  2772. );
  2773. if (
  2774. event &&
  2775. (!(elementUnderCursor instanceof HTMLCanvasElement) ||
  2776. isWritableElement(target))
  2777. ) {
  2778. return;
  2779. }
  2780. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  2781. {
  2782. clientX: this.lastViewportPosition.x,
  2783. clientY: this.lastViewportPosition.y,
  2784. },
  2785. this.state,
  2786. );
  2787. // must be called in the same frame (thus before any awaits) as the paste
  2788. // event else some browsers (FF...) will clear the clipboardData
  2789. // (something something security)
  2790. let file = event?.clipboardData?.files[0];
  2791. const data = await parseClipboard(event, isPlainPaste);
  2792. if (!file && !isPlainPaste) {
  2793. if (data.mixedContent) {
  2794. return this.addElementsFromMixedContentPaste(data.mixedContent, {
  2795. isPlainPaste,
  2796. sceneX,
  2797. sceneY,
  2798. });
  2799. } else if (data.text) {
  2800. const string = data.text.trim();
  2801. if (string.startsWith("<svg") && string.endsWith("</svg>")) {
  2802. // ignore SVG validation/normalization which will be done during image
  2803. // initialization
  2804. file = SVGStringToFile(string);
  2805. }
  2806. }
  2807. }
  2808. // prefer spreadsheet data over image file (MS Office/Libre Office)
  2809. if (isSupportedImageFile(file) && !data.spreadsheet) {
  2810. if (!this.isToolSupported("image")) {
  2811. this.setState({ errorMessage: t("errors.imageToolNotSupported") });
  2812. return;
  2813. }
  2814. this.createImageElement({ sceneX, sceneY, imageFile: file });
  2815. return;
  2816. }
  2817. if (this.props.onPaste) {
  2818. try {
  2819. if ((await this.props.onPaste(data, event)) === false) {
  2820. return;
  2821. }
  2822. } catch (error: any) {
  2823. console.error(error);
  2824. }
  2825. }
  2826. if (data.errorMessage) {
  2827. this.setState({ errorMessage: data.errorMessage });
  2828. } else if (data.spreadsheet && !isPlainPaste) {
  2829. this.setState({
  2830. pasteDialog: {
  2831. data: data.spreadsheet,
  2832. shown: true,
  2833. },
  2834. });
  2835. } else if (data.elements) {
  2836. const elements = (
  2837. data.programmaticAPI
  2838. ? convertToExcalidrawElements(
  2839. data.elements as ExcalidrawElementSkeleton[],
  2840. )
  2841. : data.elements
  2842. ) as readonly ExcalidrawElement[];
  2843. // TODO remove formatting from elements if isPlainPaste
  2844. this.addElementsFromPasteOrLibrary({
  2845. elements,
  2846. files: data.files || null,
  2847. position: "cursor",
  2848. retainSeed: isPlainPaste,
  2849. });
  2850. } else if (data.text) {
  2851. if (data.text && isMaybeMermaidDefinition(data.text)) {
  2852. const api = await import("@excalidraw/mermaid-to-excalidraw");
  2853. try {
  2854. const { elements: skeletonElements, files } =
  2855. await api.parseMermaidToExcalidraw(data.text);
  2856. const elements = convertToExcalidrawElements(skeletonElements, {
  2857. regenerateIds: true,
  2858. });
  2859. this.addElementsFromPasteOrLibrary({
  2860. elements,
  2861. files,
  2862. position: "cursor",
  2863. });
  2864. return;
  2865. } catch (err: any) {
  2866. console.warn(
  2867. `parsing pasted text as mermaid definition failed: ${err.message}`,
  2868. );
  2869. }
  2870. }
  2871. const nonEmptyLines = normalizeEOL(data.text)
  2872. .split(/\n+/)
  2873. .map((s) => s.trim())
  2874. .filter(Boolean);
  2875. const embbeddableUrls = nonEmptyLines
  2876. .map((str) => maybeParseEmbedSrc(str))
  2877. .filter((string) => {
  2878. return (
  2879. embeddableURLValidator(string, this.props.validateEmbeddable) &&
  2880. (/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(string) ||
  2881. getEmbedLink(string)?.type === "video")
  2882. );
  2883. });
  2884. if (
  2885. !IS_PLAIN_PASTE &&
  2886. embbeddableUrls.length > 0 &&
  2887. // if there were non-embeddable text (lines) mixed in with embeddable
  2888. // urls, ignore and paste as text
  2889. embbeddableUrls.length === nonEmptyLines.length
  2890. ) {
  2891. const embeddables: NonDeleted<ExcalidrawEmbeddableElement>[] = [];
  2892. for (const url of embbeddableUrls) {
  2893. const prevEmbeddable: ExcalidrawEmbeddableElement | undefined =
  2894. embeddables[embeddables.length - 1];
  2895. const embeddable = this.insertEmbeddableElement({
  2896. sceneX: prevEmbeddable
  2897. ? prevEmbeddable.x + prevEmbeddable.width + 20
  2898. : sceneX,
  2899. sceneY,
  2900. link: normalizeLink(url),
  2901. });
  2902. if (embeddable) {
  2903. embeddables.push(embeddable);
  2904. }
  2905. }
  2906. if (embeddables.length) {
  2907. this.store.scheduleCapture();
  2908. this.setState({
  2909. selectedElementIds: Object.fromEntries(
  2910. embeddables.map((embeddable) => [embeddable.id, true]),
  2911. ),
  2912. });
  2913. }
  2914. return;
  2915. }
  2916. this.addTextFromPaste(data.text, isPlainPaste);
  2917. }
  2918. this.setActiveTool({ type: "selection" });
  2919. event?.preventDefault();
  2920. },
  2921. );
  2922. addElementsFromPasteOrLibrary = (opts: {
  2923. elements: readonly ExcalidrawElement[];
  2924. files: BinaryFiles | null;
  2925. position: { clientX: number; clientY: number } | "cursor" | "center";
  2926. retainSeed?: boolean;
  2927. fitToContent?: boolean;
  2928. }) => {
  2929. const elements = restoreElements(opts.elements, null, undefined);
  2930. const [minX, minY, maxX, maxY] = getCommonBounds(elements);
  2931. const elementsCenterX = distance(minX, maxX) / 2;
  2932. const elementsCenterY = distance(minY, maxY) / 2;
  2933. const clientX =
  2934. typeof opts.position === "object"
  2935. ? opts.position.clientX
  2936. : opts.position === "cursor"
  2937. ? this.lastViewportPosition.x
  2938. : this.state.width / 2 + this.state.offsetLeft;
  2939. const clientY =
  2940. typeof opts.position === "object"
  2941. ? opts.position.clientY
  2942. : opts.position === "cursor"
  2943. ? this.lastViewportPosition.y
  2944. : this.state.height / 2 + this.state.offsetTop;
  2945. const { x, y } = viewportCoordsToSceneCoords(
  2946. { clientX, clientY },
  2947. this.state,
  2948. );
  2949. const dx = x - elementsCenterX;
  2950. const dy = y - elementsCenterY;
  2951. const [gridX, gridY] = getGridPoint(dx, dy, this.getEffectiveGridSize());
  2952. const { duplicatedElements } = duplicateElements({
  2953. type: "everything",
  2954. elements: elements.map((element) => {
  2955. return newElementWith(element, {
  2956. x: element.x + gridX - minX,
  2957. y: element.y + gridY - minY,
  2958. });
  2959. }),
  2960. randomizeSeed: !opts.retainSeed,
  2961. });
  2962. const prevElements = this.scene.getElementsIncludingDeleted();
  2963. let nextElements = [...prevElements, ...duplicatedElements];
  2964. const mappedNewSceneElements = this.props.onDuplicate?.(
  2965. nextElements,
  2966. prevElements,
  2967. );
  2968. nextElements = mappedNewSceneElements || nextElements;
  2969. syncMovedIndices(nextElements, arrayToMap(duplicatedElements));
  2970. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({ x, y });
  2971. if (topLayerFrame) {
  2972. const eligibleElements = filterElementsEligibleAsFrameChildren(
  2973. duplicatedElements,
  2974. topLayerFrame,
  2975. );
  2976. addElementsToFrame(
  2977. nextElements,
  2978. eligibleElements,
  2979. topLayerFrame,
  2980. this.state,
  2981. );
  2982. }
  2983. this.scene.replaceAllElements(nextElements);
  2984. duplicatedElements.forEach((newElement) => {
  2985. if (isTextElement(newElement) && isBoundToContainer(newElement)) {
  2986. const container = getContainerElement(
  2987. newElement,
  2988. this.scene.getElementsMapIncludingDeleted(),
  2989. );
  2990. redrawTextBoundingBox(newElement, container, this.scene);
  2991. }
  2992. });
  2993. // paste event may not fire FontFace loadingdone event in Safari, hence loading font faces manually
  2994. if (isSafari) {
  2995. Fonts.loadElementsFonts(duplicatedElements).then((fontFaces) => {
  2996. this.fonts.onLoaded(fontFaces);
  2997. });
  2998. }
  2999. if (opts.files) {
  3000. this.addMissingFiles(opts.files);
  3001. }
  3002. const nextElementsToSelect =
  3003. excludeElementsInFramesFromSelection(duplicatedElements);
  3004. this.store.scheduleCapture();
  3005. this.setState(
  3006. {
  3007. ...this.state,
  3008. // keep sidebar (presumably the library) open if it's docked and
  3009. // can fit.
  3010. //
  3011. // Note, we should close the sidebar only if we're dropping items
  3012. // from library, not when pasting from clipboard. Alas.
  3013. openSidebar:
  3014. this.state.openSidebar &&
  3015. this.device.editor.canFitSidebar &&
  3016. editorJotaiStore.get(isSidebarDockedAtom)
  3017. ? this.state.openSidebar
  3018. : null,
  3019. ...selectGroupsForSelectedElements(
  3020. {
  3021. editingGroupId: null,
  3022. selectedElementIds: nextElementsToSelect.reduce(
  3023. (acc: Record<ExcalidrawElement["id"], true>, element) => {
  3024. if (!isBoundToContainer(element)) {
  3025. acc[element.id] = true;
  3026. }
  3027. return acc;
  3028. },
  3029. {},
  3030. ),
  3031. },
  3032. this.scene.getNonDeletedElements(),
  3033. this.state,
  3034. this,
  3035. ),
  3036. },
  3037. () => {
  3038. if (opts.files) {
  3039. this.addNewImagesToImageCache();
  3040. }
  3041. },
  3042. );
  3043. this.setActiveTool({ type: "selection" });
  3044. if (opts.fitToContent) {
  3045. this.scrollToContent(duplicatedElements, {
  3046. fitToContent: true,
  3047. canvasOffsets: this.getEditorUIOffsets(),
  3048. });
  3049. }
  3050. };
  3051. // TODO rewrite this to paste both text & images at the same time if
  3052. // pasted data contains both
  3053. private async addElementsFromMixedContentPaste(
  3054. mixedContent: PastedMixedContent,
  3055. {
  3056. isPlainPaste,
  3057. sceneX,
  3058. sceneY,
  3059. }: { isPlainPaste: boolean; sceneX: number; sceneY: number },
  3060. ) {
  3061. if (
  3062. !isPlainPaste &&
  3063. mixedContent.some((node) => node.type === "imageUrl") &&
  3064. this.isToolSupported("image")
  3065. ) {
  3066. const imageURLs = mixedContent
  3067. .filter((node) => node.type === "imageUrl")
  3068. .map((node) => node.value);
  3069. const responses = await Promise.all(
  3070. imageURLs.map(async (url) => {
  3071. try {
  3072. return { file: await ImageURLToFile(url) };
  3073. } catch (error: any) {
  3074. let errorMessage = error.message;
  3075. if (error.cause === "FETCH_ERROR") {
  3076. errorMessage = t("errors.failedToFetchImage");
  3077. } else if (error.cause === "UNSUPPORTED") {
  3078. errorMessage = t("errors.unsupportedFileType");
  3079. }
  3080. return { errorMessage };
  3081. }
  3082. }),
  3083. );
  3084. let y = sceneY;
  3085. let firstImageYOffsetDone = false;
  3086. const nextSelectedIds: Record<ExcalidrawElement["id"], true> = {};
  3087. for (const response of responses) {
  3088. if (response.file) {
  3089. const initializedImageElement = await this.createImageElement({
  3090. sceneX,
  3091. sceneY: y,
  3092. imageFile: response.file,
  3093. });
  3094. if (initializedImageElement) {
  3095. // vertically center first image in the batch
  3096. if (!firstImageYOffsetDone) {
  3097. firstImageYOffsetDone = true;
  3098. y -= initializedImageElement.height / 2;
  3099. }
  3100. // hack to reset the `y` coord because we vertically center during
  3101. // insertImageElement
  3102. this.scene.mutateElement(
  3103. initializedImageElement,
  3104. { y },
  3105. { informMutation: false, isDragging: false },
  3106. );
  3107. y = initializedImageElement.y + initializedImageElement.height + 25;
  3108. nextSelectedIds[initializedImageElement.id] = true;
  3109. }
  3110. }
  3111. }
  3112. this.setState({
  3113. selectedElementIds: makeNextSelectedElementIds(
  3114. nextSelectedIds,
  3115. this.state,
  3116. ),
  3117. });
  3118. const error = responses.find((response) => !!response.errorMessage);
  3119. if (error && error.errorMessage) {
  3120. this.setState({ errorMessage: error.errorMessage });
  3121. }
  3122. } else {
  3123. const textNodes = mixedContent.filter((node) => node.type === "text");
  3124. if (textNodes.length) {
  3125. this.addTextFromPaste(
  3126. textNodes.map((node) => node.value).join("\n\n"),
  3127. isPlainPaste,
  3128. );
  3129. }
  3130. }
  3131. }
  3132. private addTextFromPaste(text: string, isPlainPaste = false) {
  3133. const { x, y } = viewportCoordsToSceneCoords(
  3134. {
  3135. clientX: this.lastViewportPosition.x,
  3136. clientY: this.lastViewportPosition.y,
  3137. },
  3138. this.state,
  3139. );
  3140. const textElementProps = {
  3141. x,
  3142. y,
  3143. strokeColor: this.state.currentItemStrokeColor,
  3144. backgroundColor: this.state.currentItemBackgroundColor,
  3145. fillStyle: this.state.currentItemFillStyle,
  3146. strokeWidth: this.state.currentItemStrokeWidth,
  3147. strokeStyle: this.state.currentItemStrokeStyle,
  3148. roundness: null,
  3149. roughness: this.state.currentItemRoughness,
  3150. opacity: this.state.currentItemOpacity,
  3151. text,
  3152. fontSize: this.state.currentItemFontSize,
  3153. fontFamily: this.state.currentItemFontFamily,
  3154. textAlign: DEFAULT_TEXT_ALIGN,
  3155. verticalAlign: DEFAULT_VERTICAL_ALIGN,
  3156. locked: false,
  3157. };
  3158. const fontString = getFontString({
  3159. fontSize: textElementProps.fontSize,
  3160. fontFamily: textElementProps.fontFamily,
  3161. });
  3162. const lineHeight = getLineHeight(textElementProps.fontFamily);
  3163. const [x1, , x2] = getVisibleSceneBounds(this.state);
  3164. // long texts should not go beyond 800 pixels in width nor should it go below 200 px
  3165. const maxTextWidth = Math.max(Math.min((x2 - x1) * 0.5, 800), 200);
  3166. const LINE_GAP = 10;
  3167. let currentY = y;
  3168. const lines = isPlainPaste ? [text] : text.split("\n");
  3169. const textElements = lines.reduce(
  3170. (acc: ExcalidrawTextElement[], line, idx) => {
  3171. const originalText = normalizeText(line).trim();
  3172. if (originalText.length) {
  3173. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  3174. x,
  3175. y: currentY,
  3176. });
  3177. let metrics = measureText(originalText, fontString, lineHeight);
  3178. const isTextUnwrapped = metrics.width > maxTextWidth;
  3179. const text = isTextUnwrapped
  3180. ? wrapText(originalText, fontString, maxTextWidth)
  3181. : originalText;
  3182. metrics = isTextUnwrapped
  3183. ? measureText(text, fontString, lineHeight)
  3184. : metrics;
  3185. const startX = x - metrics.width / 2;
  3186. const startY = currentY - metrics.height / 2;
  3187. const element = newTextElement({
  3188. ...textElementProps,
  3189. x: startX,
  3190. y: startY,
  3191. text,
  3192. originalText,
  3193. lineHeight,
  3194. autoResize: !isTextUnwrapped,
  3195. frameId: topLayerFrame ? topLayerFrame.id : null,
  3196. });
  3197. acc.push(element);
  3198. currentY += element.height + LINE_GAP;
  3199. } else {
  3200. const prevLine = lines[idx - 1]?.trim();
  3201. // add paragraph only if previous line was not empty, IOW don't add
  3202. // more than one empty line
  3203. if (prevLine) {
  3204. currentY +=
  3205. getLineHeightInPx(textElementProps.fontSize, lineHeight) +
  3206. LINE_GAP;
  3207. }
  3208. }
  3209. return acc;
  3210. },
  3211. [],
  3212. );
  3213. if (textElements.length === 0) {
  3214. return;
  3215. }
  3216. this.scene.insertElements(textElements);
  3217. this.store.scheduleCapture();
  3218. this.setState({
  3219. selectedElementIds: makeNextSelectedElementIds(
  3220. Object.fromEntries(textElements.map((el) => [el.id, true])),
  3221. this.state,
  3222. ),
  3223. });
  3224. if (
  3225. !isPlainPaste &&
  3226. textElements.length > 1 &&
  3227. PLAIN_PASTE_TOAST_SHOWN === false &&
  3228. !this.device.editor.isMobile
  3229. ) {
  3230. this.setToast({
  3231. message: t("toast.pasteAsSingleElement", {
  3232. shortcut: getShortcutKey("CtrlOrCmd+Shift+V"),
  3233. }),
  3234. duration: 5000,
  3235. });
  3236. PLAIN_PASTE_TOAST_SHOWN = true;
  3237. }
  3238. }
  3239. setAppState: React.Component<any, AppState>["setState"] = (
  3240. state,
  3241. callback,
  3242. ) => {
  3243. this.setState(state, callback);
  3244. };
  3245. removePointer = (event: React.PointerEvent<HTMLElement> | PointerEvent) => {
  3246. if (touchTimeout) {
  3247. this.resetContextMenuTimer();
  3248. }
  3249. gesture.pointers.delete(event.pointerId);
  3250. };
  3251. toggleLock = (source: "keyboard" | "ui" = "ui") => {
  3252. if (!this.state.activeTool.locked) {
  3253. trackEvent(
  3254. "toolbar",
  3255. "toggleLock",
  3256. `${source} (${this.device.editor.isMobile ? "mobile" : "desktop"})`,
  3257. );
  3258. }
  3259. this.setState((prevState) => {
  3260. return {
  3261. activeTool: {
  3262. ...prevState.activeTool,
  3263. ...updateActiveTool(
  3264. this.state,
  3265. prevState.activeTool.locked
  3266. ? { type: "selection" }
  3267. : prevState.activeTool,
  3268. ),
  3269. locked: !prevState.activeTool.locked,
  3270. },
  3271. };
  3272. });
  3273. };
  3274. updateFrameRendering = (
  3275. opts:
  3276. | Partial<AppState["frameRendering"]>
  3277. | ((
  3278. prevState: AppState["frameRendering"],
  3279. ) => Partial<AppState["frameRendering"]>),
  3280. ) => {
  3281. this.setState((prevState) => {
  3282. const next =
  3283. typeof opts === "function" ? opts(prevState.frameRendering) : opts;
  3284. return {
  3285. frameRendering: {
  3286. enabled: next?.enabled ?? prevState.frameRendering.enabled,
  3287. clip: next?.clip ?? prevState.frameRendering.clip,
  3288. name: next?.name ?? prevState.frameRendering.name,
  3289. outline: next?.outline ?? prevState.frameRendering.outline,
  3290. },
  3291. };
  3292. });
  3293. };
  3294. togglePenMode = (force: boolean | null) => {
  3295. this.setState((prevState) => {
  3296. return {
  3297. penMode: force ?? !prevState.penMode,
  3298. penDetected: true,
  3299. };
  3300. });
  3301. };
  3302. onHandToolToggle = () => {
  3303. this.actionManager.executeAction(actionToggleHandTool);
  3304. };
  3305. /**
  3306. * Zooms on canvas viewport center
  3307. */
  3308. zoomCanvas = (
  3309. /**
  3310. * Decimal fraction, auto-clamped between MIN_ZOOM and MAX_ZOOM.
  3311. * 1 = 100% zoom, 2 = 200% zoom, 0.5 = 50% zoom
  3312. */
  3313. value: number,
  3314. ) => {
  3315. this.setState({
  3316. ...getStateForZoom(
  3317. {
  3318. viewportX: this.state.width / 2 + this.state.offsetLeft,
  3319. viewportY: this.state.height / 2 + this.state.offsetTop,
  3320. nextZoom: getNormalizedZoom(value),
  3321. },
  3322. this.state,
  3323. ),
  3324. });
  3325. };
  3326. private cancelInProgressAnimation: (() => void) | null = null;
  3327. scrollToContent = (
  3328. /**
  3329. * target to scroll to
  3330. *
  3331. * - string - id of element or group, or url containing elementLink
  3332. * - ExcalidrawElement | ExcalidrawElement[] - element(s) objects
  3333. */
  3334. target:
  3335. | string
  3336. | ExcalidrawElement
  3337. | readonly ExcalidrawElement[] = this.scene.getNonDeletedElements(),
  3338. opts?: (
  3339. | {
  3340. fitToContent?: boolean;
  3341. fitToViewport?: never;
  3342. viewportZoomFactor?: number;
  3343. animate?: boolean;
  3344. duration?: number;
  3345. }
  3346. | {
  3347. fitToContent?: never;
  3348. fitToViewport?: boolean;
  3349. /** when fitToViewport=true, how much screen should the content cover,
  3350. * between 0.1 (10%) and 1 (100%)
  3351. */
  3352. viewportZoomFactor?: number;
  3353. animate?: boolean;
  3354. duration?: number;
  3355. }
  3356. ) & {
  3357. minZoom?: number;
  3358. maxZoom?: number;
  3359. canvasOffsets?: Offsets;
  3360. },
  3361. ) => {
  3362. if (typeof target === "string") {
  3363. let id: string | null;
  3364. if (isElementLink(target)) {
  3365. id = parseElementLinkFromURL(target);
  3366. } else {
  3367. id = target;
  3368. }
  3369. if (id) {
  3370. const elements = this.scene.getElementsFromId(id);
  3371. if (elements?.length) {
  3372. this.scrollToContent(elements, {
  3373. fitToContent: opts?.fitToContent ?? true,
  3374. animate: opts?.animate ?? true,
  3375. });
  3376. } else if (isElementLink(target)) {
  3377. this.setState({
  3378. toast: {
  3379. message: t("elementLink.notFound"),
  3380. duration: 3000,
  3381. closable: true,
  3382. },
  3383. });
  3384. }
  3385. }
  3386. return;
  3387. }
  3388. this.cancelInProgressAnimation?.();
  3389. // convert provided target into ExcalidrawElement[] if necessary
  3390. const targetElements = Array.isArray(target) ? target : [target];
  3391. let zoom = this.state.zoom;
  3392. let scrollX = this.state.scrollX;
  3393. let scrollY = this.state.scrollY;
  3394. if (opts?.fitToContent || opts?.fitToViewport) {
  3395. const { appState } = zoomToFit({
  3396. canvasOffsets: opts.canvasOffsets,
  3397. targetElements,
  3398. appState: this.state,
  3399. fitToViewport: !!opts?.fitToViewport,
  3400. viewportZoomFactor: opts?.viewportZoomFactor,
  3401. minZoom: opts?.minZoom,
  3402. maxZoom: opts?.maxZoom,
  3403. });
  3404. zoom = appState.zoom;
  3405. scrollX = appState.scrollX;
  3406. scrollY = appState.scrollY;
  3407. } else {
  3408. // compute only the viewport location, without any zoom adjustment
  3409. const scroll = calculateScrollCenter(targetElements, this.state);
  3410. scrollX = scroll.scrollX;
  3411. scrollY = scroll.scrollY;
  3412. }
  3413. // when animating, we use RequestAnimationFrame to prevent the animation
  3414. // from slowing down other processes
  3415. if (opts?.animate) {
  3416. const origScrollX = this.state.scrollX;
  3417. const origScrollY = this.state.scrollY;
  3418. const origZoom = this.state.zoom.value;
  3419. const cancel = easeToValuesRAF({
  3420. fromValues: {
  3421. scrollX: origScrollX,
  3422. scrollY: origScrollY,
  3423. zoom: origZoom,
  3424. },
  3425. toValues: { scrollX, scrollY, zoom: zoom.value },
  3426. interpolateValue: (from, to, progress, key) => {
  3427. // for zoom, use different easing
  3428. if (key === "zoom") {
  3429. return from * Math.pow(to / from, easeOut(progress));
  3430. }
  3431. // handle using default
  3432. return undefined;
  3433. },
  3434. onStep: ({ scrollX, scrollY, zoom }) => {
  3435. this.setState({
  3436. scrollX,
  3437. scrollY,
  3438. zoom: { value: zoom },
  3439. });
  3440. },
  3441. onStart: () => {
  3442. this.setState({ shouldCacheIgnoreZoom: true });
  3443. },
  3444. onEnd: () => {
  3445. this.setState({ shouldCacheIgnoreZoom: false });
  3446. },
  3447. onCancel: () => {
  3448. this.setState({ shouldCacheIgnoreZoom: false });
  3449. },
  3450. duration: opts?.duration ?? 500,
  3451. });
  3452. this.cancelInProgressAnimation = () => {
  3453. cancel();
  3454. this.cancelInProgressAnimation = null;
  3455. };
  3456. } else {
  3457. this.setState({ scrollX, scrollY, zoom });
  3458. }
  3459. };
  3460. private maybeUnfollowRemoteUser = () => {
  3461. if (this.state.userToFollow) {
  3462. this.setState({ userToFollow: null });
  3463. }
  3464. };
  3465. /** use when changing scrollX/scrollY/zoom based on user interaction */
  3466. private translateCanvas: React.Component<any, AppState>["setState"] = (
  3467. state,
  3468. ) => {
  3469. this.cancelInProgressAnimation?.();
  3470. this.maybeUnfollowRemoteUser();
  3471. this.setState(state);
  3472. };
  3473. setToast = (
  3474. toast: {
  3475. message: string;
  3476. closable?: boolean;
  3477. duration?: number;
  3478. } | null,
  3479. ) => {
  3480. this.setState({ toast });
  3481. };
  3482. restoreFileFromShare = async () => {
  3483. try {
  3484. const webShareTargetCache = await caches.open("web-share-target");
  3485. const response = await webShareTargetCache.match("shared-file");
  3486. if (response) {
  3487. const blob = await response.blob();
  3488. const file = new File([blob], blob.name || "", { type: blob.type });
  3489. this.loadFileToCanvas(file, null);
  3490. await webShareTargetCache.delete("shared-file");
  3491. window.history.replaceState(null, APP_NAME, window.location.pathname);
  3492. }
  3493. } catch (error: any) {
  3494. this.setState({ errorMessage: error.message });
  3495. }
  3496. };
  3497. /**
  3498. * adds supplied files to existing files in the appState.
  3499. * NOTE if file already exists in editor state, the file data is not updated
  3500. * */
  3501. public addFiles: ExcalidrawImperativeAPI["addFiles"] = withBatchedUpdates(
  3502. (files) => {
  3503. const { addedFiles } = this.addMissingFiles(files);
  3504. this.clearImageShapeCache(addedFiles);
  3505. this.scene.triggerUpdate();
  3506. this.addNewImagesToImageCache();
  3507. },
  3508. );
  3509. private addMissingFiles = (
  3510. files: BinaryFiles | BinaryFileData[],
  3511. replace = false,
  3512. ) => {
  3513. const nextFiles = replace ? {} : { ...this.files };
  3514. const addedFiles: BinaryFiles = {};
  3515. const _files = Array.isArray(files) ? files : Object.values(files);
  3516. for (const fileData of _files) {
  3517. if (nextFiles[fileData.id]) {
  3518. continue;
  3519. }
  3520. addedFiles[fileData.id] = fileData;
  3521. nextFiles[fileData.id] = fileData;
  3522. if (fileData.mimeType === MIME_TYPES.svg) {
  3523. try {
  3524. const restoredDataURL = getDataURL_sync(
  3525. normalizeSVG(dataURLToString(fileData.dataURL)),
  3526. MIME_TYPES.svg,
  3527. );
  3528. if (fileData.dataURL !== restoredDataURL) {
  3529. // bump version so persistence layer can update the store
  3530. fileData.version = (fileData.version ?? 1) + 1;
  3531. fileData.dataURL = restoredDataURL;
  3532. }
  3533. } catch (error) {
  3534. console.error(error);
  3535. }
  3536. }
  3537. }
  3538. this.files = nextFiles;
  3539. return { addedFiles };
  3540. };
  3541. public updateScene = withBatchedUpdates(
  3542. <K extends keyof AppState>(sceneData: {
  3543. elements?: SceneData["elements"];
  3544. appState?: Pick<AppState, K> | null;
  3545. collaborators?: SceneData["collaborators"];
  3546. /**
  3547. * Controls which updates should be captured by the `Store`. Captured updates are emmitted and listened to by other components, such as `History` for undo / redo purposes.
  3548. *
  3549. * - `CaptureUpdateAction.IMMEDIATELY`: Updates are immediately undoable. Use for most local updates.
  3550. * - `CaptureUpdateAction.NEVER`: Updates never make it to undo/redo stack. Use for remote updates or scene initialization.
  3551. * - `CaptureUpdateAction.EVENTUALLY`: Updates will be eventually be captured as part of a future increment.
  3552. *
  3553. * Check [API docs](https://docs.excalidraw.com/docs/@excalidraw/excalidraw/api/props/excalidraw-api#captureUpdate) for more details.
  3554. *
  3555. * @default CaptureUpdateAction.EVENTUALLY
  3556. */
  3557. captureUpdate?: SceneData["captureUpdate"];
  3558. }) => {
  3559. const { elements, appState, collaborators, captureUpdate } = sceneData;
  3560. if (captureUpdate) {
  3561. const nextElements = elements ? elements : undefined;
  3562. const observedAppState = appState
  3563. ? getObservedAppState({
  3564. ...this.store.snapshot.appState,
  3565. ...appState,
  3566. })
  3567. : undefined;
  3568. this.store.scheduleMicroAction({
  3569. action: captureUpdate,
  3570. elements: nextElements,
  3571. appState: observedAppState,
  3572. });
  3573. }
  3574. if (appState) {
  3575. this.setState(appState);
  3576. }
  3577. if (elements) {
  3578. this.scene.replaceAllElements(elements);
  3579. }
  3580. if (collaborators) {
  3581. this.setState({ collaborators });
  3582. }
  3583. },
  3584. );
  3585. public mutateElement = <TElement extends Mutable<ExcalidrawElement>>(
  3586. element: TElement,
  3587. updates: ElementUpdate<TElement>,
  3588. informMutation = true,
  3589. ) => {
  3590. return this.scene.mutateElement(element, updates, {
  3591. informMutation,
  3592. isDragging: false,
  3593. });
  3594. };
  3595. private triggerRender = (
  3596. /** force always re-renders canvas even if no change */
  3597. force?: boolean,
  3598. ) => {
  3599. if (force === true) {
  3600. this.scene.triggerUpdate();
  3601. } else {
  3602. this.setState({});
  3603. }
  3604. };
  3605. /**
  3606. * @returns whether the menu was toggled on or off
  3607. */
  3608. public toggleSidebar = ({
  3609. name,
  3610. tab,
  3611. force,
  3612. }: {
  3613. name: SidebarName | null;
  3614. tab?: SidebarTabName;
  3615. force?: boolean;
  3616. }): boolean => {
  3617. let nextName;
  3618. if (force === undefined) {
  3619. nextName =
  3620. this.state.openSidebar?.name === name &&
  3621. this.state.openSidebar?.tab === tab
  3622. ? null
  3623. : name;
  3624. } else {
  3625. nextName = force ? name : null;
  3626. }
  3627. const nextState: AppState["openSidebar"] = nextName
  3628. ? { name: nextName }
  3629. : null;
  3630. if (nextState && tab) {
  3631. nextState.tab = tab;
  3632. }
  3633. this.setState({ openSidebar: nextState });
  3634. return !!nextName;
  3635. };
  3636. private updateCurrentCursorPosition = withBatchedUpdates(
  3637. (event: MouseEvent) => {
  3638. this.lastViewportPosition.x = event.clientX;
  3639. this.lastViewportPosition.y = event.clientY;
  3640. },
  3641. );
  3642. public getEditorUIOffsets = (): Offsets => {
  3643. const toolbarBottom =
  3644. this.excalidrawContainerRef?.current
  3645. ?.querySelector(".App-toolbar")
  3646. ?.getBoundingClientRect()?.bottom ?? 0;
  3647. const sidebarRect = this.excalidrawContainerRef?.current
  3648. ?.querySelector(".sidebar")
  3649. ?.getBoundingClientRect();
  3650. const propertiesPanelRect = this.excalidrawContainerRef?.current
  3651. ?.querySelector(".App-menu__left")
  3652. ?.getBoundingClientRect();
  3653. const PADDING = 16;
  3654. return getLanguage().rtl
  3655. ? {
  3656. top: toolbarBottom + PADDING,
  3657. right:
  3658. Math.max(
  3659. this.state.width -
  3660. (propertiesPanelRect?.left ?? this.state.width),
  3661. 0,
  3662. ) + PADDING,
  3663. bottom: PADDING,
  3664. left: Math.max(sidebarRect?.right ?? 0, 0) + PADDING,
  3665. }
  3666. : {
  3667. top: toolbarBottom + PADDING,
  3668. right: Math.max(
  3669. this.state.width -
  3670. (sidebarRect?.left ?? this.state.width) +
  3671. PADDING,
  3672. 0,
  3673. ),
  3674. bottom: PADDING,
  3675. left: Math.max(propertiesPanelRect?.right ?? 0, 0) + PADDING,
  3676. };
  3677. };
  3678. // Input handling
  3679. private onKeyDown = withBatchedUpdates(
  3680. (event: React.KeyboardEvent | KeyboardEvent) => {
  3681. // normalize `event.key` when CapsLock is pressed #2372
  3682. if (
  3683. "Proxy" in window &&
  3684. ((!event.shiftKey && /^[A-Z]$/.test(event.key)) ||
  3685. (event.shiftKey && /^[a-z]$/.test(event.key)))
  3686. ) {
  3687. event = new Proxy(event, {
  3688. get(ev: any, prop) {
  3689. const value = ev[prop];
  3690. if (typeof value === "function") {
  3691. // fix for Proxies hijacking `this`
  3692. return value.bind(ev);
  3693. }
  3694. return prop === "key"
  3695. ? // CapsLock inverts capitalization based on ShiftKey, so invert
  3696. // it back
  3697. event.shiftKey
  3698. ? ev.key.toUpperCase()
  3699. : ev.key.toLowerCase()
  3700. : value;
  3701. },
  3702. });
  3703. }
  3704. if (!isInputLike(event.target)) {
  3705. if (
  3706. (event.key === KEYS.ESCAPE || event.key === KEYS.ENTER) &&
  3707. this.state.croppingElementId
  3708. ) {
  3709. this.finishImageCropping();
  3710. return;
  3711. }
  3712. const selectedElements = getSelectedElements(
  3713. this.scene.getNonDeletedElementsMap(),
  3714. this.state,
  3715. );
  3716. if (
  3717. selectedElements.length === 1 &&
  3718. isImageElement(selectedElements[0]) &&
  3719. event.key === KEYS.ENTER
  3720. ) {
  3721. this.startImageCropping(selectedElements[0]);
  3722. return;
  3723. }
  3724. // Shape switching
  3725. if (event.key === KEYS.ESCAPE) {
  3726. this.updateEditorAtom(convertElementTypePopupAtom, null);
  3727. } else if (
  3728. event.key === KEYS.TAB &&
  3729. (document.activeElement === this.excalidrawContainerRef?.current ||
  3730. document.activeElement?.classList.contains(
  3731. CLASSES.CONVERT_ELEMENT_TYPE_POPUP,
  3732. ))
  3733. ) {
  3734. event.preventDefault();
  3735. const conversionType =
  3736. getConversionTypeFromElements(selectedElements);
  3737. if (
  3738. editorJotaiStore.get(convertElementTypePopupAtom)?.type === "panel"
  3739. ) {
  3740. if (
  3741. convertElementTypes(this, {
  3742. conversionType,
  3743. direction: event.shiftKey ? "left" : "right",
  3744. })
  3745. ) {
  3746. this.store.scheduleCapture();
  3747. }
  3748. }
  3749. if (conversionType) {
  3750. this.updateEditorAtom(convertElementTypePopupAtom, {
  3751. type: "panel",
  3752. });
  3753. }
  3754. }
  3755. if (
  3756. event.key === KEYS.ESCAPE &&
  3757. this.flowChartCreator.isCreatingChart
  3758. ) {
  3759. this.flowChartCreator.clear();
  3760. this.triggerRender(true);
  3761. return;
  3762. }
  3763. const arrowKeyPressed = isArrowKey(event.key);
  3764. if (event[KEYS.CTRL_OR_CMD] && arrowKeyPressed && !event.shiftKey) {
  3765. event.preventDefault();
  3766. const selectedElements = getSelectedElements(
  3767. this.scene.getNonDeletedElementsMap(),
  3768. this.state,
  3769. );
  3770. if (
  3771. selectedElements.length === 1 &&
  3772. isFlowchartNodeElement(selectedElements[0])
  3773. ) {
  3774. this.flowChartCreator.createNodes(
  3775. selectedElements[0],
  3776. this.state,
  3777. getLinkDirectionFromKey(event.key),
  3778. this.scene,
  3779. );
  3780. }
  3781. if (
  3782. this.flowChartCreator.pendingNodes?.length &&
  3783. !isElementCompletelyInViewport(
  3784. this.flowChartCreator.pendingNodes,
  3785. this.canvas.width / window.devicePixelRatio,
  3786. this.canvas.height / window.devicePixelRatio,
  3787. {
  3788. offsetLeft: this.state.offsetLeft,
  3789. offsetTop: this.state.offsetTop,
  3790. scrollX: this.state.scrollX,
  3791. scrollY: this.state.scrollY,
  3792. zoom: this.state.zoom,
  3793. },
  3794. this.scene.getNonDeletedElementsMap(),
  3795. this.getEditorUIOffsets(),
  3796. )
  3797. ) {
  3798. this.scrollToContent(this.flowChartCreator.pendingNodes, {
  3799. animate: true,
  3800. duration: 300,
  3801. fitToContent: true,
  3802. canvasOffsets: this.getEditorUIOffsets(),
  3803. });
  3804. }
  3805. return;
  3806. }
  3807. if (event.altKey) {
  3808. const selectedElements = getSelectedElements(
  3809. this.scene.getNonDeletedElementsMap(),
  3810. this.state,
  3811. );
  3812. if (selectedElements.length === 1 && arrowKeyPressed) {
  3813. event.preventDefault();
  3814. const nextId = this.flowChartNavigator.exploreByDirection(
  3815. selectedElements[0],
  3816. this.scene.getNonDeletedElementsMap(),
  3817. getLinkDirectionFromKey(event.key),
  3818. );
  3819. if (nextId) {
  3820. this.setState((prevState) => ({
  3821. selectedElementIds: makeNextSelectedElementIds(
  3822. {
  3823. [nextId]: true,
  3824. },
  3825. prevState,
  3826. ),
  3827. }));
  3828. const nextNode = this.scene
  3829. .getNonDeletedElementsMap()
  3830. .get(nextId);
  3831. if (
  3832. nextNode &&
  3833. !isElementCompletelyInViewport(
  3834. [nextNode],
  3835. this.canvas.width / window.devicePixelRatio,
  3836. this.canvas.height / window.devicePixelRatio,
  3837. {
  3838. offsetLeft: this.state.offsetLeft,
  3839. offsetTop: this.state.offsetTop,
  3840. scrollX: this.state.scrollX,
  3841. scrollY: this.state.scrollY,
  3842. zoom: this.state.zoom,
  3843. },
  3844. this.scene.getNonDeletedElementsMap(),
  3845. this.getEditorUIOffsets(),
  3846. )
  3847. ) {
  3848. this.scrollToContent(nextNode, {
  3849. animate: true,
  3850. duration: 300,
  3851. canvasOffsets: this.getEditorUIOffsets(),
  3852. });
  3853. }
  3854. }
  3855. return;
  3856. }
  3857. }
  3858. }
  3859. if (
  3860. event[KEYS.CTRL_OR_CMD] &&
  3861. event.key === KEYS.P &&
  3862. !event.shiftKey &&
  3863. !event.altKey
  3864. ) {
  3865. this.setToast({
  3866. message: t("commandPalette.shortcutHint", {
  3867. shortcut: getShortcutFromShortcutName("commandPalette"),
  3868. }),
  3869. });
  3870. event.preventDefault();
  3871. return;
  3872. }
  3873. if (event[KEYS.CTRL_OR_CMD] && event.key.toLowerCase() === KEYS.V) {
  3874. IS_PLAIN_PASTE = event.shiftKey;
  3875. clearTimeout(IS_PLAIN_PASTE_TIMER);
  3876. // reset (100ms to be safe that we it runs after the ensuing
  3877. // paste event). Though, technically unnecessary to reset since we
  3878. // (re)set the flag before each paste event.
  3879. IS_PLAIN_PASTE_TIMER = window.setTimeout(() => {
  3880. IS_PLAIN_PASTE = false;
  3881. }, 100);
  3882. }
  3883. // prevent browser zoom in input fields
  3884. if (event[KEYS.CTRL_OR_CMD] && isWritableElement(event.target)) {
  3885. if (event.code === CODES.MINUS || event.code === CODES.EQUAL) {
  3886. event.preventDefault();
  3887. return;
  3888. }
  3889. }
  3890. // bail if
  3891. if (
  3892. // inside an input
  3893. (isWritableElement(event.target) &&
  3894. // unless pressing escape (finalize action)
  3895. event.key !== KEYS.ESCAPE) ||
  3896. // or unless using arrows (to move between buttons)
  3897. (isArrowKey(event.key) && isInputLike(event.target))
  3898. ) {
  3899. return;
  3900. }
  3901. if (event.key === KEYS.QUESTION_MARK) {
  3902. this.setState({
  3903. openDialog: { name: "help" },
  3904. });
  3905. return;
  3906. } else if (
  3907. event.key.toLowerCase() === KEYS.E &&
  3908. event.shiftKey &&
  3909. event[KEYS.CTRL_OR_CMD]
  3910. ) {
  3911. event.preventDefault();
  3912. this.setState({ openDialog: { name: "imageExport" } });
  3913. return;
  3914. }
  3915. if (event.key === KEYS.PAGE_UP || event.key === KEYS.PAGE_DOWN) {
  3916. let offset =
  3917. (event.shiftKey ? this.state.width : this.state.height) /
  3918. this.state.zoom.value;
  3919. if (event.key === KEYS.PAGE_DOWN) {
  3920. offset = -offset;
  3921. }
  3922. if (event.shiftKey) {
  3923. this.translateCanvas((state) => ({
  3924. scrollX: state.scrollX + offset,
  3925. }));
  3926. } else {
  3927. this.translateCanvas((state) => ({
  3928. scrollY: state.scrollY + offset,
  3929. }));
  3930. }
  3931. }
  3932. if (this.state.openDialog?.name === "elementLinkSelector") {
  3933. return;
  3934. }
  3935. if (this.actionManager.handleKeyDown(event)) {
  3936. return;
  3937. }
  3938. if (this.state.viewModeEnabled) {
  3939. return;
  3940. }
  3941. if (event[KEYS.CTRL_OR_CMD] && this.state.isBindingEnabled) {
  3942. this.setState({ isBindingEnabled: false });
  3943. }
  3944. if (isArrowKey(event.key)) {
  3945. let selectedElements = this.scene.getSelectedElements({
  3946. selectedElementIds: this.state.selectedElementIds,
  3947. includeBoundTextElement: true,
  3948. includeElementsInFrames: true,
  3949. });
  3950. const elbowArrow = selectedElements.find(isElbowArrow) as
  3951. | ExcalidrawArrowElement
  3952. | undefined;
  3953. const arrowIdsToRemove = new Set<string>();
  3954. selectedElements
  3955. .filter(isElbowArrow)
  3956. .filter((arrow) => {
  3957. const startElementNotInSelection =
  3958. arrow.startBinding &&
  3959. !selectedElements.some(
  3960. (el) => el.id === arrow.startBinding?.elementId,
  3961. );
  3962. const endElementNotInSelection =
  3963. arrow.endBinding &&
  3964. !selectedElements.some(
  3965. (el) => el.id === arrow.endBinding?.elementId,
  3966. );
  3967. return startElementNotInSelection || endElementNotInSelection;
  3968. })
  3969. .forEach((arrow) => arrowIdsToRemove.add(arrow.id));
  3970. selectedElements = selectedElements.filter(
  3971. (el) => !arrowIdsToRemove.has(el.id),
  3972. );
  3973. const step =
  3974. (this.getEffectiveGridSize() &&
  3975. (event.shiftKey
  3976. ? ELEMENT_TRANSLATE_AMOUNT
  3977. : this.getEffectiveGridSize())) ||
  3978. (event.shiftKey
  3979. ? ELEMENT_SHIFT_TRANSLATE_AMOUNT
  3980. : ELEMENT_TRANSLATE_AMOUNT);
  3981. let offsetX = 0;
  3982. let offsetY = 0;
  3983. if (event.key === KEYS.ARROW_LEFT) {
  3984. offsetX = -step;
  3985. } else if (event.key === KEYS.ARROW_RIGHT) {
  3986. offsetX = step;
  3987. } else if (event.key === KEYS.ARROW_UP) {
  3988. offsetY = -step;
  3989. } else if (event.key === KEYS.ARROW_DOWN) {
  3990. offsetY = step;
  3991. }
  3992. selectedElements.forEach((element) => {
  3993. this.scene.mutateElement(
  3994. element,
  3995. {
  3996. x: element.x + offsetX,
  3997. y: element.y + offsetY,
  3998. },
  3999. { informMutation: false, isDragging: false },
  4000. );
  4001. updateBoundElements(element, this.scene, {
  4002. simultaneouslyUpdated: selectedElements,
  4003. });
  4004. });
  4005. this.setState({
  4006. suggestedBindings: getSuggestedBindingsForArrows(
  4007. selectedElements.filter(
  4008. (element) => element.id !== elbowArrow?.id || step !== 0,
  4009. ),
  4010. this.scene.getNonDeletedElementsMap(),
  4011. this.state.zoom,
  4012. ),
  4013. });
  4014. this.scene.triggerUpdate();
  4015. event.preventDefault();
  4016. } else if (event.key === KEYS.ENTER) {
  4017. const selectedElements = this.scene.getSelectedElements(this.state);
  4018. if (selectedElements.length === 1) {
  4019. const selectedElement = selectedElements[0];
  4020. if (event[KEYS.CTRL_OR_CMD] || isLineElement(selectedElement)) {
  4021. if (isLinearElement(selectedElement)) {
  4022. if (
  4023. !this.state.selectedLinearElement?.isEditing ||
  4024. this.state.selectedLinearElement.elementId !==
  4025. selectedElement.id
  4026. ) {
  4027. this.store.scheduleCapture();
  4028. if (!isElbowArrow(selectedElement)) {
  4029. this.actionManager.executeAction(actionToggleLinearEditor);
  4030. }
  4031. }
  4032. }
  4033. } else if (
  4034. isTextElement(selectedElement) ||
  4035. isValidTextContainer(selectedElement)
  4036. ) {
  4037. let container;
  4038. if (!isTextElement(selectedElement)) {
  4039. container = selectedElement as ExcalidrawTextContainer;
  4040. }
  4041. const midPoint = getContainerCenter(
  4042. selectedElement,
  4043. this.state,
  4044. this.scene.getNonDeletedElementsMap(),
  4045. );
  4046. const sceneX = midPoint.x;
  4047. const sceneY = midPoint.y;
  4048. this.startTextEditing({
  4049. sceneX,
  4050. sceneY,
  4051. container,
  4052. });
  4053. event.preventDefault();
  4054. return;
  4055. } else if (isFrameLikeElement(selectedElement)) {
  4056. this.setState({
  4057. editingFrame: selectedElement.id,
  4058. });
  4059. }
  4060. }
  4061. } else if (
  4062. !event.ctrlKey &&
  4063. !event.altKey &&
  4064. !event.metaKey &&
  4065. !this.state.newElement &&
  4066. !this.state.selectionElement &&
  4067. !this.state.selectedElementsAreBeingDragged
  4068. ) {
  4069. const shape = findShapeByKey(event.key);
  4070. if (shape) {
  4071. if (this.state.activeTool.type !== shape) {
  4072. trackEvent(
  4073. "toolbar",
  4074. shape,
  4075. `keyboard (${
  4076. this.device.editor.isMobile ? "mobile" : "desktop"
  4077. })`,
  4078. );
  4079. }
  4080. if (shape === "arrow" && this.state.activeTool.type === "arrow") {
  4081. this.setState((prevState) => ({
  4082. currentItemArrowType:
  4083. prevState.currentItemArrowType === ARROW_TYPE.sharp
  4084. ? ARROW_TYPE.round
  4085. : prevState.currentItemArrowType === ARROW_TYPE.round
  4086. ? ARROW_TYPE.elbow
  4087. : ARROW_TYPE.sharp,
  4088. }));
  4089. }
  4090. this.setActiveTool({ type: shape });
  4091. event.stopPropagation();
  4092. } else if (event.key === KEYS.Q) {
  4093. this.toggleLock("keyboard");
  4094. event.stopPropagation();
  4095. }
  4096. }
  4097. if (event.key === KEYS.SPACE && gesture.pointers.size === 0) {
  4098. isHoldingSpace = true;
  4099. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  4100. event.preventDefault();
  4101. }
  4102. if (
  4103. (event.key === KEYS.G || event.key === KEYS.S) &&
  4104. !event.altKey &&
  4105. !event[KEYS.CTRL_OR_CMD]
  4106. ) {
  4107. const selectedElements = this.scene.getSelectedElements(this.state);
  4108. if (
  4109. this.state.activeTool.type === "selection" &&
  4110. !selectedElements.length
  4111. ) {
  4112. return;
  4113. }
  4114. if (
  4115. event.key === KEYS.G &&
  4116. (hasBackground(this.state.activeTool.type) ||
  4117. selectedElements.some((element) => hasBackground(element.type)))
  4118. ) {
  4119. this.setState({ openPopup: "elementBackground" });
  4120. event.stopPropagation();
  4121. }
  4122. if (event.key === KEYS.S) {
  4123. this.setState({ openPopup: "elementStroke" });
  4124. event.stopPropagation();
  4125. }
  4126. }
  4127. if (
  4128. !event[KEYS.CTRL_OR_CMD] &&
  4129. event.shiftKey &&
  4130. event.key.toLowerCase() === KEYS.F
  4131. ) {
  4132. const selectedElements = this.scene.getSelectedElements(this.state);
  4133. if (
  4134. this.state.activeTool.type === "selection" &&
  4135. !selectedElements.length
  4136. ) {
  4137. return;
  4138. }
  4139. if (
  4140. this.state.activeTool.type === "text" ||
  4141. selectedElements.find(
  4142. (element) =>
  4143. isTextElement(element) ||
  4144. getBoundTextElement(
  4145. element,
  4146. this.scene.getNonDeletedElementsMap(),
  4147. ),
  4148. )
  4149. ) {
  4150. event.preventDefault();
  4151. this.setState({ openPopup: "fontFamily" });
  4152. }
  4153. }
  4154. if (event.key === KEYS.K && !event.altKey && !event[KEYS.CTRL_OR_CMD]) {
  4155. if (this.state.activeTool.type === "laser") {
  4156. this.setActiveTool({ type: "selection" });
  4157. } else {
  4158. this.setActiveTool({ type: "laser" });
  4159. }
  4160. return;
  4161. }
  4162. if (
  4163. event[KEYS.CTRL_OR_CMD] &&
  4164. (event.key === KEYS.BACKSPACE || event.key === KEYS.DELETE)
  4165. ) {
  4166. this.updateEditorAtom(activeConfirmDialogAtom, "clearCanvas");
  4167. }
  4168. // eye dropper
  4169. // -----------------------------------------------------------------------
  4170. const lowerCased = event.key.toLocaleLowerCase();
  4171. const isPickingStroke = lowerCased === KEYS.S && event.shiftKey;
  4172. const isPickingBackground =
  4173. event.key === KEYS.I || (lowerCased === KEYS.G && event.shiftKey);
  4174. if (isPickingStroke || isPickingBackground) {
  4175. this.openEyeDropper({
  4176. type: isPickingStroke ? "stroke" : "background",
  4177. });
  4178. }
  4179. // -----------------------------------------------------------------------
  4180. },
  4181. );
  4182. private onKeyUp = withBatchedUpdates((event: KeyboardEvent) => {
  4183. if (event.key === KEYS.SPACE) {
  4184. if (
  4185. this.state.viewModeEnabled ||
  4186. this.state.openDialog?.name === "elementLinkSelector"
  4187. ) {
  4188. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  4189. } else if (
  4190. this.state.activeTool.type === "selection" ||
  4191. this.state.activeTool.type === "lasso"
  4192. ) {
  4193. resetCursor(this.interactiveCanvas);
  4194. } else {
  4195. setCursorForShape(this.interactiveCanvas, this.state);
  4196. this.setState({
  4197. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  4198. selectedGroupIds: {},
  4199. editingGroupId: null,
  4200. activeEmbeddable: null,
  4201. });
  4202. }
  4203. isHoldingSpace = false;
  4204. }
  4205. if (!event[KEYS.CTRL_OR_CMD] && !this.state.isBindingEnabled) {
  4206. this.setState({ isBindingEnabled: true });
  4207. }
  4208. if (isArrowKey(event.key)) {
  4209. bindOrUnbindLinearElements(
  4210. this.scene.getSelectedElements(this.state).filter(isLinearElement),
  4211. isBindingEnabled(this.state),
  4212. this.state.selectedLinearElement?.selectedPointsIndices ?? [],
  4213. this.scene,
  4214. this.state.zoom,
  4215. );
  4216. this.setState({ suggestedBindings: [] });
  4217. }
  4218. if (!event.altKey) {
  4219. if (this.flowChartNavigator.isExploring) {
  4220. this.flowChartNavigator.clear();
  4221. this.syncActionResult({
  4222. captureUpdate: CaptureUpdateAction.IMMEDIATELY,
  4223. });
  4224. }
  4225. }
  4226. if (!event[KEYS.CTRL_OR_CMD]) {
  4227. if (this.flowChartCreator.isCreatingChart) {
  4228. if (this.flowChartCreator.pendingNodes?.length) {
  4229. this.scene.insertElements(this.flowChartCreator.pendingNodes);
  4230. }
  4231. const firstNode = this.flowChartCreator.pendingNodes?.[0];
  4232. if (firstNode) {
  4233. this.setState((prevState) => ({
  4234. selectedElementIds: makeNextSelectedElementIds(
  4235. {
  4236. [firstNode.id]: true,
  4237. },
  4238. prevState,
  4239. ),
  4240. }));
  4241. if (
  4242. !isElementCompletelyInViewport(
  4243. [firstNode],
  4244. this.canvas.width / window.devicePixelRatio,
  4245. this.canvas.height / window.devicePixelRatio,
  4246. {
  4247. offsetLeft: this.state.offsetLeft,
  4248. offsetTop: this.state.offsetTop,
  4249. scrollX: this.state.scrollX,
  4250. scrollY: this.state.scrollY,
  4251. zoom: this.state.zoom,
  4252. },
  4253. this.scene.getNonDeletedElementsMap(),
  4254. this.getEditorUIOffsets(),
  4255. )
  4256. ) {
  4257. this.scrollToContent(firstNode, {
  4258. animate: true,
  4259. duration: 300,
  4260. canvasOffsets: this.getEditorUIOffsets(),
  4261. });
  4262. }
  4263. }
  4264. this.flowChartCreator.clear();
  4265. this.syncActionResult({
  4266. captureUpdate: CaptureUpdateAction.IMMEDIATELY,
  4267. });
  4268. }
  4269. }
  4270. });
  4271. // We purposely widen the `tool` type so this helper can be called with
  4272. // any tool without having to type check it
  4273. private isToolSupported = <T extends ToolType | "custom">(tool: T) => {
  4274. return (
  4275. this.props.UIOptions.tools?.[
  4276. tool as Extract<T, keyof AppProps["UIOptions"]["tools"]>
  4277. ] !== false
  4278. );
  4279. };
  4280. setActiveTool = (
  4281. tool: ({ type: ToolType } | { type: "custom"; customType: string }) & {
  4282. locked?: boolean;
  4283. fromSelection?: boolean;
  4284. },
  4285. keepSelection = false,
  4286. ) => {
  4287. if (!this.isToolSupported(tool.type)) {
  4288. console.warn(
  4289. `"${tool.type}" tool is disabled via "UIOptions.canvasActions.tools.${tool.type}"`,
  4290. );
  4291. return;
  4292. }
  4293. const nextActiveTool = updateActiveTool(this.state, tool);
  4294. if (nextActiveTool.type === "hand") {
  4295. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  4296. } else if (!isHoldingSpace) {
  4297. setCursorForShape(this.interactiveCanvas, {
  4298. ...this.state,
  4299. activeTool: nextActiveTool,
  4300. });
  4301. }
  4302. if (isToolIcon(document.activeElement)) {
  4303. this.focusContainer();
  4304. }
  4305. if (!isLinearElementType(nextActiveTool.type)) {
  4306. this.setState({ suggestedBindings: [] });
  4307. }
  4308. if (nextActiveTool.type === "image") {
  4309. this.onImageAction();
  4310. }
  4311. this.setState((prevState) => {
  4312. const commonResets = {
  4313. snapLines: prevState.snapLines.length ? [] : prevState.snapLines,
  4314. originSnapOffset: null,
  4315. activeEmbeddable: null,
  4316. } as const;
  4317. if (nextActiveTool.type === "freedraw") {
  4318. this.store.scheduleCapture();
  4319. }
  4320. if (nextActiveTool.type === "lasso") {
  4321. return {
  4322. ...prevState,
  4323. activeTool: nextActiveTool,
  4324. ...(keepSelection
  4325. ? {}
  4326. : {
  4327. selectedElementIds: makeNextSelectedElementIds({}, prevState),
  4328. selectedGroupIds: makeNextSelectedElementIds({}, prevState),
  4329. editingGroupId: null,
  4330. multiElement: null,
  4331. }),
  4332. ...commonResets,
  4333. };
  4334. } else if (nextActiveTool.type !== "selection") {
  4335. return {
  4336. ...prevState,
  4337. activeTool: nextActiveTool,
  4338. selectedElementIds: makeNextSelectedElementIds({}, prevState),
  4339. selectedGroupIds: makeNextSelectedElementIds({}, prevState),
  4340. editingGroupId: null,
  4341. multiElement: null,
  4342. ...commonResets,
  4343. };
  4344. }
  4345. return {
  4346. ...prevState,
  4347. activeTool: nextActiveTool,
  4348. ...commonResets,
  4349. };
  4350. });
  4351. };
  4352. setOpenDialog = (dialogType: AppState["openDialog"]) => {
  4353. this.setState({ openDialog: dialogType });
  4354. };
  4355. private setCursor = (cursor: string) => {
  4356. setCursor(this.interactiveCanvas, cursor);
  4357. };
  4358. private resetCursor = () => {
  4359. resetCursor(this.interactiveCanvas);
  4360. };
  4361. /**
  4362. * returns whether user is making a gesture with >= 2 fingers (points)
  4363. * on o touch screen (not on a trackpad). Currently only relates to Darwin
  4364. * (iOS/iPadOS,MacOS), but may work on other devices in the future if
  4365. * GestureEvent is standardized.
  4366. */
  4367. private isTouchScreenMultiTouchGesture = () => {
  4368. // we don't want to deselect when using trackpad, and multi-point gestures
  4369. // only work on touch screens, so checking for >= pointers means we're on a
  4370. // touchscreen
  4371. return gesture.pointers.size >= 2;
  4372. };
  4373. public getName = () => {
  4374. return (
  4375. this.state.name ||
  4376. this.props.name ||
  4377. `${t("labels.untitled")}-${getDateTime()}`
  4378. );
  4379. };
  4380. // fires only on Safari
  4381. private onGestureStart = withBatchedUpdates((event: GestureEvent) => {
  4382. event.preventDefault();
  4383. // we only want to deselect on touch screens because user may have selected
  4384. // elements by mistake while zooming
  4385. if (this.isTouchScreenMultiTouchGesture()) {
  4386. this.setState({
  4387. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  4388. activeEmbeddable: null,
  4389. });
  4390. }
  4391. gesture.initialScale = this.state.zoom.value;
  4392. });
  4393. // fires only on Safari
  4394. private onGestureChange = withBatchedUpdates((event: GestureEvent) => {
  4395. event.preventDefault();
  4396. // onGestureChange only has zoom factor but not the center.
  4397. // If we're on iPad or iPhone, then we recognize multi-touch and will
  4398. // zoom in at the right location in the touchmove handler
  4399. // (handleCanvasPointerMove).
  4400. //
  4401. // On Macbook trackpad, we don't have those events so will zoom in at the
  4402. // current location instead.
  4403. //
  4404. // As such, bail from this handler on touch devices.
  4405. if (this.isTouchScreenMultiTouchGesture()) {
  4406. return;
  4407. }
  4408. const initialScale = gesture.initialScale;
  4409. if (initialScale) {
  4410. this.setState((state) => ({
  4411. ...getStateForZoom(
  4412. {
  4413. viewportX: this.lastViewportPosition.x,
  4414. viewportY: this.lastViewportPosition.y,
  4415. nextZoom: getNormalizedZoom(initialScale * event.scale),
  4416. },
  4417. state,
  4418. ),
  4419. }));
  4420. }
  4421. });
  4422. // fires only on Safari
  4423. private onGestureEnd = withBatchedUpdates((event: GestureEvent) => {
  4424. event.preventDefault();
  4425. // reselect elements only on touch screens (see onGestureStart)
  4426. if (this.isTouchScreenMultiTouchGesture()) {
  4427. this.setState({
  4428. previousSelectedElementIds: {},
  4429. selectedElementIds: makeNextSelectedElementIds(
  4430. this.state.previousSelectedElementIds,
  4431. this.state,
  4432. ),
  4433. });
  4434. }
  4435. gesture.initialScale = null;
  4436. });
  4437. private handleTextWysiwyg(
  4438. element: ExcalidrawTextElement,
  4439. {
  4440. isExistingElement = false,
  4441. }: {
  4442. isExistingElement?: boolean;
  4443. },
  4444. ) {
  4445. const elementsMap = this.scene.getElementsMapIncludingDeleted();
  4446. const updateElement = (nextOriginalText: string, isDeleted: boolean) => {
  4447. this.scene.replaceAllElements([
  4448. // Not sure why we include deleted elements as well hence using deleted elements map
  4449. ...this.scene.getElementsIncludingDeleted().map((_element) => {
  4450. if (_element.id === element.id && isTextElement(_element)) {
  4451. return newElementWith(_element, {
  4452. originalText: nextOriginalText,
  4453. isDeleted: isDeleted ?? _element.isDeleted,
  4454. // returns (wrapped) text and new dimensions
  4455. ...refreshTextDimensions(
  4456. _element,
  4457. getContainerElement(_element, elementsMap),
  4458. elementsMap,
  4459. nextOriginalText,
  4460. ),
  4461. });
  4462. }
  4463. return _element;
  4464. }),
  4465. ]);
  4466. };
  4467. textWysiwyg({
  4468. id: element.id,
  4469. canvas: this.canvas,
  4470. getViewportCoords: (x, y) => {
  4471. const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
  4472. {
  4473. sceneX: x,
  4474. sceneY: y,
  4475. },
  4476. this.state,
  4477. );
  4478. return [
  4479. viewportX - this.state.offsetLeft,
  4480. viewportY - this.state.offsetTop,
  4481. ];
  4482. },
  4483. onChange: withBatchedUpdates((nextOriginalText) => {
  4484. updateElement(nextOriginalText, false);
  4485. if (isNonDeletedElement(element)) {
  4486. updateBoundElements(element, this.scene);
  4487. }
  4488. }),
  4489. onSubmit: withBatchedUpdates(({ viaKeyboard, nextOriginalText }) => {
  4490. const isDeleted = !nextOriginalText.trim();
  4491. if (isDeleted && !isExistingElement) {
  4492. // let's just remove the element from the scene, as it's an empty just created text element
  4493. this.scene.replaceAllElements(
  4494. this.scene
  4495. .getElementsIncludingDeleted()
  4496. .filter((x) => x.id !== element.id),
  4497. );
  4498. } else {
  4499. updateElement(nextOriginalText, isDeleted);
  4500. }
  4501. // select the created text element only if submitting via keyboard
  4502. // (when submitting via click it should act as signal to deselect)
  4503. if (!isDeleted && viaKeyboard) {
  4504. const elementIdToSelect = element.containerId
  4505. ? element.containerId
  4506. : element.id;
  4507. // needed to ensure state is updated before "finalize" action
  4508. // that's invoked on keyboard-submit as well
  4509. // TODO either move this into finalize as well, or handle all state
  4510. // updates in one place, skipping finalize action
  4511. flushSync(() => {
  4512. this.setState((prevState) => ({
  4513. selectedElementIds: makeNextSelectedElementIds(
  4514. {
  4515. ...prevState.selectedElementIds,
  4516. [elementIdToSelect]: true,
  4517. },
  4518. prevState,
  4519. ),
  4520. }));
  4521. });
  4522. }
  4523. if (isDeleted) {
  4524. fixBindingsAfterDeletion(this.scene.getNonDeletedElements(), [
  4525. element,
  4526. ]);
  4527. }
  4528. // we need to record either way, whether the text element was added or removed
  4529. // since we need to sync this delta to other clients, otherwise it would end up with inconsistencies
  4530. this.store.scheduleCapture();
  4531. flushSync(() => {
  4532. this.setState({
  4533. newElement: null,
  4534. editingTextElement: null,
  4535. });
  4536. });
  4537. if (this.state.activeTool.locked) {
  4538. setCursorForShape(this.interactiveCanvas, this.state);
  4539. }
  4540. this.focusContainer();
  4541. }),
  4542. element,
  4543. excalidrawContainer: this.excalidrawContainerRef.current,
  4544. app: this,
  4545. // when text is selected, it's hard (at least on iOS) to re-position the
  4546. // caret (i.e. deselect). There's not much use for always selecting
  4547. // the text on edit anyway (and users can select-all from contextmenu
  4548. // if needed)
  4549. autoSelect: !this.device.isTouchScreen,
  4550. });
  4551. // deselect all other elements when inserting text
  4552. this.deselectElements();
  4553. // do an initial update to re-initialize element position since we were
  4554. // modifying element's x/y for sake of editor (case: syncing to remote)
  4555. updateElement(element.originalText, false);
  4556. }
  4557. private deselectElements() {
  4558. this.setState({
  4559. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  4560. selectedGroupIds: {},
  4561. editingGroupId: null,
  4562. activeEmbeddable: null,
  4563. });
  4564. }
  4565. private getTextElementAtPosition(
  4566. x: number,
  4567. y: number,
  4568. ): NonDeleted<ExcalidrawTextElement> | null {
  4569. const element = this.getElementAtPosition(x, y, {
  4570. includeBoundTextElement: true,
  4571. });
  4572. if (element && isTextElement(element) && !element.isDeleted) {
  4573. return element;
  4574. }
  4575. return null;
  4576. }
  4577. // NOTE: Hot path for hit testing, so avoid unnecessary computations
  4578. private getElementAtPosition(
  4579. x: number,
  4580. y: number,
  4581. opts?: (
  4582. | {
  4583. includeBoundTextElement?: boolean;
  4584. includeLockedElements?: boolean;
  4585. }
  4586. | {
  4587. allHitElements: NonDeleted<ExcalidrawElement>[];
  4588. }
  4589. ) & {
  4590. preferSelected?: boolean;
  4591. },
  4592. ): NonDeleted<ExcalidrawElement> | null {
  4593. let allHitElements: NonDeleted<ExcalidrawElement>[] = [];
  4594. if (opts && "allHitElements" in opts) {
  4595. allHitElements = opts?.allHitElements || [];
  4596. } else {
  4597. allHitElements = this.getElementsAtPosition(x, y, {
  4598. includeBoundTextElement: opts?.includeBoundTextElement,
  4599. includeLockedElements: opts?.includeLockedElements,
  4600. });
  4601. }
  4602. if (allHitElements.length > 1) {
  4603. if (opts?.preferSelected) {
  4604. for (let index = allHitElements.length - 1; index > -1; index--) {
  4605. if (this.state.selectedElementIds[allHitElements[index].id]) {
  4606. return allHitElements[index];
  4607. }
  4608. }
  4609. }
  4610. const elementWithHighestZIndex =
  4611. allHitElements[allHitElements.length - 1];
  4612. // If we're hitting element with highest z-index only on its bounding box
  4613. // while also hitting other element figure, the latter should be considered.
  4614. return hitElementItself({
  4615. point: pointFrom(x, y),
  4616. element: elementWithHighestZIndex,
  4617. // when overlapping, we would like to be more precise
  4618. // this also avoids the need to update past tests
  4619. threshold: this.getElementHitThreshold(elementWithHighestZIndex) / 2,
  4620. elementsMap: this.scene.getNonDeletedElementsMap(),
  4621. frameNameBound: isFrameLikeElement(elementWithHighestZIndex)
  4622. ? this.frameNameBoundsCache.get(elementWithHighestZIndex)
  4623. : null,
  4624. })
  4625. ? elementWithHighestZIndex
  4626. : allHitElements[allHitElements.length - 2];
  4627. }
  4628. if (allHitElements.length === 1) {
  4629. return allHitElements[0];
  4630. }
  4631. return null;
  4632. }
  4633. // NOTE: Hot path for hit testing, so avoid unnecessary computations
  4634. private getElementsAtPosition(
  4635. x: number,
  4636. y: number,
  4637. opts?: {
  4638. includeBoundTextElement?: boolean;
  4639. includeLockedElements?: boolean;
  4640. },
  4641. ): NonDeleted<ExcalidrawElement>[] {
  4642. const iframeLikes: Ordered<ExcalidrawIframeElement>[] = [];
  4643. const elementsMap = this.scene.getNonDeletedElementsMap();
  4644. const elements = (
  4645. opts?.includeBoundTextElement && opts?.includeLockedElements
  4646. ? this.scene.getNonDeletedElements()
  4647. : this.scene
  4648. .getNonDeletedElements()
  4649. .filter(
  4650. (element) =>
  4651. (opts?.includeLockedElements || !element.locked) &&
  4652. (opts?.includeBoundTextElement ||
  4653. !(isTextElement(element) && element.containerId)),
  4654. )
  4655. )
  4656. .filter((el) => this.hitElement(x, y, el))
  4657. .filter((element) => {
  4658. // hitting a frame's element from outside the frame is not considered a hit
  4659. const containingFrame = getContainingFrame(element, elementsMap);
  4660. return containingFrame &&
  4661. this.state.frameRendering.enabled &&
  4662. this.state.frameRendering.clip
  4663. ? isCursorInFrame({ x, y }, containingFrame, elementsMap)
  4664. : true;
  4665. })
  4666. .filter((el) => {
  4667. // The parameter elements comes ordered from lower z-index to higher.
  4668. // We want to preserve that order on the returned array.
  4669. // Exception being embeddables which should be on top of everything else in
  4670. // terms of hit testing.
  4671. if (isIframeElement(el)) {
  4672. iframeLikes.push(el);
  4673. return false;
  4674. }
  4675. return true;
  4676. })
  4677. .concat(iframeLikes) as NonDeleted<ExcalidrawElement>[];
  4678. return elements;
  4679. }
  4680. getElementHitThreshold(element: ExcalidrawElement) {
  4681. return Math.max(
  4682. element.strokeWidth / 2 + 0.1,
  4683. // NOTE: Here be dragons. Do not go under the 0.63 multiplier unless you're
  4684. // willing to test extensively. The hit testing starts to become unreliable
  4685. // due to FP imprecision under 0.63 in high zoom levels.
  4686. 0.85 * (DEFAULT_COLLISION_THRESHOLD / this.state.zoom.value),
  4687. );
  4688. }
  4689. private hitElement(
  4690. x: number,
  4691. y: number,
  4692. element: ExcalidrawElement,
  4693. considerBoundingBox = true,
  4694. ) {
  4695. // if the element is selected, then hit test is done against its bounding box
  4696. if (
  4697. considerBoundingBox &&
  4698. this.state.selectedElementIds[element.id] &&
  4699. shouldShowBoundingBox([element], this.state)
  4700. ) {
  4701. // if hitting the bounding box, return early
  4702. // but if not, we should check for other cases as well (e.g. frame name)
  4703. if (
  4704. hitElementBoundingBox(
  4705. pointFrom(x, y),
  4706. element,
  4707. this.scene.getNonDeletedElementsMap(),
  4708. this.getElementHitThreshold(element),
  4709. )
  4710. ) {
  4711. return true;
  4712. }
  4713. }
  4714. // take bound text element into consideration for hit collision as well
  4715. const hitBoundTextOfElement = hitElementBoundText(
  4716. pointFrom(x, y),
  4717. element,
  4718. this.scene.getNonDeletedElementsMap(),
  4719. );
  4720. if (hitBoundTextOfElement) {
  4721. return true;
  4722. }
  4723. return hitElementItself({
  4724. point: pointFrom(x, y),
  4725. element,
  4726. threshold: this.getElementHitThreshold(element),
  4727. elementsMap: this.scene.getNonDeletedElementsMap(),
  4728. frameNameBound: isFrameLikeElement(element)
  4729. ? this.frameNameBoundsCache.get(element)
  4730. : null,
  4731. });
  4732. }
  4733. private getTextBindableContainerAtPosition(x: number, y: number) {
  4734. const elements = this.scene.getNonDeletedElements();
  4735. const selectedElements = this.scene.getSelectedElements(this.state);
  4736. if (selectedElements.length === 1) {
  4737. return isTextBindableContainer(selectedElements[0], false)
  4738. ? selectedElements[0]
  4739. : null;
  4740. }
  4741. let hitElement = null;
  4742. // We need to do hit testing from front (end of the array) to back (beginning of the array)
  4743. for (let index = elements.length - 1; index >= 0; --index) {
  4744. if (elements[index].isDeleted) {
  4745. continue;
  4746. }
  4747. const [x1, y1, x2, y2] = getElementAbsoluteCoords(
  4748. elements[index],
  4749. this.scene.getNonDeletedElementsMap(),
  4750. );
  4751. if (
  4752. isArrowElement(elements[index]) &&
  4753. hitElementItself({
  4754. point: pointFrom(x, y),
  4755. element: elements[index],
  4756. elementsMap: this.scene.getNonDeletedElementsMap(),
  4757. threshold: this.getElementHitThreshold(elements[index]),
  4758. })
  4759. ) {
  4760. hitElement = elements[index];
  4761. break;
  4762. } else if (x1 < x && x < x2 && y1 < y && y < y2) {
  4763. hitElement = elements[index];
  4764. break;
  4765. }
  4766. }
  4767. return isTextBindableContainer(hitElement, false) ? hitElement : null;
  4768. }
  4769. private startTextEditing = ({
  4770. sceneX,
  4771. sceneY,
  4772. insertAtParentCenter = true,
  4773. container,
  4774. autoEdit = true,
  4775. }: {
  4776. /** X position to insert text at */
  4777. sceneX: number;
  4778. /** Y position to insert text at */
  4779. sceneY: number;
  4780. /** whether to attempt to insert at element center if applicable */
  4781. insertAtParentCenter?: boolean;
  4782. container?: ExcalidrawTextContainer | null;
  4783. autoEdit?: boolean;
  4784. }) => {
  4785. let shouldBindToContainer = false;
  4786. let parentCenterPosition =
  4787. insertAtParentCenter &&
  4788. this.getTextWysiwygSnappedToCenterPosition(
  4789. sceneX,
  4790. sceneY,
  4791. this.state,
  4792. container,
  4793. );
  4794. if (container && parentCenterPosition) {
  4795. const boundTextElementToContainer = getBoundTextElement(
  4796. container,
  4797. this.scene.getNonDeletedElementsMap(),
  4798. );
  4799. if (!boundTextElementToContainer) {
  4800. shouldBindToContainer = true;
  4801. }
  4802. }
  4803. let existingTextElement: NonDeleted<ExcalidrawTextElement> | null = null;
  4804. const selectedElements = this.scene.getSelectedElements(this.state);
  4805. if (selectedElements.length === 1) {
  4806. if (isTextElement(selectedElements[0])) {
  4807. existingTextElement = selectedElements[0];
  4808. } else if (container) {
  4809. existingTextElement = getBoundTextElement(
  4810. selectedElements[0],
  4811. this.scene.getNonDeletedElementsMap(),
  4812. );
  4813. } else {
  4814. existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
  4815. }
  4816. } else {
  4817. existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
  4818. }
  4819. const fontFamily =
  4820. existingTextElement?.fontFamily || this.state.currentItemFontFamily;
  4821. const lineHeight =
  4822. existingTextElement?.lineHeight || getLineHeight(fontFamily);
  4823. const fontSize = this.state.currentItemFontSize;
  4824. if (
  4825. !existingTextElement &&
  4826. shouldBindToContainer &&
  4827. container &&
  4828. !isArrowElement(container)
  4829. ) {
  4830. const fontString = {
  4831. fontSize,
  4832. fontFamily,
  4833. };
  4834. const minWidth = getApproxMinLineWidth(
  4835. getFontString(fontString),
  4836. lineHeight,
  4837. );
  4838. const minHeight = getApproxMinLineHeight(fontSize, lineHeight);
  4839. const newHeight = Math.max(container.height, minHeight);
  4840. const newWidth = Math.max(container.width, minWidth);
  4841. this.scene.mutateElement(container, {
  4842. height: newHeight,
  4843. width: newWidth,
  4844. });
  4845. sceneX = container.x + newWidth / 2;
  4846. sceneY = container.y + newHeight / 2;
  4847. if (parentCenterPosition) {
  4848. parentCenterPosition = this.getTextWysiwygSnappedToCenterPosition(
  4849. sceneX,
  4850. sceneY,
  4851. this.state,
  4852. container,
  4853. );
  4854. }
  4855. }
  4856. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  4857. x: sceneX,
  4858. y: sceneY,
  4859. });
  4860. const element =
  4861. existingTextElement ||
  4862. newTextElement({
  4863. x: parentCenterPosition ? parentCenterPosition.elementCenterX : sceneX,
  4864. y: parentCenterPosition ? parentCenterPosition.elementCenterY : sceneY,
  4865. strokeColor: this.state.currentItemStrokeColor,
  4866. backgroundColor: this.state.currentItemBackgroundColor,
  4867. fillStyle: this.state.currentItemFillStyle,
  4868. strokeWidth: this.state.currentItemStrokeWidth,
  4869. strokeStyle: this.state.currentItemStrokeStyle,
  4870. roughness: this.state.currentItemRoughness,
  4871. opacity: this.state.currentItemOpacity,
  4872. text: "",
  4873. fontSize,
  4874. fontFamily,
  4875. textAlign: parentCenterPosition
  4876. ? "center"
  4877. : this.state.currentItemTextAlign,
  4878. verticalAlign: parentCenterPosition
  4879. ? VERTICAL_ALIGN.MIDDLE
  4880. : DEFAULT_VERTICAL_ALIGN,
  4881. containerId: shouldBindToContainer ? container?.id : undefined,
  4882. groupIds: container?.groupIds ?? [],
  4883. lineHeight,
  4884. angle: container
  4885. ? isArrowElement(container)
  4886. ? (0 as Radians)
  4887. : container.angle
  4888. : (0 as Radians),
  4889. frameId: topLayerFrame ? topLayerFrame.id : null,
  4890. });
  4891. if (!existingTextElement && shouldBindToContainer && container) {
  4892. this.scene.mutateElement(container, {
  4893. boundElements: (container.boundElements || []).concat({
  4894. type: "text",
  4895. id: element.id,
  4896. }),
  4897. });
  4898. }
  4899. this.setState({ editingTextElement: element });
  4900. if (!existingTextElement) {
  4901. if (container && shouldBindToContainer) {
  4902. const containerIndex = this.scene.getElementIndex(container.id);
  4903. this.scene.insertElementAtIndex(element, containerIndex + 1);
  4904. } else {
  4905. this.scene.insertElement(element);
  4906. }
  4907. }
  4908. if (autoEdit || existingTextElement || container) {
  4909. this.handleTextWysiwyg(element, {
  4910. isExistingElement: !!existingTextElement,
  4911. });
  4912. } else {
  4913. this.setState({
  4914. newElement: element,
  4915. multiElement: null,
  4916. });
  4917. }
  4918. };
  4919. private startImageCropping = (image: ExcalidrawImageElement) => {
  4920. this.store.scheduleCapture();
  4921. this.setState({
  4922. croppingElementId: image.id,
  4923. });
  4924. };
  4925. private finishImageCropping = () => {
  4926. if (this.state.croppingElementId) {
  4927. this.store.scheduleCapture();
  4928. this.setState({
  4929. croppingElementId: null,
  4930. });
  4931. }
  4932. };
  4933. private handleCanvasDoubleClick = (
  4934. event: React.MouseEvent<HTMLCanvasElement>,
  4935. ) => {
  4936. // case: double-clicking with arrow/line tool selected would both create
  4937. // text and enter multiElement mode
  4938. if (this.state.multiElement) {
  4939. return;
  4940. }
  4941. // we should only be able to double click when mode is selection
  4942. if (this.state.activeTool.type !== "selection") {
  4943. return;
  4944. }
  4945. const selectedElements = this.scene.getSelectedElements(this.state);
  4946. let { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  4947. event,
  4948. this.state,
  4949. );
  4950. if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
  4951. const selectedLinearElement: ExcalidrawLinearElement =
  4952. selectedElements[0];
  4953. if (
  4954. ((event[KEYS.CTRL_OR_CMD] && isSimpleArrow(selectedLinearElement)) ||
  4955. isLineElement(selectedLinearElement)) &&
  4956. (!this.state.selectedLinearElement?.isEditing ||
  4957. this.state.selectedLinearElement.elementId !==
  4958. selectedLinearElement.id)
  4959. ) {
  4960. // Use the proper action to ensure immediate history capture
  4961. this.actionManager.executeAction(actionToggleLinearEditor);
  4962. return;
  4963. } else if (
  4964. this.state.selectedLinearElement &&
  4965. isElbowArrow(selectedElements[0])
  4966. ) {
  4967. const hitCoords = LinearElementEditor.getSegmentMidpointHitCoords(
  4968. this.state.selectedLinearElement,
  4969. { x: sceneX, y: sceneY },
  4970. this.state,
  4971. this.scene.getNonDeletedElementsMap(),
  4972. );
  4973. const midPoint = hitCoords
  4974. ? LinearElementEditor.getSegmentMidPointIndex(
  4975. this.state.selectedLinearElement,
  4976. this.state,
  4977. hitCoords,
  4978. this.scene.getNonDeletedElementsMap(),
  4979. )
  4980. : -1;
  4981. if (midPoint && midPoint > -1) {
  4982. this.store.scheduleCapture();
  4983. LinearElementEditor.deleteFixedSegment(
  4984. selectedElements[0],
  4985. this.scene,
  4986. midPoint,
  4987. );
  4988. const nextCoords = LinearElementEditor.getSegmentMidpointHitCoords(
  4989. {
  4990. ...this.state.selectedLinearElement,
  4991. segmentMidPointHoveredCoords: null,
  4992. },
  4993. { x: sceneX, y: sceneY },
  4994. this.state,
  4995. this.scene.getNonDeletedElementsMap(),
  4996. );
  4997. const nextIndex = nextCoords
  4998. ? LinearElementEditor.getSegmentMidPointIndex(
  4999. this.state.selectedLinearElement,
  5000. this.state,
  5001. nextCoords,
  5002. this.scene.getNonDeletedElementsMap(),
  5003. )
  5004. : null;
  5005. this.setState({
  5006. selectedLinearElement: {
  5007. ...this.state.selectedLinearElement,
  5008. pointerDownState: {
  5009. ...this.state.selectedLinearElement.pointerDownState,
  5010. segmentMidpoint: {
  5011. index: nextIndex,
  5012. value: hitCoords,
  5013. added: false,
  5014. },
  5015. },
  5016. segmentMidPointHoveredCoords: nextCoords,
  5017. },
  5018. });
  5019. return;
  5020. }
  5021. } else if (
  5022. this.state.selectedLinearElement?.isEditing &&
  5023. this.state.selectedLinearElement.elementId ===
  5024. selectedLinearElement.id &&
  5025. isLineElement(selectedLinearElement)
  5026. ) {
  5027. return;
  5028. }
  5029. }
  5030. if (selectedElements.length === 1 && isImageElement(selectedElements[0])) {
  5031. this.startImageCropping(selectedElements[0]);
  5032. return;
  5033. }
  5034. resetCursor(this.interactiveCanvas);
  5035. const selectedGroupIds = getSelectedGroupIds(this.state);
  5036. if (selectedGroupIds.length > 0) {
  5037. const hitElement = this.getElementAtPosition(sceneX, sceneY);
  5038. const selectedGroupId =
  5039. hitElement &&
  5040. getSelectedGroupIdForElement(hitElement, this.state.selectedGroupIds);
  5041. if (selectedGroupId) {
  5042. this.store.scheduleCapture();
  5043. this.setState((prevState) => ({
  5044. ...prevState,
  5045. ...selectGroupsForSelectedElements(
  5046. {
  5047. editingGroupId: selectedGroupId,
  5048. selectedElementIds: { [hitElement!.id]: true },
  5049. },
  5050. this.scene.getNonDeletedElements(),
  5051. prevState,
  5052. this,
  5053. ),
  5054. }));
  5055. return;
  5056. }
  5057. }
  5058. resetCursor(this.interactiveCanvas);
  5059. if (!event[KEYS.CTRL_OR_CMD] && !this.state.viewModeEnabled) {
  5060. const hitElement = this.getElementAtPosition(sceneX, sceneY);
  5061. if (isIframeLikeElement(hitElement)) {
  5062. this.setState({
  5063. activeEmbeddable: { element: hitElement, state: "active" },
  5064. });
  5065. return;
  5066. }
  5067. // shouldn't edit/create text when inside line editor (often false positive)
  5068. if (!this.state.selectedLinearElement?.isEditing) {
  5069. const container = this.getTextBindableContainerAtPosition(
  5070. sceneX,
  5071. sceneY,
  5072. );
  5073. if (container) {
  5074. if (
  5075. hasBoundTextElement(container) ||
  5076. !isTransparent(container.backgroundColor) ||
  5077. hitElementItself({
  5078. point: pointFrom(sceneX, sceneY),
  5079. element: container,
  5080. elementsMap: this.scene.getNonDeletedElementsMap(),
  5081. threshold: this.getElementHitThreshold(container),
  5082. })
  5083. ) {
  5084. const midPoint = getContainerCenter(
  5085. container,
  5086. this.state,
  5087. this.scene.getNonDeletedElementsMap(),
  5088. );
  5089. sceneX = midPoint.x;
  5090. sceneY = midPoint.y;
  5091. }
  5092. }
  5093. this.startTextEditing({
  5094. sceneX,
  5095. sceneY,
  5096. insertAtParentCenter: !event.altKey,
  5097. container,
  5098. });
  5099. }
  5100. }
  5101. };
  5102. private getElementLinkAtPosition = (
  5103. scenePointer: Readonly<{ x: number; y: number }>,
  5104. hitElementMightBeLocked: NonDeletedExcalidrawElement | null,
  5105. ): ExcalidrawElement | undefined => {
  5106. if (hitElementMightBeLocked && hitElementMightBeLocked.locked) {
  5107. return undefined;
  5108. }
  5109. const elements = this.scene.getNonDeletedElements();
  5110. let hitElementIndex = -1;
  5111. for (let index = elements.length - 1; index >= 0; index--) {
  5112. const element = elements[index];
  5113. if (
  5114. hitElementMightBeLocked &&
  5115. element.id === hitElementMightBeLocked.id
  5116. ) {
  5117. hitElementIndex = index;
  5118. }
  5119. if (
  5120. element.link &&
  5121. index >= hitElementIndex &&
  5122. isPointHittingLink(
  5123. element,
  5124. this.scene.getNonDeletedElementsMap(),
  5125. this.state,
  5126. pointFrom(scenePointer.x, scenePointer.y),
  5127. this.device.editor.isMobile,
  5128. )
  5129. ) {
  5130. return element;
  5131. }
  5132. }
  5133. };
  5134. private redirectToLink = (
  5135. event: React.PointerEvent<HTMLCanvasElement>,
  5136. isTouchScreen: boolean,
  5137. ) => {
  5138. const draggedDistance = pointDistance(
  5139. pointFrom(
  5140. this.lastPointerDownEvent!.clientX,
  5141. this.lastPointerDownEvent!.clientY,
  5142. ),
  5143. pointFrom(
  5144. this.lastPointerUpEvent!.clientX,
  5145. this.lastPointerUpEvent!.clientY,
  5146. ),
  5147. );
  5148. if (!this.hitLinkElement || draggedDistance > DRAGGING_THRESHOLD) {
  5149. return;
  5150. }
  5151. const lastPointerDownCoords = viewportCoordsToSceneCoords(
  5152. this.lastPointerDownEvent!,
  5153. this.state,
  5154. );
  5155. const elementsMap = this.scene.getNonDeletedElementsMap();
  5156. const lastPointerDownHittingLinkIcon = isPointHittingLink(
  5157. this.hitLinkElement,
  5158. elementsMap,
  5159. this.state,
  5160. pointFrom(lastPointerDownCoords.x, lastPointerDownCoords.y),
  5161. this.device.editor.isMobile,
  5162. );
  5163. const lastPointerUpCoords = viewportCoordsToSceneCoords(
  5164. this.lastPointerUpEvent!,
  5165. this.state,
  5166. );
  5167. const lastPointerUpHittingLinkIcon = isPointHittingLink(
  5168. this.hitLinkElement,
  5169. elementsMap,
  5170. this.state,
  5171. pointFrom(lastPointerUpCoords.x, lastPointerUpCoords.y),
  5172. this.device.editor.isMobile,
  5173. );
  5174. if (lastPointerDownHittingLinkIcon && lastPointerUpHittingLinkIcon) {
  5175. hideHyperlinkToolip();
  5176. let url = this.hitLinkElement.link;
  5177. if (url) {
  5178. url = normalizeLink(url);
  5179. let customEvent;
  5180. if (this.props.onLinkOpen) {
  5181. customEvent = wrapEvent(EVENT.EXCALIDRAW_LINK, event.nativeEvent);
  5182. this.props.onLinkOpen(
  5183. {
  5184. ...this.hitLinkElement,
  5185. link: url,
  5186. },
  5187. customEvent,
  5188. );
  5189. }
  5190. if (!customEvent?.defaultPrevented) {
  5191. const target = isLocalLink(url) ? "_self" : "_blank";
  5192. const newWindow = window.open(undefined, target);
  5193. // https://mathiasbynens.github.io/rel-noopener/
  5194. if (newWindow) {
  5195. newWindow.opener = null;
  5196. newWindow.location = url;
  5197. }
  5198. }
  5199. }
  5200. }
  5201. };
  5202. private getTopLayerFrameAtSceneCoords = (sceneCoords: {
  5203. x: number;
  5204. y: number;
  5205. }) => {
  5206. const elementsMap = this.scene.getNonDeletedElementsMap();
  5207. const frames = this.scene
  5208. .getNonDeletedFramesLikes()
  5209. .filter((frame): frame is ExcalidrawFrameLikeElement =>
  5210. isCursorInFrame(sceneCoords, frame, elementsMap),
  5211. );
  5212. return frames.length ? frames[frames.length - 1] : null;
  5213. };
  5214. private handleCanvasPointerMove = (
  5215. event: React.PointerEvent<HTMLCanvasElement>,
  5216. ) => {
  5217. this.savePointer(event.clientX, event.clientY, this.state.cursorButton);
  5218. this.lastPointerMoveEvent = event.nativeEvent;
  5219. if (gesture.pointers.has(event.pointerId)) {
  5220. gesture.pointers.set(event.pointerId, {
  5221. x: event.clientX,
  5222. y: event.clientY,
  5223. });
  5224. }
  5225. const initialScale = gesture.initialScale;
  5226. if (
  5227. gesture.pointers.size === 2 &&
  5228. gesture.lastCenter &&
  5229. initialScale &&
  5230. gesture.initialDistance
  5231. ) {
  5232. const center = getCenter(gesture.pointers);
  5233. const deltaX = center.x - gesture.lastCenter.x;
  5234. const deltaY = center.y - gesture.lastCenter.y;
  5235. gesture.lastCenter = center;
  5236. const distance = getDistance(Array.from(gesture.pointers.values()));
  5237. const scaleFactor =
  5238. this.state.activeTool.type === "freedraw" && this.state.penMode
  5239. ? 1
  5240. : distance / gesture.initialDistance;
  5241. const nextZoom = scaleFactor
  5242. ? getNormalizedZoom(initialScale * scaleFactor)
  5243. : this.state.zoom.value;
  5244. this.setState((state) => {
  5245. const zoomState = getStateForZoom(
  5246. {
  5247. viewportX: center.x,
  5248. viewportY: center.y,
  5249. nextZoom,
  5250. },
  5251. state,
  5252. );
  5253. this.translateCanvas({
  5254. zoom: zoomState.zoom,
  5255. // 2x multiplier is just a magic number that makes this work correctly
  5256. // on touchscreen devices (note: if we get report that panning is slower/faster
  5257. // than actual movement, consider swapping with devicePixelRatio)
  5258. scrollX: zoomState.scrollX + 2 * (deltaX / nextZoom),
  5259. scrollY: zoomState.scrollY + 2 * (deltaY / nextZoom),
  5260. shouldCacheIgnoreZoom: true,
  5261. });
  5262. });
  5263. this.resetShouldCacheIgnoreZoomDebounced();
  5264. } else {
  5265. gesture.lastCenter =
  5266. gesture.initialDistance =
  5267. gesture.initialScale =
  5268. null;
  5269. }
  5270. if (
  5271. isHoldingSpace ||
  5272. isPanning ||
  5273. isDraggingScrollBar ||
  5274. isHandToolActive(this.state)
  5275. ) {
  5276. return;
  5277. }
  5278. const isPointerOverScrollBars = isOverScrollBars(
  5279. currentScrollBars,
  5280. event.clientX - this.state.offsetLeft,
  5281. event.clientY - this.state.offsetTop,
  5282. );
  5283. const isOverScrollBar = isPointerOverScrollBars.isOverEither;
  5284. if (
  5285. !this.state.newElement &&
  5286. !this.state.selectionElement &&
  5287. !this.state.selectedElementsAreBeingDragged &&
  5288. !this.state.multiElement
  5289. ) {
  5290. if (isOverScrollBar) {
  5291. resetCursor(this.interactiveCanvas);
  5292. } else {
  5293. setCursorForShape(this.interactiveCanvas, this.state);
  5294. }
  5295. }
  5296. const scenePointer = viewportCoordsToSceneCoords(event, this.state);
  5297. const { x: scenePointerX, y: scenePointerY } = scenePointer;
  5298. if (
  5299. !this.state.newElement &&
  5300. isActiveToolNonLinearSnappable(this.state.activeTool.type)
  5301. ) {
  5302. const { originOffset, snapLines } = getSnapLinesAtPointer(
  5303. this.scene.getNonDeletedElements(),
  5304. this,
  5305. {
  5306. x: scenePointerX,
  5307. y: scenePointerY,
  5308. },
  5309. event,
  5310. this.scene.getNonDeletedElementsMap(),
  5311. );
  5312. this.setState((prevState) => {
  5313. const nextSnapLines = updateStable(prevState.snapLines, snapLines);
  5314. const nextOriginOffset = prevState.originSnapOffset
  5315. ? updateStable(prevState.originSnapOffset, originOffset)
  5316. : originOffset;
  5317. if (
  5318. prevState.snapLines === nextSnapLines &&
  5319. prevState.originSnapOffset === nextOriginOffset
  5320. ) {
  5321. return null;
  5322. }
  5323. return {
  5324. snapLines: nextSnapLines,
  5325. originSnapOffset: nextOriginOffset,
  5326. };
  5327. });
  5328. } else if (
  5329. !this.state.newElement &&
  5330. !this.state.selectedElementsAreBeingDragged &&
  5331. !this.state.selectionElement
  5332. ) {
  5333. this.setState((prevState) => {
  5334. if (prevState.snapLines.length) {
  5335. return {
  5336. snapLines: [],
  5337. };
  5338. }
  5339. return null;
  5340. });
  5341. }
  5342. if (
  5343. this.state.selectedLinearElement?.isEditing &&
  5344. !this.state.selectedLinearElement.isDragging
  5345. ) {
  5346. const editingLinearElement = LinearElementEditor.handlePointerMove(
  5347. event,
  5348. scenePointerX,
  5349. scenePointerY,
  5350. this,
  5351. );
  5352. const linearElement = editingLinearElement
  5353. ? this.scene.getElement(editingLinearElement.elementId)
  5354. : null;
  5355. if (
  5356. editingLinearElement &&
  5357. editingLinearElement !== this.state.selectedLinearElement
  5358. ) {
  5359. // Since we are reading from previous state which is not possible with
  5360. // automatic batching in React 18 hence using flush sync to synchronously
  5361. // update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
  5362. flushSync(() => {
  5363. this.setState({
  5364. selectedLinearElement: editingLinearElement,
  5365. });
  5366. });
  5367. }
  5368. if (
  5369. editingLinearElement?.lastUncommittedPoint != null &&
  5370. linearElement &&
  5371. isBindingElementType(linearElement.type)
  5372. ) {
  5373. this.maybeSuggestBindingAtCursor(
  5374. scenePointer,
  5375. editingLinearElement.elbowed,
  5376. );
  5377. } else if (this.state.suggestedBindings.length) {
  5378. this.setState({ suggestedBindings: [] });
  5379. }
  5380. }
  5381. if (isBindingElementType(this.state.activeTool.type)) {
  5382. // Hovering with a selected tool or creating new linear element via click
  5383. // and point
  5384. const { newElement } = this.state;
  5385. if (isBindingElement(newElement, false)) {
  5386. this.setState({
  5387. suggestedBindings: maybeSuggestBindingsForLinearElementAtCoords(
  5388. newElement,
  5389. [scenePointer],
  5390. this.scene,
  5391. this.state.zoom,
  5392. this.state.startBoundElement,
  5393. ),
  5394. });
  5395. } else {
  5396. this.maybeSuggestBindingAtCursor(scenePointer, false);
  5397. }
  5398. }
  5399. if (this.state.multiElement) {
  5400. const { multiElement } = this.state;
  5401. const { x: rx, y: ry } = multiElement;
  5402. const { points, lastCommittedPoint } = multiElement;
  5403. const lastPoint = points[points.length - 1];
  5404. setCursorForShape(this.interactiveCanvas, this.state);
  5405. if (lastPoint === lastCommittedPoint) {
  5406. // if we haven't yet created a temp point and we're beyond commit-zone
  5407. // threshold, add a point
  5408. if (
  5409. pointDistance(
  5410. pointFrom(scenePointerX - rx, scenePointerY - ry),
  5411. lastPoint,
  5412. ) >= LINE_CONFIRM_THRESHOLD
  5413. ) {
  5414. this.scene.mutateElement(
  5415. multiElement,
  5416. {
  5417. points: [
  5418. ...points,
  5419. pointFrom<LocalPoint>(scenePointerX - rx, scenePointerY - ry),
  5420. ],
  5421. },
  5422. { informMutation: false, isDragging: false },
  5423. );
  5424. } else {
  5425. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  5426. // in this branch, we're inside the commit zone, and no uncommitted
  5427. // point exists. Thus do nothing (don't add/remove points).
  5428. }
  5429. } else if (
  5430. points.length > 2 &&
  5431. lastCommittedPoint &&
  5432. pointDistance(
  5433. pointFrom(scenePointerX - rx, scenePointerY - ry),
  5434. lastCommittedPoint,
  5435. ) < LINE_CONFIRM_THRESHOLD
  5436. ) {
  5437. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  5438. this.scene.mutateElement(
  5439. multiElement,
  5440. {
  5441. points: points.slice(0, -1),
  5442. },
  5443. { informMutation: false, isDragging: false },
  5444. );
  5445. } else {
  5446. const [gridX, gridY] = getGridPoint(
  5447. scenePointerX,
  5448. scenePointerY,
  5449. event[KEYS.CTRL_OR_CMD] || isElbowArrow(multiElement)
  5450. ? null
  5451. : this.getEffectiveGridSize(),
  5452. );
  5453. const [lastCommittedX, lastCommittedY] =
  5454. multiElement?.lastCommittedPoint ?? [0, 0];
  5455. let dxFromLastCommitted = gridX - rx - lastCommittedX;
  5456. let dyFromLastCommitted = gridY - ry - lastCommittedY;
  5457. if (shouldRotateWithDiscreteAngle(event)) {
  5458. ({ width: dxFromLastCommitted, height: dyFromLastCommitted } =
  5459. getLockedLinearCursorAlignSize(
  5460. // actual coordinate of the last committed point
  5461. lastCommittedX + rx,
  5462. lastCommittedY + ry,
  5463. // cursor-grid coordinate
  5464. gridX,
  5465. gridY,
  5466. ));
  5467. }
  5468. if (isPathALoop(points, this.state.zoom.value)) {
  5469. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  5470. }
  5471. // update last uncommitted point
  5472. this.scene.mutateElement(
  5473. multiElement,
  5474. {
  5475. points: [
  5476. ...points.slice(0, -1),
  5477. pointFrom<LocalPoint>(
  5478. lastCommittedX + dxFromLastCommitted,
  5479. lastCommittedY + dyFromLastCommitted,
  5480. ),
  5481. ],
  5482. },
  5483. {
  5484. isDragging: true,
  5485. informMutation: false,
  5486. },
  5487. );
  5488. // in this path, we're mutating multiElement to reflect
  5489. // how it will be after adding pointer position as the next point
  5490. // trigger update here so that new element canvas renders again to reflect this
  5491. this.triggerRender(false);
  5492. }
  5493. return;
  5494. }
  5495. const hasDeselectedButton = Boolean(event.buttons);
  5496. if (
  5497. hasDeselectedButton ||
  5498. (this.state.activeTool.type !== "selection" &&
  5499. this.state.activeTool.type !== "text" &&
  5500. this.state.activeTool.type !== "eraser")
  5501. ) {
  5502. return;
  5503. }
  5504. const elements = this.scene.getNonDeletedElements();
  5505. const selectedElements = this.scene.getSelectedElements(this.state);
  5506. if (
  5507. selectedElements.length === 1 &&
  5508. !isOverScrollBar &&
  5509. !this.state.selectedLinearElement?.isEditing
  5510. ) {
  5511. // for linear elements, we'd like to prioritize point dragging over edge resizing
  5512. // therefore, we update and check hovered point index first
  5513. if (this.state.selectedLinearElement) {
  5514. this.handleHoverSelectedLinearElement(
  5515. this.state.selectedLinearElement,
  5516. scenePointerX,
  5517. scenePointerY,
  5518. );
  5519. }
  5520. if (
  5521. (!this.state.selectedLinearElement ||
  5522. this.state.selectedLinearElement.hoverPointIndex === -1) &&
  5523. this.state.openDialog?.name !== "elementLinkSelector" &&
  5524. !(selectedElements.length === 1 && isElbowArrow(selectedElements[0]))
  5525. ) {
  5526. const elementWithTransformHandleType =
  5527. getElementWithTransformHandleType(
  5528. elements,
  5529. this.state,
  5530. scenePointerX,
  5531. scenePointerY,
  5532. this.state.zoom,
  5533. event.pointerType,
  5534. this.scene.getNonDeletedElementsMap(),
  5535. this.device,
  5536. );
  5537. if (
  5538. elementWithTransformHandleType &&
  5539. elementWithTransformHandleType.transformHandleType
  5540. ) {
  5541. setCursor(
  5542. this.interactiveCanvas,
  5543. getCursorForResizingElement(elementWithTransformHandleType),
  5544. );
  5545. return;
  5546. }
  5547. }
  5548. } else if (
  5549. selectedElements.length > 1 &&
  5550. !isOverScrollBar &&
  5551. this.state.openDialog?.name !== "elementLinkSelector"
  5552. ) {
  5553. const transformHandleType = getTransformHandleTypeFromCoords(
  5554. getCommonBounds(selectedElements),
  5555. scenePointerX,
  5556. scenePointerY,
  5557. this.state.zoom,
  5558. event.pointerType,
  5559. this.device,
  5560. );
  5561. if (transformHandleType) {
  5562. setCursor(
  5563. this.interactiveCanvas,
  5564. getCursorForResizingElement({
  5565. transformHandleType,
  5566. }),
  5567. );
  5568. return;
  5569. }
  5570. }
  5571. const hitElementMightBeLocked = this.getElementAtPosition(
  5572. scenePointerX,
  5573. scenePointerY,
  5574. {
  5575. preferSelected: true,
  5576. includeLockedElements: true,
  5577. },
  5578. );
  5579. let hitElement: ExcalidrawElement | null = null;
  5580. if (hitElementMightBeLocked && hitElementMightBeLocked.locked) {
  5581. hitElement = null;
  5582. } else {
  5583. hitElement = hitElementMightBeLocked;
  5584. }
  5585. this.hitLinkElement = this.getElementLinkAtPosition(
  5586. scenePointer,
  5587. hitElementMightBeLocked,
  5588. );
  5589. if (isEraserActive(this.state)) {
  5590. return;
  5591. }
  5592. if (
  5593. this.hitLinkElement &&
  5594. !this.state.selectedElementIds[this.hitLinkElement.id]
  5595. ) {
  5596. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  5597. showHyperlinkTooltip(
  5598. this.hitLinkElement,
  5599. this.state,
  5600. this.scene.getNonDeletedElementsMap(),
  5601. );
  5602. } else {
  5603. hideHyperlinkToolip();
  5604. if (
  5605. hitElement &&
  5606. (hitElement.link || isEmbeddableElement(hitElement)) &&
  5607. this.state.selectedElementIds[hitElement.id] &&
  5608. !this.state.contextMenu &&
  5609. !this.state.showHyperlinkPopup
  5610. ) {
  5611. this.setState({ showHyperlinkPopup: "info" });
  5612. } else if (this.state.activeTool.type === "text") {
  5613. setCursor(
  5614. this.interactiveCanvas,
  5615. isTextElement(hitElement) ? CURSOR_TYPE.TEXT : CURSOR_TYPE.CROSSHAIR,
  5616. );
  5617. } else if (this.state.viewModeEnabled) {
  5618. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  5619. } else if (this.state.openDialog?.name === "elementLinkSelector") {
  5620. setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
  5621. } else if (isOverScrollBar) {
  5622. setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
  5623. } else if (
  5624. // if using cmd/ctrl, we're not dragging
  5625. !event[KEYS.CTRL_OR_CMD]
  5626. ) {
  5627. if (
  5628. (hitElement ||
  5629. this.isHittingCommonBoundingBoxOfSelectedElements(
  5630. scenePointer,
  5631. selectedElements,
  5632. )) &&
  5633. !hitElement?.locked
  5634. ) {
  5635. if (
  5636. hitElement &&
  5637. isIframeLikeElement(hitElement) &&
  5638. this.isIframeLikeElementCenter(
  5639. hitElement,
  5640. event,
  5641. scenePointerX,
  5642. scenePointerY,
  5643. )
  5644. ) {
  5645. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  5646. this.setState({
  5647. activeEmbeddable: { element: hitElement, state: "hover" },
  5648. });
  5649. } else if (
  5650. !hitElement ||
  5651. // Ebow arrows can only be moved when unconnected
  5652. !isElbowArrow(hitElement) ||
  5653. !(hitElement.startBinding || hitElement.endBinding)
  5654. ) {
  5655. setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
  5656. if (this.state.activeEmbeddable?.state === "hover") {
  5657. this.setState({ activeEmbeddable: null });
  5658. }
  5659. }
  5660. }
  5661. } else {
  5662. setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
  5663. }
  5664. if (this.state.selectedLinearElement) {
  5665. this.handleHoverSelectedLinearElement(
  5666. this.state.selectedLinearElement,
  5667. scenePointerX,
  5668. scenePointerY,
  5669. );
  5670. }
  5671. }
  5672. if (this.state.openDialog?.name === "elementLinkSelector" && hitElement) {
  5673. this.setState((prevState) => {
  5674. return {
  5675. hoveredElementIds: updateStable(
  5676. prevState.hoveredElementIds,
  5677. selectGroupsForSelectedElements(
  5678. {
  5679. editingGroupId: prevState.editingGroupId,
  5680. selectedElementIds: { [hitElement!.id]: true },
  5681. },
  5682. this.scene.getNonDeletedElements(),
  5683. prevState,
  5684. this,
  5685. ).selectedElementIds,
  5686. ),
  5687. };
  5688. });
  5689. } else if (
  5690. this.state.openDialog?.name === "elementLinkSelector" &&
  5691. !hitElement
  5692. ) {
  5693. this.setState((prevState) => ({
  5694. hoveredElementIds: updateStable(prevState.hoveredElementIds, {}),
  5695. }));
  5696. }
  5697. };
  5698. private handleEraser = (
  5699. event: PointerEvent,
  5700. scenePointer: { x: number; y: number },
  5701. ) => {
  5702. const elementsToErase = this.eraserTrail.addPointToPath(
  5703. scenePointer.x,
  5704. scenePointer.y,
  5705. event.altKey,
  5706. );
  5707. this.elementsPendingErasure = new Set(elementsToErase);
  5708. this.triggerRender();
  5709. };
  5710. // set touch moving for mobile context menu
  5711. private handleTouchMove = (event: React.TouchEvent<HTMLCanvasElement>) => {
  5712. invalidateContextMenu = true;
  5713. };
  5714. handleHoverSelectedLinearElement(
  5715. linearElementEditor: LinearElementEditor,
  5716. scenePointerX: number,
  5717. scenePointerY: number,
  5718. ) {
  5719. const elementsMap = this.scene.getNonDeletedElementsMap();
  5720. const element = LinearElementEditor.getElement(
  5721. linearElementEditor.elementId,
  5722. elementsMap,
  5723. );
  5724. if (!element) {
  5725. return;
  5726. }
  5727. if (this.state.selectedLinearElement) {
  5728. let hoverPointIndex = -1;
  5729. let segmentMidPointHoveredCoords = null;
  5730. if (
  5731. hitElementItself({
  5732. point: pointFrom(scenePointerX, scenePointerY),
  5733. element,
  5734. elementsMap,
  5735. threshold: this.getElementHitThreshold(element),
  5736. })
  5737. ) {
  5738. hoverPointIndex = LinearElementEditor.getPointIndexUnderCursor(
  5739. element,
  5740. elementsMap,
  5741. this.state.zoom,
  5742. scenePointerX,
  5743. scenePointerY,
  5744. );
  5745. segmentMidPointHoveredCoords =
  5746. LinearElementEditor.getSegmentMidpointHitCoords(
  5747. linearElementEditor,
  5748. { x: scenePointerX, y: scenePointerY },
  5749. this.state,
  5750. this.scene.getNonDeletedElementsMap(),
  5751. );
  5752. const isHoveringAPointHandle = isElbowArrow(element)
  5753. ? hoverPointIndex === 0 ||
  5754. hoverPointIndex === element.points.length - 1
  5755. : hoverPointIndex >= 0;
  5756. if (isHoveringAPointHandle || segmentMidPointHoveredCoords) {
  5757. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  5758. } else if (this.hitElement(scenePointerX, scenePointerY, element)) {
  5759. if (
  5760. // Ebow arrows can only be moved when unconnected
  5761. !isElbowArrow(element) ||
  5762. !(element.startBinding || element.endBinding)
  5763. ) {
  5764. setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
  5765. }
  5766. }
  5767. } else if (this.hitElement(scenePointerX, scenePointerY, element)) {
  5768. if (
  5769. // Ebow arrows can only be moved when unconnected
  5770. !isElbowArrow(element) ||
  5771. !(element.startBinding || element.endBinding)
  5772. ) {
  5773. setCursor(this.interactiveCanvas, CURSOR_TYPE.MOVE);
  5774. }
  5775. }
  5776. if (
  5777. this.state.selectedLinearElement.hoverPointIndex !== hoverPointIndex
  5778. ) {
  5779. this.setState({
  5780. selectedLinearElement: {
  5781. ...this.state.selectedLinearElement,
  5782. hoverPointIndex,
  5783. },
  5784. });
  5785. }
  5786. if (
  5787. !LinearElementEditor.arePointsEqual(
  5788. this.state.selectedLinearElement.segmentMidPointHoveredCoords,
  5789. segmentMidPointHoveredCoords,
  5790. )
  5791. ) {
  5792. this.setState({
  5793. selectedLinearElement: {
  5794. ...this.state.selectedLinearElement,
  5795. segmentMidPointHoveredCoords,
  5796. },
  5797. });
  5798. }
  5799. } else {
  5800. setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
  5801. }
  5802. }
  5803. private handleCanvasPointerDown = (
  5804. event: React.PointerEvent<HTMLElement>,
  5805. ) => {
  5806. const target = event.target as HTMLElement;
  5807. // capture subsequent pointer events to the canvas
  5808. // this makes other elements non-interactive until pointer up
  5809. if (target.setPointerCapture) {
  5810. target.setPointerCapture(event.pointerId);
  5811. }
  5812. this.maybeCleanupAfterMissingPointerUp(event.nativeEvent);
  5813. this.maybeUnfollowRemoteUser();
  5814. if (this.state.searchMatches) {
  5815. this.setState((state) => {
  5816. return {
  5817. searchMatches: state.searchMatches && {
  5818. focusedId: null,
  5819. matches: state.searchMatches.matches.map((searchMatch) => ({
  5820. ...searchMatch,
  5821. focus: false,
  5822. })),
  5823. },
  5824. };
  5825. });
  5826. this.updateEditorAtom(searchItemInFocusAtom, null);
  5827. }
  5828. if (editorJotaiStore.get(convertElementTypePopupAtom)) {
  5829. this.updateEditorAtom(convertElementTypePopupAtom, null);
  5830. }
  5831. // since contextMenu options are potentially evaluated on each render,
  5832. // and an contextMenu action may depend on selection state, we must
  5833. // close the contextMenu before we update the selection on pointerDown
  5834. // (e.g. resetting selection)
  5835. if (this.state.contextMenu) {
  5836. this.setState({ contextMenu: null });
  5837. }
  5838. if (this.state.snapLines) {
  5839. this.setAppState({ snapLines: [] });
  5840. }
  5841. this.updateGestureOnPointerDown(event);
  5842. // if dragging element is freedraw and another pointerdown event occurs
  5843. // a second finger is on the screen
  5844. // discard the freedraw element if it is very short because it is likely
  5845. // just a spike, otherwise finalize the freedraw element when the second
  5846. // finger is lifted
  5847. if (
  5848. event.pointerType === "touch" &&
  5849. this.state.newElement &&
  5850. this.state.newElement.type === "freedraw"
  5851. ) {
  5852. const element = this.state.newElement as ExcalidrawFreeDrawElement;
  5853. this.updateScene({
  5854. ...(element.points.length < 10
  5855. ? {
  5856. elements: this.scene
  5857. .getElementsIncludingDeleted()
  5858. .filter((el) => el.id !== element.id),
  5859. }
  5860. : {}),
  5861. appState: {
  5862. newElement: null,
  5863. editingTextElement: null,
  5864. startBoundElement: null,
  5865. suggestedBindings: [],
  5866. selectedElementIds: makeNextSelectedElementIds(
  5867. Object.keys(this.state.selectedElementIds)
  5868. .filter((key) => key !== element.id)
  5869. .reduce((obj: { [id: string]: true }, key) => {
  5870. obj[key] = this.state.selectedElementIds[key];
  5871. return obj;
  5872. }, {}),
  5873. this.state,
  5874. ),
  5875. },
  5876. captureUpdate:
  5877. this.state.openDialog?.name === "elementLinkSelector"
  5878. ? CaptureUpdateAction.EVENTUALLY
  5879. : CaptureUpdateAction.NEVER,
  5880. });
  5881. return;
  5882. }
  5883. // remove any active selection when we start to interact with canvas
  5884. // (mainly, we care about removing selection outside the component which
  5885. // would prevent our copy handling otherwise)
  5886. const selection = document.getSelection();
  5887. if (selection?.anchorNode) {
  5888. selection.removeAllRanges();
  5889. }
  5890. this.maybeOpenContextMenuAfterPointerDownOnTouchDevices(event);
  5891. //fires only once, if pen is detected, penMode is enabled
  5892. //the user can disable this by toggling the penMode button
  5893. if (!this.state.penDetected && event.pointerType === "pen") {
  5894. this.setState((prevState) => {
  5895. return {
  5896. penMode: true,
  5897. penDetected: true,
  5898. };
  5899. });
  5900. }
  5901. if (
  5902. !this.device.isTouchScreen &&
  5903. ["pen", "touch"].includes(event.pointerType)
  5904. ) {
  5905. this.device = updateObject(this.device, { isTouchScreen: true });
  5906. }
  5907. if (isPanning) {
  5908. return;
  5909. }
  5910. this.lastPointerDownEvent = event;
  5911. // we must exit before we set `cursorButton` state and `savePointer`
  5912. // else it will send pointer state & laser pointer events in collab when
  5913. // panning
  5914. if (this.handleCanvasPanUsingWheelOrSpaceDrag(event)) {
  5915. return;
  5916. }
  5917. this.setState({
  5918. lastPointerDownWith: event.pointerType,
  5919. cursorButton: "down",
  5920. });
  5921. this.savePointer(event.clientX, event.clientY, "down");
  5922. if (
  5923. event.button === POINTER_BUTTON.ERASER &&
  5924. this.state.activeTool.type !== TOOL_TYPE.eraser
  5925. ) {
  5926. this.setState(
  5927. {
  5928. activeTool: updateActiveTool(this.state, {
  5929. type: TOOL_TYPE.eraser,
  5930. lastActiveToolBeforeEraser: this.state.activeTool,
  5931. }),
  5932. },
  5933. () => {
  5934. this.handleCanvasPointerDown(event);
  5935. const onPointerUp = () => {
  5936. unsubPointerUp();
  5937. unsubCleanup?.();
  5938. if (isEraserActive(this.state)) {
  5939. this.setState({
  5940. activeTool: updateActiveTool(this.state, {
  5941. ...(this.state.activeTool.lastActiveTool || {
  5942. type: TOOL_TYPE.selection,
  5943. }),
  5944. lastActiveToolBeforeEraser: null,
  5945. }),
  5946. });
  5947. }
  5948. };
  5949. const unsubPointerUp = addEventListener(
  5950. window,
  5951. EVENT.POINTER_UP,
  5952. onPointerUp,
  5953. {
  5954. once: true,
  5955. },
  5956. );
  5957. let unsubCleanup: UnsubscribeCallback | undefined;
  5958. // subscribe inside rAF lest it'd be triggered on the same pointerdown
  5959. // if we start erasing while coming from blurred document since
  5960. // we cleanup pointer events on focus
  5961. requestAnimationFrame(() => {
  5962. unsubCleanup =
  5963. this.missingPointerEventCleanupEmitter.once(onPointerUp);
  5964. });
  5965. },
  5966. );
  5967. return;
  5968. }
  5969. // only handle left mouse button or touch
  5970. if (
  5971. event.button !== POINTER_BUTTON.MAIN &&
  5972. event.button !== POINTER_BUTTON.TOUCH &&
  5973. event.button !== POINTER_BUTTON.ERASER
  5974. ) {
  5975. return;
  5976. }
  5977. // don't select while panning
  5978. if (gesture.pointers.size > 1) {
  5979. return;
  5980. }
  5981. // State for the duration of a pointer interaction, which starts with a
  5982. // pointerDown event, ends with a pointerUp event (or another pointerDown)
  5983. const pointerDownState = this.initialPointerDownState(event);
  5984. this.setState({
  5985. selectedElementsAreBeingDragged: false,
  5986. });
  5987. if (this.handleDraggingScrollBar(event, pointerDownState)) {
  5988. return;
  5989. }
  5990. this.clearSelectionIfNotUsingSelection();
  5991. this.updateBindingEnabledOnPointerMove(event);
  5992. if (this.handleSelectionOnPointerDown(event, pointerDownState)) {
  5993. return;
  5994. }
  5995. const allowOnPointerDown =
  5996. !this.state.penMode ||
  5997. event.pointerType !== "touch" ||
  5998. this.state.activeTool.type === "selection" ||
  5999. this.state.activeTool.type === "lasso" ||
  6000. this.state.activeTool.type === "text" ||
  6001. this.state.activeTool.type === "image";
  6002. if (!allowOnPointerDown) {
  6003. return;
  6004. }
  6005. if (this.state.activeTool.type === "lasso") {
  6006. this.lassoTrail.startPath(
  6007. pointerDownState.origin.x,
  6008. pointerDownState.origin.y,
  6009. event.shiftKey,
  6010. );
  6011. } else if (this.state.activeTool.type === "text") {
  6012. this.handleTextOnPointerDown(event, pointerDownState);
  6013. } else if (
  6014. this.state.activeTool.type === "arrow" ||
  6015. this.state.activeTool.type === "line"
  6016. ) {
  6017. this.handleLinearElementOnPointerDown(
  6018. event,
  6019. this.state.activeTool.type,
  6020. pointerDownState,
  6021. );
  6022. } else if (this.state.activeTool.type === "freedraw") {
  6023. this.handleFreeDrawElementOnPointerDown(
  6024. event,
  6025. this.state.activeTool.type,
  6026. pointerDownState,
  6027. );
  6028. } else if (this.state.activeTool.type === "custom") {
  6029. setCursorForShape(this.interactiveCanvas, this.state);
  6030. } else if (
  6031. this.state.activeTool.type === TOOL_TYPE.frame ||
  6032. this.state.activeTool.type === TOOL_TYPE.magicframe
  6033. ) {
  6034. this.createFrameElementOnPointerDown(
  6035. pointerDownState,
  6036. this.state.activeTool.type,
  6037. );
  6038. } else if (this.state.activeTool.type === "laser") {
  6039. this.laserTrails.startPath(
  6040. pointerDownState.lastCoords.x,
  6041. pointerDownState.lastCoords.y,
  6042. );
  6043. } else if (
  6044. this.state.activeTool.type !== "eraser" &&
  6045. this.state.activeTool.type !== "hand" &&
  6046. this.state.activeTool.type !== "image"
  6047. ) {
  6048. this.createGenericElementOnPointerDown(
  6049. this.state.activeTool.type,
  6050. pointerDownState,
  6051. );
  6052. }
  6053. this.props?.onPointerDown?.(this.state.activeTool, pointerDownState);
  6054. this.onPointerDownEmitter.trigger(
  6055. this.state.activeTool,
  6056. pointerDownState,
  6057. event,
  6058. );
  6059. if (this.state.activeTool.type === "eraser") {
  6060. this.eraserTrail.startPath(
  6061. pointerDownState.lastCoords.x,
  6062. pointerDownState.lastCoords.y,
  6063. );
  6064. }
  6065. const onPointerMove =
  6066. this.onPointerMoveFromPointerDownHandler(pointerDownState);
  6067. const onPointerUp =
  6068. this.onPointerUpFromPointerDownHandler(pointerDownState);
  6069. const onKeyDown = this.onKeyDownFromPointerDownHandler(pointerDownState);
  6070. const onKeyUp = this.onKeyUpFromPointerDownHandler(pointerDownState);
  6071. this.missingPointerEventCleanupEmitter.once((_event) =>
  6072. onPointerUp(_event || event.nativeEvent),
  6073. );
  6074. if (!this.state.viewModeEnabled || this.state.activeTool.type === "laser") {
  6075. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
  6076. window.addEventListener(EVENT.POINTER_UP, onPointerUp);
  6077. window.addEventListener(EVENT.KEYDOWN, onKeyDown);
  6078. window.addEventListener(EVENT.KEYUP, onKeyUp);
  6079. pointerDownState.eventListeners.onMove = onPointerMove;
  6080. pointerDownState.eventListeners.onUp = onPointerUp;
  6081. pointerDownState.eventListeners.onKeyUp = onKeyUp;
  6082. pointerDownState.eventListeners.onKeyDown = onKeyDown;
  6083. }
  6084. };
  6085. private handleCanvasPointerUp = (
  6086. event: React.PointerEvent<HTMLCanvasElement>,
  6087. ) => {
  6088. this.removePointer(event);
  6089. this.lastPointerUpEvent = event;
  6090. const scenePointer = viewportCoordsToSceneCoords(
  6091. { clientX: event.clientX, clientY: event.clientY },
  6092. this.state,
  6093. );
  6094. const clicklength =
  6095. event.timeStamp - (this.lastPointerDownEvent?.timeStamp ?? 0);
  6096. if (this.device.editor.isMobile && clicklength < 300) {
  6097. const hitElement = this.getElementAtPosition(
  6098. scenePointer.x,
  6099. scenePointer.y,
  6100. );
  6101. if (
  6102. isIframeLikeElement(hitElement) &&
  6103. this.isIframeLikeElementCenter(
  6104. hitElement,
  6105. event,
  6106. scenePointer.x,
  6107. scenePointer.y,
  6108. )
  6109. ) {
  6110. this.handleEmbeddableCenterClick(hitElement);
  6111. return;
  6112. }
  6113. }
  6114. if (this.device.isTouchScreen) {
  6115. const hitElement = this.getElementAtPosition(
  6116. scenePointer.x,
  6117. scenePointer.y,
  6118. {
  6119. includeLockedElements: true,
  6120. },
  6121. );
  6122. this.hitLinkElement = this.getElementLinkAtPosition(
  6123. scenePointer,
  6124. hitElement,
  6125. );
  6126. }
  6127. if (
  6128. this.hitLinkElement &&
  6129. !this.state.selectedElementIds[this.hitLinkElement.id]
  6130. ) {
  6131. if (
  6132. clicklength < 300 &&
  6133. isIframeLikeElement(this.hitLinkElement) &&
  6134. !isPointHittingLinkIcon(
  6135. this.hitLinkElement,
  6136. this.scene.getNonDeletedElementsMap(),
  6137. this.state,
  6138. pointFrom(scenePointer.x, scenePointer.y),
  6139. )
  6140. ) {
  6141. this.handleEmbeddableCenterClick(this.hitLinkElement);
  6142. } else {
  6143. this.redirectToLink(event, this.device.isTouchScreen);
  6144. }
  6145. } else if (this.state.viewModeEnabled) {
  6146. this.setState({
  6147. activeEmbeddable: null,
  6148. selectedElementIds: {},
  6149. });
  6150. }
  6151. };
  6152. private maybeOpenContextMenuAfterPointerDownOnTouchDevices = (
  6153. event: React.PointerEvent<HTMLElement>,
  6154. ): void => {
  6155. // deal with opening context menu on touch devices
  6156. if (event.pointerType === "touch") {
  6157. invalidateContextMenu = false;
  6158. if (touchTimeout) {
  6159. // If there's already a touchTimeout, this means that there's another
  6160. // touch down and we are doing another touch, so we shouldn't open the
  6161. // context menu.
  6162. invalidateContextMenu = true;
  6163. } else {
  6164. // open the context menu with the first touch's clientX and clientY
  6165. // if the touch is not moving
  6166. touchTimeout = window.setTimeout(() => {
  6167. touchTimeout = 0;
  6168. if (!invalidateContextMenu) {
  6169. this.handleCanvasContextMenu(event);
  6170. }
  6171. }, TOUCH_CTX_MENU_TIMEOUT);
  6172. }
  6173. }
  6174. };
  6175. private resetContextMenuTimer = () => {
  6176. clearTimeout(touchTimeout);
  6177. touchTimeout = 0;
  6178. invalidateContextMenu = false;
  6179. };
  6180. /**
  6181. * pointerup may not fire in certian cases (user tabs away...), so in order
  6182. * to properly cleanup pointerdown state, we need to fire any hanging
  6183. * pointerup handlers manually
  6184. */
  6185. private maybeCleanupAfterMissingPointerUp = (event: PointerEvent | null) => {
  6186. lastPointerUp?.();
  6187. this.missingPointerEventCleanupEmitter.trigger(event).clear();
  6188. };
  6189. // Returns whether the event is a panning
  6190. public handleCanvasPanUsingWheelOrSpaceDrag = (
  6191. event: React.PointerEvent<HTMLElement> | MouseEvent,
  6192. ): boolean => {
  6193. if (
  6194. !(
  6195. gesture.pointers.size <= 1 &&
  6196. (event.button === POINTER_BUTTON.WHEEL ||
  6197. (event.button === POINTER_BUTTON.MAIN && isHoldingSpace) ||
  6198. isHandToolActive(this.state) ||
  6199. this.state.viewModeEnabled)
  6200. )
  6201. ) {
  6202. return false;
  6203. }
  6204. isPanning = true;
  6205. // due to event.preventDefault below, container wouldn't get focus
  6206. // automatically
  6207. this.focusContainer();
  6208. // preventing defualt while text editing messes with cursor/focus
  6209. if (!this.state.editingTextElement) {
  6210. // necessary to prevent browser from scrolling the page if excalidraw
  6211. // not full-page #4489
  6212. //
  6213. // as such, the above is broken when panning canvas while in wysiwyg
  6214. event.preventDefault();
  6215. }
  6216. let nextPastePrevented = false;
  6217. const isLinux =
  6218. typeof window === undefined
  6219. ? false
  6220. : /Linux/.test(window.navigator.platform);
  6221. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRABBING);
  6222. let { clientX: lastX, clientY: lastY } = event;
  6223. const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
  6224. const deltaX = lastX - event.clientX;
  6225. const deltaY = lastY - event.clientY;
  6226. lastX = event.clientX;
  6227. lastY = event.clientY;
  6228. /*
  6229. * Prevent paste event if we move while middle clicking on Linux.
  6230. * See issue #1383.
  6231. */
  6232. if (
  6233. isLinux &&
  6234. !nextPastePrevented &&
  6235. (Math.abs(deltaX) > 1 || Math.abs(deltaY) > 1)
  6236. ) {
  6237. nextPastePrevented = true;
  6238. /* Prevent the next paste event */
  6239. const preventNextPaste = (event: ClipboardEvent) => {
  6240. document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
  6241. event.stopPropagation();
  6242. };
  6243. /*
  6244. * Reenable next paste in case of disabled middle click paste for
  6245. * any reason:
  6246. * - right click paste
  6247. * - empty clipboard
  6248. */
  6249. const enableNextPaste = () => {
  6250. setTimeout(() => {
  6251. document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
  6252. window.removeEventListener(EVENT.POINTER_UP, enableNextPaste);
  6253. }, 100);
  6254. };
  6255. document.body.addEventListener(EVENT.PASTE, preventNextPaste);
  6256. window.addEventListener(EVENT.POINTER_UP, enableNextPaste);
  6257. }
  6258. this.translateCanvas({
  6259. scrollX: this.state.scrollX - deltaX / this.state.zoom.value,
  6260. scrollY: this.state.scrollY - deltaY / this.state.zoom.value,
  6261. });
  6262. });
  6263. const teardown = withBatchedUpdates(
  6264. (lastPointerUp = () => {
  6265. lastPointerUp = null;
  6266. isPanning = false;
  6267. if (!isHoldingSpace) {
  6268. if (this.state.viewModeEnabled) {
  6269. setCursor(this.interactiveCanvas, CURSOR_TYPE.GRAB);
  6270. } else {
  6271. setCursorForShape(this.interactiveCanvas, this.state);
  6272. }
  6273. }
  6274. this.setState({
  6275. cursorButton: "up",
  6276. });
  6277. this.savePointer(event.clientX, event.clientY, "up");
  6278. window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
  6279. window.removeEventListener(EVENT.POINTER_UP, teardown);
  6280. window.removeEventListener(EVENT.BLUR, teardown);
  6281. onPointerMove.flush();
  6282. }),
  6283. );
  6284. window.addEventListener(EVENT.BLUR, teardown);
  6285. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove, {
  6286. passive: true,
  6287. });
  6288. window.addEventListener(EVENT.POINTER_UP, teardown);
  6289. return true;
  6290. };
  6291. private updateGestureOnPointerDown(
  6292. event: React.PointerEvent<HTMLElement>,
  6293. ): void {
  6294. gesture.pointers.set(event.pointerId, {
  6295. x: event.clientX,
  6296. y: event.clientY,
  6297. });
  6298. if (gesture.pointers.size === 2) {
  6299. gesture.lastCenter = getCenter(gesture.pointers);
  6300. gesture.initialScale = this.state.zoom.value;
  6301. gesture.initialDistance = getDistance(
  6302. Array.from(gesture.pointers.values()),
  6303. );
  6304. }
  6305. }
  6306. private initialPointerDownState(
  6307. event: React.PointerEvent<HTMLElement>,
  6308. ): PointerDownState {
  6309. const origin = viewportCoordsToSceneCoords(event, this.state);
  6310. const selectedElements = this.scene.getSelectedElements(this.state);
  6311. const [minX, minY, maxX, maxY] = getCommonBounds(selectedElements);
  6312. const isElbowArrowOnly = selectedElements.findIndex(isElbowArrow) === 0;
  6313. return {
  6314. origin,
  6315. withCmdOrCtrl: event[KEYS.CTRL_OR_CMD],
  6316. originInGrid: tupleToCoors(
  6317. getGridPoint(
  6318. origin.x,
  6319. origin.y,
  6320. event[KEYS.CTRL_OR_CMD] || isElbowArrowOnly
  6321. ? null
  6322. : this.getEffectiveGridSize(),
  6323. ),
  6324. ),
  6325. scrollbars: isOverScrollBars(
  6326. currentScrollBars,
  6327. event.clientX - this.state.offsetLeft,
  6328. event.clientY - this.state.offsetTop,
  6329. ),
  6330. // we need to duplicate because we'll be updating this state
  6331. lastCoords: { ...origin },
  6332. originalElements: this.scene
  6333. .getNonDeletedElements()
  6334. .reduce((acc, element) => {
  6335. acc.set(element.id, deepCopyElement(element));
  6336. return acc;
  6337. }, new Map() as PointerDownState["originalElements"]),
  6338. resize: {
  6339. handleType: false,
  6340. isResizing: false,
  6341. offset: { x: 0, y: 0 },
  6342. arrowDirection: "origin",
  6343. center: { x: (maxX + minX) / 2, y: (maxY + minY) / 2 },
  6344. },
  6345. hit: {
  6346. element: null,
  6347. allHitElements: [],
  6348. wasAddedToSelection: false,
  6349. hasBeenDuplicated: false,
  6350. hasHitCommonBoundingBoxOfSelectedElements:
  6351. this.isHittingCommonBoundingBoxOfSelectedElements(
  6352. origin,
  6353. selectedElements,
  6354. ),
  6355. },
  6356. drag: {
  6357. hasOccurred: false,
  6358. offset: null,
  6359. origin: { ...origin },
  6360. },
  6361. eventListeners: {
  6362. onMove: null,
  6363. onUp: null,
  6364. onKeyUp: null,
  6365. onKeyDown: null,
  6366. },
  6367. boxSelection: {
  6368. hasOccurred: false,
  6369. },
  6370. };
  6371. }
  6372. // Returns whether the event is a dragging a scrollbar
  6373. private handleDraggingScrollBar(
  6374. event: React.PointerEvent<HTMLElement>,
  6375. pointerDownState: PointerDownState,
  6376. ): boolean {
  6377. if (
  6378. !(pointerDownState.scrollbars.isOverEither && !this.state.multiElement)
  6379. ) {
  6380. return false;
  6381. }
  6382. isDraggingScrollBar = true;
  6383. pointerDownState.lastCoords.x = event.clientX;
  6384. pointerDownState.lastCoords.y = event.clientY;
  6385. const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
  6386. const target = event.target;
  6387. if (!(target instanceof HTMLElement)) {
  6388. return;
  6389. }
  6390. this.handlePointerMoveOverScrollbars(event, pointerDownState);
  6391. });
  6392. const onPointerUp = withBatchedUpdates(() => {
  6393. lastPointerUp = null;
  6394. isDraggingScrollBar = false;
  6395. setCursorForShape(this.interactiveCanvas, this.state);
  6396. this.setState({
  6397. cursorButton: "up",
  6398. });
  6399. this.savePointer(event.clientX, event.clientY, "up");
  6400. window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
  6401. window.removeEventListener(EVENT.POINTER_UP, onPointerUp);
  6402. onPointerMove.flush();
  6403. });
  6404. lastPointerUp = onPointerUp;
  6405. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
  6406. window.addEventListener(EVENT.POINTER_UP, onPointerUp);
  6407. return true;
  6408. }
  6409. private clearSelectionIfNotUsingSelection = (): void => {
  6410. if (
  6411. this.state.activeTool.type !== "selection" &&
  6412. this.state.activeTool.type !== "lasso"
  6413. ) {
  6414. this.setState({
  6415. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  6416. selectedGroupIds: {},
  6417. editingGroupId: null,
  6418. activeEmbeddable: null,
  6419. });
  6420. }
  6421. };
  6422. /**
  6423. * @returns whether the pointer event has been completely handled
  6424. */
  6425. private handleSelectionOnPointerDown = (
  6426. event: React.PointerEvent<HTMLElement>,
  6427. pointerDownState: PointerDownState,
  6428. ): boolean => {
  6429. if (this.state.activeTool.type === "selection") {
  6430. const elements = this.scene.getNonDeletedElements();
  6431. const elementsMap = this.scene.getNonDeletedElementsMap();
  6432. const selectedElements = this.scene.getSelectedElements(this.state);
  6433. if (
  6434. selectedElements.length === 1 &&
  6435. !this.state.selectedLinearElement?.isEditing &&
  6436. !isElbowArrow(selectedElements[0]) &&
  6437. !(
  6438. this.state.selectedLinearElement &&
  6439. this.state.selectedLinearElement.hoverPointIndex !== -1
  6440. )
  6441. ) {
  6442. const elementWithTransformHandleType =
  6443. getElementWithTransformHandleType(
  6444. elements,
  6445. this.state,
  6446. pointerDownState.origin.x,
  6447. pointerDownState.origin.y,
  6448. this.state.zoom,
  6449. event.pointerType,
  6450. this.scene.getNonDeletedElementsMap(),
  6451. this.device,
  6452. );
  6453. if (elementWithTransformHandleType != null) {
  6454. if (
  6455. elementWithTransformHandleType.transformHandleType === "rotation"
  6456. ) {
  6457. this.setState({
  6458. resizingElement: elementWithTransformHandleType.element,
  6459. });
  6460. pointerDownState.resize.handleType =
  6461. elementWithTransformHandleType.transformHandleType;
  6462. } else if (this.state.croppingElementId) {
  6463. pointerDownState.resize.handleType =
  6464. elementWithTransformHandleType.transformHandleType;
  6465. } else {
  6466. this.setState({
  6467. resizingElement: elementWithTransformHandleType.element,
  6468. });
  6469. pointerDownState.resize.handleType =
  6470. elementWithTransformHandleType.transformHandleType;
  6471. }
  6472. }
  6473. } else if (selectedElements.length > 1) {
  6474. pointerDownState.resize.handleType = getTransformHandleTypeFromCoords(
  6475. getCommonBounds(selectedElements),
  6476. pointerDownState.origin.x,
  6477. pointerDownState.origin.y,
  6478. this.state.zoom,
  6479. event.pointerType,
  6480. this.device,
  6481. );
  6482. }
  6483. if (pointerDownState.resize.handleType) {
  6484. pointerDownState.resize.isResizing = true;
  6485. pointerDownState.resize.offset = tupleToCoors(
  6486. getResizeOffsetXY(
  6487. pointerDownState.resize.handleType,
  6488. selectedElements,
  6489. elementsMap,
  6490. pointerDownState.origin.x,
  6491. pointerDownState.origin.y,
  6492. ),
  6493. );
  6494. if (
  6495. selectedElements.length === 1 &&
  6496. isLinearElement(selectedElements[0]) &&
  6497. selectedElements[0].points.length === 2
  6498. ) {
  6499. pointerDownState.resize.arrowDirection = getResizeArrowDirection(
  6500. pointerDownState.resize.handleType,
  6501. selectedElements[0],
  6502. );
  6503. }
  6504. } else {
  6505. if (this.state.selectedLinearElement) {
  6506. const linearElementEditor = this.state.selectedLinearElement;
  6507. const ret = LinearElementEditor.handlePointerDown(
  6508. event,
  6509. this,
  6510. this.store,
  6511. pointerDownState.origin,
  6512. linearElementEditor,
  6513. this.scene,
  6514. );
  6515. if (ret.hitElement) {
  6516. pointerDownState.hit.element = ret.hitElement;
  6517. }
  6518. if (ret.linearElementEditor) {
  6519. this.setState({ selectedLinearElement: ret.linearElementEditor });
  6520. }
  6521. if (ret.didAddPoint) {
  6522. return true;
  6523. }
  6524. }
  6525. const allHitElements = this.getElementsAtPosition(
  6526. pointerDownState.origin.x,
  6527. pointerDownState.origin.y,
  6528. {
  6529. includeLockedElements: true,
  6530. },
  6531. );
  6532. const unlockedHitElements = allHitElements.filter((e) => !e.locked);
  6533. // Cannot set preferSelected in getElementAtPosition as we do in pointer move; consider:
  6534. // A & B: both unlocked, A selected, B on top, A & B overlaps in some way
  6535. // we want to select B when clicking on the overlapping area
  6536. const hitElementMightBeLocked = this.getElementAtPosition(
  6537. pointerDownState.origin.x,
  6538. pointerDownState.origin.y,
  6539. {
  6540. allHitElements,
  6541. },
  6542. );
  6543. if (
  6544. !hitElementMightBeLocked ||
  6545. hitElementMightBeLocked.id !== this.state.activeLockedId
  6546. ) {
  6547. this.setState({
  6548. activeLockedId: null,
  6549. });
  6550. }
  6551. if (
  6552. hitElementMightBeLocked &&
  6553. hitElementMightBeLocked.locked &&
  6554. !unlockedHitElements.some(
  6555. (el) => this.state.selectedElementIds[el.id],
  6556. )
  6557. ) {
  6558. pointerDownState.hit.element = null;
  6559. } else {
  6560. // hitElement may already be set above, so check first
  6561. pointerDownState.hit.element =
  6562. pointerDownState.hit.element ??
  6563. this.getElementAtPosition(
  6564. pointerDownState.origin.x,
  6565. pointerDownState.origin.y,
  6566. );
  6567. }
  6568. this.hitLinkElement = this.getElementLinkAtPosition(
  6569. pointerDownState.origin,
  6570. hitElementMightBeLocked,
  6571. );
  6572. if (this.hitLinkElement) {
  6573. return true;
  6574. }
  6575. if (
  6576. this.state.croppingElementId &&
  6577. pointerDownState.hit.element?.id !== this.state.croppingElementId
  6578. ) {
  6579. this.finishImageCropping();
  6580. }
  6581. if (pointerDownState.hit.element) {
  6582. // Early return if pointer is hitting link icon
  6583. const hitLinkElement = this.getElementLinkAtPosition(
  6584. {
  6585. x: pointerDownState.origin.x,
  6586. y: pointerDownState.origin.y,
  6587. },
  6588. pointerDownState.hit.element,
  6589. );
  6590. if (hitLinkElement) {
  6591. return false;
  6592. }
  6593. }
  6594. // For overlapped elements one position may hit
  6595. // multiple elements
  6596. pointerDownState.hit.allHitElements = unlockedHitElements;
  6597. const hitElement = pointerDownState.hit.element;
  6598. const someHitElementIsSelected =
  6599. pointerDownState.hit.allHitElements.some((element) =>
  6600. this.isASelectedElement(element),
  6601. );
  6602. if (
  6603. (hitElement === null || !someHitElementIsSelected) &&
  6604. !event.shiftKey &&
  6605. !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
  6606. ) {
  6607. this.clearSelection(hitElement);
  6608. }
  6609. if (this.state.selectedLinearElement?.isEditing) {
  6610. this.setState({
  6611. selectedElementIds: makeNextSelectedElementIds(
  6612. {
  6613. [this.state.selectedLinearElement.elementId]: true,
  6614. },
  6615. this.state,
  6616. ),
  6617. });
  6618. // If we click on something
  6619. } else if (hitElement != null) {
  6620. // == deep selection ==
  6621. // on CMD/CTRL, drill down to hit element regardless of groups etc.
  6622. if (event[KEYS.CTRL_OR_CMD]) {
  6623. if (event.altKey) {
  6624. // ctrl + alt means we're lasso selecting
  6625. return false;
  6626. }
  6627. if (!this.state.selectedElementIds[hitElement.id]) {
  6628. pointerDownState.hit.wasAddedToSelection = true;
  6629. }
  6630. this.setState((prevState) => ({
  6631. ...editGroupForSelectedElement(prevState, hitElement),
  6632. previousSelectedElementIds: this.state.selectedElementIds,
  6633. }));
  6634. // mark as not completely handled so as to allow dragging etc.
  6635. return false;
  6636. }
  6637. // deselect if item is selected
  6638. // if shift is not clicked, this will always return true
  6639. // otherwise, it will trigger selection based on current
  6640. // state of the box
  6641. if (!this.state.selectedElementIds[hitElement.id]) {
  6642. // if we are currently editing a group, exiting editing mode and deselect the group.
  6643. if (
  6644. this.state.editingGroupId &&
  6645. !isElementInGroup(hitElement, this.state.editingGroupId)
  6646. ) {
  6647. this.setState({
  6648. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  6649. selectedGroupIds: {},
  6650. editingGroupId: null,
  6651. activeEmbeddable: null,
  6652. });
  6653. }
  6654. // Add hit element to selection. At this point if we're not holding
  6655. // SHIFT the previously selected element(s) were deselected above
  6656. // (make sure you use setState updater to use latest state)
  6657. // With shift-selection, we want to make sure that frames and their containing
  6658. // elements are not selected at the same time.
  6659. if (
  6660. !someHitElementIsSelected &&
  6661. !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
  6662. ) {
  6663. this.setState((prevState) => {
  6664. let nextSelectedElementIds: { [id: string]: true } = {
  6665. ...prevState.selectedElementIds,
  6666. [hitElement.id]: true,
  6667. };
  6668. const previouslySelectedElements: ExcalidrawElement[] = [];
  6669. Object.keys(prevState.selectedElementIds).forEach((id) => {
  6670. const element = this.scene.getElement(id);
  6671. element && previouslySelectedElements.push(element);
  6672. });
  6673. // if hitElement is frame-like, deselect all of its elements
  6674. // if they are selected
  6675. if (isFrameLikeElement(hitElement)) {
  6676. getFrameChildren(
  6677. previouslySelectedElements,
  6678. hitElement.id,
  6679. ).forEach((element) => {
  6680. delete nextSelectedElementIds[element.id];
  6681. });
  6682. } else if (hitElement.frameId) {
  6683. // if hitElement is in a frame and its frame has been selected
  6684. // disable selection for the given element
  6685. if (nextSelectedElementIds[hitElement.frameId]) {
  6686. delete nextSelectedElementIds[hitElement.id];
  6687. }
  6688. } else {
  6689. // hitElement is neither a frame nor an element in a frame
  6690. // but since hitElement could be in a group with some frames
  6691. // this means selecting hitElement will have the frames selected as well
  6692. // because we want to keep the invariant:
  6693. // - frames and their elements are not selected at the same time
  6694. // we deselect elements in those frames that were previously selected
  6695. const groupIds = hitElement.groupIds;
  6696. const framesInGroups = new Set(
  6697. groupIds
  6698. .flatMap((gid) =>
  6699. getElementsInGroup(
  6700. this.scene.getNonDeletedElements(),
  6701. gid,
  6702. ),
  6703. )
  6704. .filter((element) => isFrameLikeElement(element))
  6705. .map((frame) => frame.id),
  6706. );
  6707. if (framesInGroups.size > 0) {
  6708. previouslySelectedElements.forEach((element) => {
  6709. if (
  6710. element.frameId &&
  6711. framesInGroups.has(element.frameId)
  6712. ) {
  6713. // deselect element and groups containing the element
  6714. delete nextSelectedElementIds[element.id];
  6715. element.groupIds
  6716. .flatMap((gid) =>
  6717. getElementsInGroup(
  6718. this.scene.getNonDeletedElements(),
  6719. gid,
  6720. ),
  6721. )
  6722. .forEach((element) => {
  6723. delete nextSelectedElementIds[element.id];
  6724. });
  6725. }
  6726. });
  6727. }
  6728. }
  6729. // Finally, in shape selection mode, we'd like to
  6730. // keep only one shape or group selected at a time.
  6731. // This means, if the hitElement is a different shape or group
  6732. // than the previously selected ones, we deselect the previous ones
  6733. // and select the hitElement
  6734. if (prevState.openDialog?.name === "elementLinkSelector") {
  6735. if (
  6736. !hitElement.groupIds.some(
  6737. (gid) => prevState.selectedGroupIds[gid],
  6738. )
  6739. ) {
  6740. nextSelectedElementIds = {
  6741. [hitElement.id]: true,
  6742. };
  6743. }
  6744. }
  6745. return {
  6746. ...selectGroupsForSelectedElements(
  6747. {
  6748. editingGroupId: prevState.editingGroupId,
  6749. selectedElementIds: nextSelectedElementIds,
  6750. },
  6751. this.scene.getNonDeletedElements(),
  6752. prevState,
  6753. this,
  6754. ),
  6755. showHyperlinkPopup:
  6756. hitElement.link || isEmbeddableElement(hitElement)
  6757. ? "info"
  6758. : false,
  6759. };
  6760. });
  6761. pointerDownState.hit.wasAddedToSelection = true;
  6762. }
  6763. }
  6764. }
  6765. this.setState({
  6766. previousSelectedElementIds: this.state.selectedElementIds,
  6767. });
  6768. }
  6769. }
  6770. return false;
  6771. };
  6772. private isASelectedElement(hitElement: ExcalidrawElement | null): boolean {
  6773. return hitElement != null && this.state.selectedElementIds[hitElement.id];
  6774. }
  6775. private isHittingCommonBoundingBoxOfSelectedElements(
  6776. point: Readonly<{ x: number; y: number }>,
  6777. selectedElements: readonly ExcalidrawElement[],
  6778. ): boolean {
  6779. if (selectedElements.length < 2) {
  6780. return false;
  6781. }
  6782. // How many pixels off the shape boundary we still consider a hit
  6783. const threshold = Math.max(
  6784. DEFAULT_COLLISION_THRESHOLD / this.state.zoom.value,
  6785. 1,
  6786. );
  6787. const [x1, y1, x2, y2] = getCommonBounds(selectedElements);
  6788. return (
  6789. point.x > x1 - threshold &&
  6790. point.x < x2 + threshold &&
  6791. point.y > y1 - threshold &&
  6792. point.y < y2 + threshold
  6793. );
  6794. }
  6795. private handleTextOnPointerDown = (
  6796. event: React.PointerEvent<HTMLElement>,
  6797. pointerDownState: PointerDownState,
  6798. ): void => {
  6799. // if we're currently still editing text, clicking outside
  6800. // should only finalize it, not create another (irrespective
  6801. // of state.activeTool.locked)
  6802. if (this.state.editingTextElement) {
  6803. return;
  6804. }
  6805. let sceneX = pointerDownState.origin.x;
  6806. let sceneY = pointerDownState.origin.y;
  6807. const element = this.getElementAtPosition(sceneX, sceneY, {
  6808. includeBoundTextElement: true,
  6809. });
  6810. // FIXME
  6811. let container = this.getTextBindableContainerAtPosition(sceneX, sceneY);
  6812. if (hasBoundTextElement(element)) {
  6813. container = element as ExcalidrawTextContainer;
  6814. sceneX = element.x + element.width / 2;
  6815. sceneY = element.y + element.height / 2;
  6816. }
  6817. this.startTextEditing({
  6818. sceneX,
  6819. sceneY,
  6820. insertAtParentCenter: !event.altKey,
  6821. container,
  6822. autoEdit: false,
  6823. });
  6824. resetCursor(this.interactiveCanvas);
  6825. if (!this.state.activeTool.locked) {
  6826. this.setState({
  6827. activeTool: updateActiveTool(this.state, { type: "selection" }),
  6828. });
  6829. }
  6830. };
  6831. private handleFreeDrawElementOnPointerDown = (
  6832. event: React.PointerEvent<HTMLElement>,
  6833. elementType: ExcalidrawFreeDrawElement["type"],
  6834. pointerDownState: PointerDownState,
  6835. ) => {
  6836. // Begin a mark capture. This does not have to update state yet.
  6837. const [gridX, gridY] = getGridPoint(
  6838. pointerDownState.origin.x,
  6839. pointerDownState.origin.y,
  6840. null,
  6841. );
  6842. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  6843. x: gridX,
  6844. y: gridY,
  6845. });
  6846. const simulatePressure = event.pressure === 0.5;
  6847. const element = newFreeDrawElement({
  6848. type: elementType,
  6849. x: gridX,
  6850. y: gridY,
  6851. strokeColor: this.state.currentItemStrokeColor,
  6852. backgroundColor: this.state.currentItemBackgroundColor,
  6853. fillStyle: this.state.currentItemFillStyle,
  6854. strokeWidth: this.state.currentItemStrokeWidth,
  6855. strokeStyle: this.state.currentItemStrokeStyle,
  6856. roughness: this.state.currentItemRoughness,
  6857. opacity: this.state.currentItemOpacity,
  6858. roundness: null,
  6859. simulatePressure,
  6860. locked: false,
  6861. frameId: topLayerFrame ? topLayerFrame.id : null,
  6862. points: [pointFrom<LocalPoint>(0, 0)],
  6863. pressures: simulatePressure ? [] : [event.pressure],
  6864. });
  6865. this.scene.insertElement(element);
  6866. this.setState((prevState) => {
  6867. const nextSelectedElementIds = {
  6868. ...prevState.selectedElementIds,
  6869. };
  6870. delete nextSelectedElementIds[element.id];
  6871. return {
  6872. selectedElementIds: makeNextSelectedElementIds(
  6873. nextSelectedElementIds,
  6874. prevState,
  6875. ),
  6876. };
  6877. });
  6878. const boundElement = getHoveredElementForBinding(
  6879. pointerDownState.origin,
  6880. this.scene.getNonDeletedElements(),
  6881. this.scene.getNonDeletedElementsMap(),
  6882. this.state.zoom,
  6883. );
  6884. this.setState({
  6885. newElement: element,
  6886. startBoundElement: boundElement,
  6887. suggestedBindings: [],
  6888. });
  6889. };
  6890. public insertIframeElement = ({
  6891. sceneX,
  6892. sceneY,
  6893. width,
  6894. height,
  6895. }: {
  6896. sceneX: number;
  6897. sceneY: number;
  6898. width: number;
  6899. height: number;
  6900. }) => {
  6901. const [gridX, gridY] = getGridPoint(
  6902. sceneX,
  6903. sceneY,
  6904. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  6905. ? null
  6906. : this.getEffectiveGridSize(),
  6907. );
  6908. const element = newIframeElement({
  6909. type: "iframe",
  6910. x: gridX,
  6911. y: gridY,
  6912. strokeColor: "transparent",
  6913. backgroundColor: "transparent",
  6914. fillStyle: this.state.currentItemFillStyle,
  6915. strokeWidth: this.state.currentItemStrokeWidth,
  6916. strokeStyle: this.state.currentItemStrokeStyle,
  6917. roughness: this.state.currentItemRoughness,
  6918. roundness: this.getCurrentItemRoundness("iframe"),
  6919. opacity: this.state.currentItemOpacity,
  6920. locked: false,
  6921. width,
  6922. height,
  6923. });
  6924. this.scene.insertElement(element);
  6925. return element;
  6926. };
  6927. //create rectangle element with youtube top left on nearest grid point width / hight 640/360
  6928. public insertEmbeddableElement = ({
  6929. sceneX,
  6930. sceneY,
  6931. link,
  6932. }: {
  6933. sceneX: number;
  6934. sceneY: number;
  6935. link: string;
  6936. }) => {
  6937. const [gridX, gridY] = getGridPoint(
  6938. sceneX,
  6939. sceneY,
  6940. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  6941. ? null
  6942. : this.getEffectiveGridSize(),
  6943. );
  6944. const embedLink = getEmbedLink(link);
  6945. if (!embedLink) {
  6946. return;
  6947. }
  6948. if (embedLink.error instanceof URIError) {
  6949. this.setToast({
  6950. message: t("toast.unrecognizedLinkFormat"),
  6951. closable: true,
  6952. });
  6953. }
  6954. const element = newEmbeddableElement({
  6955. type: "embeddable",
  6956. x: gridX,
  6957. y: gridY,
  6958. strokeColor: "transparent",
  6959. backgroundColor: "transparent",
  6960. fillStyle: this.state.currentItemFillStyle,
  6961. strokeWidth: this.state.currentItemStrokeWidth,
  6962. strokeStyle: this.state.currentItemStrokeStyle,
  6963. roughness: this.state.currentItemRoughness,
  6964. roundness: this.getCurrentItemRoundness("embeddable"),
  6965. opacity: this.state.currentItemOpacity,
  6966. locked: false,
  6967. width: embedLink.intrinsicSize.w,
  6968. height: embedLink.intrinsicSize.h,
  6969. link,
  6970. });
  6971. this.scene.insertElement(element);
  6972. return element;
  6973. };
  6974. private createImageElement = async ({
  6975. sceneX,
  6976. sceneY,
  6977. addToFrameUnderCursor = true,
  6978. imageFile,
  6979. }: {
  6980. sceneX: number;
  6981. sceneY: number;
  6982. addToFrameUnderCursor?: boolean;
  6983. imageFile: File;
  6984. }) => {
  6985. const [gridX, gridY] = getGridPoint(
  6986. sceneX,
  6987. sceneY,
  6988. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  6989. ? null
  6990. : this.getEffectiveGridSize(),
  6991. );
  6992. const topLayerFrame = addToFrameUnderCursor
  6993. ? this.getTopLayerFrameAtSceneCoords({
  6994. x: gridX,
  6995. y: gridY,
  6996. })
  6997. : null;
  6998. const placeholderSize = 100 / this.state.zoom.value;
  6999. const placeholderImageElement = newImageElement({
  7000. type: "image",
  7001. strokeColor: this.state.currentItemStrokeColor,
  7002. backgroundColor: this.state.currentItemBackgroundColor,
  7003. fillStyle: this.state.currentItemFillStyle,
  7004. strokeWidth: this.state.currentItemStrokeWidth,
  7005. strokeStyle: this.state.currentItemStrokeStyle,
  7006. roughness: this.state.currentItemRoughness,
  7007. roundness: null,
  7008. opacity: this.state.currentItemOpacity,
  7009. locked: false,
  7010. frameId: topLayerFrame ? topLayerFrame.id : null,
  7011. x: gridX - placeholderSize / 2,
  7012. y: gridY - placeholderSize / 2,
  7013. width: placeholderSize,
  7014. height: placeholderSize,
  7015. });
  7016. const initializedImageElement = await this.insertImageElement(
  7017. placeholderImageElement,
  7018. imageFile,
  7019. );
  7020. return initializedImageElement;
  7021. };
  7022. private handleLinearElementOnPointerDown = (
  7023. event: React.PointerEvent<HTMLElement>,
  7024. elementType: ExcalidrawLinearElement["type"],
  7025. pointerDownState: PointerDownState,
  7026. ): void => {
  7027. if (this.state.multiElement) {
  7028. const { multiElement } = this.state;
  7029. // finalize if completing a loop
  7030. if (
  7031. multiElement.type === "line" &&
  7032. isPathALoop(multiElement.points, this.state.zoom.value)
  7033. ) {
  7034. this.scene.mutateElement(multiElement, {
  7035. lastCommittedPoint:
  7036. multiElement.points[multiElement.points.length - 1],
  7037. });
  7038. this.actionManager.executeAction(actionFinalize);
  7039. return;
  7040. }
  7041. // Elbow arrows cannot be created by putting down points
  7042. // only the start and end points can be defined
  7043. if (isElbowArrow(multiElement) && multiElement.points.length > 1) {
  7044. this.scene.mutateElement(multiElement, {
  7045. lastCommittedPoint:
  7046. multiElement.points[multiElement.points.length - 1],
  7047. });
  7048. this.actionManager.executeAction(actionFinalize);
  7049. return;
  7050. }
  7051. const { x: rx, y: ry, lastCommittedPoint } = multiElement;
  7052. // clicking inside commit zone → finalize arrow
  7053. if (
  7054. multiElement.points.length > 1 &&
  7055. lastCommittedPoint &&
  7056. pointDistance(
  7057. pointFrom(
  7058. pointerDownState.origin.x - rx,
  7059. pointerDownState.origin.y - ry,
  7060. ),
  7061. lastCommittedPoint,
  7062. ) < LINE_CONFIRM_THRESHOLD
  7063. ) {
  7064. this.actionManager.executeAction(actionFinalize);
  7065. return;
  7066. }
  7067. this.setState((prevState) => ({
  7068. selectedElementIds: makeNextSelectedElementIds(
  7069. {
  7070. ...prevState.selectedElementIds,
  7071. [multiElement.id]: true,
  7072. },
  7073. prevState,
  7074. ),
  7075. }));
  7076. // clicking outside commit zone → update reference for last committed
  7077. // point
  7078. this.scene.mutateElement(multiElement, {
  7079. lastCommittedPoint: multiElement.points[multiElement.points.length - 1],
  7080. });
  7081. setCursor(this.interactiveCanvas, CURSOR_TYPE.POINTER);
  7082. } else {
  7083. const [gridX, gridY] = getGridPoint(
  7084. pointerDownState.origin.x,
  7085. pointerDownState.origin.y,
  7086. event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
  7087. );
  7088. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  7089. x: gridX,
  7090. y: gridY,
  7091. });
  7092. /* If arrow is pre-arrowheads, it will have undefined for both start and end arrowheads.
  7093. If so, we want it to be null for start and "arrow" for end. If the linear item is not
  7094. an arrow, we want it to be null for both. Otherwise, we want it to use the
  7095. values from appState. */
  7096. const { currentItemStartArrowhead, currentItemEndArrowhead } = this.state;
  7097. const [startArrowhead, endArrowhead] =
  7098. elementType === "arrow"
  7099. ? [currentItemStartArrowhead, currentItemEndArrowhead]
  7100. : [null, null];
  7101. const element =
  7102. elementType === "arrow"
  7103. ? newArrowElement({
  7104. type: elementType,
  7105. x: gridX,
  7106. y: gridY,
  7107. strokeColor: this.state.currentItemStrokeColor,
  7108. backgroundColor: this.state.currentItemBackgroundColor,
  7109. fillStyle: this.state.currentItemFillStyle,
  7110. strokeWidth: this.state.currentItemStrokeWidth,
  7111. strokeStyle: this.state.currentItemStrokeStyle,
  7112. roughness: this.state.currentItemRoughness,
  7113. opacity: this.state.currentItemOpacity,
  7114. roundness:
  7115. this.state.currentItemArrowType === ARROW_TYPE.round
  7116. ? { type: ROUNDNESS.PROPORTIONAL_RADIUS }
  7117. : // note, roundness doesn't have any effect for elbow arrows,
  7118. // but it's best to set it to null as well
  7119. null,
  7120. startArrowhead,
  7121. endArrowhead,
  7122. locked: false,
  7123. frameId: topLayerFrame ? topLayerFrame.id : null,
  7124. elbowed: this.state.currentItemArrowType === ARROW_TYPE.elbow,
  7125. fixedSegments:
  7126. this.state.currentItemArrowType === ARROW_TYPE.elbow
  7127. ? []
  7128. : null,
  7129. })
  7130. : newLinearElement({
  7131. type: elementType,
  7132. x: gridX,
  7133. y: gridY,
  7134. strokeColor: this.state.currentItemStrokeColor,
  7135. backgroundColor: this.state.currentItemBackgroundColor,
  7136. fillStyle: this.state.currentItemFillStyle,
  7137. strokeWidth: this.state.currentItemStrokeWidth,
  7138. strokeStyle: this.state.currentItemStrokeStyle,
  7139. roughness: this.state.currentItemRoughness,
  7140. opacity: this.state.currentItemOpacity,
  7141. roundness:
  7142. this.state.currentItemRoundness === "round"
  7143. ? { type: ROUNDNESS.PROPORTIONAL_RADIUS }
  7144. : null,
  7145. locked: false,
  7146. frameId: topLayerFrame ? topLayerFrame.id : null,
  7147. });
  7148. this.setState((prevState) => {
  7149. const nextSelectedElementIds = {
  7150. ...prevState.selectedElementIds,
  7151. };
  7152. delete nextSelectedElementIds[element.id];
  7153. return {
  7154. selectedElementIds: makeNextSelectedElementIds(
  7155. nextSelectedElementIds,
  7156. prevState,
  7157. ),
  7158. };
  7159. });
  7160. this.scene.mutateElement(element, {
  7161. points: [...element.points, pointFrom<LocalPoint>(0, 0)],
  7162. });
  7163. const boundElement = getHoveredElementForBinding(
  7164. pointerDownState.origin,
  7165. this.scene.getNonDeletedElements(),
  7166. this.scene.getNonDeletedElementsMap(),
  7167. this.state.zoom,
  7168. isElbowArrow(element),
  7169. isElbowArrow(element),
  7170. );
  7171. this.scene.insertElement(element);
  7172. this.setState({
  7173. newElement: element,
  7174. startBoundElement: boundElement,
  7175. suggestedBindings: [],
  7176. });
  7177. }
  7178. };
  7179. private getCurrentItemRoundness(
  7180. elementType:
  7181. | "selection"
  7182. | "rectangle"
  7183. | "diamond"
  7184. | "ellipse"
  7185. | "iframe"
  7186. | "embeddable",
  7187. ) {
  7188. return this.state.currentItemRoundness === "round"
  7189. ? {
  7190. type: isUsingAdaptiveRadius(elementType)
  7191. ? ROUNDNESS.ADAPTIVE_RADIUS
  7192. : ROUNDNESS.PROPORTIONAL_RADIUS,
  7193. }
  7194. : null;
  7195. }
  7196. private createGenericElementOnPointerDown = (
  7197. elementType: ExcalidrawGenericElement["type"] | "embeddable",
  7198. pointerDownState: PointerDownState,
  7199. ): void => {
  7200. const [gridX, gridY] = getGridPoint(
  7201. pointerDownState.origin.x,
  7202. pointerDownState.origin.y,
  7203. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  7204. ? null
  7205. : this.getEffectiveGridSize(),
  7206. );
  7207. const topLayerFrame = this.getTopLayerFrameAtSceneCoords({
  7208. x: gridX,
  7209. y: gridY,
  7210. });
  7211. const baseElementAttributes = {
  7212. x: gridX,
  7213. y: gridY,
  7214. strokeColor: this.state.currentItemStrokeColor,
  7215. backgroundColor: this.state.currentItemBackgroundColor,
  7216. fillStyle: this.state.currentItemFillStyle,
  7217. strokeWidth: this.state.currentItemStrokeWidth,
  7218. strokeStyle: this.state.currentItemStrokeStyle,
  7219. roughness: this.state.currentItemRoughness,
  7220. opacity: this.state.currentItemOpacity,
  7221. roundness: this.getCurrentItemRoundness(elementType),
  7222. locked: false,
  7223. frameId: topLayerFrame ? topLayerFrame.id : null,
  7224. } as const;
  7225. let element;
  7226. if (elementType === "embeddable") {
  7227. element = newEmbeddableElement({
  7228. type: "embeddable",
  7229. ...baseElementAttributes,
  7230. });
  7231. } else {
  7232. element = newElement({
  7233. type: elementType,
  7234. ...baseElementAttributes,
  7235. });
  7236. }
  7237. if (element.type === "selection") {
  7238. this.setState({
  7239. selectionElement: element,
  7240. });
  7241. } else {
  7242. this.scene.insertElement(element);
  7243. this.setState({
  7244. multiElement: null,
  7245. newElement: element,
  7246. });
  7247. }
  7248. };
  7249. private createFrameElementOnPointerDown = (
  7250. pointerDownState: PointerDownState,
  7251. type: Extract<ToolType, "frame" | "magicframe">,
  7252. ): void => {
  7253. const [gridX, gridY] = getGridPoint(
  7254. pointerDownState.origin.x,
  7255. pointerDownState.origin.y,
  7256. this.lastPointerDownEvent?.[KEYS.CTRL_OR_CMD]
  7257. ? null
  7258. : this.getEffectiveGridSize(),
  7259. );
  7260. const constructorOpts = {
  7261. x: gridX,
  7262. y: gridY,
  7263. opacity: this.state.currentItemOpacity,
  7264. locked: false,
  7265. ...FRAME_STYLE,
  7266. } as const;
  7267. const frame =
  7268. type === TOOL_TYPE.magicframe
  7269. ? newMagicFrameElement(constructorOpts)
  7270. : newFrameElement(constructorOpts);
  7271. this.scene.insertElement(frame);
  7272. this.setState({
  7273. multiElement: null,
  7274. newElement: frame,
  7275. });
  7276. };
  7277. private maybeCacheReferenceSnapPoints(
  7278. event: KeyboardModifiersObject,
  7279. selectedElements: ExcalidrawElement[],
  7280. recomputeAnyways: boolean = false,
  7281. ) {
  7282. if (
  7283. isSnappingEnabled({
  7284. event,
  7285. app: this,
  7286. selectedElements,
  7287. }) &&
  7288. (recomputeAnyways || !SnapCache.getReferenceSnapPoints())
  7289. ) {
  7290. SnapCache.setReferenceSnapPoints(
  7291. getReferenceSnapPoints(
  7292. this.scene.getNonDeletedElements(),
  7293. selectedElements,
  7294. this.state,
  7295. this.scene.getNonDeletedElementsMap(),
  7296. ),
  7297. );
  7298. }
  7299. }
  7300. private maybeCacheVisibleGaps(
  7301. event: KeyboardModifiersObject,
  7302. selectedElements: ExcalidrawElement[],
  7303. recomputeAnyways: boolean = false,
  7304. ) {
  7305. if (
  7306. isSnappingEnabled({
  7307. event,
  7308. app: this,
  7309. selectedElements,
  7310. }) &&
  7311. (recomputeAnyways || !SnapCache.getVisibleGaps())
  7312. ) {
  7313. SnapCache.setVisibleGaps(
  7314. getVisibleGaps(
  7315. this.scene.getNonDeletedElements(),
  7316. selectedElements,
  7317. this.state,
  7318. this.scene.getNonDeletedElementsMap(),
  7319. ),
  7320. );
  7321. }
  7322. }
  7323. private onKeyDownFromPointerDownHandler(
  7324. pointerDownState: PointerDownState,
  7325. ): (event: KeyboardEvent) => void {
  7326. return withBatchedUpdates((event: KeyboardEvent) => {
  7327. if (this.maybeHandleResize(pointerDownState, event)) {
  7328. return;
  7329. }
  7330. this.maybeDragNewGenericElement(pointerDownState, event);
  7331. });
  7332. }
  7333. private onKeyUpFromPointerDownHandler(
  7334. pointerDownState: PointerDownState,
  7335. ): (event: KeyboardEvent) => void {
  7336. return withBatchedUpdates((event: KeyboardEvent) => {
  7337. // Prevents focus from escaping excalidraw tab
  7338. event.key === KEYS.ALT && event.preventDefault();
  7339. if (this.maybeHandleResize(pointerDownState, event)) {
  7340. return;
  7341. }
  7342. this.maybeDragNewGenericElement(pointerDownState, event);
  7343. });
  7344. }
  7345. private onPointerMoveFromPointerDownHandler(
  7346. pointerDownState: PointerDownState,
  7347. ) {
  7348. return withBatchedUpdatesThrottled((event: PointerEvent) => {
  7349. if (this.state.openDialog?.name === "elementLinkSelector") {
  7350. return;
  7351. }
  7352. const pointerCoords = viewportCoordsToSceneCoords(event, this.state);
  7353. if (this.state.activeLockedId) {
  7354. this.setState({
  7355. activeLockedId: null,
  7356. });
  7357. }
  7358. if (
  7359. this.state.selectedLinearElement &&
  7360. this.state.selectedLinearElement.elbowed &&
  7361. this.state.selectedLinearElement.pointerDownState.segmentMidpoint.index
  7362. ) {
  7363. const [gridX, gridY] = getGridPoint(
  7364. pointerCoords.x,
  7365. pointerCoords.y,
  7366. event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
  7367. );
  7368. let index =
  7369. this.state.selectedLinearElement.pointerDownState.segmentMidpoint
  7370. .index;
  7371. if (index < 0) {
  7372. const nextCoords = LinearElementEditor.getSegmentMidpointHitCoords(
  7373. {
  7374. ...this.state.selectedLinearElement,
  7375. segmentMidPointHoveredCoords: null,
  7376. },
  7377. { x: gridX, y: gridY },
  7378. this.state,
  7379. this.scene.getNonDeletedElementsMap(),
  7380. );
  7381. index = nextCoords
  7382. ? LinearElementEditor.getSegmentMidPointIndex(
  7383. this.state.selectedLinearElement,
  7384. this.state,
  7385. nextCoords,
  7386. this.scene.getNonDeletedElementsMap(),
  7387. )
  7388. : -1;
  7389. }
  7390. const ret = LinearElementEditor.moveFixedSegment(
  7391. this.state.selectedLinearElement,
  7392. index,
  7393. gridX,
  7394. gridY,
  7395. this.scene,
  7396. );
  7397. this.setState({
  7398. selectedLinearElement: {
  7399. ...this.state.selectedLinearElement,
  7400. segmentMidPointHoveredCoords: ret.segmentMidPointHoveredCoords,
  7401. pointerDownState: ret.pointerDownState,
  7402. },
  7403. });
  7404. return;
  7405. }
  7406. const lastPointerCoords =
  7407. this.lastPointerMoveCoords ?? pointerDownState.origin;
  7408. this.lastPointerMoveCoords = pointerCoords;
  7409. // We need to initialize dragOffsetXY only after we've updated
  7410. // `state.selectedElementIds` on pointerDown. Doing it here in pointerMove
  7411. // event handler should hopefully ensure we're already working with
  7412. // the updated state.
  7413. if (pointerDownState.drag.offset === null) {
  7414. pointerDownState.drag.offset = tupleToCoors(
  7415. getDragOffsetXY(
  7416. this.scene.getSelectedElements(this.state),
  7417. pointerDownState.origin.x,
  7418. pointerDownState.origin.y,
  7419. ),
  7420. );
  7421. }
  7422. const target = event.target;
  7423. if (!(target instanceof HTMLElement)) {
  7424. return;
  7425. }
  7426. if (this.handlePointerMoveOverScrollbars(event, pointerDownState)) {
  7427. return;
  7428. }
  7429. if (isEraserActive(this.state)) {
  7430. this.handleEraser(event, pointerCoords);
  7431. return;
  7432. }
  7433. if (this.state.activeTool.type === "laser") {
  7434. this.laserTrails.addPointToPath(pointerCoords.x, pointerCoords.y);
  7435. }
  7436. const [gridX, gridY] = getGridPoint(
  7437. pointerCoords.x,
  7438. pointerCoords.y,
  7439. event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
  7440. );
  7441. // for arrows/lines, don't start dragging until a given threshold
  7442. // to ensure we don't create a 2-point arrow by mistake when
  7443. // user clicks mouse in a way that it moves a tiny bit (thus
  7444. // triggering pointermove)
  7445. if (
  7446. !pointerDownState.drag.hasOccurred &&
  7447. (this.state.activeTool.type === "arrow" ||
  7448. this.state.activeTool.type === "line")
  7449. ) {
  7450. if (
  7451. pointDistance(
  7452. pointFrom(pointerCoords.x, pointerCoords.y),
  7453. pointFrom(pointerDownState.origin.x, pointerDownState.origin.y),
  7454. ) *
  7455. this.state.zoom.value <
  7456. MINIMUM_ARROW_SIZE
  7457. ) {
  7458. return;
  7459. }
  7460. }
  7461. if (pointerDownState.resize.isResizing) {
  7462. pointerDownState.lastCoords.x = pointerCoords.x;
  7463. pointerDownState.lastCoords.y = pointerCoords.y;
  7464. if (this.maybeHandleCrop(pointerDownState, event)) {
  7465. return true;
  7466. }
  7467. if (this.maybeHandleResize(pointerDownState, event)) {
  7468. return true;
  7469. }
  7470. }
  7471. const elementsMap = this.scene.getNonDeletedElementsMap();
  7472. if (this.state.selectedLinearElement) {
  7473. const linearElementEditor = this.state.selectedLinearElement;
  7474. if (
  7475. LinearElementEditor.shouldAddMidpoint(
  7476. this.state.selectedLinearElement,
  7477. pointerCoords,
  7478. this.state,
  7479. elementsMap,
  7480. )
  7481. ) {
  7482. const ret = LinearElementEditor.addMidpoint(
  7483. this.state.selectedLinearElement,
  7484. pointerCoords,
  7485. this,
  7486. !event[KEYS.CTRL_OR_CMD],
  7487. this.scene,
  7488. );
  7489. if (!ret) {
  7490. return;
  7491. }
  7492. // Since we are reading from previous state which is not possible with
  7493. // automatic batching in React 18 hence using flush sync to synchronously
  7494. // update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
  7495. flushSync(() => {
  7496. if (this.state.selectedLinearElement) {
  7497. this.setState({
  7498. selectedLinearElement: {
  7499. ...this.state.selectedLinearElement,
  7500. pointerDownState: ret.pointerDownState,
  7501. selectedPointsIndices: ret.selectedPointsIndices,
  7502. segmentMidPointHoveredCoords: null,
  7503. },
  7504. });
  7505. }
  7506. });
  7507. return;
  7508. } else if (
  7509. linearElementEditor.pointerDownState.segmentMidpoint.value !== null &&
  7510. !linearElementEditor.pointerDownState.segmentMidpoint.added
  7511. ) {
  7512. return;
  7513. }
  7514. const newState = LinearElementEditor.handlePointDragging(
  7515. event,
  7516. this,
  7517. pointerCoords.x,
  7518. pointerCoords.y,
  7519. linearElementEditor,
  7520. );
  7521. if (newState) {
  7522. pointerDownState.lastCoords.x = pointerCoords.x;
  7523. pointerDownState.lastCoords.y = pointerCoords.y;
  7524. pointerDownState.drag.hasOccurred = true;
  7525. this.setState(newState);
  7526. return;
  7527. }
  7528. }
  7529. const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(
  7530. (element) => this.isASelectedElement(element),
  7531. );
  7532. const isSelectingPointsInLineEditor =
  7533. this.state.selectedLinearElement?.isEditing &&
  7534. event.shiftKey &&
  7535. this.state.selectedLinearElement.elementId ===
  7536. pointerDownState.hit.element?.id;
  7537. if (
  7538. (hasHitASelectedElement ||
  7539. pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements) &&
  7540. !isSelectingPointsInLineEditor &&
  7541. this.state.activeTool.type !== "lasso"
  7542. ) {
  7543. const selectedElements = this.scene.getSelectedElements(this.state);
  7544. if (selectedElements.every((element) => element.locked)) {
  7545. return;
  7546. }
  7547. const selectedElementsHasAFrame = selectedElements.find((e) =>
  7548. isFrameLikeElement(e),
  7549. );
  7550. const topLayerFrame = this.getTopLayerFrameAtSceneCoords(pointerCoords);
  7551. const frameToHighlight =
  7552. topLayerFrame && !selectedElementsHasAFrame ? topLayerFrame : null;
  7553. // Only update the state if there is a difference
  7554. if (this.state.frameToHighlight !== frameToHighlight) {
  7555. flushSync(() => {
  7556. this.setState({ frameToHighlight });
  7557. });
  7558. }
  7559. // Marking that click was used for dragging to check
  7560. // if elements should be deselected on pointerup
  7561. pointerDownState.drag.hasOccurred = true;
  7562. // prevent dragging even if we're no longer holding cmd/ctrl otherwise
  7563. // it would have weird results (stuff jumping all over the screen)
  7564. // Checking for editingTextElement to avoid jump while editing on mobile #6503
  7565. if (
  7566. selectedElements.length > 0 &&
  7567. !pointerDownState.withCmdOrCtrl &&
  7568. !this.state.editingTextElement &&
  7569. this.state.activeEmbeddable?.state !== "active"
  7570. ) {
  7571. const dragOffset = {
  7572. x: pointerCoords.x - pointerDownState.drag.origin.x,
  7573. y: pointerCoords.y - pointerDownState.drag.origin.y,
  7574. };
  7575. const originalElements = [
  7576. ...pointerDownState.originalElements.values(),
  7577. ];
  7578. // We only drag in one direction if shift is pressed
  7579. const lockDirection = event.shiftKey;
  7580. if (lockDirection) {
  7581. const distanceX = Math.abs(dragOffset.x);
  7582. const distanceY = Math.abs(dragOffset.y);
  7583. const lockX = lockDirection && distanceX < distanceY;
  7584. const lockY = lockDirection && distanceX > distanceY;
  7585. if (lockX) {
  7586. dragOffset.x = 0;
  7587. }
  7588. if (lockY) {
  7589. dragOffset.y = 0;
  7590. }
  7591. }
  7592. // #region move crop region
  7593. if (this.state.croppingElementId) {
  7594. const croppingElement = this.scene
  7595. .getNonDeletedElementsMap()
  7596. .get(this.state.croppingElementId);
  7597. if (
  7598. croppingElement &&
  7599. isImageElement(croppingElement) &&
  7600. croppingElement.crop !== null &&
  7601. pointerDownState.hit.element === croppingElement
  7602. ) {
  7603. const crop = croppingElement.crop;
  7604. const image =
  7605. isInitializedImageElement(croppingElement) &&
  7606. this.imageCache.get(croppingElement.fileId)?.image;
  7607. if (image && !(image instanceof Promise)) {
  7608. const instantDragOffset = vectorScale(
  7609. vector(
  7610. pointerCoords.x - lastPointerCoords.x,
  7611. pointerCoords.y - lastPointerCoords.y,
  7612. ),
  7613. Math.max(this.state.zoom.value, 2),
  7614. );
  7615. const [x1, y1, x2, y2, cx, cy] = getElementAbsoluteCoords(
  7616. croppingElement,
  7617. elementsMap,
  7618. );
  7619. const topLeft = vectorFromPoint(
  7620. pointRotateRads(
  7621. pointFrom(x1, y1),
  7622. pointFrom(cx, cy),
  7623. croppingElement.angle,
  7624. ),
  7625. );
  7626. const topRight = vectorFromPoint(
  7627. pointRotateRads(
  7628. pointFrom(x2, y1),
  7629. pointFrom(cx, cy),
  7630. croppingElement.angle,
  7631. ),
  7632. );
  7633. const bottomLeft = vectorFromPoint(
  7634. pointRotateRads(
  7635. pointFrom(x1, y2),
  7636. pointFrom(cx, cy),
  7637. croppingElement.angle,
  7638. ),
  7639. );
  7640. const topEdge = vectorNormalize(
  7641. vectorSubtract(topRight, topLeft),
  7642. );
  7643. const leftEdge = vectorNormalize(
  7644. vectorSubtract(bottomLeft, topLeft),
  7645. );
  7646. // project instantDrafOffset onto leftEdge and topEdge to decompose
  7647. const offsetVector = vector(
  7648. vectorDot(instantDragOffset, topEdge),
  7649. vectorDot(instantDragOffset, leftEdge),
  7650. );
  7651. const nextCrop = {
  7652. ...crop,
  7653. x: clamp(
  7654. crop.x -
  7655. offsetVector[0] * Math.sign(croppingElement.scale[0]),
  7656. 0,
  7657. image.naturalWidth - crop.width,
  7658. ),
  7659. y: clamp(
  7660. crop.y -
  7661. offsetVector[1] * Math.sign(croppingElement.scale[1]),
  7662. 0,
  7663. image.naturalHeight - crop.height,
  7664. ),
  7665. };
  7666. this.scene.mutateElement(croppingElement, {
  7667. crop: nextCrop,
  7668. });
  7669. return;
  7670. }
  7671. }
  7672. }
  7673. // Snap cache *must* be synchronously popuplated before initial drag,
  7674. // otherwise the first drag even will not snap, causing a jump before
  7675. // it snaps to its position if previously snapped already.
  7676. this.maybeCacheVisibleGaps(event, selectedElements);
  7677. this.maybeCacheReferenceSnapPoints(event, selectedElements);
  7678. const { snapOffset, snapLines } = snapDraggedElements(
  7679. originalElements,
  7680. dragOffset,
  7681. this,
  7682. event,
  7683. this.scene.getNonDeletedElementsMap(),
  7684. );
  7685. this.setState({ snapLines });
  7686. // when we're editing the name of a frame, we want the user to be
  7687. // able to select and interact with the text input
  7688. if (!this.state.editingFrame) {
  7689. dragSelectedElements(
  7690. pointerDownState,
  7691. selectedElements,
  7692. dragOffset,
  7693. this.scene,
  7694. snapOffset,
  7695. event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
  7696. );
  7697. }
  7698. this.setState({
  7699. selectedElementsAreBeingDragged: true,
  7700. // element is being dragged and selectionElement that was created on pointer down
  7701. // should be removed
  7702. selectionElement: null,
  7703. });
  7704. if (
  7705. selectedElements.length !== 1 ||
  7706. !isElbowArrow(selectedElements[0])
  7707. ) {
  7708. this.setState({
  7709. suggestedBindings: getSuggestedBindingsForArrows(
  7710. selectedElements,
  7711. this.scene.getNonDeletedElementsMap(),
  7712. this.state.zoom,
  7713. ),
  7714. });
  7715. }
  7716. // We duplicate the selected element if alt is pressed on pointer move
  7717. if (event.altKey && !pointerDownState.hit.hasBeenDuplicated) {
  7718. // Move the currently selected elements to the top of the z index stack, and
  7719. // put the duplicates where the selected elements used to be.
  7720. // (the origin point where the dragging started)
  7721. pointerDownState.hit.hasBeenDuplicated = true;
  7722. const elements = this.scene.getElementsIncludingDeleted();
  7723. const hitElement = pointerDownState.hit.element;
  7724. const selectedElements = this.scene.getSelectedElements({
  7725. selectedElementIds: this.state.selectedElementIds,
  7726. includeBoundTextElement: true,
  7727. includeElementsInFrames: true,
  7728. });
  7729. if (
  7730. hitElement &&
  7731. // hit element may not end up being selected
  7732. // if we're alt-dragging a common bounding box
  7733. // over the hit element
  7734. pointerDownState.hit.wasAddedToSelection &&
  7735. !selectedElements.find((el) => el.id === hitElement.id)
  7736. ) {
  7737. selectedElements.push(hitElement);
  7738. }
  7739. const idsOfElementsToDuplicate = new Map(
  7740. selectedElements.map((el) => [el.id, el]),
  7741. );
  7742. const {
  7743. duplicatedElements,
  7744. duplicateElementsMap,
  7745. elementsWithDuplicates,
  7746. origIdToDuplicateId,
  7747. } = duplicateElements({
  7748. type: "in-place",
  7749. elements,
  7750. appState: this.state,
  7751. randomizeSeed: true,
  7752. idsOfElementsToDuplicate,
  7753. overrides: ({ duplicateElement, origElement }) => {
  7754. return {
  7755. // reset to the original element's frameId (unless we've
  7756. // duplicated alongside a frame in which case we need to
  7757. // keep the duplicate frame's id) so that the element
  7758. // frame membership is refreshed on pointerup
  7759. // NOTE this is a hacky solution and should be done
  7760. // differently
  7761. frameId: duplicateElement.frameId ?? origElement.frameId,
  7762. seed: randomInteger(),
  7763. };
  7764. },
  7765. });
  7766. duplicatedElements.forEach((element) => {
  7767. pointerDownState.originalElements.set(
  7768. element.id,
  7769. deepCopyElement(element),
  7770. );
  7771. });
  7772. const mappedClonedElements = elementsWithDuplicates.map((el) => {
  7773. if (idsOfElementsToDuplicate.has(el.id)) {
  7774. const origEl = pointerDownState.originalElements.get(el.id);
  7775. if (origEl) {
  7776. return newElementWith(el, {
  7777. x: origEl.x,
  7778. y: origEl.y,
  7779. });
  7780. }
  7781. }
  7782. return el;
  7783. });
  7784. const mappedNewSceneElements = this.props.onDuplicate?.(
  7785. mappedClonedElements,
  7786. elements,
  7787. );
  7788. const elementsWithIndices = syncMovedIndices(
  7789. mappedNewSceneElements || mappedClonedElements,
  7790. arrayToMap(duplicatedElements),
  7791. );
  7792. // we need to update synchronously so as to keep pointerDownState,
  7793. // appState, and scene elements in sync
  7794. flushSync(() => {
  7795. // swap hit element with the duplicated one
  7796. if (pointerDownState.hit.element) {
  7797. const cloneId = origIdToDuplicateId.get(
  7798. pointerDownState.hit.element.id,
  7799. );
  7800. const clonedElement =
  7801. cloneId && duplicateElementsMap.get(cloneId);
  7802. pointerDownState.hit.element = clonedElement || null;
  7803. }
  7804. // swap hit elements with the duplicated ones
  7805. pointerDownState.hit.allHitElements =
  7806. pointerDownState.hit.allHitElements.reduce(
  7807. (
  7808. acc: typeof pointerDownState.hit.allHitElements,
  7809. origHitElement,
  7810. ) => {
  7811. const cloneId = origIdToDuplicateId.get(origHitElement.id);
  7812. const clonedElement =
  7813. cloneId && duplicateElementsMap.get(cloneId);
  7814. if (clonedElement) {
  7815. acc.push(clonedElement);
  7816. }
  7817. return acc;
  7818. },
  7819. [],
  7820. );
  7821. // update drag origin to the position at which we started
  7822. // the duplication so that the drag offset is correct
  7823. pointerDownState.drag.origin = viewportCoordsToSceneCoords(
  7824. event,
  7825. this.state,
  7826. );
  7827. // switch selected elements to the duplicated ones
  7828. this.setState((prevState) => ({
  7829. ...getSelectionStateForElements(
  7830. duplicatedElements,
  7831. this.scene.getNonDeletedElements(),
  7832. prevState,
  7833. ),
  7834. }));
  7835. this.scene.replaceAllElements(elementsWithIndices);
  7836. this.maybeCacheVisibleGaps(event, selectedElements, true);
  7837. this.maybeCacheReferenceSnapPoints(event, selectedElements, true);
  7838. });
  7839. }
  7840. return;
  7841. }
  7842. }
  7843. if (this.state.selectionElement) {
  7844. pointerDownState.lastCoords.x = pointerCoords.x;
  7845. pointerDownState.lastCoords.y = pointerCoords.y;
  7846. if (event.altKey) {
  7847. this.setActiveTool(
  7848. { type: "lasso", fromSelection: true },
  7849. event.shiftKey,
  7850. );
  7851. this.lassoTrail.startPath(
  7852. pointerDownState.origin.x,
  7853. pointerDownState.origin.y,
  7854. event.shiftKey,
  7855. );
  7856. this.setAppState({
  7857. selectionElement: null,
  7858. });
  7859. return;
  7860. }
  7861. this.maybeDragNewGenericElement(pointerDownState, event);
  7862. } else if (this.state.activeTool.type === "lasso") {
  7863. if (!event.altKey && this.state.activeTool.fromSelection) {
  7864. this.setActiveTool({ type: "selection" });
  7865. this.createGenericElementOnPointerDown("selection", pointerDownState);
  7866. pointerDownState.lastCoords.x = pointerCoords.x;
  7867. pointerDownState.lastCoords.y = pointerCoords.y;
  7868. this.maybeDragNewGenericElement(pointerDownState, event);
  7869. this.lassoTrail.endPath();
  7870. } else {
  7871. this.lassoTrail.addPointToPath(
  7872. pointerCoords.x,
  7873. pointerCoords.y,
  7874. event.shiftKey,
  7875. );
  7876. }
  7877. } else {
  7878. // It is very important to read this.state within each move event,
  7879. // otherwise we would read a stale one!
  7880. const newElement = this.state.newElement;
  7881. if (!newElement) {
  7882. return;
  7883. }
  7884. if (newElement.type === "freedraw") {
  7885. const points = newElement.points;
  7886. const dx = pointerCoords.x - newElement.x;
  7887. const dy = pointerCoords.y - newElement.y;
  7888. const lastPoint = points.length > 0 && points[points.length - 1];
  7889. const discardPoint =
  7890. lastPoint && lastPoint[0] === dx && lastPoint[1] === dy;
  7891. if (!discardPoint) {
  7892. const pressures = newElement.simulatePressure
  7893. ? newElement.pressures
  7894. : [...newElement.pressures, event.pressure];
  7895. this.scene.mutateElement(
  7896. newElement,
  7897. {
  7898. points: [...points, pointFrom<LocalPoint>(dx, dy)],
  7899. pressures,
  7900. },
  7901. {
  7902. informMutation: false,
  7903. isDragging: false,
  7904. },
  7905. );
  7906. this.setState({
  7907. newElement,
  7908. });
  7909. }
  7910. } else if (isLinearElement(newElement)) {
  7911. pointerDownState.drag.hasOccurred = true;
  7912. const points = newElement.points;
  7913. let dx = gridX - newElement.x;
  7914. let dy = gridY - newElement.y;
  7915. if (shouldRotateWithDiscreteAngle(event) && points.length === 2) {
  7916. ({ width: dx, height: dy } = getLockedLinearCursorAlignSize(
  7917. newElement.x,
  7918. newElement.y,
  7919. pointerCoords.x,
  7920. pointerCoords.y,
  7921. ));
  7922. }
  7923. if (points.length === 1) {
  7924. this.scene.mutateElement(
  7925. newElement,
  7926. {
  7927. points: [...points, pointFrom<LocalPoint>(dx, dy)],
  7928. },
  7929. { informMutation: false, isDragging: false },
  7930. );
  7931. } else if (
  7932. points.length === 2 ||
  7933. (points.length > 1 && isElbowArrow(newElement))
  7934. ) {
  7935. this.scene.mutateElement(
  7936. newElement,
  7937. {
  7938. points: [...points.slice(0, -1), pointFrom<LocalPoint>(dx, dy)],
  7939. },
  7940. { isDragging: true, informMutation: false },
  7941. );
  7942. }
  7943. this.setState({
  7944. newElement,
  7945. });
  7946. if (isBindingElement(newElement, false)) {
  7947. // When creating a linear element by dragging
  7948. this.setState({
  7949. suggestedBindings: maybeSuggestBindingsForLinearElementAtCoords(
  7950. newElement,
  7951. [pointerCoords],
  7952. this.scene,
  7953. this.state.zoom,
  7954. this.state.startBoundElement,
  7955. ),
  7956. });
  7957. }
  7958. } else {
  7959. pointerDownState.lastCoords.x = pointerCoords.x;
  7960. pointerDownState.lastCoords.y = pointerCoords.y;
  7961. this.maybeDragNewGenericElement(pointerDownState, event, false);
  7962. }
  7963. }
  7964. if (this.state.activeTool.type === "selection") {
  7965. pointerDownState.boxSelection.hasOccurred = true;
  7966. const elements = this.scene.getNonDeletedElements();
  7967. // box-select line editor points
  7968. if (this.state.selectedLinearElement?.isEditing) {
  7969. LinearElementEditor.handleBoxSelection(
  7970. event,
  7971. this.state,
  7972. this.setState.bind(this),
  7973. this.scene.getNonDeletedElementsMap(),
  7974. );
  7975. // regular box-select
  7976. } else {
  7977. let shouldReuseSelection = true;
  7978. if (!event.shiftKey && isSomeElementSelected(elements, this.state)) {
  7979. if (
  7980. pointerDownState.withCmdOrCtrl &&
  7981. pointerDownState.hit.element
  7982. ) {
  7983. this.setState((prevState) =>
  7984. selectGroupsForSelectedElements(
  7985. {
  7986. ...prevState,
  7987. selectedElementIds: {
  7988. [pointerDownState.hit.element!.id]: true,
  7989. },
  7990. },
  7991. this.scene.getNonDeletedElements(),
  7992. prevState,
  7993. this,
  7994. ),
  7995. );
  7996. } else {
  7997. shouldReuseSelection = false;
  7998. }
  7999. }
  8000. const elementsWithinSelection = this.state.selectionElement
  8001. ? getElementsWithinSelection(
  8002. elements,
  8003. this.state.selectionElement,
  8004. this.scene.getNonDeletedElementsMap(),
  8005. false,
  8006. )
  8007. : [];
  8008. this.setState((prevState) => {
  8009. const nextSelectedElementIds = {
  8010. ...(shouldReuseSelection && prevState.selectedElementIds),
  8011. ...elementsWithinSelection.reduce(
  8012. (acc: Record<ExcalidrawElement["id"], true>, element) => {
  8013. acc[element.id] = true;
  8014. return acc;
  8015. },
  8016. {},
  8017. ),
  8018. };
  8019. if (pointerDownState.hit.element) {
  8020. // if using ctrl/cmd, select the hitElement only if we
  8021. // haven't box-selected anything else
  8022. if (!elementsWithinSelection.length) {
  8023. nextSelectedElementIds[pointerDownState.hit.element.id] = true;
  8024. } else {
  8025. delete nextSelectedElementIds[pointerDownState.hit.element.id];
  8026. }
  8027. }
  8028. prevState = !shouldReuseSelection
  8029. ? { ...prevState, selectedGroupIds: {}, editingGroupId: null }
  8030. : prevState;
  8031. return {
  8032. ...selectGroupsForSelectedElements(
  8033. {
  8034. editingGroupId: prevState.editingGroupId,
  8035. selectedElementIds: nextSelectedElementIds,
  8036. },
  8037. this.scene.getNonDeletedElements(),
  8038. prevState,
  8039. this,
  8040. ),
  8041. // select linear element only when we haven't box-selected anything else
  8042. selectedLinearElement:
  8043. elementsWithinSelection.length === 1 &&
  8044. isLinearElement(elementsWithinSelection[0])
  8045. ? new LinearElementEditor(
  8046. elementsWithinSelection[0],
  8047. this.scene.getNonDeletedElementsMap(),
  8048. )
  8049. : null,
  8050. showHyperlinkPopup:
  8051. elementsWithinSelection.length === 1 &&
  8052. (elementsWithinSelection[0].link ||
  8053. isEmbeddableElement(elementsWithinSelection[0]))
  8054. ? "info"
  8055. : false,
  8056. };
  8057. });
  8058. }
  8059. }
  8060. });
  8061. }
  8062. // Returns whether the pointer move happened over either scrollbar
  8063. private handlePointerMoveOverScrollbars(
  8064. event: PointerEvent,
  8065. pointerDownState: PointerDownState,
  8066. ): boolean {
  8067. if (pointerDownState.scrollbars.isOverHorizontal) {
  8068. const x = event.clientX;
  8069. const dx = x - pointerDownState.lastCoords.x;
  8070. this.translateCanvas({
  8071. scrollX:
  8072. this.state.scrollX -
  8073. (dx * (currentScrollBars.horizontal?.deltaMultiplier || 1)) /
  8074. this.state.zoom.value,
  8075. });
  8076. pointerDownState.lastCoords.x = x;
  8077. return true;
  8078. }
  8079. if (pointerDownState.scrollbars.isOverVertical) {
  8080. const y = event.clientY;
  8081. const dy = y - pointerDownState.lastCoords.y;
  8082. this.translateCanvas({
  8083. scrollY:
  8084. this.state.scrollY -
  8085. (dy * (currentScrollBars.vertical?.deltaMultiplier || 1)) /
  8086. this.state.zoom.value,
  8087. });
  8088. pointerDownState.lastCoords.y = y;
  8089. return true;
  8090. }
  8091. return false;
  8092. }
  8093. private onPointerUpFromPointerDownHandler(
  8094. pointerDownState: PointerDownState,
  8095. ): (event: PointerEvent) => void {
  8096. return withBatchedUpdates((childEvent: PointerEvent) => {
  8097. this.removePointer(childEvent);
  8098. if (pointerDownState.eventListeners.onMove) {
  8099. pointerDownState.eventListeners.onMove.flush();
  8100. }
  8101. const {
  8102. newElement,
  8103. resizingElement,
  8104. croppingElementId,
  8105. multiElement,
  8106. activeTool,
  8107. isResizing,
  8108. isRotating,
  8109. isCropping,
  8110. } = this.state;
  8111. this.setState((prevState) => ({
  8112. isResizing: false,
  8113. isRotating: false,
  8114. isCropping: false,
  8115. resizingElement: null,
  8116. selectionElement: null,
  8117. frameToHighlight: null,
  8118. elementsToHighlight: null,
  8119. cursorButton: "up",
  8120. snapLines: updateStable(prevState.snapLines, []),
  8121. originSnapOffset: null,
  8122. }));
  8123. // just in case, tool changes mid drag, always clean up
  8124. this.lassoTrail.endPath();
  8125. this.lastPointerMoveCoords = null;
  8126. SnapCache.setReferenceSnapPoints(null);
  8127. SnapCache.setVisibleGaps(null);
  8128. this.savePointer(childEvent.clientX, childEvent.clientY, "up");
  8129. // if current elements are still selected
  8130. // and the pointer is just over a locked element
  8131. // do not allow activeLockedId to be set
  8132. const hitElements = pointerDownState.hit.allHitElements;
  8133. const sceneCoords = viewportCoordsToSceneCoords(
  8134. { clientX: childEvent.clientX, clientY: childEvent.clientY },
  8135. this.state,
  8136. );
  8137. if (
  8138. this.state.activeTool.type === "selection" &&
  8139. !pointerDownState.boxSelection.hasOccurred &&
  8140. !pointerDownState.resize.isResizing &&
  8141. !hitElements.some((el) => this.state.selectedElementIds[el.id])
  8142. ) {
  8143. const hitLockedElement = this.getElementAtPosition(
  8144. sceneCoords.x,
  8145. sceneCoords.y,
  8146. {
  8147. includeLockedElements: true,
  8148. },
  8149. );
  8150. this.store.scheduleCapture();
  8151. if (hitLockedElement?.locked) {
  8152. this.setState({
  8153. activeLockedId:
  8154. hitLockedElement.groupIds.length > 0
  8155. ? hitLockedElement.groupIds.at(-1) || ""
  8156. : hitLockedElement.id,
  8157. });
  8158. } else {
  8159. this.setState({
  8160. activeLockedId: null,
  8161. });
  8162. }
  8163. } else {
  8164. this.setState({
  8165. activeLockedId: null,
  8166. });
  8167. }
  8168. this.setState({
  8169. selectedElementsAreBeingDragged: false,
  8170. });
  8171. const elementsMap = this.scene.getNonDeletedElementsMap();
  8172. if (
  8173. pointerDownState.drag.hasOccurred &&
  8174. pointerDownState.hit?.element?.id
  8175. ) {
  8176. const element = elementsMap.get(pointerDownState.hit.element.id);
  8177. if (isBindableElement(element)) {
  8178. // Renormalize elbow arrows when they are changed via indirect move
  8179. element.boundElements
  8180. ?.filter((e) => e.type === "arrow")
  8181. .map((e) => elementsMap.get(e.id))
  8182. .filter((e) => isElbowArrow(e))
  8183. .forEach((e) => {
  8184. !!e && this.scene.mutateElement(e, {});
  8185. });
  8186. }
  8187. }
  8188. // Handle end of dragging a point of a linear element, might close a loop
  8189. // and sets binding element
  8190. if (this.state.selectedLinearElement?.isEditing) {
  8191. if (
  8192. !pointerDownState.boxSelection.hasOccurred &&
  8193. pointerDownState.hit?.element?.id !==
  8194. this.state.selectedLinearElement.elementId
  8195. ) {
  8196. this.actionManager.executeAction(actionFinalize);
  8197. } else {
  8198. const editingLinearElement = LinearElementEditor.handlePointerUp(
  8199. childEvent,
  8200. this.state.selectedLinearElement,
  8201. this.state,
  8202. this.scene,
  8203. );
  8204. if (editingLinearElement !== this.state.selectedLinearElement) {
  8205. this.setState({
  8206. selectedLinearElement: editingLinearElement,
  8207. suggestedBindings: [],
  8208. });
  8209. }
  8210. }
  8211. } else if (this.state.selectedLinearElement) {
  8212. // Normalize elbow arrow points, remove close parallel segments
  8213. if (this.state.selectedLinearElement.elbowed) {
  8214. const element = LinearElementEditor.getElement(
  8215. this.state.selectedLinearElement.elementId,
  8216. this.scene.getNonDeletedElementsMap(),
  8217. );
  8218. if (element) {
  8219. this.scene.mutateElement(
  8220. element as ExcalidrawElbowArrowElement,
  8221. {},
  8222. );
  8223. }
  8224. }
  8225. if (
  8226. pointerDownState.hit?.element?.id !==
  8227. this.state.selectedLinearElement.elementId
  8228. ) {
  8229. const selectedELements = this.scene.getSelectedElements(this.state);
  8230. // set selectedLinearElement to null if there is more than one element selected since we don't want to show linear element handles
  8231. if (selectedELements.length > 1) {
  8232. this.setState({ selectedLinearElement: null });
  8233. }
  8234. } else if (this.state.selectedLinearElement.isDragging) {
  8235. this.actionManager.executeAction(actionFinalize, "ui", {
  8236. event: childEvent,
  8237. sceneCoords,
  8238. });
  8239. }
  8240. }
  8241. this.missingPointerEventCleanupEmitter.clear();
  8242. window.removeEventListener(
  8243. EVENT.POINTER_MOVE,
  8244. pointerDownState.eventListeners.onMove!,
  8245. );
  8246. window.removeEventListener(
  8247. EVENT.POINTER_UP,
  8248. pointerDownState.eventListeners.onUp!,
  8249. );
  8250. window.removeEventListener(
  8251. EVENT.KEYDOWN,
  8252. pointerDownState.eventListeners.onKeyDown!,
  8253. );
  8254. window.removeEventListener(
  8255. EVENT.KEYUP,
  8256. pointerDownState.eventListeners.onKeyUp!,
  8257. );
  8258. this.props?.onPointerUp?.(activeTool, pointerDownState);
  8259. this.onPointerUpEmitter.trigger(
  8260. this.state.activeTool,
  8261. pointerDownState,
  8262. childEvent,
  8263. );
  8264. if (newElement?.type === "freedraw") {
  8265. const pointerCoords = viewportCoordsToSceneCoords(
  8266. childEvent,
  8267. this.state,
  8268. );
  8269. const points = newElement.points;
  8270. let dx = pointerCoords.x - newElement.x;
  8271. let dy = pointerCoords.y - newElement.y;
  8272. // Allows dots to avoid being flagged as infinitely small
  8273. if (dx === points[0][0] && dy === points[0][1]) {
  8274. dy += 0.0001;
  8275. dx += 0.0001;
  8276. }
  8277. const pressures = newElement.simulatePressure
  8278. ? []
  8279. : [...newElement.pressures, childEvent.pressure];
  8280. this.scene.mutateElement(newElement, {
  8281. points: [...points, pointFrom<LocalPoint>(dx, dy)],
  8282. pressures,
  8283. lastCommittedPoint: pointFrom<LocalPoint>(dx, dy),
  8284. });
  8285. this.actionManager.executeAction(actionFinalize);
  8286. return;
  8287. }
  8288. if (isLinearElement(newElement)) {
  8289. if (newElement!.points.length > 1) {
  8290. this.store.scheduleCapture();
  8291. }
  8292. const pointerCoords = viewportCoordsToSceneCoords(
  8293. childEvent,
  8294. this.state,
  8295. );
  8296. const dragDistance =
  8297. pointDistance(
  8298. pointFrom(pointerCoords.x, pointerCoords.y),
  8299. pointFrom(pointerDownState.origin.x, pointerDownState.origin.y),
  8300. ) * this.state.zoom.value;
  8301. if (
  8302. (!pointerDownState.drag.hasOccurred ||
  8303. dragDistance < MINIMUM_ARROW_SIZE) &&
  8304. newElement &&
  8305. !multiElement
  8306. ) {
  8307. if (this.device.isTouchScreen) {
  8308. const FIXED_DELTA_X = Math.min(
  8309. (this.state.width * 0.7) / this.state.zoom.value,
  8310. 100,
  8311. );
  8312. this.scene.mutateElement(
  8313. newElement,
  8314. {
  8315. x: newElement.x - FIXED_DELTA_X / 2,
  8316. points: [
  8317. pointFrom<LocalPoint>(0, 0),
  8318. pointFrom<LocalPoint>(FIXED_DELTA_X, 0),
  8319. ],
  8320. },
  8321. { informMutation: false, isDragging: false },
  8322. );
  8323. this.actionManager.executeAction(actionFinalize);
  8324. } else {
  8325. const dx = pointerCoords.x - newElement.x;
  8326. const dy = pointerCoords.y - newElement.y;
  8327. this.scene.mutateElement(
  8328. newElement,
  8329. {
  8330. points: [...newElement.points, pointFrom<LocalPoint>(dx, dy)],
  8331. },
  8332. { informMutation: false, isDragging: false },
  8333. );
  8334. this.setState({
  8335. multiElement: newElement,
  8336. newElement,
  8337. });
  8338. }
  8339. } else if (pointerDownState.drag.hasOccurred && !multiElement) {
  8340. if (
  8341. isBindingEnabled(this.state) &&
  8342. isBindingElement(newElement, false)
  8343. ) {
  8344. this.actionManager.executeAction(actionFinalize, "ui", {
  8345. event: childEvent,
  8346. sceneCoords,
  8347. });
  8348. }
  8349. this.setState({ suggestedBindings: [], startBoundElement: null });
  8350. if (!activeTool.locked) {
  8351. resetCursor(this.interactiveCanvas);
  8352. this.setState((prevState) => ({
  8353. newElement: null,
  8354. activeTool: updateActiveTool(this.state, {
  8355. type: "selection",
  8356. }),
  8357. selectedElementIds: makeNextSelectedElementIds(
  8358. {
  8359. ...prevState.selectedElementIds,
  8360. [newElement.id]: true,
  8361. },
  8362. prevState,
  8363. ),
  8364. selectedLinearElement: new LinearElementEditor(
  8365. newElement,
  8366. this.scene.getNonDeletedElementsMap(),
  8367. ),
  8368. }));
  8369. } else {
  8370. this.setState((prevState) => ({
  8371. newElement: null,
  8372. }));
  8373. }
  8374. // so that the scene gets rendered again to display the newly drawn linear as well
  8375. this.scene.triggerUpdate();
  8376. }
  8377. return;
  8378. }
  8379. if (isTextElement(newElement)) {
  8380. const minWidth = getMinTextElementWidth(
  8381. getFontString({
  8382. fontSize: newElement.fontSize,
  8383. fontFamily: newElement.fontFamily,
  8384. }),
  8385. newElement.lineHeight,
  8386. );
  8387. if (newElement.width < minWidth) {
  8388. this.scene.mutateElement(newElement, {
  8389. autoResize: true,
  8390. });
  8391. }
  8392. this.resetCursor();
  8393. this.handleTextWysiwyg(newElement, {
  8394. isExistingElement: true,
  8395. });
  8396. }
  8397. if (
  8398. activeTool.type !== "selection" &&
  8399. newElement &&
  8400. isInvisiblySmallElement(newElement)
  8401. ) {
  8402. // remove invisible element which was added in onPointerDown
  8403. // update the store snapshot, so that invisible elements are not captured by the store
  8404. this.updateScene({
  8405. elements: this.scene
  8406. .getElementsIncludingDeleted()
  8407. .filter((el) => el.id !== newElement.id),
  8408. appState: {
  8409. newElement: null,
  8410. },
  8411. captureUpdate: CaptureUpdateAction.NEVER,
  8412. });
  8413. return;
  8414. }
  8415. if (isFrameLikeElement(newElement)) {
  8416. const elementsInsideFrame = getElementsInNewFrame(
  8417. this.scene.getElementsIncludingDeleted(),
  8418. newElement,
  8419. this.scene.getNonDeletedElementsMap(),
  8420. );
  8421. this.scene.replaceAllElements(
  8422. addElementsToFrame(
  8423. this.scene.getElementsMapIncludingDeleted(),
  8424. elementsInsideFrame,
  8425. newElement,
  8426. this.state,
  8427. ),
  8428. );
  8429. }
  8430. if (newElement) {
  8431. this.scene.mutateElement(
  8432. newElement,
  8433. getNormalizedDimensions(newElement),
  8434. {
  8435. informMutation: false,
  8436. isDragging: false,
  8437. },
  8438. );
  8439. // the above does not guarantee the scene to be rendered again, hence the trigger below
  8440. this.scene.triggerUpdate();
  8441. }
  8442. if (pointerDownState.drag.hasOccurred) {
  8443. const sceneCoords = viewportCoordsToSceneCoords(childEvent, this.state);
  8444. // when editing the points of a linear element, we check if the
  8445. // linear element still is in the frame afterwards
  8446. // if not, the linear element will be removed from its frame (if any)
  8447. if (
  8448. this.state.selectedLinearElement &&
  8449. this.state.selectedLinearElement.isDragging
  8450. ) {
  8451. const linearElement = this.scene.getElement(
  8452. this.state.selectedLinearElement.elementId,
  8453. );
  8454. if (linearElement?.frameId) {
  8455. const frame = getContainingFrame(linearElement, elementsMap);
  8456. if (frame && linearElement) {
  8457. if (
  8458. !elementOverlapsWithFrame(
  8459. linearElement,
  8460. frame,
  8461. this.scene.getNonDeletedElementsMap(),
  8462. )
  8463. ) {
  8464. // remove the linear element from all groups
  8465. // before removing it from the frame as well
  8466. this.scene.mutateElement(linearElement, {
  8467. groupIds: [],
  8468. });
  8469. removeElementsFromFrame(
  8470. [linearElement],
  8471. this.scene.getNonDeletedElementsMap(),
  8472. );
  8473. this.scene.triggerUpdate();
  8474. }
  8475. }
  8476. }
  8477. } else {
  8478. // update the relationships between selected elements and frames
  8479. const topLayerFrame = this.getTopLayerFrameAtSceneCoords(sceneCoords);
  8480. const selectedElements = this.scene.getSelectedElements(this.state);
  8481. let nextElements = this.scene.getElementsMapIncludingDeleted();
  8482. const updateGroupIdsAfterEditingGroup = (
  8483. elements: ExcalidrawElement[],
  8484. ) => {
  8485. if (elements.length > 0) {
  8486. for (const element of elements) {
  8487. const index = element.groupIds.indexOf(
  8488. this.state.editingGroupId!,
  8489. );
  8490. this.scene.mutateElement(
  8491. element,
  8492. {
  8493. groupIds: element.groupIds.slice(0, index),
  8494. },
  8495. { informMutation: false, isDragging: false },
  8496. );
  8497. }
  8498. nextElements.forEach((element) => {
  8499. if (
  8500. element.groupIds.length &&
  8501. getElementsInGroup(
  8502. nextElements,
  8503. element.groupIds[element.groupIds.length - 1],
  8504. ).length < 2
  8505. ) {
  8506. this.scene.mutateElement(
  8507. element,
  8508. {
  8509. groupIds: [],
  8510. },
  8511. { informMutation: false, isDragging: false },
  8512. );
  8513. }
  8514. });
  8515. this.setState({
  8516. editingGroupId: null,
  8517. });
  8518. }
  8519. };
  8520. if (
  8521. topLayerFrame &&
  8522. !this.state.selectedElementIds[topLayerFrame.id]
  8523. ) {
  8524. const elementsToAdd = selectedElements.filter(
  8525. (element) =>
  8526. element.frameId !== topLayerFrame.id &&
  8527. isElementInFrame(element, nextElements, this.state),
  8528. );
  8529. if (this.state.editingGroupId) {
  8530. updateGroupIdsAfterEditingGroup(elementsToAdd);
  8531. }
  8532. nextElements = addElementsToFrame(
  8533. nextElements,
  8534. elementsToAdd,
  8535. topLayerFrame,
  8536. this.state,
  8537. );
  8538. } else if (!topLayerFrame) {
  8539. if (this.state.editingGroupId) {
  8540. const elementsToRemove = selectedElements.filter(
  8541. (element) =>
  8542. element.frameId &&
  8543. !isElementInFrame(element, nextElements, this.state),
  8544. );
  8545. updateGroupIdsAfterEditingGroup(elementsToRemove);
  8546. }
  8547. }
  8548. nextElements = updateFrameMembershipOfSelectedElements(
  8549. nextElements,
  8550. this.state,
  8551. this,
  8552. );
  8553. this.scene.replaceAllElements(nextElements);
  8554. }
  8555. }
  8556. if (resizingElement) {
  8557. this.store.scheduleCapture();
  8558. }
  8559. if (resizingElement && isInvisiblySmallElement(resizingElement)) {
  8560. // update the store snapshot, so that invisible elements are not captured by the store
  8561. this.updateScene({
  8562. elements: this.scene
  8563. .getElementsIncludingDeleted()
  8564. .filter((el) => el.id !== resizingElement.id),
  8565. captureUpdate: CaptureUpdateAction.NEVER,
  8566. });
  8567. }
  8568. // handle frame membership for resizing frames and/or selected elements
  8569. if (pointerDownState.resize.isResizing) {
  8570. let nextElements = updateFrameMembershipOfSelectedElements(
  8571. this.scene.getElementsIncludingDeleted(),
  8572. this.state,
  8573. this,
  8574. );
  8575. const selectedFrames = this.scene
  8576. .getSelectedElements(this.state)
  8577. .filter((element): element is ExcalidrawFrameLikeElement =>
  8578. isFrameLikeElement(element),
  8579. );
  8580. for (const frame of selectedFrames) {
  8581. nextElements = replaceAllElementsInFrame(
  8582. nextElements,
  8583. getElementsInResizingFrame(
  8584. this.scene.getElementsIncludingDeleted(),
  8585. frame,
  8586. this.state,
  8587. elementsMap,
  8588. ),
  8589. frame,
  8590. this,
  8591. );
  8592. }
  8593. this.scene.replaceAllElements(nextElements);
  8594. }
  8595. // Code below handles selection when element(s) weren't
  8596. // drag or added to selection on pointer down phase.
  8597. const hitElement = pointerDownState.hit.element;
  8598. if (
  8599. this.state.selectedLinearElement?.elementId !== hitElement?.id &&
  8600. isLinearElement(hitElement)
  8601. ) {
  8602. const selectedElements = this.scene.getSelectedElements(this.state);
  8603. // set selectedLinearElement when no other element selected except
  8604. // the one we've hit
  8605. if (selectedElements.length === 1) {
  8606. this.setState({
  8607. selectedLinearElement: new LinearElementEditor(
  8608. hitElement,
  8609. this.scene.getNonDeletedElementsMap(),
  8610. ),
  8611. });
  8612. }
  8613. }
  8614. // click outside the cropping region to exit
  8615. if (
  8616. // not in the cropping mode at all
  8617. !croppingElementId ||
  8618. // in the cropping mode
  8619. (croppingElementId &&
  8620. // not cropping and no hit element
  8621. ((!hitElement && !isCropping) ||
  8622. // hitting something else
  8623. (hitElement && hitElement.id !== croppingElementId)))
  8624. ) {
  8625. this.finishImageCropping();
  8626. }
  8627. const pointerStart = this.lastPointerDownEvent;
  8628. const pointerEnd = this.lastPointerUpEvent || this.lastPointerMoveEvent;
  8629. if (isEraserActive(this.state) && pointerStart && pointerEnd) {
  8630. this.eraserTrail.endPath();
  8631. const draggedDistance = pointDistance(
  8632. pointFrom(pointerStart.clientX, pointerStart.clientY),
  8633. pointFrom(pointerEnd.clientX, pointerEnd.clientY),
  8634. );
  8635. if (draggedDistance === 0) {
  8636. const scenePointer = viewportCoordsToSceneCoords(
  8637. {
  8638. clientX: pointerEnd.clientX,
  8639. clientY: pointerEnd.clientY,
  8640. },
  8641. this.state,
  8642. );
  8643. const hitElements = this.getElementsAtPosition(
  8644. scenePointer.x,
  8645. scenePointer.y,
  8646. );
  8647. hitElements.forEach((hitElement) =>
  8648. this.elementsPendingErasure.add(hitElement.id),
  8649. );
  8650. }
  8651. this.eraseElements();
  8652. return;
  8653. } else if (this.elementsPendingErasure.size) {
  8654. this.restoreReadyToEraseElements();
  8655. }
  8656. if (
  8657. hitElement &&
  8658. !pointerDownState.drag.hasOccurred &&
  8659. !pointerDownState.hit.wasAddedToSelection &&
  8660. // if we're editing a line, pointerup shouldn't switch selection if
  8661. // box selected
  8662. (!this.state.selectedLinearElement?.isEditing ||
  8663. !pointerDownState.boxSelection.hasOccurred) &&
  8664. // hitElement can be set when alt + ctrl to toggle lasso and we will
  8665. // just respect the selected elements from lasso instead
  8666. this.state.activeTool.type !== "lasso"
  8667. ) {
  8668. // when inside line editor, shift selects points instead
  8669. if (
  8670. childEvent.shiftKey &&
  8671. !this.state.selectedLinearElement?.isEditing
  8672. ) {
  8673. if (this.state.selectedElementIds[hitElement.id]) {
  8674. if (isSelectedViaGroup(this.state, hitElement)) {
  8675. this.setState((_prevState) => {
  8676. const nextSelectedElementIds = {
  8677. ..._prevState.selectedElementIds,
  8678. };
  8679. // We want to unselect all groups hitElement is part of
  8680. // as well as all elements that are part of the groups
  8681. // hitElement is part of
  8682. for (const groupedElement of hitElement.groupIds.flatMap(
  8683. (groupId) =>
  8684. getElementsInGroup(
  8685. this.scene.getNonDeletedElements(),
  8686. groupId,
  8687. ),
  8688. )) {
  8689. delete nextSelectedElementIds[groupedElement.id];
  8690. }
  8691. return {
  8692. selectedGroupIds: {
  8693. ..._prevState.selectedElementIds,
  8694. ...hitElement.groupIds
  8695. .map((gId) => ({ [gId]: false }))
  8696. .reduce((prev, acc) => ({ ...prev, ...acc }), {}),
  8697. },
  8698. selectedElementIds: makeNextSelectedElementIds(
  8699. nextSelectedElementIds,
  8700. _prevState,
  8701. ),
  8702. };
  8703. });
  8704. // if not dragging a linear element point (outside editor)
  8705. } else if (!this.state.selectedLinearElement?.isDragging) {
  8706. // remove element from selection while
  8707. // keeping prev elements selected
  8708. this.setState((prevState) => {
  8709. const newSelectedElementIds = {
  8710. ...prevState.selectedElementIds,
  8711. };
  8712. delete newSelectedElementIds[hitElement!.id];
  8713. const newSelectedElements = getSelectedElements(
  8714. this.scene.getNonDeletedElements(),
  8715. { selectedElementIds: newSelectedElementIds },
  8716. );
  8717. return {
  8718. ...selectGroupsForSelectedElements(
  8719. {
  8720. editingGroupId: prevState.editingGroupId,
  8721. selectedElementIds: newSelectedElementIds,
  8722. },
  8723. this.scene.getNonDeletedElements(),
  8724. prevState,
  8725. this,
  8726. ),
  8727. // set selectedLinearElement only if thats the only element selected
  8728. selectedLinearElement:
  8729. newSelectedElements.length === 1 &&
  8730. isLinearElement(newSelectedElements[0])
  8731. ? new LinearElementEditor(
  8732. newSelectedElements[0],
  8733. this.scene.getNonDeletedElementsMap(),
  8734. )
  8735. : prevState.selectedLinearElement,
  8736. };
  8737. });
  8738. }
  8739. } else if (
  8740. hitElement.frameId &&
  8741. this.state.selectedElementIds[hitElement.frameId]
  8742. ) {
  8743. // when hitElement is part of a selected frame, deselect the frame
  8744. // to avoid frame and containing elements selected simultaneously
  8745. this.setState((prevState) => {
  8746. const nextSelectedElementIds: {
  8747. [id: string]: true;
  8748. } = {
  8749. ...prevState.selectedElementIds,
  8750. [hitElement.id]: true,
  8751. };
  8752. // deselect the frame
  8753. delete nextSelectedElementIds[hitElement.frameId!];
  8754. // deselect groups containing the frame
  8755. (this.scene.getElement(hitElement.frameId!)?.groupIds ?? [])
  8756. .flatMap((gid) =>
  8757. getElementsInGroup(this.scene.getNonDeletedElements(), gid),
  8758. )
  8759. .forEach((element) => {
  8760. delete nextSelectedElementIds[element.id];
  8761. });
  8762. return {
  8763. ...selectGroupsForSelectedElements(
  8764. {
  8765. editingGroupId: prevState.editingGroupId,
  8766. selectedElementIds: nextSelectedElementIds,
  8767. },
  8768. this.scene.getNonDeletedElements(),
  8769. prevState,
  8770. this,
  8771. ),
  8772. showHyperlinkPopup:
  8773. hitElement.link || isEmbeddableElement(hitElement)
  8774. ? "info"
  8775. : false,
  8776. };
  8777. });
  8778. } else {
  8779. // add element to selection while keeping prev elements selected
  8780. this.setState((_prevState) => ({
  8781. selectedElementIds: makeNextSelectedElementIds(
  8782. {
  8783. ..._prevState.selectedElementIds,
  8784. [hitElement!.id]: true,
  8785. },
  8786. _prevState,
  8787. ),
  8788. }));
  8789. }
  8790. } else {
  8791. this.setState((prevState) => ({
  8792. ...selectGroupsForSelectedElements(
  8793. {
  8794. editingGroupId: prevState.editingGroupId,
  8795. selectedElementIds: { [hitElement.id]: true },
  8796. },
  8797. this.scene.getNonDeletedElements(),
  8798. prevState,
  8799. this,
  8800. ),
  8801. selectedLinearElement:
  8802. isLinearElement(hitElement) &&
  8803. // Don't set `selectedLinearElement` if its same as the hitElement, this is mainly to prevent resetting the `hoverPointIndex` to -1.
  8804. // Future we should update the API to take care of setting the correct `hoverPointIndex` when initialized
  8805. prevState.selectedLinearElement?.elementId !== hitElement.id
  8806. ? new LinearElementEditor(
  8807. hitElement,
  8808. this.scene.getNonDeletedElementsMap(),
  8809. )
  8810. : prevState.selectedLinearElement,
  8811. }));
  8812. }
  8813. }
  8814. if (
  8815. // do not clear selection if lasso is active
  8816. this.state.activeTool.type !== "lasso" &&
  8817. // not elbow midpoint dragged
  8818. !(hitElement && isElbowArrow(hitElement)) &&
  8819. // not dragged
  8820. !pointerDownState.drag.hasOccurred &&
  8821. // not resized
  8822. !this.state.isResizing &&
  8823. // only hitting the bounding box of the previous hit element
  8824. ((hitElement &&
  8825. hitElementBoundingBoxOnly(
  8826. {
  8827. point: pointFrom(
  8828. pointerDownState.origin.x,
  8829. pointerDownState.origin.y,
  8830. ),
  8831. element: hitElement,
  8832. elementsMap,
  8833. threshold: this.getElementHitThreshold(hitElement),
  8834. frameNameBound: isFrameLikeElement(hitElement)
  8835. ? this.frameNameBoundsCache.get(hitElement)
  8836. : null,
  8837. },
  8838. elementsMap,
  8839. )) ||
  8840. (!hitElement &&
  8841. pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements))
  8842. ) {
  8843. if (this.state.selectedLinearElement?.isEditing) {
  8844. // Exit editing mode but keep the element selected
  8845. this.actionManager.executeAction(actionToggleLinearEditor);
  8846. } else {
  8847. // Deselect selected elements
  8848. this.setState({
  8849. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  8850. selectedGroupIds: {},
  8851. editingGroupId: null,
  8852. activeEmbeddable: null,
  8853. });
  8854. }
  8855. // reset cursor
  8856. setCursor(this.interactiveCanvas, CURSOR_TYPE.AUTO);
  8857. return;
  8858. }
  8859. if (!activeTool.locked && activeTool.type !== "freedraw" && newElement) {
  8860. this.setState((prevState) => ({
  8861. selectedElementIds: makeNextSelectedElementIds(
  8862. {
  8863. ...prevState.selectedElementIds,
  8864. [newElement.id]: true,
  8865. },
  8866. prevState,
  8867. ),
  8868. showHyperlinkPopup:
  8869. isEmbeddableElement(newElement) && !newElement.link
  8870. ? "editor"
  8871. : prevState.showHyperlinkPopup,
  8872. }));
  8873. }
  8874. if (
  8875. activeTool.type !== "selection" ||
  8876. isSomeElementSelected(this.scene.getNonDeletedElements(), this.state) ||
  8877. !isShallowEqual(
  8878. this.state.previousSelectedElementIds,
  8879. this.state.selectedElementIds,
  8880. )
  8881. ) {
  8882. this.store.scheduleCapture();
  8883. }
  8884. if (
  8885. (pointerDownState.drag.hasOccurred &&
  8886. !this.state.selectedLinearElement) ||
  8887. isResizing ||
  8888. isRotating ||
  8889. isCropping
  8890. ) {
  8891. // We only allow binding via linear elements, specifically via dragging
  8892. // the endpoints ("start" or "end").
  8893. const linearElements = this.scene
  8894. .getSelectedElements(this.state)
  8895. .filter(isLinearElement);
  8896. bindOrUnbindLinearElements(
  8897. linearElements,
  8898. isBindingEnabled(this.state),
  8899. this.state.selectedLinearElement?.selectedPointsIndices ?? [],
  8900. this.scene,
  8901. this.state.zoom,
  8902. );
  8903. }
  8904. if (activeTool.type === "laser") {
  8905. this.laserTrails.endPath();
  8906. return;
  8907. }
  8908. if (
  8909. !activeTool.locked &&
  8910. activeTool.type !== "freedraw" &&
  8911. (activeTool.type !== "lasso" ||
  8912. // if lasso is turned on but from selection => reset to selection
  8913. (activeTool.type === "lasso" && activeTool.fromSelection))
  8914. ) {
  8915. resetCursor(this.interactiveCanvas);
  8916. this.setState({
  8917. newElement: null,
  8918. suggestedBindings: [],
  8919. activeTool: updateActiveTool(this.state, { type: "selection" }),
  8920. });
  8921. } else {
  8922. this.setState({
  8923. newElement: null,
  8924. suggestedBindings: [],
  8925. });
  8926. }
  8927. if (
  8928. hitElement &&
  8929. this.lastPointerUpEvent &&
  8930. this.lastPointerDownEvent &&
  8931. this.lastPointerUpEvent.timeStamp -
  8932. this.lastPointerDownEvent.timeStamp <
  8933. 300 &&
  8934. gesture.pointers.size <= 1 &&
  8935. isIframeLikeElement(hitElement) &&
  8936. this.isIframeLikeElementCenter(
  8937. hitElement,
  8938. this.lastPointerUpEvent,
  8939. pointerDownState.origin.x,
  8940. pointerDownState.origin.y,
  8941. )
  8942. ) {
  8943. this.handleEmbeddableCenterClick(hitElement);
  8944. }
  8945. });
  8946. }
  8947. private restoreReadyToEraseElements = () => {
  8948. this.elementsPendingErasure = new Set();
  8949. this.triggerRender();
  8950. };
  8951. private eraseElements = () => {
  8952. let didChange = false;
  8953. const elements = this.scene.getElementsIncludingDeleted().map((ele) => {
  8954. if (
  8955. this.elementsPendingErasure.has(ele.id) ||
  8956. (ele.frameId && this.elementsPendingErasure.has(ele.frameId)) ||
  8957. (isBoundToContainer(ele) &&
  8958. this.elementsPendingErasure.has(ele.containerId))
  8959. ) {
  8960. didChange = true;
  8961. return newElementWith(ele, { isDeleted: true });
  8962. }
  8963. return ele;
  8964. });
  8965. this.elementsPendingErasure = new Set();
  8966. if (didChange) {
  8967. this.store.scheduleCapture();
  8968. this.scene.replaceAllElements(elements);
  8969. }
  8970. };
  8971. private initializeImage = async (
  8972. placeholderImageElement: ExcalidrawImageElement,
  8973. imageFile: File,
  8974. ) => {
  8975. // at this point this should be guaranteed image file, but we do this check
  8976. // to satisfy TS down the line
  8977. if (!isSupportedImageFile(imageFile)) {
  8978. throw new Error(t("errors.unsupportedFileType"));
  8979. }
  8980. const mimeType = imageFile.type;
  8981. setCursor(this.interactiveCanvas, "wait");
  8982. if (mimeType === MIME_TYPES.svg) {
  8983. try {
  8984. imageFile = SVGStringToFile(
  8985. normalizeSVG(await imageFile.text()),
  8986. imageFile.name,
  8987. );
  8988. } catch (error: any) {
  8989. console.warn(error);
  8990. throw new Error(t("errors.svgImageInsertError"));
  8991. }
  8992. }
  8993. // generate image id (by default the file digest) before any
  8994. // resizing/compression takes place to keep it more portable
  8995. const fileId = await ((this.props.generateIdForFile?.(
  8996. imageFile,
  8997. ) as Promise<FileId>) || generateIdFromFile(imageFile));
  8998. if (!fileId) {
  8999. console.warn(
  9000. "Couldn't generate file id or the supplied `generateIdForFile` didn't resolve to one.",
  9001. );
  9002. throw new Error(t("errors.imageInsertError"));
  9003. }
  9004. const existingFileData = this.files[fileId];
  9005. if (!existingFileData?.dataURL) {
  9006. try {
  9007. imageFile = await resizeImageFile(imageFile, {
  9008. maxWidthOrHeight: DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
  9009. });
  9010. } catch (error: any) {
  9011. console.error(
  9012. "Error trying to resizing image file on insertion",
  9013. error,
  9014. );
  9015. }
  9016. if (imageFile.size > MAX_ALLOWED_FILE_BYTES) {
  9017. throw new Error(
  9018. t("errors.fileTooBig", {
  9019. maxSize: `${Math.trunc(MAX_ALLOWED_FILE_BYTES / 1024 / 1024)}MB`,
  9020. }),
  9021. );
  9022. }
  9023. }
  9024. const dataURL =
  9025. this.files[fileId]?.dataURL || (await getDataURL(imageFile));
  9026. return new Promise<NonDeleted<InitializedExcalidrawImageElement>>(
  9027. async (resolve, reject) => {
  9028. try {
  9029. let initializedImageElement = this.getLatestInitializedImageElement(
  9030. placeholderImageElement,
  9031. fileId,
  9032. );
  9033. this.addMissingFiles([
  9034. {
  9035. mimeType,
  9036. id: fileId,
  9037. dataURL,
  9038. created: Date.now(),
  9039. lastRetrieved: Date.now(),
  9040. },
  9041. ]);
  9042. if (!this.imageCache.get(fileId)) {
  9043. this.addNewImagesToImageCache();
  9044. const { erroredFiles } = await this.updateImageCache([
  9045. initializedImageElement,
  9046. ]);
  9047. if (erroredFiles.size) {
  9048. throw new Error("Image cache update resulted with an error.");
  9049. }
  9050. }
  9051. const imageHTML = await this.imageCache.get(fileId)?.image;
  9052. if (
  9053. imageHTML &&
  9054. this.state.newElement?.id !== initializedImageElement.id
  9055. ) {
  9056. initializedImageElement = this.getLatestInitializedImageElement(
  9057. placeholderImageElement,
  9058. fileId,
  9059. );
  9060. const naturalDimensions = this.getImageNaturalDimensions(
  9061. initializedImageElement,
  9062. imageHTML,
  9063. );
  9064. // no need to create a new instance anymore, just assign the natural dimensions
  9065. Object.assign(initializedImageElement, naturalDimensions);
  9066. }
  9067. resolve(initializedImageElement);
  9068. } catch (error: any) {
  9069. console.error(error);
  9070. reject(new Error(t("errors.imageInsertError")));
  9071. }
  9072. },
  9073. );
  9074. };
  9075. /**
  9076. * use during async image initialization,
  9077. * when the placeholder image could have been modified in the meantime,
  9078. * and when you don't want to loose those modifications
  9079. */
  9080. private getLatestInitializedImageElement = (
  9081. imagePlaceholder: ExcalidrawImageElement,
  9082. fileId: FileId,
  9083. ) => {
  9084. const latestImageElement =
  9085. this.scene.getElement(imagePlaceholder.id) ?? imagePlaceholder;
  9086. return newElementWith(
  9087. latestImageElement as InitializedExcalidrawImageElement,
  9088. {
  9089. fileId,
  9090. },
  9091. );
  9092. };
  9093. /**
  9094. * inserts image into elements array and rerenders
  9095. */
  9096. private insertImageElement = async (
  9097. placeholderImageElement: ExcalidrawImageElement,
  9098. imageFile: File,
  9099. ) => {
  9100. // we should be handling all cases upstream, but in case we forget to handle
  9101. // a future case, let's throw here
  9102. if (!this.isToolSupported("image")) {
  9103. this.setState({ errorMessage: t("errors.imageToolNotSupported") });
  9104. return;
  9105. }
  9106. this.scene.insertElement(placeholderImageElement);
  9107. try {
  9108. const initializedImageElement = await this.initializeImage(
  9109. placeholderImageElement,
  9110. imageFile,
  9111. );
  9112. const nextElements = this.scene
  9113. .getElementsIncludingDeleted()
  9114. .map((element) => {
  9115. if (element.id === initializedImageElement.id) {
  9116. return initializedImageElement;
  9117. }
  9118. return element;
  9119. });
  9120. this.updateScene({
  9121. captureUpdate: CaptureUpdateAction.IMMEDIATELY,
  9122. elements: nextElements,
  9123. appState: {
  9124. selectedElementIds: makeNextSelectedElementIds(
  9125. { [initializedImageElement.id]: true },
  9126. this.state,
  9127. ),
  9128. },
  9129. });
  9130. return initializedImageElement;
  9131. } catch (error: any) {
  9132. this.store.scheduleAction(CaptureUpdateAction.NEVER);
  9133. this.scene.mutateElement(placeholderImageElement, {
  9134. isDeleted: true,
  9135. });
  9136. this.actionManager.executeAction(actionFinalize);
  9137. this.setState({
  9138. errorMessage: error.message || t("errors.imageInsertError"),
  9139. });
  9140. return null;
  9141. }
  9142. };
  9143. private onImageAction = async () => {
  9144. try {
  9145. const clientX = this.state.width / 2 + this.state.offsetLeft;
  9146. const clientY = this.state.height / 2 + this.state.offsetTop;
  9147. const { x, y } = viewportCoordsToSceneCoords(
  9148. { clientX, clientY },
  9149. this.state,
  9150. );
  9151. const imageFile = await fileOpen({
  9152. description: "Image",
  9153. extensions: Object.keys(
  9154. IMAGE_MIME_TYPES,
  9155. ) as (keyof typeof IMAGE_MIME_TYPES)[],
  9156. });
  9157. await this.createImageElement({
  9158. sceneX: x,
  9159. sceneY: y,
  9160. addToFrameUnderCursor: false,
  9161. imageFile,
  9162. });
  9163. // avoid being batched (just in case)
  9164. this.setState({}, () => {
  9165. this.actionManager.executeAction(actionFinalize);
  9166. });
  9167. } catch (error: any) {
  9168. if (error.name !== "AbortError") {
  9169. console.error(error);
  9170. } else {
  9171. console.warn(error);
  9172. }
  9173. this.setState(
  9174. {
  9175. newElement: null,
  9176. activeTool: updateActiveTool(this.state, { type: "selection" }),
  9177. },
  9178. () => {
  9179. this.actionManager.executeAction(actionFinalize);
  9180. },
  9181. );
  9182. }
  9183. };
  9184. private getImageNaturalDimensions = (
  9185. imageElement: ExcalidrawImageElement,
  9186. imageHTML: HTMLImageElement,
  9187. ) => {
  9188. const minHeight = Math.max(this.state.height - 120, 160);
  9189. // max 65% of canvas height, clamped to <300px, vh - 120px>
  9190. const maxHeight = Math.min(
  9191. minHeight,
  9192. Math.floor(this.state.height * 0.5) / this.state.zoom.value,
  9193. );
  9194. const height = Math.min(imageHTML.naturalHeight, maxHeight);
  9195. const width = height * (imageHTML.naturalWidth / imageHTML.naturalHeight);
  9196. // add current imageElement width/height to account for previous centering
  9197. // of the placeholder image
  9198. const x = imageElement.x + imageElement.width / 2 - width / 2;
  9199. const y = imageElement.y + imageElement.height / 2 - height / 2;
  9200. return {
  9201. x,
  9202. y,
  9203. width,
  9204. height,
  9205. crop: null,
  9206. };
  9207. };
  9208. /** updates image cache, refreshing updated elements and/or setting status
  9209. to error for images that fail during <img> element creation */
  9210. private updateImageCache = async (
  9211. elements: readonly InitializedExcalidrawImageElement[],
  9212. files = this.files,
  9213. ) => {
  9214. const { updatedFiles, erroredFiles } = await _updateImageCache({
  9215. imageCache: this.imageCache,
  9216. fileIds: elements.map((element) => element.fileId),
  9217. files,
  9218. });
  9219. if (erroredFiles.size) {
  9220. this.store.scheduleAction(CaptureUpdateAction.NEVER);
  9221. this.scene.replaceAllElements(
  9222. elements.map((element) => {
  9223. if (
  9224. isInitializedImageElement(element) &&
  9225. erroredFiles.has(element.fileId)
  9226. ) {
  9227. return newElementWith(element, {
  9228. status: "error",
  9229. });
  9230. }
  9231. return element;
  9232. }),
  9233. );
  9234. }
  9235. return { updatedFiles, erroredFiles };
  9236. };
  9237. /** adds new images to imageCache and re-renders if needed */
  9238. private addNewImagesToImageCache = async (
  9239. imageElements: InitializedExcalidrawImageElement[] = getInitializedImageElements(
  9240. this.scene.getNonDeletedElements(),
  9241. ),
  9242. files: BinaryFiles = this.files,
  9243. ) => {
  9244. const uncachedImageElements = imageElements.filter(
  9245. (element) => !element.isDeleted && !this.imageCache.has(element.fileId),
  9246. );
  9247. if (uncachedImageElements.length) {
  9248. const { updatedFiles } = await this.updateImageCache(
  9249. uncachedImageElements,
  9250. files,
  9251. );
  9252. if (updatedFiles.size) {
  9253. for (const element of uncachedImageElements) {
  9254. if (updatedFiles.has(element.fileId)) {
  9255. ShapeCache.delete(element);
  9256. }
  9257. }
  9258. }
  9259. if (updatedFiles.size) {
  9260. this.scene.triggerUpdate();
  9261. }
  9262. }
  9263. };
  9264. /** generally you should use `addNewImagesToImageCache()` directly if you need
  9265. * to render new images. This is just a failsafe */
  9266. private scheduleImageRefresh = throttle(() => {
  9267. this.addNewImagesToImageCache();
  9268. }, IMAGE_RENDER_TIMEOUT);
  9269. private updateBindingEnabledOnPointerMove = (
  9270. event: React.PointerEvent<HTMLElement>,
  9271. ) => {
  9272. const shouldEnableBinding = shouldEnableBindingForPointerEvent(event);
  9273. if (this.state.isBindingEnabled !== shouldEnableBinding) {
  9274. this.setState({ isBindingEnabled: shouldEnableBinding });
  9275. }
  9276. };
  9277. private maybeSuggestBindingAtCursor = (
  9278. pointerCoords: {
  9279. x: number;
  9280. y: number;
  9281. },
  9282. considerAll: boolean,
  9283. ): void => {
  9284. const hoveredBindableElement = getHoveredElementForBinding(
  9285. pointerCoords,
  9286. this.scene.getNonDeletedElements(),
  9287. this.scene.getNonDeletedElementsMap(),
  9288. this.state.zoom,
  9289. false,
  9290. considerAll,
  9291. );
  9292. this.setState({
  9293. suggestedBindings:
  9294. hoveredBindableElement != null ? [hoveredBindableElement] : [],
  9295. });
  9296. };
  9297. private clearSelection(hitElement: ExcalidrawElement | null): void {
  9298. this.setState((prevState) => ({
  9299. selectedElementIds: makeNextSelectedElementIds({}, prevState),
  9300. activeEmbeddable: null,
  9301. selectedGroupIds: {},
  9302. // Continue editing the same group if the user selected a different
  9303. // element from it
  9304. editingGroupId:
  9305. prevState.editingGroupId &&
  9306. hitElement != null &&
  9307. isElementInGroup(hitElement, prevState.editingGroupId)
  9308. ? prevState.editingGroupId
  9309. : null,
  9310. }));
  9311. this.setState({
  9312. selectedElementIds: makeNextSelectedElementIds({}, this.state),
  9313. activeEmbeddable: null,
  9314. previousSelectedElementIds: this.state.selectedElementIds,
  9315. });
  9316. }
  9317. private handleInteractiveCanvasRef = (canvas: HTMLCanvasElement | null) => {
  9318. // canvas is null when unmounting
  9319. if (canvas !== null) {
  9320. this.interactiveCanvas = canvas;
  9321. // -----------------------------------------------------------------------
  9322. // NOTE wheel, touchstart, touchend events must be registered outside
  9323. // of react because react binds them them passively (so we can't prevent
  9324. // default on them)
  9325. this.interactiveCanvas.addEventListener(
  9326. EVENT.TOUCH_START,
  9327. this.onTouchStart,
  9328. { passive: false },
  9329. );
  9330. this.interactiveCanvas.addEventListener(EVENT.TOUCH_END, this.onTouchEnd);
  9331. // -----------------------------------------------------------------------
  9332. } else {
  9333. this.interactiveCanvas?.removeEventListener(
  9334. EVENT.TOUCH_START,
  9335. this.onTouchStart,
  9336. );
  9337. this.interactiveCanvas?.removeEventListener(
  9338. EVENT.TOUCH_END,
  9339. this.onTouchEnd,
  9340. );
  9341. }
  9342. };
  9343. private handleAppOnDrop = async (event: React.DragEvent<HTMLDivElement>) => {
  9344. // must be retrieved first, in the same frame
  9345. const { file, fileHandle } = await getFileFromEvent(event);
  9346. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  9347. event,
  9348. this.state,
  9349. );
  9350. try {
  9351. // if image tool not supported, don't show an error here and let it fall
  9352. // through so we still support importing scene data from images. If no
  9353. // scene data encoded, we'll show an error then
  9354. if (isSupportedImageFile(file) && this.isToolSupported("image")) {
  9355. // first attempt to decode scene from the image if it's embedded
  9356. // ---------------------------------------------------------------------
  9357. if (file?.type === MIME_TYPES.png || file?.type === MIME_TYPES.svg) {
  9358. try {
  9359. const scene = await loadFromBlob(
  9360. file,
  9361. this.state,
  9362. this.scene.getElementsIncludingDeleted(),
  9363. fileHandle,
  9364. );
  9365. this.syncActionResult({
  9366. ...scene,
  9367. appState: {
  9368. ...(scene.appState || this.state),
  9369. isLoading: false,
  9370. },
  9371. replaceFiles: true,
  9372. captureUpdate: CaptureUpdateAction.IMMEDIATELY,
  9373. });
  9374. return;
  9375. } catch (error: any) {
  9376. // Don't throw for image scene daa
  9377. if (error.name !== "EncodingError") {
  9378. throw new Error(t("alerts.couldNotLoadInvalidFile"));
  9379. }
  9380. }
  9381. }
  9382. // if no scene is embedded or we fail for whatever reason, fall back
  9383. // to importing as regular image
  9384. // ---------------------------------------------------------------------
  9385. this.createImageElement({ sceneX, sceneY, imageFile: file });
  9386. return;
  9387. }
  9388. } catch (error: any) {
  9389. return this.setState({
  9390. isLoading: false,
  9391. errorMessage: error.message,
  9392. });
  9393. }
  9394. const libraryJSON = event.dataTransfer.getData(MIME_TYPES.excalidrawlib);
  9395. if (libraryJSON && typeof libraryJSON === "string") {
  9396. try {
  9397. const libraryItems = parseLibraryJSON(libraryJSON);
  9398. this.addElementsFromPasteOrLibrary({
  9399. elements: distributeLibraryItemsOnSquareGrid(libraryItems),
  9400. position: event,
  9401. files: null,
  9402. });
  9403. } catch (error: any) {
  9404. this.setState({ errorMessage: error.message });
  9405. }
  9406. return;
  9407. }
  9408. if (file) {
  9409. // Attempt to parse an excalidraw/excalidrawlib file
  9410. await this.loadFileToCanvas(file, fileHandle);
  9411. }
  9412. if (event.dataTransfer?.types?.includes("text/plain")) {
  9413. const text = event.dataTransfer?.getData("text");
  9414. if (
  9415. text &&
  9416. embeddableURLValidator(text, this.props.validateEmbeddable) &&
  9417. (/^(http|https):\/\/[^\s/$.?#].[^\s]*$/.test(text) ||
  9418. getEmbedLink(text)?.type === "video")
  9419. ) {
  9420. const embeddable = this.insertEmbeddableElement({
  9421. sceneX,
  9422. sceneY,
  9423. link: normalizeLink(text),
  9424. });
  9425. if (embeddable) {
  9426. this.store.scheduleCapture();
  9427. this.setState({ selectedElementIds: { [embeddable.id]: true } });
  9428. }
  9429. }
  9430. }
  9431. };
  9432. loadFileToCanvas = async (
  9433. file: File,
  9434. fileHandle: FileSystemHandle | null,
  9435. ) => {
  9436. file = await normalizeFile(file);
  9437. try {
  9438. const elements = this.scene.getElementsIncludingDeleted();
  9439. let ret;
  9440. try {
  9441. ret = await loadSceneOrLibraryFromBlob(
  9442. file,
  9443. this.state,
  9444. elements,
  9445. fileHandle,
  9446. );
  9447. } catch (error: any) {
  9448. const imageSceneDataError = error instanceof ImageSceneDataError;
  9449. if (
  9450. imageSceneDataError &&
  9451. error.code === "IMAGE_NOT_CONTAINS_SCENE_DATA" &&
  9452. !this.isToolSupported("image")
  9453. ) {
  9454. this.setState({
  9455. isLoading: false,
  9456. errorMessage: t("errors.imageToolNotSupported"),
  9457. });
  9458. return;
  9459. }
  9460. const errorMessage = imageSceneDataError
  9461. ? t("alerts.cannotRestoreFromImage")
  9462. : t("alerts.couldNotLoadInvalidFile");
  9463. this.setState({
  9464. isLoading: false,
  9465. errorMessage,
  9466. });
  9467. }
  9468. if (!ret) {
  9469. return;
  9470. }
  9471. if (ret.type === MIME_TYPES.excalidraw) {
  9472. // restore the fractional indices by mutating elements
  9473. syncInvalidIndices(elements.concat(ret.data.elements));
  9474. // don't capture and only update the store snapshot for old elements,
  9475. // otherwise we would end up with duplicated fractional indices on undo
  9476. this.store.scheduleMicroAction({
  9477. action: CaptureUpdateAction.NEVER,
  9478. elements,
  9479. appState: undefined,
  9480. });
  9481. this.setState({ isLoading: true });
  9482. this.syncActionResult({
  9483. ...ret.data,
  9484. appState: {
  9485. ...(ret.data.appState || this.state),
  9486. isLoading: false,
  9487. },
  9488. replaceFiles: true,
  9489. captureUpdate: CaptureUpdateAction.IMMEDIATELY,
  9490. });
  9491. } else if (ret.type === MIME_TYPES.excalidrawlib) {
  9492. await this.library
  9493. .updateLibrary({
  9494. libraryItems: file,
  9495. merge: true,
  9496. openLibraryMenu: true,
  9497. })
  9498. .catch((error) => {
  9499. console.error(error);
  9500. this.setState({ errorMessage: t("errors.importLibraryError") });
  9501. });
  9502. }
  9503. } catch (error: any) {
  9504. this.setState({ isLoading: false, errorMessage: error.message });
  9505. }
  9506. };
  9507. private handleCanvasContextMenu = (
  9508. event: React.MouseEvent<HTMLElement | HTMLCanvasElement>,
  9509. ) => {
  9510. event.preventDefault();
  9511. if (
  9512. (("pointerType" in event.nativeEvent &&
  9513. event.nativeEvent.pointerType === "touch") ||
  9514. ("pointerType" in event.nativeEvent &&
  9515. event.nativeEvent.pointerType === "pen" &&
  9516. // always allow if user uses a pen secondary button
  9517. event.button !== POINTER_BUTTON.SECONDARY)) &&
  9518. this.state.activeTool.type !== "selection"
  9519. ) {
  9520. return;
  9521. }
  9522. const { x, y } = viewportCoordsToSceneCoords(event, this.state);
  9523. const element = this.getElementAtPosition(x, y, {
  9524. preferSelected: true,
  9525. includeLockedElements: true,
  9526. });
  9527. const selectedElements = this.scene.getSelectedElements(this.state);
  9528. const isHittingCommonBoundBox =
  9529. this.isHittingCommonBoundingBoxOfSelectedElements(
  9530. { x, y },
  9531. selectedElements,
  9532. );
  9533. const type = element || isHittingCommonBoundBox ? "element" : "canvas";
  9534. const container = this.excalidrawContainerRef.current!;
  9535. const { top: offsetTop, left: offsetLeft } =
  9536. container.getBoundingClientRect();
  9537. const left = event.clientX - offsetLeft;
  9538. const top = event.clientY - offsetTop;
  9539. trackEvent("contextMenu", "openContextMenu", type);
  9540. this.setState(
  9541. {
  9542. ...(element && !this.state.selectedElementIds[element.id]
  9543. ? {
  9544. ...this.state,
  9545. ...selectGroupsForSelectedElements(
  9546. {
  9547. editingGroupId: this.state.editingGroupId,
  9548. selectedElementIds: { [element.id]: true },
  9549. },
  9550. this.scene.getNonDeletedElements(),
  9551. this.state,
  9552. this,
  9553. ),
  9554. selectedLinearElement: isLinearElement(element)
  9555. ? new LinearElementEditor(
  9556. element,
  9557. this.scene.getNonDeletedElementsMap(),
  9558. )
  9559. : null,
  9560. }
  9561. : this.state),
  9562. showHyperlinkPopup: false,
  9563. },
  9564. () => {
  9565. this.setState({
  9566. contextMenu: { top, left, items: this.getContextMenuItems(type) },
  9567. });
  9568. },
  9569. );
  9570. };
  9571. private maybeDragNewGenericElement = (
  9572. pointerDownState: PointerDownState,
  9573. event: MouseEvent | KeyboardEvent,
  9574. informMutation = true,
  9575. ): void => {
  9576. const selectionElement = this.state.selectionElement;
  9577. const pointerCoords = pointerDownState.lastCoords;
  9578. if (selectionElement && this.state.activeTool.type !== "eraser") {
  9579. dragNewElement({
  9580. newElement: selectionElement,
  9581. elementType: this.state.activeTool.type,
  9582. originX: pointerDownState.origin.x,
  9583. originY: pointerDownState.origin.y,
  9584. x: pointerCoords.x,
  9585. y: pointerCoords.y,
  9586. width: distance(pointerDownState.origin.x, pointerCoords.x),
  9587. height: distance(pointerDownState.origin.y, pointerCoords.y),
  9588. shouldMaintainAspectRatio: shouldMaintainAspectRatio(event),
  9589. shouldResizeFromCenter: false,
  9590. scene: this.scene,
  9591. zoom: this.state.zoom.value,
  9592. informMutation: false,
  9593. });
  9594. return;
  9595. }
  9596. const newElement = this.state.newElement;
  9597. if (!newElement) {
  9598. return;
  9599. }
  9600. let [gridX, gridY] = getGridPoint(
  9601. pointerCoords.x,
  9602. pointerCoords.y,
  9603. event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
  9604. );
  9605. const image =
  9606. isInitializedImageElement(newElement) &&
  9607. this.imageCache.get(newElement.fileId)?.image;
  9608. const aspectRatio =
  9609. image && !(image instanceof Promise) ? image.width / image.height : null;
  9610. this.maybeCacheReferenceSnapPoints(event, [newElement]);
  9611. const { snapOffset, snapLines } = snapNewElement(
  9612. newElement,
  9613. this,
  9614. event,
  9615. {
  9616. x:
  9617. pointerDownState.originInGrid.x +
  9618. (this.state.originSnapOffset?.x ?? 0),
  9619. y:
  9620. pointerDownState.originInGrid.y +
  9621. (this.state.originSnapOffset?.y ?? 0),
  9622. },
  9623. {
  9624. x: gridX - pointerDownState.originInGrid.x,
  9625. y: gridY - pointerDownState.originInGrid.y,
  9626. },
  9627. this.scene.getNonDeletedElementsMap(),
  9628. );
  9629. gridX += snapOffset.x;
  9630. gridY += snapOffset.y;
  9631. this.setState({
  9632. snapLines,
  9633. });
  9634. dragNewElement({
  9635. newElement,
  9636. elementType: this.state.activeTool.type,
  9637. originX: pointerDownState.originInGrid.x,
  9638. originY: pointerDownState.originInGrid.y,
  9639. x: gridX,
  9640. y: gridY,
  9641. width: distance(pointerDownState.originInGrid.x, gridX),
  9642. height: distance(pointerDownState.originInGrid.y, gridY),
  9643. shouldMaintainAspectRatio: isImageElement(newElement)
  9644. ? !shouldMaintainAspectRatio(event)
  9645. : shouldMaintainAspectRatio(event),
  9646. shouldResizeFromCenter: shouldResizeFromCenter(event),
  9647. zoom: this.state.zoom.value,
  9648. scene: this.scene,
  9649. widthAspectRatio: aspectRatio,
  9650. originOffset: this.state.originSnapOffset,
  9651. informMutation,
  9652. });
  9653. this.setState({
  9654. newElement,
  9655. });
  9656. // highlight elements that are to be added to frames on frames creation
  9657. if (
  9658. this.state.activeTool.type === TOOL_TYPE.frame ||
  9659. this.state.activeTool.type === TOOL_TYPE.magicframe
  9660. ) {
  9661. this.setState({
  9662. elementsToHighlight: getElementsInResizingFrame(
  9663. this.scene.getNonDeletedElements(),
  9664. newElement as ExcalidrawFrameLikeElement,
  9665. this.state,
  9666. this.scene.getNonDeletedElementsMap(),
  9667. ),
  9668. });
  9669. }
  9670. };
  9671. private maybeHandleCrop = (
  9672. pointerDownState: PointerDownState,
  9673. event: MouseEvent | KeyboardEvent,
  9674. ): boolean => {
  9675. // to crop, we must already be in the cropping mode, where croppingElement has been set
  9676. if (!this.state.croppingElementId) {
  9677. return false;
  9678. }
  9679. const transformHandleType = pointerDownState.resize.handleType;
  9680. const pointerCoords = pointerDownState.lastCoords;
  9681. const [x, y] = getGridPoint(
  9682. pointerCoords.x - pointerDownState.resize.offset.x,
  9683. pointerCoords.y - pointerDownState.resize.offset.y,
  9684. event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
  9685. );
  9686. const croppingElement = this.scene
  9687. .getNonDeletedElementsMap()
  9688. .get(this.state.croppingElementId);
  9689. if (
  9690. transformHandleType &&
  9691. croppingElement &&
  9692. isImageElement(croppingElement)
  9693. ) {
  9694. const croppingAtStateStart = pointerDownState.originalElements.get(
  9695. croppingElement.id,
  9696. );
  9697. const image =
  9698. isInitializedImageElement(croppingElement) &&
  9699. this.imageCache.get(croppingElement.fileId)?.image;
  9700. if (
  9701. croppingAtStateStart &&
  9702. isImageElement(croppingAtStateStart) &&
  9703. image &&
  9704. !(image instanceof Promise)
  9705. ) {
  9706. const [gridX, gridY] = getGridPoint(
  9707. pointerCoords.x,
  9708. pointerCoords.y,
  9709. event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
  9710. );
  9711. const dragOffset = {
  9712. x: gridX - pointerDownState.originInGrid.x,
  9713. y: gridY - pointerDownState.originInGrid.y,
  9714. };
  9715. this.maybeCacheReferenceSnapPoints(event, [croppingElement]);
  9716. const { snapOffset, snapLines } = snapResizingElements(
  9717. [croppingElement],
  9718. [croppingAtStateStart],
  9719. this,
  9720. event,
  9721. dragOffset,
  9722. transformHandleType,
  9723. );
  9724. this.scene.mutateElement(
  9725. croppingElement,
  9726. cropElement(
  9727. croppingElement,
  9728. this.scene.getNonDeletedElementsMap(),
  9729. transformHandleType,
  9730. image.naturalWidth,
  9731. image.naturalHeight,
  9732. x + snapOffset.x,
  9733. y + snapOffset.y,
  9734. event.shiftKey
  9735. ? croppingAtStateStart.width / croppingAtStateStart.height
  9736. : undefined,
  9737. ),
  9738. );
  9739. updateBoundElements(croppingElement, this.scene, {
  9740. newSize: {
  9741. width: croppingElement.width,
  9742. height: croppingElement.height,
  9743. },
  9744. });
  9745. this.setState({
  9746. isCropping: transformHandleType && transformHandleType !== "rotation",
  9747. snapLines,
  9748. });
  9749. }
  9750. return true;
  9751. }
  9752. return false;
  9753. };
  9754. private maybeHandleResize = (
  9755. pointerDownState: PointerDownState,
  9756. event: MouseEvent | KeyboardEvent,
  9757. ): boolean => {
  9758. const selectedElements = this.scene.getSelectedElements(this.state);
  9759. const selectedFrames = selectedElements.filter(
  9760. (element): element is ExcalidrawFrameLikeElement =>
  9761. isFrameLikeElement(element),
  9762. );
  9763. const transformHandleType = pointerDownState.resize.handleType;
  9764. if (
  9765. // Frames cannot be rotated.
  9766. (selectedFrames.length > 0 && transformHandleType === "rotation") ||
  9767. // Elbow arrows cannot be transformed (resized or rotated).
  9768. (selectedElements.length === 1 && isElbowArrow(selectedElements[0])) ||
  9769. // Do not resize when in crop mode
  9770. this.state.croppingElementId
  9771. ) {
  9772. return false;
  9773. }
  9774. this.setState({
  9775. // TODO: rename this state field to "isScaling" to distinguish
  9776. // it from the generic "isResizing" which includes scaling and
  9777. // rotating
  9778. isResizing: transformHandleType && transformHandleType !== "rotation",
  9779. isRotating: transformHandleType === "rotation",
  9780. activeEmbeddable: null,
  9781. });
  9782. const pointerCoords = pointerDownState.lastCoords;
  9783. let [resizeX, resizeY] = getGridPoint(
  9784. pointerCoords.x - pointerDownState.resize.offset.x,
  9785. pointerCoords.y - pointerDownState.resize.offset.y,
  9786. event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
  9787. );
  9788. const frameElementsOffsetsMap = new Map<
  9789. string,
  9790. {
  9791. x: number;
  9792. y: number;
  9793. }
  9794. >();
  9795. selectedFrames.forEach((frame) => {
  9796. const elementsInFrame = getFrameChildren(
  9797. this.scene.getNonDeletedElements(),
  9798. frame.id,
  9799. );
  9800. elementsInFrame.forEach((element) => {
  9801. frameElementsOffsetsMap.set(frame.id + element.id, {
  9802. x: element.x - frame.x,
  9803. y: element.y - frame.y,
  9804. });
  9805. });
  9806. });
  9807. // check needed for avoiding flickering when a key gets pressed
  9808. // during dragging
  9809. if (!this.state.selectedElementsAreBeingDragged) {
  9810. const [gridX, gridY] = getGridPoint(
  9811. pointerCoords.x,
  9812. pointerCoords.y,
  9813. event[KEYS.CTRL_OR_CMD] ? null : this.getEffectiveGridSize(),
  9814. );
  9815. const dragOffset = {
  9816. x: gridX - pointerDownState.originInGrid.x,
  9817. y: gridY - pointerDownState.originInGrid.y,
  9818. };
  9819. const originalElements = [...pointerDownState.originalElements.values()];
  9820. this.maybeCacheReferenceSnapPoints(event, selectedElements);
  9821. const { snapOffset, snapLines } = snapResizingElements(
  9822. selectedElements,
  9823. getSelectedElements(originalElements, this.state),
  9824. this,
  9825. event,
  9826. dragOffset,
  9827. transformHandleType,
  9828. );
  9829. resizeX += snapOffset.x;
  9830. resizeY += snapOffset.y;
  9831. this.setState({
  9832. snapLines,
  9833. });
  9834. }
  9835. if (
  9836. transformElements(
  9837. pointerDownState.originalElements,
  9838. transformHandleType,
  9839. selectedElements,
  9840. this.scene,
  9841. shouldRotateWithDiscreteAngle(event),
  9842. shouldResizeFromCenter(event),
  9843. selectedElements.some((element) => isImageElement(element))
  9844. ? !shouldMaintainAspectRatio(event)
  9845. : shouldMaintainAspectRatio(event),
  9846. resizeX,
  9847. resizeY,
  9848. pointerDownState.resize.center.x,
  9849. pointerDownState.resize.center.y,
  9850. )
  9851. ) {
  9852. const suggestedBindings = getSuggestedBindingsForArrows(
  9853. selectedElements,
  9854. this.scene.getNonDeletedElementsMap(),
  9855. this.state.zoom,
  9856. );
  9857. const elementsToHighlight = new Set<ExcalidrawElement>();
  9858. selectedFrames.forEach((frame) => {
  9859. getElementsInResizingFrame(
  9860. this.scene.getNonDeletedElements(),
  9861. frame,
  9862. this.state,
  9863. this.scene.getNonDeletedElementsMap(),
  9864. ).forEach((element) => elementsToHighlight.add(element));
  9865. });
  9866. this.setState({
  9867. elementsToHighlight: [...elementsToHighlight],
  9868. suggestedBindings,
  9869. });
  9870. return true;
  9871. }
  9872. return false;
  9873. };
  9874. private getContextMenuItems = (
  9875. type: "canvas" | "element",
  9876. ): ContextMenuItems => {
  9877. const options: ContextMenuItems = [];
  9878. options.push(actionCopyAsPng, actionCopyAsSvg);
  9879. // canvas contextMenu
  9880. // -------------------------------------------------------------------------
  9881. if (type === "canvas") {
  9882. if (this.state.viewModeEnabled) {
  9883. return [
  9884. ...options,
  9885. actionToggleGridMode,
  9886. actionToggleZenMode,
  9887. actionToggleViewMode,
  9888. actionToggleStats,
  9889. ];
  9890. }
  9891. return [
  9892. actionPaste,
  9893. CONTEXT_MENU_SEPARATOR,
  9894. actionCopyAsPng,
  9895. actionCopyAsSvg,
  9896. copyText,
  9897. CONTEXT_MENU_SEPARATOR,
  9898. actionSelectAll,
  9899. actionUnlockAllElements,
  9900. CONTEXT_MENU_SEPARATOR,
  9901. actionToggleGridMode,
  9902. actionToggleObjectsSnapMode,
  9903. actionToggleZenMode,
  9904. actionToggleViewMode,
  9905. actionToggleStats,
  9906. ];
  9907. }
  9908. // element contextMenu
  9909. // -------------------------------------------------------------------------
  9910. options.push(copyText);
  9911. if (this.state.viewModeEnabled) {
  9912. return [actionCopy, ...options];
  9913. }
  9914. return [
  9915. CONTEXT_MENU_SEPARATOR,
  9916. actionCut,
  9917. actionCopy,
  9918. actionPaste,
  9919. CONTEXT_MENU_SEPARATOR,
  9920. actionSelectAllElementsInFrame,
  9921. actionRemoveAllElementsFromFrame,
  9922. actionWrapSelectionInFrame,
  9923. CONTEXT_MENU_SEPARATOR,
  9924. actionToggleCropEditor,
  9925. CONTEXT_MENU_SEPARATOR,
  9926. ...options,
  9927. CONTEXT_MENU_SEPARATOR,
  9928. actionCopyStyles,
  9929. actionPasteStyles,
  9930. CONTEXT_MENU_SEPARATOR,
  9931. actionGroup,
  9932. actionTextAutoResize,
  9933. actionUnbindText,
  9934. actionBindText,
  9935. actionWrapTextInContainer,
  9936. actionUngroup,
  9937. CONTEXT_MENU_SEPARATOR,
  9938. actionAddToLibrary,
  9939. CONTEXT_MENU_SEPARATOR,
  9940. actionSendBackward,
  9941. actionBringForward,
  9942. actionSendToBack,
  9943. actionBringToFront,
  9944. CONTEXT_MENU_SEPARATOR,
  9945. actionFlipHorizontal,
  9946. actionFlipVertical,
  9947. CONTEXT_MENU_SEPARATOR,
  9948. actionToggleLinearEditor,
  9949. CONTEXT_MENU_SEPARATOR,
  9950. actionLink,
  9951. actionCopyElementLink,
  9952. CONTEXT_MENU_SEPARATOR,
  9953. actionDuplicateSelection,
  9954. actionToggleElementLock,
  9955. CONTEXT_MENU_SEPARATOR,
  9956. actionDeleteSelected,
  9957. ];
  9958. };
  9959. private handleWheel = withBatchedUpdates(
  9960. (
  9961. event: WheelEvent | React.WheelEvent<HTMLDivElement | HTMLCanvasElement>,
  9962. ) => {
  9963. // if not scrolling on canvas/wysiwyg, ignore
  9964. if (
  9965. !(
  9966. event.target instanceof HTMLCanvasElement ||
  9967. event.target instanceof HTMLTextAreaElement ||
  9968. event.target instanceof HTMLIFrameElement
  9969. )
  9970. ) {
  9971. // prevent zooming the browser (but allow scrolling DOM)
  9972. if (event[KEYS.CTRL_OR_CMD]) {
  9973. event.preventDefault();
  9974. }
  9975. return;
  9976. }
  9977. event.preventDefault();
  9978. if (isPanning) {
  9979. return;
  9980. }
  9981. const { deltaX, deltaY } = event;
  9982. // note that event.ctrlKey is necessary to handle pinch zooming
  9983. if (event.metaKey || event.ctrlKey) {
  9984. const sign = Math.sign(deltaY);
  9985. const MAX_STEP = ZOOM_STEP * 100;
  9986. const absDelta = Math.abs(deltaY);
  9987. let delta = deltaY;
  9988. if (absDelta > MAX_STEP) {
  9989. delta = MAX_STEP * sign;
  9990. }
  9991. let newZoom = this.state.zoom.value - delta / 100;
  9992. // increase zoom steps the more zoomed-in we are (applies to >100% only)
  9993. newZoom +=
  9994. Math.log10(Math.max(1, this.state.zoom.value)) *
  9995. -sign *
  9996. // reduced amplification for small deltas (small movements on a trackpad)
  9997. Math.min(1, absDelta / 20);
  9998. this.translateCanvas((state) => ({
  9999. ...getStateForZoom(
  10000. {
  10001. viewportX: this.lastViewportPosition.x,
  10002. viewportY: this.lastViewportPosition.y,
  10003. nextZoom: getNormalizedZoom(newZoom),
  10004. },
  10005. state,
  10006. ),
  10007. shouldCacheIgnoreZoom: true,
  10008. }));
  10009. this.resetShouldCacheIgnoreZoomDebounced();
  10010. return;
  10011. }
  10012. // scroll horizontally when shift pressed
  10013. if (event.shiftKey) {
  10014. this.translateCanvas(({ zoom, scrollX }) => ({
  10015. // on Mac, shift+wheel tends to result in deltaX
  10016. scrollX: scrollX - (deltaY || deltaX) / zoom.value,
  10017. }));
  10018. return;
  10019. }
  10020. this.translateCanvas(({ zoom, scrollX, scrollY }) => ({
  10021. scrollX: scrollX - deltaX / zoom.value,
  10022. scrollY: scrollY - deltaY / zoom.value,
  10023. }));
  10024. },
  10025. );
  10026. private getTextWysiwygSnappedToCenterPosition(
  10027. x: number,
  10028. y: number,
  10029. appState: AppState,
  10030. container?: ExcalidrawTextContainer | null,
  10031. ) {
  10032. if (container) {
  10033. let elementCenterX = container.x + container.width / 2;
  10034. let elementCenterY = container.y + container.height / 2;
  10035. const elementCenter = getContainerCenter(
  10036. container,
  10037. appState,
  10038. this.scene.getNonDeletedElementsMap(),
  10039. );
  10040. if (elementCenter) {
  10041. elementCenterX = elementCenter.x;
  10042. elementCenterY = elementCenter.y;
  10043. }
  10044. const distanceToCenter = Math.hypot(
  10045. x - elementCenterX,
  10046. y - elementCenterY,
  10047. );
  10048. const isSnappedToCenter =
  10049. distanceToCenter < TEXT_TO_CENTER_SNAP_THRESHOLD;
  10050. if (isSnappedToCenter) {
  10051. const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
  10052. { sceneX: elementCenterX, sceneY: elementCenterY },
  10053. appState,
  10054. );
  10055. return { viewportX, viewportY, elementCenterX, elementCenterY };
  10056. }
  10057. }
  10058. }
  10059. private savePointer = (x: number, y: number, button: "up" | "down") => {
  10060. if (!x || !y) {
  10061. return;
  10062. }
  10063. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  10064. { clientX: x, clientY: y },
  10065. this.state,
  10066. );
  10067. if (isNaN(sceneX) || isNaN(sceneY)) {
  10068. // sometimes the pointer goes off screen
  10069. }
  10070. const pointer: CollaboratorPointer = {
  10071. x: sceneX,
  10072. y: sceneY,
  10073. tool: this.state.activeTool.type === "laser" ? "laser" : "pointer",
  10074. };
  10075. this.props.onPointerUpdate?.({
  10076. pointer,
  10077. button,
  10078. pointersMap: gesture.pointers,
  10079. });
  10080. };
  10081. private resetShouldCacheIgnoreZoomDebounced = debounce(() => {
  10082. if (!this.unmounted) {
  10083. this.setState({ shouldCacheIgnoreZoom: false });
  10084. }
  10085. }, 300);
  10086. private updateDOMRect = (cb?: () => void) => {
  10087. if (this.excalidrawContainerRef?.current) {
  10088. const excalidrawContainer = this.excalidrawContainerRef.current;
  10089. const {
  10090. width,
  10091. height,
  10092. left: offsetLeft,
  10093. top: offsetTop,
  10094. } = excalidrawContainer.getBoundingClientRect();
  10095. const {
  10096. width: currentWidth,
  10097. height: currentHeight,
  10098. offsetTop: currentOffsetTop,
  10099. offsetLeft: currentOffsetLeft,
  10100. } = this.state;
  10101. if (
  10102. width === currentWidth &&
  10103. height === currentHeight &&
  10104. offsetLeft === currentOffsetLeft &&
  10105. offsetTop === currentOffsetTop
  10106. ) {
  10107. if (cb) {
  10108. cb();
  10109. }
  10110. return;
  10111. }
  10112. this.setState(
  10113. {
  10114. width,
  10115. height,
  10116. offsetLeft,
  10117. offsetTop,
  10118. },
  10119. () => {
  10120. cb && cb();
  10121. },
  10122. );
  10123. }
  10124. };
  10125. public refresh = () => {
  10126. this.setState({ ...this.getCanvasOffsets() });
  10127. };
  10128. private getCanvasOffsets(): Pick<AppState, "offsetTop" | "offsetLeft"> {
  10129. if (this.excalidrawContainerRef?.current) {
  10130. const excalidrawContainer = this.excalidrawContainerRef.current;
  10131. const { left, top } = excalidrawContainer.getBoundingClientRect();
  10132. return {
  10133. offsetLeft: left,
  10134. offsetTop: top,
  10135. };
  10136. }
  10137. return {
  10138. offsetLeft: 0,
  10139. offsetTop: 0,
  10140. };
  10141. }
  10142. private async updateLanguage() {
  10143. const currentLang =
  10144. languages.find((lang) => lang.code === this.props.langCode) ||
  10145. defaultLang;
  10146. await setLanguage(currentLang);
  10147. this.setAppState({});
  10148. }
  10149. }
  10150. // -----------------------------------------------------------------------------
  10151. // TEST HOOKS
  10152. // -----------------------------------------------------------------------------
  10153. declare global {
  10154. interface Window {
  10155. h: {
  10156. scene: Scene;
  10157. elements: readonly ExcalidrawElement[];
  10158. state: AppState;
  10159. setState: React.Component<any, AppState>["setState"];
  10160. app: InstanceType<typeof App>;
  10161. history: History;
  10162. store: Store;
  10163. };
  10164. }
  10165. }
  10166. export const createTestHook = () => {
  10167. if (isTestEnv() || isDevEnv()) {
  10168. window.h = window.h || ({} as Window["h"]);
  10169. Object.defineProperties(window.h, {
  10170. elements: {
  10171. configurable: true,
  10172. get() {
  10173. return this.app?.scene.getElementsIncludingDeleted();
  10174. },
  10175. set(elements: ExcalidrawElement[]) {
  10176. return this.app?.scene.replaceAllElements(
  10177. syncInvalidIndices(elements),
  10178. );
  10179. },
  10180. },
  10181. scene: {
  10182. configurable: true,
  10183. get() {
  10184. return this.app?.scene;
  10185. },
  10186. },
  10187. });
  10188. }
  10189. };
  10190. createTestHook();
  10191. export default App;