App.tsx 192 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312
  1. import React, { useContext } from "react";
  2. import { flushSync } from "react-dom";
  3. import { RoughCanvas } from "roughjs/bin/canvas";
  4. import rough from "roughjs/bin/rough";
  5. import clsx from "clsx";
  6. import { nanoid } from "nanoid";
  7. import {
  8. actionAddToLibrary,
  9. actionBringForward,
  10. actionBringToFront,
  11. actionCopy,
  12. actionCopyAsPng,
  13. actionCopyAsSvg,
  14. copyText,
  15. actionCopyStyles,
  16. actionCut,
  17. actionDeleteSelected,
  18. actionDuplicateSelection,
  19. actionFinalize,
  20. actionFlipHorizontal,
  21. actionFlipVertical,
  22. actionGroup,
  23. actionPasteStyles,
  24. actionSelectAll,
  25. actionSendBackward,
  26. actionSendToBack,
  27. actionToggleGridMode,
  28. actionToggleStats,
  29. actionToggleZenMode,
  30. actionUnbindText,
  31. actionBindText,
  32. actionUngroup,
  33. actionLink,
  34. actionToggleLock,
  35. actionToggleLinearEditor,
  36. } from "../actions";
  37. import { createRedoAction, createUndoAction } from "../actions/actionHistory";
  38. import { ActionManager } from "../actions/manager";
  39. import { actions } from "../actions/register";
  40. import { ActionResult } from "../actions/types";
  41. import { trackEvent } from "../analytics";
  42. import { getDefaultAppState, isEraserActive } from "../appState";
  43. import {
  44. parseClipboard,
  45. probablySupportsClipboardBlob,
  46. probablySupportsClipboardWriteText,
  47. } from "../clipboard";
  48. import {
  49. APP_NAME,
  50. CURSOR_TYPE,
  51. DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
  52. DEFAULT_UI_OPTIONS,
  53. DEFAULT_VERTICAL_ALIGN,
  54. DRAGGING_THRESHOLD,
  55. ELEMENT_READY_TO_ERASE_OPACITY,
  56. ELEMENT_SHIFT_TRANSLATE_AMOUNT,
  57. ELEMENT_TRANSLATE_AMOUNT,
  58. ENV,
  59. EVENT,
  60. GRID_SIZE,
  61. IMAGE_RENDER_TIMEOUT,
  62. LINE_CONFIRM_THRESHOLD,
  63. MAX_ALLOWED_FILE_BYTES,
  64. MIME_TYPES,
  65. MQ_MAX_HEIGHT_LANDSCAPE,
  66. MQ_MAX_WIDTH_LANDSCAPE,
  67. MQ_MAX_WIDTH_PORTRAIT,
  68. MQ_RIGHT_SIDEBAR_MIN_WIDTH,
  69. MQ_SM_MAX_WIDTH,
  70. POINTER_BUTTON,
  71. SCROLL_TIMEOUT,
  72. TAP_TWICE_TIMEOUT,
  73. TEXT_TO_CENTER_SNAP_THRESHOLD,
  74. THEME,
  75. TOUCH_CTX_MENU_TIMEOUT,
  76. VERTICAL_ALIGN,
  77. ZOOM_STEP,
  78. } from "../constants";
  79. import { loadFromBlob } from "../data";
  80. import Library, { distributeLibraryItemsOnSquareGrid } from "../data/library";
  81. import { restore, restoreElements } from "../data/restore";
  82. import {
  83. dragNewElement,
  84. dragSelectedElements,
  85. duplicateElement,
  86. getCommonBounds,
  87. getCursorForResizingElement,
  88. getDragOffsetXY,
  89. getElementWithTransformHandleType,
  90. getNormalizedDimensions,
  91. getResizeArrowDirection,
  92. getResizeOffsetXY,
  93. getLockedLinearCursorAlignSize,
  94. getTransformHandleTypeFromCoords,
  95. hitTest,
  96. isHittingElementBoundingBoxWithoutHittingElement,
  97. isInvisiblySmallElement,
  98. isNonDeletedElement,
  99. isTextElement,
  100. newElement,
  101. newLinearElement,
  102. newTextElement,
  103. newImageElement,
  104. textWysiwyg,
  105. transformElements,
  106. updateTextElement,
  107. } from "../element";
  108. import {
  109. bindOrUnbindLinearElement,
  110. bindOrUnbindSelectedElements,
  111. fixBindingsAfterDeletion,
  112. fixBindingsAfterDuplication,
  113. getEligibleElementsForBinding,
  114. getHoveredElementForBinding,
  115. isBindingEnabled,
  116. isLinearElementSimpleAndAlreadyBound,
  117. maybeBindLinearElement,
  118. shouldEnableBindingForPointerEvent,
  119. unbindLinearElements,
  120. updateBoundElements,
  121. } from "../element/binding";
  122. import { LinearElementEditor } from "../element/linearElementEditor";
  123. import { mutateElement, newElementWith } from "../element/mutateElement";
  124. import { deepCopyElement, newFreeDrawElement } from "../element/newElement";
  125. import {
  126. hasBoundTextElement,
  127. isBindingElement,
  128. isBindingElementType,
  129. isBoundToContainer,
  130. isImageElement,
  131. isInitializedImageElement,
  132. isLinearElement,
  133. isLinearElementType,
  134. isTextBindableContainer,
  135. } from "../element/typeChecks";
  136. import {
  137. ExcalidrawBindableElement,
  138. ExcalidrawElement,
  139. ExcalidrawFreeDrawElement,
  140. ExcalidrawGenericElement,
  141. ExcalidrawLinearElement,
  142. ExcalidrawTextElement,
  143. NonDeleted,
  144. InitializedExcalidrawImageElement,
  145. ExcalidrawImageElement,
  146. FileId,
  147. NonDeletedExcalidrawElement,
  148. ExcalidrawTextContainer,
  149. } from "../element/types";
  150. import { getCenter, getDistance } from "../gesture";
  151. import {
  152. editGroupForSelectedElement,
  153. getElementsInGroup,
  154. getSelectedGroupIdForElement,
  155. getSelectedGroupIds,
  156. isElementInGroup,
  157. isSelectedViaGroup,
  158. selectGroupsForSelectedElements,
  159. } from "../groups";
  160. import History from "../history";
  161. import { defaultLang, getLanguage, languages, setLanguage, t } from "../i18n";
  162. import {
  163. CODES,
  164. shouldResizeFromCenter,
  165. shouldMaintainAspectRatio,
  166. shouldRotateWithDiscreteAngle,
  167. isArrowKey,
  168. KEYS,
  169. isAndroid,
  170. } from "../keys";
  171. import { distance2d, getGridPoint, isPathALoop } from "../math";
  172. import { renderScene } from "../renderer/renderScene";
  173. import { invalidateShapeForElement } from "../renderer/renderElement";
  174. import {
  175. calculateScrollCenter,
  176. getTextBindableContainerAtPosition,
  177. getElementsAtPosition,
  178. getElementsWithinSelection,
  179. getNormalizedZoom,
  180. getSelectedElements,
  181. hasBackground,
  182. isOverScrollBars,
  183. isSomeElementSelected,
  184. } from "../scene";
  185. import Scene from "../scene/Scene";
  186. import { RenderConfig, ScrollBars } from "../scene/types";
  187. import { getStateForZoom } from "../scene/zoom";
  188. import { findShapeByKey, SHAPES } from "../shapes";
  189. import {
  190. AppClassProperties,
  191. AppProps,
  192. AppState,
  193. BinaryFileData,
  194. DataURL,
  195. ExcalidrawImperativeAPI,
  196. BinaryFiles,
  197. Gesture,
  198. GestureEvent,
  199. LibraryItems,
  200. PointerDownState,
  201. SceneData,
  202. Device,
  203. } from "../types";
  204. import {
  205. debounce,
  206. distance,
  207. getFontString,
  208. getNearestScrollableContainer,
  209. isInputLike,
  210. isToolIcon,
  211. isWritableElement,
  212. resetCursor,
  213. resolvablePromise,
  214. sceneCoordsToViewportCoords,
  215. setCursor,
  216. setCursorForShape,
  217. tupleToCoors,
  218. viewportCoordsToSceneCoords,
  219. withBatchedUpdates,
  220. wrapEvent,
  221. withBatchedUpdatesThrottled,
  222. updateObject,
  223. setEraserCursor,
  224. updateActiveTool,
  225. } from "../utils";
  226. import ContextMenu, { ContextMenuOption } from "./ContextMenu";
  227. import LayerUI from "./LayerUI";
  228. import { Toast } from "./Toast";
  229. import { actionToggleViewMode } from "../actions/actionToggleViewMode";
  230. import {
  231. dataURLToFile,
  232. generateIdFromFile,
  233. getDataURL,
  234. getFileFromEvent,
  235. isSupportedImageFile,
  236. loadSceneOrLibraryFromBlob,
  237. normalizeFile,
  238. parseLibraryJSON,
  239. resizeImageFile,
  240. SVGStringToFile,
  241. } from "../data/blob";
  242. import {
  243. getInitializedImageElements,
  244. loadHTMLImageElement,
  245. normalizeSVG,
  246. updateImageCache as _updateImageCache,
  247. } from "../element/image";
  248. import throttle from "lodash.throttle";
  249. import { fileOpen, FileSystemHandle } from "../data/filesystem";
  250. import {
  251. bindTextToShapeAfterDuplication,
  252. getApproxMinLineHeight,
  253. getApproxMinLineWidth,
  254. getBoundTextElement,
  255. getContainerDims,
  256. } from "../element/textElement";
  257. import { isHittingElementNotConsideringBoundingBox } from "../element/collision";
  258. import {
  259. normalizeLink,
  260. showHyperlinkTooltip,
  261. hideHyperlinkToolip,
  262. Hyperlink,
  263. isPointHittingLinkIcon,
  264. isLocalLink,
  265. } from "../element/Hyperlink";
  266. import { shouldShowBoundingBox } from "../element/transformHandles";
  267. const deviceContextInitialValue = {
  268. isSmScreen: false,
  269. isMobile: false,
  270. isTouchScreen: false,
  271. canDeviceFitSidebar: false,
  272. };
  273. const DeviceContext = React.createContext<Device>(deviceContextInitialValue);
  274. export const useDevice = () => useContext<Device>(DeviceContext);
  275. const ExcalidrawContainerContext = React.createContext<{
  276. container: HTMLDivElement | null;
  277. id: string | null;
  278. }>({ container: null, id: null });
  279. export const useExcalidrawContainer = () =>
  280. useContext(ExcalidrawContainerContext);
  281. const ExcalidrawElementsContext = React.createContext<
  282. readonly NonDeletedExcalidrawElement[]
  283. >([]);
  284. const ExcalidrawAppStateContext = React.createContext<AppState>({
  285. ...getDefaultAppState(),
  286. width: 0,
  287. height: 0,
  288. offsetLeft: 0,
  289. offsetTop: 0,
  290. });
  291. const ExcalidrawSetAppStateContent = React.createContext<
  292. React.Component<any, AppState>["setState"]
  293. >(() => {});
  294. export const useExcalidrawElements = () =>
  295. useContext(ExcalidrawElementsContext);
  296. export const useExcalidrawAppState = () =>
  297. useContext(ExcalidrawAppStateContext);
  298. export const useExcalidrawSetAppState = () =>
  299. useContext(ExcalidrawSetAppStateContent);
  300. let didTapTwice: boolean = false;
  301. let tappedTwiceTimer = 0;
  302. let cursorX = 0;
  303. let cursorY = 0;
  304. let isHoldingSpace: boolean = false;
  305. let isPanning: boolean = false;
  306. let isDraggingScrollBar: boolean = false;
  307. let currentScrollBars: ScrollBars = { horizontal: null, vertical: null };
  308. let touchTimeout = 0;
  309. let invalidateContextMenu = false;
  310. // remove this hack when we can sync render & resizeObserver (state update)
  311. // to rAF. See #5439
  312. let THROTTLE_NEXT_RENDER = true;
  313. let lastPointerUp: ((event: any) => void) | null = null;
  314. const gesture: Gesture = {
  315. pointers: new Map(),
  316. lastCenter: null,
  317. initialDistance: null,
  318. initialScale: null,
  319. };
  320. class App extends React.Component<AppProps, AppState> {
  321. canvas: AppClassProperties["canvas"] = null;
  322. rc: RoughCanvas | null = null;
  323. unmounted: boolean = false;
  324. actionManager: ActionManager;
  325. device: Device = deviceContextInitialValue;
  326. detachIsMobileMqHandler?: () => void;
  327. private excalidrawContainerRef = React.createRef<HTMLDivElement>();
  328. public static defaultProps: Partial<AppProps> = {
  329. // needed for tests to pass since we directly render App in many tests
  330. UIOptions: DEFAULT_UI_OPTIONS,
  331. };
  332. public scene: Scene;
  333. private resizeObserver: ResizeObserver | undefined;
  334. private nearestScrollableContainer: HTMLElement | Document | undefined;
  335. public library: AppClassProperties["library"];
  336. public libraryItemsFromStorage: LibraryItems | undefined;
  337. private id: string;
  338. private history: History;
  339. private excalidrawContainerValue: {
  340. container: HTMLDivElement | null;
  341. id: string;
  342. };
  343. public files: BinaryFiles = {};
  344. public imageCache: AppClassProperties["imageCache"] = new Map();
  345. hitLinkElement?: NonDeletedExcalidrawElement;
  346. lastPointerDown: React.PointerEvent<HTMLCanvasElement> | null = null;
  347. lastPointerUp: React.PointerEvent<HTMLElement> | PointerEvent | null = null;
  348. contextMenuOpen: boolean = false;
  349. lastScenePointer: { x: number; y: number } | null = null;
  350. constructor(props: AppProps) {
  351. super(props);
  352. const defaultAppState = getDefaultAppState();
  353. const {
  354. excalidrawRef,
  355. viewModeEnabled = false,
  356. zenModeEnabled = false,
  357. gridModeEnabled = false,
  358. theme = defaultAppState.theme,
  359. name = defaultAppState.name,
  360. } = props;
  361. this.state = {
  362. ...defaultAppState,
  363. theme,
  364. isLoading: true,
  365. ...this.getCanvasOffsets(),
  366. viewModeEnabled,
  367. zenModeEnabled,
  368. gridSize: gridModeEnabled ? GRID_SIZE : null,
  369. name,
  370. width: window.innerWidth,
  371. height: window.innerHeight,
  372. showHyperlinkPopup: false,
  373. isSidebarDocked: false,
  374. };
  375. this.id = nanoid();
  376. this.library = new Library(this);
  377. if (excalidrawRef) {
  378. const readyPromise =
  379. ("current" in excalidrawRef && excalidrawRef.current?.readyPromise) ||
  380. resolvablePromise<ExcalidrawImperativeAPI>();
  381. const api: ExcalidrawImperativeAPI = {
  382. ready: true,
  383. readyPromise,
  384. updateScene: this.updateScene,
  385. updateLibrary: this.library.updateLibrary,
  386. addFiles: this.addFiles,
  387. resetScene: this.resetScene,
  388. getSceneElementsIncludingDeleted: this.getSceneElementsIncludingDeleted,
  389. history: {
  390. clear: this.resetHistory,
  391. },
  392. scrollToContent: this.scrollToContent,
  393. getSceneElements: this.getSceneElements,
  394. getAppState: () => this.state,
  395. getFiles: () => this.files,
  396. refresh: this.refresh,
  397. setToast: this.setToast,
  398. id: this.id,
  399. setActiveTool: this.setActiveTool,
  400. setCursor: this.setCursor,
  401. resetCursor: this.resetCursor,
  402. toggleMenu: this.toggleMenu,
  403. } as const;
  404. if (typeof excalidrawRef === "function") {
  405. excalidrawRef(api);
  406. } else {
  407. excalidrawRef.current = api;
  408. }
  409. readyPromise.resolve(api);
  410. }
  411. this.excalidrawContainerValue = {
  412. container: this.excalidrawContainerRef.current,
  413. id: this.id,
  414. };
  415. this.scene = new Scene();
  416. this.history = new History();
  417. this.actionManager = new ActionManager(
  418. this.syncActionResult,
  419. () => this.state,
  420. () => this.scene.getElementsIncludingDeleted(),
  421. this,
  422. );
  423. this.actionManager.registerAll(actions);
  424. this.actionManager.registerAction(createUndoAction(this.history));
  425. this.actionManager.registerAction(createRedoAction(this.history));
  426. }
  427. private renderCanvas() {
  428. const canvasScale = window.devicePixelRatio;
  429. const {
  430. width: canvasDOMWidth,
  431. height: canvasDOMHeight,
  432. viewModeEnabled,
  433. } = this.state;
  434. const canvasWidth = canvasDOMWidth * canvasScale;
  435. const canvasHeight = canvasDOMHeight * canvasScale;
  436. if (viewModeEnabled) {
  437. return (
  438. <canvas
  439. className="excalidraw__canvas"
  440. style={{
  441. width: canvasDOMWidth,
  442. height: canvasDOMHeight,
  443. cursor: CURSOR_TYPE.GRAB,
  444. }}
  445. width={canvasWidth}
  446. height={canvasHeight}
  447. ref={this.handleCanvasRef}
  448. onContextMenu={this.handleCanvasContextMenu}
  449. onPointerMove={this.handleCanvasPointerMove}
  450. onPointerUp={this.handleCanvasPointerUp}
  451. onPointerCancel={this.removePointer}
  452. onTouchMove={this.handleTouchMove}
  453. onPointerDown={this.handleCanvasPointerDown}
  454. >
  455. {t("labels.drawingCanvas")}
  456. </canvas>
  457. );
  458. }
  459. return (
  460. <canvas
  461. className="excalidraw__canvas"
  462. style={{
  463. width: canvasDOMWidth,
  464. height: canvasDOMHeight,
  465. }}
  466. width={canvasWidth}
  467. height={canvasHeight}
  468. ref={this.handleCanvasRef}
  469. onContextMenu={this.handleCanvasContextMenu}
  470. onPointerDown={this.handleCanvasPointerDown}
  471. onDoubleClick={this.handleCanvasDoubleClick}
  472. onPointerMove={this.handleCanvasPointerMove}
  473. onPointerUp={this.handleCanvasPointerUp}
  474. onPointerCancel={this.removePointer}
  475. onTouchMove={this.handleTouchMove}
  476. >
  477. {t("labels.drawingCanvas")}
  478. </canvas>
  479. );
  480. }
  481. public render() {
  482. const selectedElement = getSelectedElements(
  483. this.scene.getNonDeletedElements(),
  484. this.state,
  485. );
  486. const {
  487. onCollabButtonClick,
  488. renderTopRightUI,
  489. renderFooter,
  490. renderCustomStats,
  491. } = this.props;
  492. return (
  493. <div
  494. className={clsx("excalidraw excalidraw-container", {
  495. "excalidraw--view-mode": this.state.viewModeEnabled,
  496. "excalidraw--mobile": this.device.isMobile,
  497. })}
  498. ref={this.excalidrawContainerRef}
  499. onDrop={this.handleAppOnDrop}
  500. tabIndex={0}
  501. onKeyDown={
  502. this.props.handleKeyboardGlobally ? undefined : this.onKeyDown
  503. }
  504. >
  505. <ExcalidrawContainerContext.Provider
  506. value={this.excalidrawContainerValue}
  507. >
  508. <DeviceContext.Provider value={this.device}>
  509. <ExcalidrawSetAppStateContent.Provider value={this.setAppState}>
  510. <ExcalidrawAppStateContext.Provider value={this.state}>
  511. <ExcalidrawElementsContext.Provider
  512. value={this.scene.getNonDeletedElements()}
  513. >
  514. <LayerUI
  515. canvas={this.canvas}
  516. appState={this.state}
  517. files={this.files}
  518. setAppState={this.setAppState}
  519. actionManager={this.actionManager}
  520. elements={this.scene.getNonDeletedElements()}
  521. onCollabButtonClick={onCollabButtonClick}
  522. onLockToggle={this.toggleLock}
  523. onPenModeToggle={this.togglePenMode}
  524. onInsertElements={(elements) =>
  525. this.addElementsFromPasteOrLibrary({
  526. elements,
  527. position: "center",
  528. files: null,
  529. })
  530. }
  531. langCode={getLanguage().code}
  532. isCollaborating={this.props.isCollaborating}
  533. renderTopRightUI={renderTopRightUI}
  534. renderCustomFooter={renderFooter}
  535. renderCustomStats={renderCustomStats}
  536. renderCustomSidebar={this.props.renderSidebar}
  537. showExitZenModeBtn={
  538. typeof this.props?.zenModeEnabled === "undefined" &&
  539. this.state.zenModeEnabled
  540. }
  541. libraryReturnUrl={this.props.libraryReturnUrl}
  542. UIOptions={this.props.UIOptions}
  543. focusContainer={this.focusContainer}
  544. library={this.library}
  545. id={this.id}
  546. onImageAction={this.onImageAction}
  547. />
  548. <div className="excalidraw-textEditorContainer" />
  549. <div className="excalidraw-contextMenuContainer" />
  550. {selectedElement.length === 1 &&
  551. this.state.showHyperlinkPopup && (
  552. <Hyperlink
  553. key={selectedElement[0].id}
  554. element={selectedElement[0]}
  555. setAppState={this.setAppState}
  556. onLinkOpen={this.props.onLinkOpen}
  557. />
  558. )}
  559. {this.state.toast !== null && (
  560. <Toast
  561. message={this.state.toast.message}
  562. onClose={() => this.setToast(null)}
  563. duration={this.state.toast.duration}
  564. closable={this.state.toast.closable}
  565. />
  566. )}
  567. <main>{this.renderCanvas()}</main>
  568. </ExcalidrawElementsContext.Provider>{" "}
  569. </ExcalidrawAppStateContext.Provider>
  570. </ExcalidrawSetAppStateContent.Provider>
  571. </DeviceContext.Provider>
  572. </ExcalidrawContainerContext.Provider>
  573. </div>
  574. );
  575. }
  576. public focusContainer: AppClassProperties["focusContainer"] = () => {
  577. if (this.props.autoFocus) {
  578. this.excalidrawContainerRef.current?.focus();
  579. }
  580. };
  581. public getSceneElementsIncludingDeleted = () => {
  582. return this.scene.getElementsIncludingDeleted();
  583. };
  584. public getSceneElements = () => {
  585. return this.scene.getNonDeletedElements();
  586. };
  587. private syncActionResult = withBatchedUpdates(
  588. (actionResult: ActionResult) => {
  589. // Since context menu closes when action triggered so setting to false
  590. this.contextMenuOpen = false;
  591. if (this.unmounted || actionResult === false) {
  592. return;
  593. }
  594. let editingElement: AppState["editingElement"] | null = null;
  595. if (actionResult.elements) {
  596. actionResult.elements.forEach((element) => {
  597. if (
  598. this.state.editingElement?.id === element.id &&
  599. this.state.editingElement !== element &&
  600. isNonDeletedElement(element)
  601. ) {
  602. editingElement = element;
  603. }
  604. });
  605. this.scene.replaceAllElements(actionResult.elements);
  606. if (actionResult.commitToHistory) {
  607. this.history.resumeRecording();
  608. }
  609. }
  610. if (actionResult.files) {
  611. this.files = actionResult.replaceFiles
  612. ? actionResult.files
  613. : { ...this.files, ...actionResult.files };
  614. this.addNewImagesToImageCache();
  615. }
  616. if (actionResult.appState || editingElement) {
  617. if (actionResult.commitToHistory) {
  618. this.history.resumeRecording();
  619. }
  620. let viewModeEnabled = actionResult?.appState?.viewModeEnabled || false;
  621. let zenModeEnabled = actionResult?.appState?.zenModeEnabled || false;
  622. let gridSize = actionResult?.appState?.gridSize || null;
  623. const theme =
  624. actionResult?.appState?.theme || this.props.theme || THEME.LIGHT;
  625. let name = actionResult?.appState?.name ?? this.state.name;
  626. if (typeof this.props.viewModeEnabled !== "undefined") {
  627. viewModeEnabled = this.props.viewModeEnabled;
  628. }
  629. if (typeof this.props.zenModeEnabled !== "undefined") {
  630. zenModeEnabled = this.props.zenModeEnabled;
  631. }
  632. if (typeof this.props.gridModeEnabled !== "undefined") {
  633. gridSize = this.props.gridModeEnabled ? GRID_SIZE : null;
  634. }
  635. if (typeof this.props.name !== "undefined") {
  636. name = this.props.name;
  637. }
  638. this.setState(
  639. (state) => {
  640. // using Object.assign instead of spread to fool TS 4.2.2+ into
  641. // regarding the resulting type as not containing undefined
  642. // (which the following expression will never contain)
  643. return Object.assign(actionResult.appState || {}, {
  644. editingElement:
  645. editingElement || actionResult.appState?.editingElement || null,
  646. viewModeEnabled,
  647. zenModeEnabled,
  648. gridSize,
  649. theme,
  650. name,
  651. });
  652. },
  653. () => {
  654. if (actionResult.syncHistory) {
  655. this.history.setCurrentState(
  656. this.state,
  657. this.scene.getElementsIncludingDeleted(),
  658. );
  659. }
  660. },
  661. );
  662. }
  663. },
  664. );
  665. // Lifecycle
  666. private onBlur = withBatchedUpdates(() => {
  667. isHoldingSpace = false;
  668. this.setState({ isBindingEnabled: true });
  669. });
  670. private onUnload = () => {
  671. this.onBlur();
  672. };
  673. private disableEvent: EventListener = (event) => {
  674. event.preventDefault();
  675. };
  676. private onFontLoaded = () => {
  677. this.scene.getElementsIncludingDeleted().forEach((element) => {
  678. if (isTextElement(element)) {
  679. invalidateShapeForElement(element);
  680. }
  681. });
  682. this.onSceneUpdated();
  683. };
  684. private resetHistory = () => {
  685. this.history.clear();
  686. };
  687. /**
  688. * Resets scene & history.
  689. * ! Do not use to clear scene user action !
  690. */
  691. private resetScene = withBatchedUpdates(
  692. (opts?: { resetLoadingState: boolean }) => {
  693. this.scene.replaceAllElements([]);
  694. this.setState((state) => ({
  695. ...getDefaultAppState(),
  696. isLoading: opts?.resetLoadingState ? false : state.isLoading,
  697. theme: this.state.theme,
  698. }));
  699. this.resetHistory();
  700. },
  701. );
  702. private initializeScene = async () => {
  703. if ("launchQueue" in window && "LaunchParams" in window) {
  704. (window as any).launchQueue.setConsumer(
  705. async (launchParams: { files: any[] }) => {
  706. if (!launchParams.files.length) {
  707. return;
  708. }
  709. const fileHandle = launchParams.files[0];
  710. const blob: Blob = await fileHandle.getFile();
  711. this.loadFileToCanvas(
  712. new File([blob], blob.name || "", { type: blob.type }),
  713. fileHandle,
  714. );
  715. },
  716. );
  717. }
  718. if (this.props.theme) {
  719. this.setState({ theme: this.props.theme });
  720. }
  721. if (!this.state.isLoading) {
  722. this.setState({ isLoading: true });
  723. }
  724. let initialData = null;
  725. try {
  726. initialData = (await this.props.initialData) || null;
  727. if (initialData?.libraryItems) {
  728. this.library
  729. .updateLibrary({
  730. libraryItems: initialData.libraryItems,
  731. merge: true,
  732. })
  733. .catch((error) => {
  734. console.error(error);
  735. });
  736. }
  737. } catch (error: any) {
  738. console.error(error);
  739. initialData = {
  740. appState: {
  741. errorMessage:
  742. error.message ||
  743. "Encountered an error during importing or restoring scene data",
  744. },
  745. };
  746. }
  747. const scene = restore(initialData, null, null);
  748. scene.appState = {
  749. ...scene.appState,
  750. theme: this.props.theme || scene.appState.theme,
  751. // we're falling back to current (pre-init) state when deciding
  752. // whether to open the library, to handle a case where we
  753. // update the state outside of initialData (e.g. when loading the app
  754. // with a library install link, which should auto-open the library)
  755. openSidebar: scene.appState?.openSidebar || this.state.openSidebar,
  756. activeTool:
  757. scene.appState.activeTool.type === "image"
  758. ? { ...scene.appState.activeTool, type: "selection" }
  759. : scene.appState.activeTool,
  760. isLoading: false,
  761. toast: this.state.toast,
  762. };
  763. if (initialData?.scrollToContent) {
  764. scene.appState = {
  765. ...scene.appState,
  766. ...calculateScrollCenter(
  767. scene.elements,
  768. {
  769. ...scene.appState,
  770. width: this.state.width,
  771. height: this.state.height,
  772. offsetTop: this.state.offsetTop,
  773. offsetLeft: this.state.offsetLeft,
  774. },
  775. null,
  776. ),
  777. };
  778. }
  779. this.resetHistory();
  780. this.syncActionResult({
  781. ...scene,
  782. commitToHistory: true,
  783. });
  784. };
  785. private refreshDeviceState = (container: HTMLDivElement) => {
  786. const { width, height } = container.getBoundingClientRect();
  787. const sidebarBreakpoint =
  788. this.props.UIOptions.dockedSidebarBreakpoint != null
  789. ? this.props.UIOptions.dockedSidebarBreakpoint
  790. : MQ_RIGHT_SIDEBAR_MIN_WIDTH;
  791. this.device = updateObject(this.device, {
  792. isSmScreen: width < MQ_SM_MAX_WIDTH,
  793. isMobile:
  794. width < MQ_MAX_WIDTH_PORTRAIT ||
  795. (height < MQ_MAX_HEIGHT_LANDSCAPE && width < MQ_MAX_WIDTH_LANDSCAPE),
  796. canDeviceFitSidebar: width > sidebarBreakpoint,
  797. });
  798. };
  799. public async componentDidMount() {
  800. this.unmounted = false;
  801. this.excalidrawContainerValue.container =
  802. this.excalidrawContainerRef.current;
  803. if (
  804. process.env.NODE_ENV === ENV.TEST ||
  805. process.env.NODE_ENV === ENV.DEVELOPMENT
  806. ) {
  807. const setState = this.setState.bind(this);
  808. Object.defineProperties(window.h, {
  809. state: {
  810. configurable: true,
  811. get: () => {
  812. return this.state;
  813. },
  814. },
  815. setState: {
  816. configurable: true,
  817. value: (...args: Parameters<typeof setState>) => {
  818. return this.setState(...args);
  819. },
  820. },
  821. app: {
  822. configurable: true,
  823. value: this,
  824. },
  825. history: {
  826. configurable: true,
  827. value: this.history,
  828. },
  829. });
  830. }
  831. this.scene.addCallback(this.onSceneUpdated);
  832. this.addEventListeners();
  833. if (this.excalidrawContainerRef.current) {
  834. this.focusContainer();
  835. }
  836. if (
  837. this.excalidrawContainerRef.current &&
  838. // bounding rects don't work in tests so updating
  839. // the state on init would result in making the test enviro run
  840. // in mobile breakpoint (0 width/height), making everything fail
  841. process.env.NODE_ENV !== "test"
  842. ) {
  843. this.refreshDeviceState(this.excalidrawContainerRef.current);
  844. }
  845. if ("ResizeObserver" in window && this.excalidrawContainerRef?.current) {
  846. this.resizeObserver = new ResizeObserver(() => {
  847. THROTTLE_NEXT_RENDER = false;
  848. // recompute device dimensions state
  849. // ---------------------------------------------------------------------
  850. this.refreshDeviceState(this.excalidrawContainerRef.current!);
  851. // refresh offsets
  852. // ---------------------------------------------------------------------
  853. this.updateDOMRect();
  854. });
  855. this.resizeObserver?.observe(this.excalidrawContainerRef.current);
  856. } else if (window.matchMedia) {
  857. const mdScreenQuery = window.matchMedia(
  858. `(max-width: ${MQ_MAX_WIDTH_PORTRAIT}px), (max-height: ${MQ_MAX_HEIGHT_LANDSCAPE}px) and (max-width: ${MQ_MAX_WIDTH_LANDSCAPE}px)`,
  859. );
  860. const smScreenQuery = window.matchMedia(
  861. `(max-width: ${MQ_SM_MAX_WIDTH}px)`,
  862. );
  863. const canDeviceFitSidebarMediaQuery = window.matchMedia(
  864. `(min-width: ${
  865. // NOTE this won't update if a different breakpoint is supplied
  866. // after mount
  867. this.props.UIOptions.dockedSidebarBreakpoint != null
  868. ? this.props.UIOptions.dockedSidebarBreakpoint
  869. : MQ_RIGHT_SIDEBAR_MIN_WIDTH
  870. }px)`,
  871. );
  872. const handler = () => {
  873. this.excalidrawContainerRef.current!.getBoundingClientRect();
  874. this.device = updateObject(this.device, {
  875. isSmScreen: smScreenQuery.matches,
  876. isMobile: mdScreenQuery.matches,
  877. canDeviceFitSidebar: canDeviceFitSidebarMediaQuery.matches,
  878. });
  879. };
  880. mdScreenQuery.addListener(handler);
  881. this.detachIsMobileMqHandler = () =>
  882. mdScreenQuery.removeListener(handler);
  883. }
  884. const searchParams = new URLSearchParams(window.location.search.slice(1));
  885. if (searchParams.has("web-share-target")) {
  886. // Obtain a file that was shared via the Web Share Target API.
  887. this.restoreFileFromShare();
  888. } else {
  889. this.updateDOMRect(this.initializeScene);
  890. }
  891. }
  892. public componentWillUnmount() {
  893. this.files = {};
  894. this.imageCache.clear();
  895. this.resizeObserver?.disconnect();
  896. this.unmounted = true;
  897. this.removeEventListeners();
  898. this.scene.destroy();
  899. clearTimeout(touchTimeout);
  900. touchTimeout = 0;
  901. }
  902. private onResize = withBatchedUpdates(() => {
  903. this.scene
  904. .getElementsIncludingDeleted()
  905. .forEach((element) => invalidateShapeForElement(element));
  906. this.setState({});
  907. });
  908. private removeEventListeners() {
  909. document.removeEventListener(EVENT.POINTER_UP, this.removePointer);
  910. document.removeEventListener(EVENT.COPY, this.onCopy);
  911. document.removeEventListener(EVENT.PASTE, this.pasteFromClipboard);
  912. document.removeEventListener(EVENT.CUT, this.onCut);
  913. this.excalidrawContainerRef.current?.removeEventListener(
  914. EVENT.WHEEL,
  915. this.onWheel,
  916. );
  917. this.nearestScrollableContainer?.removeEventListener(
  918. EVENT.SCROLL,
  919. this.onScroll,
  920. );
  921. document.removeEventListener(EVENT.KEYDOWN, this.onKeyDown, false);
  922. document.removeEventListener(
  923. EVENT.MOUSE_MOVE,
  924. this.updateCurrentCursorPosition,
  925. false,
  926. );
  927. document.removeEventListener(EVENT.KEYUP, this.onKeyUp);
  928. window.removeEventListener(EVENT.RESIZE, this.onResize, false);
  929. window.removeEventListener(EVENT.UNLOAD, this.onUnload, false);
  930. window.removeEventListener(EVENT.BLUR, this.onBlur, false);
  931. this.excalidrawContainerRef.current?.removeEventListener(
  932. EVENT.DRAG_OVER,
  933. this.disableEvent,
  934. false,
  935. );
  936. this.excalidrawContainerRef.current?.removeEventListener(
  937. EVENT.DROP,
  938. this.disableEvent,
  939. false,
  940. );
  941. document.removeEventListener(
  942. EVENT.GESTURE_START,
  943. this.onGestureStart as any,
  944. false,
  945. );
  946. document.removeEventListener(
  947. EVENT.GESTURE_CHANGE,
  948. this.onGestureChange as any,
  949. false,
  950. );
  951. document.removeEventListener(
  952. EVENT.GESTURE_END,
  953. this.onGestureEnd as any,
  954. false,
  955. );
  956. this.detachIsMobileMqHandler?.();
  957. }
  958. private addEventListeners() {
  959. this.removeEventListeners();
  960. document.addEventListener(EVENT.POINTER_UP, this.removePointer); // #3553
  961. document.addEventListener(EVENT.COPY, this.onCopy);
  962. this.excalidrawContainerRef.current?.addEventListener(
  963. EVENT.WHEEL,
  964. this.onWheel,
  965. { passive: false },
  966. );
  967. if (this.props.handleKeyboardGlobally) {
  968. document.addEventListener(EVENT.KEYDOWN, this.onKeyDown, false);
  969. }
  970. document.addEventListener(EVENT.KEYUP, this.onKeyUp, { passive: true });
  971. document.addEventListener(
  972. EVENT.MOUSE_MOVE,
  973. this.updateCurrentCursorPosition,
  974. );
  975. // rerender text elements on font load to fix #637 && #1553
  976. document.fonts?.addEventListener?.("loadingdone", this.onFontLoaded);
  977. // Safari-only desktop pinch zoom
  978. document.addEventListener(
  979. EVENT.GESTURE_START,
  980. this.onGestureStart as any,
  981. false,
  982. );
  983. document.addEventListener(
  984. EVENT.GESTURE_CHANGE,
  985. this.onGestureChange as any,
  986. false,
  987. );
  988. document.addEventListener(
  989. EVENT.GESTURE_END,
  990. this.onGestureEnd as any,
  991. false,
  992. );
  993. if (this.state.viewModeEnabled) {
  994. return;
  995. }
  996. document.addEventListener(EVENT.PASTE, this.pasteFromClipboard);
  997. document.addEventListener(EVENT.CUT, this.onCut);
  998. if (this.props.detectScroll) {
  999. this.nearestScrollableContainer = getNearestScrollableContainer(
  1000. this.excalidrawContainerRef.current!,
  1001. );
  1002. this.nearestScrollableContainer.addEventListener(
  1003. EVENT.SCROLL,
  1004. this.onScroll,
  1005. );
  1006. }
  1007. window.addEventListener(EVENT.RESIZE, this.onResize, false);
  1008. window.addEventListener(EVENT.UNLOAD, this.onUnload, false);
  1009. window.addEventListener(EVENT.BLUR, this.onBlur, false);
  1010. this.excalidrawContainerRef.current?.addEventListener(
  1011. EVENT.DRAG_OVER,
  1012. this.disableEvent,
  1013. false,
  1014. );
  1015. this.excalidrawContainerRef.current?.addEventListener(
  1016. EVENT.DROP,
  1017. this.disableEvent,
  1018. false,
  1019. );
  1020. }
  1021. componentDidUpdate(prevProps: AppProps, prevState: AppState) {
  1022. if (
  1023. this.excalidrawContainerRef.current &&
  1024. prevProps.UIOptions.dockedSidebarBreakpoint !==
  1025. this.props.UIOptions.dockedSidebarBreakpoint
  1026. ) {
  1027. this.refreshDeviceState(this.excalidrawContainerRef.current);
  1028. }
  1029. if (
  1030. prevState.scrollX !== this.state.scrollX ||
  1031. prevState.scrollY !== this.state.scrollY
  1032. ) {
  1033. this.props?.onScrollChange?.(this.state.scrollX, this.state.scrollY);
  1034. }
  1035. if (
  1036. Object.keys(this.state.selectedElementIds).length &&
  1037. isEraserActive(this.state)
  1038. ) {
  1039. this.setState({
  1040. activeTool: updateActiveTool(this.state, { type: "selection" }),
  1041. });
  1042. }
  1043. if (
  1044. this.state.activeTool.type === "eraser" &&
  1045. prevState.theme !== this.state.theme
  1046. ) {
  1047. setEraserCursor(this.canvas, this.state.theme);
  1048. }
  1049. // Hide hyperlink popup if shown when element type is not selection
  1050. if (
  1051. prevState.activeTool.type === "selection" &&
  1052. this.state.activeTool.type !== "selection" &&
  1053. this.state.showHyperlinkPopup
  1054. ) {
  1055. this.setState({ showHyperlinkPopup: false });
  1056. }
  1057. if (prevProps.langCode !== this.props.langCode) {
  1058. this.updateLanguage();
  1059. }
  1060. if (prevProps.viewModeEnabled !== this.props.viewModeEnabled) {
  1061. this.setState({ viewModeEnabled: !!this.props.viewModeEnabled });
  1062. }
  1063. if (prevState.viewModeEnabled !== this.state.viewModeEnabled) {
  1064. this.addEventListeners();
  1065. this.deselectElements();
  1066. }
  1067. if (prevProps.zenModeEnabled !== this.props.zenModeEnabled) {
  1068. this.setState({ zenModeEnabled: !!this.props.zenModeEnabled });
  1069. }
  1070. if (prevProps.theme !== this.props.theme && this.props.theme) {
  1071. this.setState({ theme: this.props.theme });
  1072. }
  1073. if (prevProps.gridModeEnabled !== this.props.gridModeEnabled) {
  1074. this.setState({
  1075. gridSize: this.props.gridModeEnabled ? GRID_SIZE : null,
  1076. });
  1077. }
  1078. if (this.props.name && prevProps.name !== this.props.name) {
  1079. this.setState({
  1080. name: this.props.name,
  1081. });
  1082. }
  1083. this.excalidrawContainerRef.current?.classList.toggle(
  1084. "theme--dark",
  1085. this.state.theme === "dark",
  1086. );
  1087. if (
  1088. this.state.editingLinearElement &&
  1089. !this.state.selectedElementIds[this.state.editingLinearElement.elementId]
  1090. ) {
  1091. // defer so that the commitToHistory flag isn't reset via current update
  1092. setTimeout(() => {
  1093. // execute only if the condition still holds when the deferred callback
  1094. // executes (it can be scheduled multiple times depending on how
  1095. // many times the component renders)
  1096. this.state.editingLinearElement &&
  1097. this.actionManager.executeAction(actionFinalize);
  1098. });
  1099. }
  1100. if (
  1101. this.state.selectedLinearElement &&
  1102. !this.state.selectedElementIds[this.state.selectedLinearElement.elementId]
  1103. ) {
  1104. // To make sure `selectedLinearElement` is in sync with `selectedElementIds`, however this shouldn't be needed once
  1105. // we have a single API to update `selectedElementIds`
  1106. this.setState({ selectedLinearElement: null });
  1107. }
  1108. const { multiElement } = prevState;
  1109. if (
  1110. prevState.activeTool !== this.state.activeTool &&
  1111. multiElement != null &&
  1112. isBindingEnabled(this.state) &&
  1113. isBindingElement(multiElement, false)
  1114. ) {
  1115. maybeBindLinearElement(
  1116. multiElement,
  1117. this.state,
  1118. this.scene,
  1119. tupleToCoors(
  1120. LinearElementEditor.getPointAtIndexGlobalCoordinates(
  1121. multiElement,
  1122. -1,
  1123. ),
  1124. ),
  1125. );
  1126. }
  1127. this.renderScene();
  1128. this.history.record(this.state, this.scene.getElementsIncludingDeleted());
  1129. // Do not notify consumers if we're still loading the scene. Among other
  1130. // potential issues, this fixes a case where the tab isn't focused during
  1131. // init, which would trigger onChange with empty elements, which would then
  1132. // override whatever is in localStorage currently.
  1133. if (!this.state.isLoading) {
  1134. this.props.onChange?.(
  1135. this.scene.getElementsIncludingDeleted(),
  1136. this.state,
  1137. this.files,
  1138. );
  1139. }
  1140. }
  1141. private renderScene = () => {
  1142. const cursorButton: {
  1143. [id: string]: string | undefined;
  1144. } = {};
  1145. const pointerViewportCoords: RenderConfig["remotePointerViewportCoords"] =
  1146. {};
  1147. const remoteSelectedElementIds: RenderConfig["remoteSelectedElementIds"] =
  1148. {};
  1149. const pointerUsernames: { [id: string]: string } = {};
  1150. const pointerUserStates: { [id: string]: string } = {};
  1151. this.state.collaborators.forEach((user, socketId) => {
  1152. if (user.selectedElementIds) {
  1153. for (const id of Object.keys(user.selectedElementIds)) {
  1154. if (!(id in remoteSelectedElementIds)) {
  1155. remoteSelectedElementIds[id] = [];
  1156. }
  1157. remoteSelectedElementIds[id].push(socketId);
  1158. }
  1159. }
  1160. if (!user.pointer) {
  1161. return;
  1162. }
  1163. if (user.username) {
  1164. pointerUsernames[socketId] = user.username;
  1165. }
  1166. if (user.userState) {
  1167. pointerUserStates[socketId] = user.userState;
  1168. }
  1169. pointerViewportCoords[socketId] = sceneCoordsToViewportCoords(
  1170. {
  1171. sceneX: user.pointer.x,
  1172. sceneY: user.pointer.y,
  1173. },
  1174. this.state,
  1175. );
  1176. cursorButton[socketId] = user.button;
  1177. });
  1178. const renderingElements = this.scene
  1179. .getNonDeletedElements()
  1180. .filter((element) => {
  1181. if (isImageElement(element)) {
  1182. if (
  1183. // not placed on canvas yet (but in elements array)
  1184. this.state.pendingImageElementId === element.id
  1185. ) {
  1186. return false;
  1187. }
  1188. }
  1189. // don't render text element that's being currently edited (it's
  1190. // rendered on remote only)
  1191. return (
  1192. !this.state.editingElement ||
  1193. this.state.editingElement.type !== "text" ||
  1194. element.id !== this.state.editingElement.id
  1195. );
  1196. });
  1197. renderScene(
  1198. {
  1199. elements: renderingElements,
  1200. appState: this.state,
  1201. scale: window.devicePixelRatio,
  1202. rc: this.rc!,
  1203. canvas: this.canvas!,
  1204. renderConfig: {
  1205. scrollX: this.state.scrollX,
  1206. scrollY: this.state.scrollY,
  1207. viewBackgroundColor: this.state.viewBackgroundColor,
  1208. zoom: this.state.zoom,
  1209. remotePointerViewportCoords: pointerViewportCoords,
  1210. remotePointerButton: cursorButton,
  1211. remoteSelectedElementIds,
  1212. remotePointerUsernames: pointerUsernames,
  1213. remotePointerUserStates: pointerUserStates,
  1214. shouldCacheIgnoreZoom: this.state.shouldCacheIgnoreZoom,
  1215. theme: this.state.theme,
  1216. imageCache: this.imageCache,
  1217. isExporting: false,
  1218. renderScrollbars: !this.device.isMobile,
  1219. },
  1220. callback: ({ atLeastOneVisibleElement, scrollBars }) => {
  1221. if (scrollBars) {
  1222. currentScrollBars = scrollBars;
  1223. }
  1224. const scrolledOutside =
  1225. // hide when editing text
  1226. isTextElement(this.state.editingElement)
  1227. ? false
  1228. : !atLeastOneVisibleElement && renderingElements.length > 0;
  1229. if (this.state.scrolledOutside !== scrolledOutside) {
  1230. this.setState({ scrolledOutside });
  1231. }
  1232. this.scheduleImageRefresh();
  1233. },
  1234. },
  1235. THROTTLE_NEXT_RENDER && window.EXCALIDRAW_THROTTLE_RENDER === true,
  1236. );
  1237. if (!THROTTLE_NEXT_RENDER) {
  1238. THROTTLE_NEXT_RENDER = true;
  1239. }
  1240. };
  1241. private onScroll = debounce(() => {
  1242. const { offsetTop, offsetLeft } = this.getCanvasOffsets();
  1243. this.setState((state) => {
  1244. if (state.offsetLeft === offsetLeft && state.offsetTop === offsetTop) {
  1245. return null;
  1246. }
  1247. return { offsetTop, offsetLeft };
  1248. });
  1249. }, SCROLL_TIMEOUT);
  1250. // Copy/paste
  1251. private onCut = withBatchedUpdates((event: ClipboardEvent) => {
  1252. const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
  1253. document.activeElement,
  1254. );
  1255. if (!isExcalidrawActive || isWritableElement(event.target)) {
  1256. return;
  1257. }
  1258. this.cutAll();
  1259. event.preventDefault();
  1260. event.stopPropagation();
  1261. });
  1262. private onCopy = withBatchedUpdates((event: ClipboardEvent) => {
  1263. const isExcalidrawActive = this.excalidrawContainerRef.current?.contains(
  1264. document.activeElement,
  1265. );
  1266. if (!isExcalidrawActive || isWritableElement(event.target)) {
  1267. return;
  1268. }
  1269. this.copyAll();
  1270. event.preventDefault();
  1271. event.stopPropagation();
  1272. });
  1273. private cutAll = () => {
  1274. this.actionManager.executeAction(actionCut, "keyboard");
  1275. };
  1276. private copyAll = () => {
  1277. this.actionManager.executeAction(actionCopy, "keyboard");
  1278. };
  1279. private static resetTapTwice() {
  1280. didTapTwice = false;
  1281. }
  1282. private onTapStart = (event: TouchEvent) => {
  1283. // fix for Apple Pencil Scribble
  1284. // On Android, preventing the event would disable contextMenu on tap-hold
  1285. if (!isAndroid) {
  1286. event.preventDefault();
  1287. }
  1288. if (!didTapTwice) {
  1289. didTapTwice = true;
  1290. clearTimeout(tappedTwiceTimer);
  1291. tappedTwiceTimer = window.setTimeout(
  1292. App.resetTapTwice,
  1293. TAP_TWICE_TIMEOUT,
  1294. );
  1295. return;
  1296. }
  1297. // insert text only if we tapped twice with a single finger
  1298. // event.touches.length === 1 will also prevent inserting text when user's zooming
  1299. if (didTapTwice && event.touches.length === 1) {
  1300. const [touch] = event.touches;
  1301. // @ts-ignore
  1302. this.handleCanvasDoubleClick({
  1303. clientX: touch.clientX,
  1304. clientY: touch.clientY,
  1305. });
  1306. didTapTwice = false;
  1307. clearTimeout(tappedTwiceTimer);
  1308. }
  1309. if (isAndroid) {
  1310. event.preventDefault();
  1311. }
  1312. if (event.touches.length === 2) {
  1313. this.setState({
  1314. selectedElementIds: {},
  1315. });
  1316. }
  1317. };
  1318. private onTapEnd = (event: TouchEvent) => {
  1319. this.resetContextMenuTimer();
  1320. if (event.touches.length > 0) {
  1321. this.setState({
  1322. previousSelectedElementIds: {},
  1323. selectedElementIds: this.state.previousSelectedElementIds,
  1324. });
  1325. } else {
  1326. gesture.pointers.clear();
  1327. }
  1328. };
  1329. private pasteFromClipboard = withBatchedUpdates(
  1330. async (event: ClipboardEvent | null) => {
  1331. // #686
  1332. const target = document.activeElement;
  1333. const isExcalidrawActive =
  1334. this.excalidrawContainerRef.current?.contains(target);
  1335. if (!isExcalidrawActive) {
  1336. return;
  1337. }
  1338. const elementUnderCursor = document.elementFromPoint(cursorX, cursorY);
  1339. if (
  1340. // if no ClipboardEvent supplied, assume we're pasting via contextMenu
  1341. // thus these checks don't make sense
  1342. event &&
  1343. (!(elementUnderCursor instanceof HTMLCanvasElement) ||
  1344. isWritableElement(target))
  1345. ) {
  1346. return;
  1347. }
  1348. // must be called in the same frame (thus before any awaits) as the paste
  1349. // event else some browsers (FF...) will clear the clipboardData
  1350. // (something something security)
  1351. let file = event?.clipboardData?.files[0];
  1352. const data = await parseClipboard(event);
  1353. if (!file && data.text) {
  1354. const string = data.text.trim();
  1355. if (string.startsWith("<svg") && string.endsWith("</svg>")) {
  1356. // ignore SVG validation/normalization which will be done during image
  1357. // initialization
  1358. file = SVGStringToFile(string);
  1359. }
  1360. }
  1361. // prefer spreadsheet data over image file (MS Office/Libre Office)
  1362. if (isSupportedImageFile(file) && !data.spreadsheet) {
  1363. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  1364. { clientX: cursorX, clientY: cursorY },
  1365. this.state,
  1366. );
  1367. const imageElement = this.createImageElement({ sceneX, sceneY });
  1368. this.insertImageElement(imageElement, file);
  1369. this.initializeImageDimensions(imageElement);
  1370. this.setState({ selectedElementIds: { [imageElement.id]: true } });
  1371. return;
  1372. }
  1373. if (this.props.onPaste) {
  1374. try {
  1375. if ((await this.props.onPaste(data, event)) === false) {
  1376. return;
  1377. }
  1378. } catch (error: any) {
  1379. console.error(error);
  1380. }
  1381. }
  1382. if (data.errorMessage) {
  1383. this.setState({ errorMessage: data.errorMessage });
  1384. } else if (data.spreadsheet) {
  1385. this.setState({
  1386. pasteDialog: {
  1387. data: data.spreadsheet,
  1388. shown: true,
  1389. },
  1390. });
  1391. } else if (data.elements) {
  1392. this.addElementsFromPasteOrLibrary({
  1393. elements: data.elements,
  1394. files: data.files || null,
  1395. position: "cursor",
  1396. });
  1397. } else if (data.text) {
  1398. this.addTextFromPaste(data.text);
  1399. }
  1400. this.setActiveTool({ type: "selection" });
  1401. event?.preventDefault();
  1402. },
  1403. );
  1404. private addElementsFromPasteOrLibrary = (opts: {
  1405. elements: readonly ExcalidrawElement[];
  1406. files: BinaryFiles | null;
  1407. position: { clientX: number; clientY: number } | "cursor" | "center";
  1408. }) => {
  1409. const elements = restoreElements(opts.elements, null);
  1410. const [minX, minY, maxX, maxY] = getCommonBounds(elements);
  1411. const elementsCenterX = distance(minX, maxX) / 2;
  1412. const elementsCenterY = distance(minY, maxY) / 2;
  1413. const clientX =
  1414. typeof opts.position === "object"
  1415. ? opts.position.clientX
  1416. : opts.position === "cursor"
  1417. ? cursorX
  1418. : this.state.width / 2 + this.state.offsetLeft;
  1419. const clientY =
  1420. typeof opts.position === "object"
  1421. ? opts.position.clientY
  1422. : opts.position === "cursor"
  1423. ? cursorY
  1424. : this.state.height / 2 + this.state.offsetTop;
  1425. const { x, y } = viewportCoordsToSceneCoords(
  1426. { clientX, clientY },
  1427. this.state,
  1428. );
  1429. const dx = x - elementsCenterX;
  1430. const dy = y - elementsCenterY;
  1431. const groupIdMap = new Map();
  1432. const [gridX, gridY] = getGridPoint(dx, dy, this.state.gridSize);
  1433. const oldIdToDuplicatedId = new Map();
  1434. const newElements = elements.map((element) => {
  1435. const newElement = duplicateElement(
  1436. this.state.editingGroupId,
  1437. groupIdMap,
  1438. element,
  1439. {
  1440. x: element.x + gridX - minX,
  1441. y: element.y + gridY - minY,
  1442. },
  1443. );
  1444. oldIdToDuplicatedId.set(element.id, newElement.id);
  1445. return newElement;
  1446. });
  1447. bindTextToShapeAfterDuplication(newElements, elements, oldIdToDuplicatedId);
  1448. const nextElements = [
  1449. ...this.scene.getElementsIncludingDeleted(),
  1450. ...newElements,
  1451. ];
  1452. fixBindingsAfterDuplication(nextElements, elements, oldIdToDuplicatedId);
  1453. if (opts.files) {
  1454. this.files = { ...this.files, ...opts.files };
  1455. }
  1456. this.scene.replaceAllElements(nextElements);
  1457. this.history.resumeRecording();
  1458. this.setState(
  1459. selectGroupsForSelectedElements(
  1460. {
  1461. ...this.state,
  1462. // keep sidebar (presumably the library) open if it's docked and
  1463. // can fit.
  1464. //
  1465. // Note, we should close the sidebar only if we're dropping items
  1466. // from library, not when pasting from clipboard. Alas.
  1467. openSidebar:
  1468. this.state.openSidebar &&
  1469. this.device.canDeviceFitSidebar &&
  1470. this.state.isSidebarDocked
  1471. ? this.state.openSidebar
  1472. : null,
  1473. selectedElementIds: newElements.reduce(
  1474. (acc: Record<ExcalidrawElement["id"], true>, element) => {
  1475. if (!isBoundToContainer(element)) {
  1476. acc[element.id] = true;
  1477. }
  1478. return acc;
  1479. },
  1480. {},
  1481. ),
  1482. selectedGroupIds: {},
  1483. },
  1484. this.scene.getNonDeletedElements(),
  1485. ),
  1486. () => {
  1487. if (opts.files) {
  1488. this.addNewImagesToImageCache();
  1489. }
  1490. },
  1491. );
  1492. this.setActiveTool({ type: "selection" });
  1493. };
  1494. private addTextFromPaste(text: any) {
  1495. const { x, y } = viewportCoordsToSceneCoords(
  1496. { clientX: cursorX, clientY: cursorY },
  1497. this.state,
  1498. );
  1499. const element = newTextElement({
  1500. x,
  1501. y,
  1502. strokeColor: this.state.currentItemStrokeColor,
  1503. backgroundColor: this.state.currentItemBackgroundColor,
  1504. fillStyle: this.state.currentItemFillStyle,
  1505. strokeWidth: this.state.currentItemStrokeWidth,
  1506. strokeStyle: this.state.currentItemStrokeStyle,
  1507. roughness: this.state.currentItemRoughness,
  1508. opacity: this.state.currentItemOpacity,
  1509. strokeSharpness: this.state.currentItemStrokeSharpness,
  1510. text,
  1511. fontSize: this.state.currentItemFontSize,
  1512. fontFamily: this.state.currentItemFontFamily,
  1513. textAlign: this.state.currentItemTextAlign,
  1514. verticalAlign: DEFAULT_VERTICAL_ALIGN,
  1515. locked: false,
  1516. });
  1517. this.scene.replaceAllElements([
  1518. ...this.scene.getElementsIncludingDeleted(),
  1519. element,
  1520. ]);
  1521. this.setState({ selectedElementIds: { [element.id]: true } });
  1522. this.history.resumeRecording();
  1523. }
  1524. // Collaboration
  1525. setAppState: React.Component<any, AppState>["setState"] = (state) => {
  1526. this.setState(state);
  1527. };
  1528. removePointer = (event: React.PointerEvent<HTMLElement> | PointerEvent) => {
  1529. if (touchTimeout) {
  1530. this.resetContextMenuTimer();
  1531. }
  1532. gesture.pointers.delete(event.pointerId);
  1533. };
  1534. toggleLock = (source: "keyboard" | "ui" = "ui") => {
  1535. if (!this.state.activeTool.locked) {
  1536. trackEvent(
  1537. "toolbar",
  1538. "toggleLock",
  1539. `${source} (${this.device.isMobile ? "mobile" : "desktop"})`,
  1540. );
  1541. }
  1542. this.setState((prevState) => {
  1543. return {
  1544. activeTool: {
  1545. ...prevState.activeTool,
  1546. ...updateActiveTool(
  1547. this.state,
  1548. prevState.activeTool.locked
  1549. ? { type: "selection" }
  1550. : prevState.activeTool,
  1551. ),
  1552. locked: !prevState.activeTool.locked,
  1553. },
  1554. };
  1555. });
  1556. };
  1557. togglePenMode = () => {
  1558. this.setState((prevState) => {
  1559. return {
  1560. penMode: !prevState.penMode,
  1561. };
  1562. });
  1563. };
  1564. scrollToContent = (
  1565. target:
  1566. | ExcalidrawElement
  1567. | readonly ExcalidrawElement[] = this.scene.getNonDeletedElements(),
  1568. ) => {
  1569. this.setState({
  1570. ...calculateScrollCenter(
  1571. Array.isArray(target) ? target : [target],
  1572. this.state,
  1573. this.canvas,
  1574. ),
  1575. });
  1576. };
  1577. setToast = (
  1578. toast: {
  1579. message: string;
  1580. closable?: boolean;
  1581. duration?: number;
  1582. } | null,
  1583. ) => {
  1584. this.setState({ toast });
  1585. };
  1586. restoreFileFromShare = async () => {
  1587. try {
  1588. const webShareTargetCache = await caches.open("web-share-target");
  1589. const response = await webShareTargetCache.match("shared-file");
  1590. if (response) {
  1591. const blob = await response.blob();
  1592. const file = new File([blob], blob.name || "", { type: blob.type });
  1593. this.loadFileToCanvas(file, null);
  1594. await webShareTargetCache.delete("shared-file");
  1595. window.history.replaceState(null, APP_NAME, window.location.pathname);
  1596. }
  1597. } catch (error: any) {
  1598. this.setState({ errorMessage: error.message });
  1599. }
  1600. };
  1601. /** adds supplied files to existing files in the appState */
  1602. public addFiles: ExcalidrawImperativeAPI["addFiles"] = withBatchedUpdates(
  1603. (files) => {
  1604. const filesMap = files.reduce((acc, fileData) => {
  1605. acc.set(fileData.id, fileData);
  1606. return acc;
  1607. }, new Map<FileId, BinaryFileData>());
  1608. this.files = { ...this.files, ...Object.fromEntries(filesMap) };
  1609. this.scene.getNonDeletedElements().forEach((element) => {
  1610. if (
  1611. isInitializedImageElement(element) &&
  1612. filesMap.has(element.fileId)
  1613. ) {
  1614. this.imageCache.delete(element.fileId);
  1615. invalidateShapeForElement(element);
  1616. }
  1617. });
  1618. this.scene.informMutation();
  1619. this.addNewImagesToImageCache();
  1620. },
  1621. );
  1622. public updateScene = withBatchedUpdates(
  1623. <K extends keyof AppState>(sceneData: {
  1624. elements?: SceneData["elements"];
  1625. appState?: Pick<AppState, K> | null;
  1626. collaborators?: SceneData["collaborators"];
  1627. commitToHistory?: SceneData["commitToHistory"];
  1628. }) => {
  1629. if (sceneData.commitToHistory) {
  1630. this.history.resumeRecording();
  1631. }
  1632. if (sceneData.appState) {
  1633. this.setState(sceneData.appState);
  1634. }
  1635. if (sceneData.elements) {
  1636. this.scene.replaceAllElements(sceneData.elements);
  1637. }
  1638. if (sceneData.collaborators) {
  1639. this.setState({ collaborators: sceneData.collaborators });
  1640. }
  1641. },
  1642. );
  1643. private onSceneUpdated = () => {
  1644. this.setState({});
  1645. };
  1646. /**
  1647. * @returns whether the menu was toggled on or off
  1648. */
  1649. public toggleMenu = (
  1650. type: "library" | "customSidebar",
  1651. force?: boolean,
  1652. ): boolean => {
  1653. if (type === "customSidebar" && !this.props.renderSidebar) {
  1654. console.warn(
  1655. `attempting to toggle "customSidebar", but no "props.renderSidebar" is defined`,
  1656. );
  1657. return false;
  1658. }
  1659. if (type === "library" || type === "customSidebar") {
  1660. let nextValue;
  1661. if (force === undefined) {
  1662. nextValue = this.state.openSidebar === type ? null : type;
  1663. } else {
  1664. nextValue = force ? type : null;
  1665. }
  1666. this.setState({ openSidebar: nextValue });
  1667. return !!nextValue;
  1668. }
  1669. return false;
  1670. };
  1671. private updateCurrentCursorPosition = withBatchedUpdates(
  1672. (event: MouseEvent) => {
  1673. cursorX = event.clientX;
  1674. cursorY = event.clientY;
  1675. },
  1676. );
  1677. // Input handling
  1678. private onKeyDown = withBatchedUpdates(
  1679. (event: React.KeyboardEvent | KeyboardEvent) => {
  1680. // normalize `event.key` when CapsLock is pressed #2372
  1681. if (
  1682. "Proxy" in window &&
  1683. ((!event.shiftKey && /^[A-Z]$/.test(event.key)) ||
  1684. (event.shiftKey && /^[a-z]$/.test(event.key)))
  1685. ) {
  1686. event = new Proxy(event, {
  1687. get(ev: any, prop) {
  1688. const value = ev[prop];
  1689. if (typeof value === "function") {
  1690. // fix for Proxies hijacking `this`
  1691. return value.bind(ev);
  1692. }
  1693. return prop === "key"
  1694. ? // CapsLock inverts capitalization based on ShiftKey, so invert
  1695. // it back
  1696. event.shiftKey
  1697. ? ev.key.toUpperCase()
  1698. : ev.key.toLowerCase()
  1699. : value;
  1700. },
  1701. });
  1702. }
  1703. // prevent browser zoom in input fields
  1704. if (event[KEYS.CTRL_OR_CMD] && isWritableElement(event.target)) {
  1705. if (event.code === CODES.MINUS || event.code === CODES.EQUAL) {
  1706. event.preventDefault();
  1707. return;
  1708. }
  1709. }
  1710. // bail if
  1711. if (
  1712. // inside an input
  1713. (isWritableElement(event.target) &&
  1714. // unless pressing escape (finalize action)
  1715. event.key !== KEYS.ESCAPE) ||
  1716. // or unless using arrows (to move between buttons)
  1717. (isArrowKey(event.key) && isInputLike(event.target))
  1718. ) {
  1719. return;
  1720. }
  1721. if (event.key === KEYS.QUESTION_MARK) {
  1722. this.setState({
  1723. showHelpDialog: true,
  1724. });
  1725. }
  1726. if (this.actionManager.handleKeyDown(event)) {
  1727. return;
  1728. }
  1729. if (this.state.viewModeEnabled) {
  1730. return;
  1731. }
  1732. if (event[KEYS.CTRL_OR_CMD] && this.state.isBindingEnabled) {
  1733. this.setState({ isBindingEnabled: false });
  1734. }
  1735. if (event.code === CODES.ZERO) {
  1736. const nextState = this.toggleMenu("library");
  1737. // track only openings
  1738. if (nextState) {
  1739. trackEvent(
  1740. "library",
  1741. "toggleLibrary (open)",
  1742. `keyboard (${this.device.isMobile ? "mobile" : "desktop"})`,
  1743. );
  1744. }
  1745. }
  1746. if (isArrowKey(event.key)) {
  1747. const step =
  1748. (this.state.gridSize &&
  1749. (event.shiftKey
  1750. ? ELEMENT_TRANSLATE_AMOUNT
  1751. : this.state.gridSize)) ||
  1752. (event.shiftKey
  1753. ? ELEMENT_SHIFT_TRANSLATE_AMOUNT
  1754. : ELEMENT_TRANSLATE_AMOUNT);
  1755. const selectedElements = getSelectedElements(
  1756. this.scene.getNonDeletedElements(),
  1757. this.state,
  1758. true,
  1759. );
  1760. let offsetX = 0;
  1761. let offsetY = 0;
  1762. if (event.key === KEYS.ARROW_LEFT) {
  1763. offsetX = -step;
  1764. } else if (event.key === KEYS.ARROW_RIGHT) {
  1765. offsetX = step;
  1766. } else if (event.key === KEYS.ARROW_UP) {
  1767. offsetY = -step;
  1768. } else if (event.key === KEYS.ARROW_DOWN) {
  1769. offsetY = step;
  1770. }
  1771. selectedElements.forEach((element) => {
  1772. mutateElement(element, {
  1773. x: element.x + offsetX,
  1774. y: element.y + offsetY,
  1775. });
  1776. updateBoundElements(element, {
  1777. simultaneouslyUpdated: selectedElements,
  1778. });
  1779. });
  1780. this.maybeSuggestBindingForAll(selectedElements);
  1781. event.preventDefault();
  1782. } else if (event.key === KEYS.ENTER) {
  1783. const selectedElements = getSelectedElements(
  1784. this.scene.getNonDeletedElements(),
  1785. this.state,
  1786. );
  1787. if (selectedElements.length === 1) {
  1788. if (isLinearElement(selectedElements[0])) {
  1789. if (
  1790. !this.state.editingLinearElement ||
  1791. this.state.editingLinearElement.elementId !==
  1792. selectedElements[0].id
  1793. ) {
  1794. this.history.resumeRecording();
  1795. this.setState({
  1796. editingLinearElement: new LinearElementEditor(
  1797. selectedElements[0],
  1798. this.scene,
  1799. ),
  1800. });
  1801. }
  1802. } else {
  1803. const selectedElement = selectedElements[0];
  1804. this.startTextEditing({
  1805. sceneX: selectedElement.x + selectedElement.width / 2,
  1806. sceneY: selectedElement.y + selectedElement.height / 2,
  1807. shouldBind: true,
  1808. });
  1809. event.preventDefault();
  1810. return;
  1811. }
  1812. }
  1813. } else if (
  1814. !event.ctrlKey &&
  1815. !event.altKey &&
  1816. !event.metaKey &&
  1817. this.state.draggingElement === null
  1818. ) {
  1819. const shape = findShapeByKey(event.key);
  1820. if (shape) {
  1821. if (this.state.activeTool.type !== shape) {
  1822. trackEvent(
  1823. "toolbar",
  1824. shape,
  1825. `keyboard (${this.device.isMobile ? "mobile" : "desktop"})`,
  1826. );
  1827. }
  1828. this.setActiveTool({ type: shape });
  1829. event.stopPropagation();
  1830. } else if (event.key === KEYS.Q) {
  1831. this.toggleLock("keyboard");
  1832. event.stopPropagation();
  1833. }
  1834. }
  1835. if (event.key === KEYS.SPACE && gesture.pointers.size === 0) {
  1836. isHoldingSpace = true;
  1837. setCursor(this.canvas, CURSOR_TYPE.GRABBING);
  1838. event.preventDefault();
  1839. }
  1840. if (
  1841. (event.key === KEYS.G || event.key === KEYS.S) &&
  1842. !event.altKey &&
  1843. !event[KEYS.CTRL_OR_CMD]
  1844. ) {
  1845. const selectedElements = getSelectedElements(
  1846. this.scene.getNonDeletedElements(),
  1847. this.state,
  1848. );
  1849. if (
  1850. this.state.activeTool.type === "selection" &&
  1851. !selectedElements.length
  1852. ) {
  1853. return;
  1854. }
  1855. if (
  1856. event.key === KEYS.G &&
  1857. (hasBackground(this.state.activeTool.type) ||
  1858. selectedElements.some((element) => hasBackground(element.type)))
  1859. ) {
  1860. this.setState({ openPopup: "backgroundColorPicker" });
  1861. event.stopPropagation();
  1862. }
  1863. if (event.key === KEYS.S) {
  1864. this.setState({ openPopup: "strokeColorPicker" });
  1865. event.stopPropagation();
  1866. }
  1867. }
  1868. },
  1869. );
  1870. private onWheel = withBatchedUpdates((event: WheelEvent) => {
  1871. // prevent browser pinch zoom on DOM elements
  1872. if (!(event.target instanceof HTMLCanvasElement) && event.ctrlKey) {
  1873. event.preventDefault();
  1874. }
  1875. });
  1876. private onKeyUp = withBatchedUpdates((event: KeyboardEvent) => {
  1877. if (event.key === KEYS.SPACE) {
  1878. if (this.state.viewModeEnabled) {
  1879. setCursor(this.canvas, CURSOR_TYPE.GRAB);
  1880. } else if (this.state.activeTool.type === "selection") {
  1881. resetCursor(this.canvas);
  1882. } else {
  1883. setCursorForShape(this.canvas, this.state);
  1884. this.setState({
  1885. selectedElementIds: {},
  1886. selectedGroupIds: {},
  1887. editingGroupId: null,
  1888. });
  1889. }
  1890. isHoldingSpace = false;
  1891. }
  1892. if (!event[KEYS.CTRL_OR_CMD] && !this.state.isBindingEnabled) {
  1893. this.setState({ isBindingEnabled: true });
  1894. }
  1895. if (isArrowKey(event.key)) {
  1896. const selectedElements = getSelectedElements(
  1897. this.scene.getNonDeletedElements(),
  1898. this.state,
  1899. );
  1900. isBindingEnabled(this.state)
  1901. ? bindOrUnbindSelectedElements(selectedElements)
  1902. : unbindLinearElements(selectedElements);
  1903. this.setState({ suggestedBindings: [] });
  1904. }
  1905. });
  1906. private setActiveTool = (
  1907. tool:
  1908. | { type: typeof SHAPES[number]["value"] | "eraser" }
  1909. | { type: "custom"; customType: string },
  1910. ) => {
  1911. const nextActiveTool = updateActiveTool(this.state, tool);
  1912. if (!isHoldingSpace) {
  1913. setCursorForShape(this.canvas, this.state);
  1914. }
  1915. if (isToolIcon(document.activeElement)) {
  1916. this.focusContainer();
  1917. }
  1918. if (!isLinearElementType(nextActiveTool.type)) {
  1919. this.setState({ suggestedBindings: [] });
  1920. }
  1921. if (nextActiveTool.type === "image") {
  1922. this.onImageAction();
  1923. }
  1924. if (nextActiveTool.type !== "selection") {
  1925. this.setState({
  1926. activeTool: nextActiveTool,
  1927. selectedElementIds: {},
  1928. selectedGroupIds: {},
  1929. editingGroupId: null,
  1930. });
  1931. } else {
  1932. this.setState({ activeTool: nextActiveTool });
  1933. }
  1934. };
  1935. private setCursor = (cursor: string) => {
  1936. setCursor(this.canvas, cursor);
  1937. };
  1938. private resetCursor = () => {
  1939. resetCursor(this.canvas);
  1940. };
  1941. /**
  1942. * returns whether user is making a gesture with >= 2 fingers (points)
  1943. * on o touch screen (not on a trackpad). Currently only relates to Darwin
  1944. * (iOS/iPadOS,MacOS), but may work on other devices in the future if
  1945. * GestureEvent is standardized.
  1946. */
  1947. private isTouchScreenMultiTouchGesture = () => {
  1948. // we don't want to deselect when using trackpad, and multi-point gestures
  1949. // only work on touch screens, so checking for >= pointers means we're on a
  1950. // touchscreen
  1951. return gesture.pointers.size >= 2;
  1952. };
  1953. // fires only on Safari
  1954. private onGestureStart = withBatchedUpdates((event: GestureEvent) => {
  1955. event.preventDefault();
  1956. // we only want to deselect on touch screens because user may have selected
  1957. // elements by mistake while zooming
  1958. if (this.isTouchScreenMultiTouchGesture()) {
  1959. this.setState({
  1960. selectedElementIds: {},
  1961. });
  1962. }
  1963. gesture.initialScale = this.state.zoom.value;
  1964. });
  1965. // fires only on Safari
  1966. private onGestureChange = withBatchedUpdates((event: GestureEvent) => {
  1967. event.preventDefault();
  1968. // onGestureChange only has zoom factor but not the center.
  1969. // If we're on iPad or iPhone, then we recognize multi-touch and will
  1970. // zoom in at the right location in the touchmove handler
  1971. // (handleCanvasPointerMove).
  1972. //
  1973. // On Macbook trackpad, we don't have those events so will zoom in at the
  1974. // current location instead.
  1975. //
  1976. // As such, bail from this handler on touch devices.
  1977. if (this.isTouchScreenMultiTouchGesture()) {
  1978. return;
  1979. }
  1980. const initialScale = gesture.initialScale;
  1981. if (initialScale) {
  1982. this.setState((state) => ({
  1983. ...getStateForZoom(
  1984. {
  1985. viewportX: cursorX,
  1986. viewportY: cursorY,
  1987. nextZoom: getNormalizedZoom(initialScale * event.scale),
  1988. },
  1989. state,
  1990. ),
  1991. }));
  1992. }
  1993. });
  1994. // fires only on Safari
  1995. private onGestureEnd = withBatchedUpdates((event: GestureEvent) => {
  1996. event.preventDefault();
  1997. // reselect elements only on touch screens (see onGestureStart)
  1998. if (this.isTouchScreenMultiTouchGesture()) {
  1999. this.setState({
  2000. previousSelectedElementIds: {},
  2001. selectedElementIds: this.state.previousSelectedElementIds,
  2002. });
  2003. }
  2004. gesture.initialScale = null;
  2005. });
  2006. private handleTextWysiwyg(
  2007. element: ExcalidrawTextElement,
  2008. {
  2009. isExistingElement = false,
  2010. }: {
  2011. isExistingElement?: boolean;
  2012. },
  2013. ) {
  2014. const updateElement = (
  2015. text: string,
  2016. originalText: string,
  2017. isDeleted: boolean,
  2018. ) => {
  2019. this.scene.replaceAllElements([
  2020. ...this.scene.getElementsIncludingDeleted().map((_element) => {
  2021. if (_element.id === element.id && isTextElement(_element)) {
  2022. return updateTextElement(_element, {
  2023. text,
  2024. isDeleted,
  2025. originalText,
  2026. });
  2027. }
  2028. return _element;
  2029. }),
  2030. ]);
  2031. };
  2032. textWysiwyg({
  2033. id: element.id,
  2034. canvas: this.canvas,
  2035. getViewportCoords: (x, y) => {
  2036. const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
  2037. {
  2038. sceneX: x,
  2039. sceneY: y,
  2040. },
  2041. this.state,
  2042. );
  2043. return [
  2044. viewportX - this.state.offsetLeft,
  2045. viewportY - this.state.offsetTop,
  2046. ];
  2047. },
  2048. onChange: withBatchedUpdates((text) => {
  2049. updateElement(text, text, false);
  2050. if (isNonDeletedElement(element)) {
  2051. updateBoundElements(element);
  2052. }
  2053. }),
  2054. onSubmit: withBatchedUpdates(({ text, viaKeyboard, originalText }) => {
  2055. const isDeleted = !text.trim();
  2056. updateElement(text, originalText, isDeleted);
  2057. // select the created text element only if submitting via keyboard
  2058. // (when submitting via click it should act as signal to deselect)
  2059. if (!isDeleted && viaKeyboard) {
  2060. const elementIdToSelect = element.containerId
  2061. ? element.containerId
  2062. : element.id;
  2063. this.setState((prevState) => ({
  2064. selectedElementIds: {
  2065. ...prevState.selectedElementIds,
  2066. [elementIdToSelect]: true,
  2067. },
  2068. }));
  2069. }
  2070. if (isDeleted) {
  2071. fixBindingsAfterDeletion(this.scene.getNonDeletedElements(), [
  2072. element,
  2073. ]);
  2074. }
  2075. if (!isDeleted || isExistingElement) {
  2076. this.history.resumeRecording();
  2077. }
  2078. this.setState({
  2079. draggingElement: null,
  2080. editingElement: null,
  2081. });
  2082. if (this.state.activeTool.locked) {
  2083. setCursorForShape(this.canvas, this.state);
  2084. }
  2085. this.focusContainer();
  2086. }),
  2087. element,
  2088. excalidrawContainer: this.excalidrawContainerRef.current,
  2089. app: this,
  2090. });
  2091. // deselect all other elements when inserting text
  2092. this.deselectElements();
  2093. // do an initial update to re-initialize element position since we were
  2094. // modifying element's x/y for sake of editor (case: syncing to remote)
  2095. updateElement(element.text, element.originalText, false);
  2096. }
  2097. private deselectElements() {
  2098. this.setState({
  2099. selectedElementIds: {},
  2100. selectedGroupIds: {},
  2101. editingGroupId: null,
  2102. });
  2103. }
  2104. private getTextElementAtPosition(
  2105. x: number,
  2106. y: number,
  2107. ): NonDeleted<ExcalidrawTextElement> | null {
  2108. const element = this.getElementAtPosition(x, y, {
  2109. includeBoundTextElement: true,
  2110. });
  2111. if (element && isTextElement(element) && !element.isDeleted) {
  2112. return element;
  2113. }
  2114. return null;
  2115. }
  2116. private getElementAtPosition(
  2117. x: number,
  2118. y: number,
  2119. opts?: {
  2120. /** if true, returns the first selected element (with highest z-index)
  2121. of all hit elements */
  2122. preferSelected?: boolean;
  2123. includeBoundTextElement?: boolean;
  2124. includeLockedElements?: boolean;
  2125. },
  2126. ): NonDeleted<ExcalidrawElement> | null {
  2127. const allHitElements = this.getElementsAtPosition(
  2128. x,
  2129. y,
  2130. opts?.includeBoundTextElement,
  2131. opts?.includeLockedElements,
  2132. );
  2133. if (allHitElements.length > 1) {
  2134. if (opts?.preferSelected) {
  2135. for (let index = allHitElements.length - 1; index > -1; index--) {
  2136. if (this.state.selectedElementIds[allHitElements[index].id]) {
  2137. return allHitElements[index];
  2138. }
  2139. }
  2140. }
  2141. const elementWithHighestZIndex =
  2142. allHitElements[allHitElements.length - 1];
  2143. // If we're hitting element with highest z-index only on its bounding box
  2144. // while also hitting other element figure, the latter should be considered.
  2145. return isHittingElementBoundingBoxWithoutHittingElement(
  2146. elementWithHighestZIndex,
  2147. this.state,
  2148. x,
  2149. y,
  2150. )
  2151. ? allHitElements[allHitElements.length - 2]
  2152. : elementWithHighestZIndex;
  2153. }
  2154. if (allHitElements.length === 1) {
  2155. return allHitElements[0];
  2156. }
  2157. return null;
  2158. }
  2159. private getElementsAtPosition(
  2160. x: number,
  2161. y: number,
  2162. includeBoundTextElement: boolean = false,
  2163. includeLockedElements: boolean = false,
  2164. ): NonDeleted<ExcalidrawElement>[] {
  2165. const elements =
  2166. includeBoundTextElement && includeLockedElements
  2167. ? this.scene.getNonDeletedElements()
  2168. : this.scene
  2169. .getNonDeletedElements()
  2170. .filter(
  2171. (element) =>
  2172. (includeLockedElements || !element.locked) &&
  2173. (includeBoundTextElement ||
  2174. !(isTextElement(element) && element.containerId)),
  2175. );
  2176. return getElementsAtPosition(elements, (element) =>
  2177. hitTest(element, this.state, x, y),
  2178. );
  2179. }
  2180. private startTextEditing = ({
  2181. sceneX,
  2182. sceneY,
  2183. shouldBind,
  2184. insertAtParentCenter = true,
  2185. }: {
  2186. /** X position to insert text at */
  2187. sceneX: number;
  2188. /** Y position to insert text at */
  2189. sceneY: number;
  2190. shouldBind: boolean;
  2191. /** whether to attempt to insert at element center if applicable */
  2192. insertAtParentCenter?: boolean;
  2193. }) => {
  2194. let parentCenterPosition =
  2195. insertAtParentCenter &&
  2196. this.getTextWysiwygSnappedToCenterPosition(
  2197. sceneX,
  2198. sceneY,
  2199. this.state,
  2200. this.canvas,
  2201. window.devicePixelRatio,
  2202. );
  2203. let existingTextElement: NonDeleted<ExcalidrawTextElement> | null = null;
  2204. let container: ExcalidrawTextContainer | null = null;
  2205. const selectedElements = getSelectedElements(
  2206. this.scene.getNonDeletedElements(),
  2207. this.state,
  2208. );
  2209. if (selectedElements.length === 1) {
  2210. if (isTextElement(selectedElements[0])) {
  2211. existingTextElement = selectedElements[0];
  2212. } else if (isTextBindableContainer(selectedElements[0], false)) {
  2213. existingTextElement = getBoundTextElement(selectedElements[0]);
  2214. } else {
  2215. existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
  2216. }
  2217. } else {
  2218. existingTextElement = this.getTextElementAtPosition(sceneX, sceneY);
  2219. }
  2220. // bind to container when shouldBind is true or
  2221. // clicked on center of container
  2222. if (
  2223. !container &&
  2224. !existingTextElement &&
  2225. (shouldBind || parentCenterPosition)
  2226. ) {
  2227. container = getTextBindableContainerAtPosition(
  2228. this.scene
  2229. .getNonDeletedElements()
  2230. .filter(
  2231. (ele) =>
  2232. isTextBindableContainer(ele, false) && !getBoundTextElement(ele),
  2233. ),
  2234. sceneX,
  2235. sceneY,
  2236. );
  2237. }
  2238. if (!existingTextElement && container) {
  2239. const fontString = {
  2240. fontSize: this.state.currentItemFontSize,
  2241. fontFamily: this.state.currentItemFontFamily,
  2242. };
  2243. const minWidth = getApproxMinLineWidth(getFontString(fontString));
  2244. const minHeight = getApproxMinLineHeight(getFontString(fontString));
  2245. const containerDims = getContainerDims(container);
  2246. const newHeight = Math.max(containerDims.height, minHeight);
  2247. const newWidth = Math.max(containerDims.width, minWidth);
  2248. mutateElement(container, { height: newHeight, width: newWidth });
  2249. sceneX = container.x + newWidth / 2;
  2250. sceneY = container.y + newHeight / 2;
  2251. if (parentCenterPosition) {
  2252. parentCenterPosition = this.getTextWysiwygSnappedToCenterPosition(
  2253. sceneX,
  2254. sceneY,
  2255. this.state,
  2256. this.canvas,
  2257. window.devicePixelRatio,
  2258. );
  2259. }
  2260. }
  2261. const element = existingTextElement
  2262. ? existingTextElement
  2263. : newTextElement({
  2264. x: parentCenterPosition
  2265. ? parentCenterPosition.elementCenterX
  2266. : sceneX,
  2267. y: parentCenterPosition
  2268. ? parentCenterPosition.elementCenterY
  2269. : sceneY,
  2270. strokeColor: this.state.currentItemStrokeColor,
  2271. backgroundColor: this.state.currentItemBackgroundColor,
  2272. fillStyle: this.state.currentItemFillStyle,
  2273. strokeWidth: this.state.currentItemStrokeWidth,
  2274. strokeStyle: this.state.currentItemStrokeStyle,
  2275. roughness: this.state.currentItemRoughness,
  2276. opacity: this.state.currentItemOpacity,
  2277. strokeSharpness: this.state.currentItemStrokeSharpness,
  2278. text: "",
  2279. fontSize: this.state.currentItemFontSize,
  2280. fontFamily: this.state.currentItemFontFamily,
  2281. textAlign: parentCenterPosition
  2282. ? "center"
  2283. : this.state.currentItemTextAlign,
  2284. verticalAlign: parentCenterPosition
  2285. ? VERTICAL_ALIGN.MIDDLE
  2286. : DEFAULT_VERTICAL_ALIGN,
  2287. containerId: container?.id ?? undefined,
  2288. groupIds: container?.groupIds ?? [],
  2289. locked: false,
  2290. });
  2291. this.setState({ editingElement: element });
  2292. if (!existingTextElement) {
  2293. this.scene.replaceAllElements([
  2294. ...this.scene.getElementsIncludingDeleted(),
  2295. element,
  2296. ]);
  2297. // case: creating new text not centered to parent element → offset Y
  2298. // so that the text is centered to cursor position
  2299. if (!parentCenterPosition) {
  2300. mutateElement(element, {
  2301. y: element.y - element.baseline / 2,
  2302. });
  2303. }
  2304. }
  2305. this.setState({
  2306. editingElement: element,
  2307. });
  2308. this.handleTextWysiwyg(element, {
  2309. isExistingElement: !!existingTextElement,
  2310. });
  2311. };
  2312. private handleCanvasDoubleClick = (
  2313. event: React.MouseEvent<HTMLCanvasElement>,
  2314. ) => {
  2315. // case: double-clicking with arrow/line tool selected would both create
  2316. // text and enter multiElement mode
  2317. if (this.state.multiElement) {
  2318. return;
  2319. }
  2320. // we should only be able to double click when mode is selection
  2321. if (this.state.activeTool.type !== "selection") {
  2322. return;
  2323. }
  2324. const selectedElements = getSelectedElements(
  2325. this.scene.getNonDeletedElements(),
  2326. this.state,
  2327. );
  2328. if (selectedElements.length === 1 && isLinearElement(selectedElements[0])) {
  2329. if (
  2330. !this.state.editingLinearElement ||
  2331. this.state.editingLinearElement.elementId !== selectedElements[0].id
  2332. ) {
  2333. this.history.resumeRecording();
  2334. this.setState({
  2335. editingLinearElement: new LinearElementEditor(
  2336. selectedElements[0],
  2337. this.scene,
  2338. ),
  2339. });
  2340. }
  2341. return;
  2342. }
  2343. resetCursor(this.canvas);
  2344. let { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  2345. event,
  2346. this.state,
  2347. );
  2348. const selectedGroupIds = getSelectedGroupIds(this.state);
  2349. if (selectedGroupIds.length > 0) {
  2350. const hitElement = this.getElementAtPosition(sceneX, sceneY);
  2351. const selectedGroupId =
  2352. hitElement &&
  2353. getSelectedGroupIdForElement(hitElement, this.state.selectedGroupIds);
  2354. if (selectedGroupId) {
  2355. this.setState((prevState) =>
  2356. selectGroupsForSelectedElements(
  2357. {
  2358. ...prevState,
  2359. editingGroupId: selectedGroupId,
  2360. selectedElementIds: { [hitElement!.id]: true },
  2361. selectedGroupIds: {},
  2362. },
  2363. this.scene.getNonDeletedElements(),
  2364. ),
  2365. );
  2366. return;
  2367. }
  2368. }
  2369. resetCursor(this.canvas);
  2370. if (!event[KEYS.CTRL_OR_CMD] && !this.state.viewModeEnabled) {
  2371. const selectedElements = getSelectedElements(
  2372. this.scene.getNonDeletedElements(),
  2373. this.state,
  2374. );
  2375. if (selectedElements.length === 1) {
  2376. const selectedElement = selectedElements[0];
  2377. const canBindText = hasBoundTextElement(selectedElement);
  2378. if (canBindText) {
  2379. sceneX = selectedElement.x + selectedElement.width / 2;
  2380. sceneY = selectedElement.y + selectedElement.height / 2;
  2381. }
  2382. }
  2383. this.startTextEditing({
  2384. sceneX,
  2385. sceneY,
  2386. shouldBind: false,
  2387. insertAtParentCenter: !event.altKey,
  2388. });
  2389. }
  2390. };
  2391. private getElementLinkAtPosition = (
  2392. scenePointer: Readonly<{ x: number; y: number }>,
  2393. hitElement: NonDeletedExcalidrawElement | null,
  2394. ): ExcalidrawElement | undefined => {
  2395. // Reversing so we traverse the elements in decreasing order
  2396. // of z-index
  2397. const elements = this.scene.getNonDeletedElements().slice().reverse();
  2398. let hitElementIndex = Infinity;
  2399. return elements.find((element, index) => {
  2400. if (hitElement && element.id === hitElement.id) {
  2401. hitElementIndex = index;
  2402. }
  2403. return (
  2404. element.link &&
  2405. index <= hitElementIndex &&
  2406. isPointHittingLinkIcon(
  2407. element,
  2408. this.state,
  2409. [scenePointer.x, scenePointer.y],
  2410. this.device.isMobile,
  2411. )
  2412. );
  2413. });
  2414. };
  2415. private redirectToLink = (
  2416. event: React.PointerEvent<HTMLCanvasElement>,
  2417. isTouchScreen: boolean,
  2418. ) => {
  2419. const draggedDistance = distance2d(
  2420. this.lastPointerDown!.clientX,
  2421. this.lastPointerDown!.clientY,
  2422. this.lastPointerUp!.clientX,
  2423. this.lastPointerUp!.clientY,
  2424. );
  2425. if (
  2426. !this.hitLinkElement ||
  2427. // For touch screen allow dragging threshold else strict check
  2428. (isTouchScreen && draggedDistance > DRAGGING_THRESHOLD) ||
  2429. (!isTouchScreen && draggedDistance !== 0)
  2430. ) {
  2431. return;
  2432. }
  2433. const lastPointerDownCoords = viewportCoordsToSceneCoords(
  2434. this.lastPointerDown!,
  2435. this.state,
  2436. );
  2437. const lastPointerDownHittingLinkIcon = isPointHittingLinkIcon(
  2438. this.hitLinkElement,
  2439. this.state,
  2440. [lastPointerDownCoords.x, lastPointerDownCoords.y],
  2441. this.device.isMobile,
  2442. );
  2443. const lastPointerUpCoords = viewportCoordsToSceneCoords(
  2444. this.lastPointerUp!,
  2445. this.state,
  2446. );
  2447. const lastPointerUpHittingLinkIcon = isPointHittingLinkIcon(
  2448. this.hitLinkElement,
  2449. this.state,
  2450. [lastPointerUpCoords.x, lastPointerUpCoords.y],
  2451. this.device.isMobile,
  2452. );
  2453. if (lastPointerDownHittingLinkIcon && lastPointerUpHittingLinkIcon) {
  2454. const url = this.hitLinkElement.link;
  2455. if (url) {
  2456. let customEvent;
  2457. if (this.props.onLinkOpen) {
  2458. customEvent = wrapEvent(EVENT.EXCALIDRAW_LINK, event.nativeEvent);
  2459. this.props.onLinkOpen(this.hitLinkElement, customEvent);
  2460. }
  2461. if (!customEvent?.defaultPrevented) {
  2462. const target = isLocalLink(url) ? "_self" : "_blank";
  2463. const newWindow = window.open(undefined, target);
  2464. // https://mathiasbynens.github.io/rel-noopener/
  2465. if (newWindow) {
  2466. newWindow.opener = null;
  2467. newWindow.location = normalizeLink(url);
  2468. }
  2469. }
  2470. }
  2471. }
  2472. };
  2473. private handleCanvasPointerMove = (
  2474. event: React.PointerEvent<HTMLCanvasElement>,
  2475. ) => {
  2476. this.savePointer(event.clientX, event.clientY, this.state.cursorButton);
  2477. if (gesture.pointers.has(event.pointerId)) {
  2478. gesture.pointers.set(event.pointerId, {
  2479. x: event.clientX,
  2480. y: event.clientY,
  2481. });
  2482. }
  2483. const initialScale = gesture.initialScale;
  2484. if (
  2485. gesture.pointers.size === 2 &&
  2486. gesture.lastCenter &&
  2487. initialScale &&
  2488. gesture.initialDistance
  2489. ) {
  2490. const center = getCenter(gesture.pointers);
  2491. const deltaX = center.x - gesture.lastCenter.x;
  2492. const deltaY = center.y - gesture.lastCenter.y;
  2493. gesture.lastCenter = center;
  2494. const distance = getDistance(Array.from(gesture.pointers.values()));
  2495. const scaleFactor =
  2496. this.state.activeTool.type === "freedraw" && this.state.penMode
  2497. ? 1
  2498. : distance / gesture.initialDistance;
  2499. const nextZoom = scaleFactor
  2500. ? getNormalizedZoom(initialScale * scaleFactor)
  2501. : this.state.zoom.value;
  2502. this.setState((state) => {
  2503. const zoomState = getStateForZoom(
  2504. {
  2505. viewportX: center.x,
  2506. viewportY: center.y,
  2507. nextZoom,
  2508. },
  2509. state,
  2510. );
  2511. return {
  2512. zoom: zoomState.zoom,
  2513. scrollX: zoomState.scrollX + deltaX / nextZoom,
  2514. scrollY: zoomState.scrollY + deltaY / nextZoom,
  2515. shouldCacheIgnoreZoom: true,
  2516. };
  2517. });
  2518. this.resetShouldCacheIgnoreZoomDebounced();
  2519. } else {
  2520. gesture.lastCenter =
  2521. gesture.initialDistance =
  2522. gesture.initialScale =
  2523. null;
  2524. }
  2525. if (isHoldingSpace || isPanning || isDraggingScrollBar) {
  2526. return;
  2527. }
  2528. const isPointerOverScrollBars = isOverScrollBars(
  2529. currentScrollBars,
  2530. event.clientX - this.state.offsetLeft,
  2531. event.clientY - this.state.offsetTop,
  2532. );
  2533. const isOverScrollBar = isPointerOverScrollBars.isOverEither;
  2534. if (!this.state.draggingElement && !this.state.multiElement) {
  2535. if (isOverScrollBar) {
  2536. resetCursor(this.canvas);
  2537. } else {
  2538. setCursorForShape(this.canvas, this.state);
  2539. }
  2540. }
  2541. const scenePointer = viewportCoordsToSceneCoords(event, this.state);
  2542. const { x: scenePointerX, y: scenePointerY } = scenePointer;
  2543. if (
  2544. this.state.editingLinearElement &&
  2545. !this.state.editingLinearElement.isDragging
  2546. ) {
  2547. const editingLinearElement = LinearElementEditor.handlePointerMove(
  2548. event,
  2549. scenePointerX,
  2550. scenePointerY,
  2551. this.state,
  2552. );
  2553. if (
  2554. editingLinearElement &&
  2555. editingLinearElement !== this.state.editingLinearElement
  2556. ) {
  2557. // Since we are reading from previous state which is not possible with
  2558. // automatic batching in React 18 hence using flush sync to synchronously
  2559. // update the state. Check https://github.com/excalidraw/excalidraw/pull/5508 for more details.
  2560. flushSync(() => {
  2561. this.setState({
  2562. editingLinearElement,
  2563. });
  2564. });
  2565. }
  2566. if (editingLinearElement?.lastUncommittedPoint != null) {
  2567. this.maybeSuggestBindingAtCursor(scenePointer);
  2568. } else {
  2569. this.setState({ suggestedBindings: [] });
  2570. }
  2571. }
  2572. if (isBindingElementType(this.state.activeTool.type)) {
  2573. // Hovering with a selected tool or creating new linear element via click
  2574. // and point
  2575. const { draggingElement } = this.state;
  2576. if (isBindingElement(draggingElement, false)) {
  2577. this.maybeSuggestBindingsForLinearElementAtCoords(
  2578. draggingElement,
  2579. [scenePointer],
  2580. this.state.startBoundElement,
  2581. );
  2582. } else {
  2583. this.maybeSuggestBindingAtCursor(scenePointer);
  2584. }
  2585. }
  2586. if (this.state.multiElement) {
  2587. const { multiElement } = this.state;
  2588. const { x: rx, y: ry } = multiElement;
  2589. const { points, lastCommittedPoint } = multiElement;
  2590. const lastPoint = points[points.length - 1];
  2591. setCursorForShape(this.canvas, this.state);
  2592. if (lastPoint === lastCommittedPoint) {
  2593. // if we haven't yet created a temp point and we're beyond commit-zone
  2594. // threshold, add a point
  2595. if (
  2596. distance2d(
  2597. scenePointerX - rx,
  2598. scenePointerY - ry,
  2599. lastPoint[0],
  2600. lastPoint[1],
  2601. ) >= LINE_CONFIRM_THRESHOLD
  2602. ) {
  2603. mutateElement(multiElement, {
  2604. points: [...points, [scenePointerX - rx, scenePointerY - ry]],
  2605. });
  2606. } else {
  2607. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  2608. // in this branch, we're inside the commit zone, and no uncommitted
  2609. // point exists. Thus do nothing (don't add/remove points).
  2610. }
  2611. } else if (
  2612. points.length > 2 &&
  2613. lastCommittedPoint &&
  2614. distance2d(
  2615. scenePointerX - rx,
  2616. scenePointerY - ry,
  2617. lastCommittedPoint[0],
  2618. lastCommittedPoint[1],
  2619. ) < LINE_CONFIRM_THRESHOLD
  2620. ) {
  2621. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  2622. mutateElement(multiElement, {
  2623. points: points.slice(0, -1),
  2624. });
  2625. } else {
  2626. const [gridX, gridY] = getGridPoint(
  2627. scenePointerX,
  2628. scenePointerY,
  2629. this.state.gridSize,
  2630. );
  2631. const [lastCommittedX, lastCommittedY] =
  2632. multiElement?.lastCommittedPoint ?? [0, 0];
  2633. let dxFromLastCommitted = gridX - rx - lastCommittedX;
  2634. let dyFromLastCommitted = gridY - ry - lastCommittedY;
  2635. if (shouldRotateWithDiscreteAngle(event)) {
  2636. ({ width: dxFromLastCommitted, height: dyFromLastCommitted } =
  2637. getLockedLinearCursorAlignSize(
  2638. // actual coordinate of the last committed point
  2639. lastCommittedX + rx,
  2640. lastCommittedY + ry,
  2641. // cursor-grid coordinate
  2642. gridX,
  2643. gridY,
  2644. ));
  2645. }
  2646. if (isPathALoop(points, this.state.zoom.value)) {
  2647. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  2648. }
  2649. // update last uncommitted point
  2650. mutateElement(multiElement, {
  2651. points: [
  2652. ...points.slice(0, -1),
  2653. [
  2654. lastCommittedX + dxFromLastCommitted,
  2655. lastCommittedY + dyFromLastCommitted,
  2656. ],
  2657. ],
  2658. });
  2659. }
  2660. return;
  2661. }
  2662. const hasDeselectedButton = Boolean(event.buttons);
  2663. if (
  2664. hasDeselectedButton ||
  2665. (this.state.activeTool.type !== "selection" &&
  2666. this.state.activeTool.type !== "text" &&
  2667. this.state.activeTool.type !== "eraser")
  2668. ) {
  2669. return;
  2670. }
  2671. const elements = this.scene.getNonDeletedElements();
  2672. const selectedElements = getSelectedElements(elements, this.state);
  2673. if (
  2674. selectedElements.length === 1 &&
  2675. !isOverScrollBar &&
  2676. !this.state.editingLinearElement
  2677. ) {
  2678. const elementWithTransformHandleType = getElementWithTransformHandleType(
  2679. elements,
  2680. this.state,
  2681. scenePointerX,
  2682. scenePointerY,
  2683. this.state.zoom,
  2684. event.pointerType,
  2685. );
  2686. if (
  2687. elementWithTransformHandleType &&
  2688. elementWithTransformHandleType.transformHandleType
  2689. ) {
  2690. setCursor(
  2691. this.canvas,
  2692. getCursorForResizingElement(elementWithTransformHandleType),
  2693. );
  2694. return;
  2695. }
  2696. } else if (selectedElements.length > 1 && !isOverScrollBar) {
  2697. const transformHandleType = getTransformHandleTypeFromCoords(
  2698. getCommonBounds(selectedElements),
  2699. scenePointerX,
  2700. scenePointerY,
  2701. this.state.zoom,
  2702. event.pointerType,
  2703. );
  2704. if (transformHandleType) {
  2705. setCursor(
  2706. this.canvas,
  2707. getCursorForResizingElement({
  2708. transformHandleType,
  2709. }),
  2710. );
  2711. return;
  2712. }
  2713. }
  2714. const hitElement = this.getElementAtPosition(
  2715. scenePointer.x,
  2716. scenePointer.y,
  2717. );
  2718. this.hitLinkElement = this.getElementLinkAtPosition(
  2719. scenePointer,
  2720. hitElement,
  2721. );
  2722. if (isEraserActive(this.state)) {
  2723. return;
  2724. }
  2725. if (
  2726. this.hitLinkElement &&
  2727. !this.state.selectedElementIds[this.hitLinkElement.id]
  2728. ) {
  2729. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  2730. showHyperlinkTooltip(this.hitLinkElement, this.state);
  2731. } else {
  2732. hideHyperlinkToolip();
  2733. if (
  2734. hitElement &&
  2735. hitElement.link &&
  2736. this.state.selectedElementIds[hitElement.id] &&
  2737. !this.contextMenuOpen &&
  2738. !this.state.showHyperlinkPopup
  2739. ) {
  2740. this.setState({ showHyperlinkPopup: "info" });
  2741. } else if (this.state.activeTool.type === "text") {
  2742. setCursor(
  2743. this.canvas,
  2744. isTextElement(hitElement) ? CURSOR_TYPE.TEXT : CURSOR_TYPE.CROSSHAIR,
  2745. );
  2746. } else if (this.state.viewModeEnabled) {
  2747. setCursor(this.canvas, CURSOR_TYPE.GRAB);
  2748. } else if (isOverScrollBar) {
  2749. setCursor(this.canvas, CURSOR_TYPE.AUTO);
  2750. } else if (this.state.selectedLinearElement) {
  2751. this.handleHoverSelectedLinearElement(
  2752. this.state.selectedLinearElement,
  2753. scenePointerX,
  2754. scenePointerY,
  2755. );
  2756. } else if (
  2757. // if using cmd/ctrl, we're not dragging
  2758. !event[KEYS.CTRL_OR_CMD] &&
  2759. (hitElement ||
  2760. this.isHittingCommonBoundingBoxOfSelectedElements(
  2761. scenePointer,
  2762. selectedElements,
  2763. )) &&
  2764. !hitElement?.locked
  2765. ) {
  2766. setCursor(this.canvas, CURSOR_TYPE.MOVE);
  2767. } else {
  2768. setCursor(this.canvas, CURSOR_TYPE.AUTO);
  2769. }
  2770. }
  2771. };
  2772. private handleEraser = (
  2773. event: PointerEvent,
  2774. pointerDownState: PointerDownState,
  2775. scenePointer: { x: number; y: number },
  2776. ) => {
  2777. const updateElementIds = (elements: ExcalidrawElement[]) => {
  2778. elements.forEach((element) => {
  2779. if (element.locked) {
  2780. return;
  2781. }
  2782. idsToUpdate.push(element.id);
  2783. if (event.altKey) {
  2784. if (
  2785. pointerDownState.elementIdsToErase[element.id] &&
  2786. pointerDownState.elementIdsToErase[element.id].erase
  2787. ) {
  2788. pointerDownState.elementIdsToErase[element.id].erase = false;
  2789. }
  2790. } else if (!pointerDownState.elementIdsToErase[element.id]) {
  2791. pointerDownState.elementIdsToErase[element.id] = {
  2792. erase: true,
  2793. opacity: element.opacity,
  2794. };
  2795. }
  2796. });
  2797. };
  2798. const idsToUpdate: Array<string> = [];
  2799. const distance = distance2d(
  2800. pointerDownState.lastCoords.x,
  2801. pointerDownState.lastCoords.y,
  2802. scenePointer.x,
  2803. scenePointer.y,
  2804. );
  2805. const threshold = 10 / this.state.zoom.value;
  2806. const point = { ...pointerDownState.lastCoords };
  2807. let samplingInterval = 0;
  2808. while (samplingInterval <= distance) {
  2809. const hitElements = this.getElementsAtPosition(point.x, point.y);
  2810. updateElementIds(hitElements);
  2811. // Exit since we reached current point
  2812. if (samplingInterval === distance) {
  2813. break;
  2814. }
  2815. // Calculate next point in the line at a distance of sampling interval
  2816. samplingInterval = Math.min(samplingInterval + threshold, distance);
  2817. const distanceRatio = samplingInterval / distance;
  2818. const nextX =
  2819. (1 - distanceRatio) * point.x + distanceRatio * scenePointer.x;
  2820. const nextY =
  2821. (1 - distanceRatio) * point.y + distanceRatio * scenePointer.y;
  2822. point.x = nextX;
  2823. point.y = nextY;
  2824. }
  2825. const elements = this.scene.getElementsIncludingDeleted().map((ele) => {
  2826. const id =
  2827. isBoundToContainer(ele) && idsToUpdate.includes(ele.containerId)
  2828. ? ele.containerId
  2829. : ele.id;
  2830. if (idsToUpdate.includes(id)) {
  2831. if (event.altKey) {
  2832. if (
  2833. pointerDownState.elementIdsToErase[id] &&
  2834. pointerDownState.elementIdsToErase[id].erase === false
  2835. ) {
  2836. return newElementWith(ele, {
  2837. opacity: pointerDownState.elementIdsToErase[id].opacity,
  2838. });
  2839. }
  2840. } else {
  2841. return newElementWith(ele, {
  2842. opacity: ELEMENT_READY_TO_ERASE_OPACITY,
  2843. });
  2844. }
  2845. }
  2846. return ele;
  2847. });
  2848. this.scene.replaceAllElements(elements);
  2849. pointerDownState.lastCoords.x = scenePointer.x;
  2850. pointerDownState.lastCoords.y = scenePointer.y;
  2851. };
  2852. // set touch moving for mobile context menu
  2853. private handleTouchMove = (event: React.TouchEvent<HTMLCanvasElement>) => {
  2854. invalidateContextMenu = true;
  2855. };
  2856. handleHoverSelectedLinearElement(
  2857. linearElementEditor: LinearElementEditor,
  2858. scenePointerX: number,
  2859. scenePointerY: number,
  2860. ) {
  2861. const element = LinearElementEditor.getElement(
  2862. linearElementEditor.elementId,
  2863. );
  2864. if (!element) {
  2865. return;
  2866. }
  2867. if (this.state.selectedLinearElement) {
  2868. let hoverPointIndex = -1;
  2869. let segmentMidPointHoveredCoords = null;
  2870. if (
  2871. isHittingElementNotConsideringBoundingBox(element, this.state, [
  2872. scenePointerX,
  2873. scenePointerY,
  2874. ])
  2875. ) {
  2876. hoverPointIndex = LinearElementEditor.getPointIndexUnderCursor(
  2877. element,
  2878. this.state.zoom,
  2879. scenePointerX,
  2880. scenePointerY,
  2881. );
  2882. segmentMidPointHoveredCoords =
  2883. LinearElementEditor.getSegmentMidpointHitCoords(
  2884. linearElementEditor,
  2885. { x: scenePointerX, y: scenePointerY },
  2886. this.state,
  2887. );
  2888. if (hoverPointIndex >= 0 || segmentMidPointHoveredCoords) {
  2889. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  2890. } else {
  2891. setCursor(this.canvas, CURSOR_TYPE.MOVE);
  2892. }
  2893. } else if (
  2894. shouldShowBoundingBox([element], this.state) &&
  2895. isHittingElementBoundingBoxWithoutHittingElement(
  2896. element,
  2897. this.state,
  2898. scenePointerX,
  2899. scenePointerY,
  2900. )
  2901. ) {
  2902. setCursor(this.canvas, CURSOR_TYPE.MOVE);
  2903. }
  2904. if (
  2905. this.state.selectedLinearElement.hoverPointIndex !== hoverPointIndex
  2906. ) {
  2907. this.setState({
  2908. selectedLinearElement: {
  2909. ...this.state.selectedLinearElement,
  2910. hoverPointIndex,
  2911. },
  2912. });
  2913. }
  2914. if (
  2915. !LinearElementEditor.arePointsEqual(
  2916. this.state.selectedLinearElement.segmentMidPointHoveredCoords,
  2917. segmentMidPointHoveredCoords,
  2918. )
  2919. ) {
  2920. this.setState({
  2921. selectedLinearElement: {
  2922. ...this.state.selectedLinearElement,
  2923. segmentMidPointHoveredCoords,
  2924. },
  2925. });
  2926. }
  2927. } else {
  2928. setCursor(this.canvas, CURSOR_TYPE.AUTO);
  2929. }
  2930. }
  2931. private handleCanvasPointerDown = (
  2932. event: React.PointerEvent<HTMLCanvasElement>,
  2933. ) => {
  2934. // remove any active selection when we start to interact with canvas
  2935. // (mainly, we care about removing selection outside the component which
  2936. // would prevent our copy handling otherwise)
  2937. const selection = document.getSelection();
  2938. if (selection?.anchorNode) {
  2939. selection.removeAllRanges();
  2940. }
  2941. this.maybeOpenContextMenuAfterPointerDownOnTouchDevices(event);
  2942. this.maybeCleanupAfterMissingPointerUp(event);
  2943. //fires only once, if pen is detected, penMode is enabled
  2944. //the user can disable this by toggling the penMode button
  2945. if (!this.state.penDetected && event.pointerType === "pen") {
  2946. this.setState((prevState) => {
  2947. return {
  2948. penMode: true,
  2949. penDetected: true,
  2950. };
  2951. });
  2952. }
  2953. if (
  2954. !this.device.isTouchScreen &&
  2955. ["pen", "touch"].includes(event.pointerType)
  2956. ) {
  2957. this.device = updateObject(this.device, { isTouchScreen: true });
  2958. }
  2959. if (isPanning) {
  2960. return;
  2961. }
  2962. this.lastPointerDown = event;
  2963. this.setState({
  2964. lastPointerDownWith: event.pointerType,
  2965. cursorButton: "down",
  2966. });
  2967. this.savePointer(event.clientX, event.clientY, "down");
  2968. this.updateGestureOnPointerDown(event);
  2969. if (this.handleCanvasPanUsingWheelOrSpaceDrag(event)) {
  2970. return;
  2971. }
  2972. // only handle left mouse button or touch
  2973. if (
  2974. event.button !== POINTER_BUTTON.MAIN &&
  2975. event.button !== POINTER_BUTTON.TOUCH
  2976. ) {
  2977. return;
  2978. }
  2979. // don't select while panning
  2980. if (gesture.pointers.size > 1) {
  2981. return;
  2982. }
  2983. // State for the duration of a pointer interaction, which starts with a
  2984. // pointerDown event, ends with a pointerUp event (or another pointerDown)
  2985. const pointerDownState = this.initialPointerDownState(event);
  2986. if (this.handleDraggingScrollBar(event, pointerDownState)) {
  2987. return;
  2988. }
  2989. // Since context menu closes on pointer down so setting to false
  2990. this.contextMenuOpen = false;
  2991. this.clearSelectionIfNotUsingSelection();
  2992. this.updateBindingEnabledOnPointerMove(event);
  2993. if (this.handleSelectionOnPointerDown(event, pointerDownState)) {
  2994. return;
  2995. }
  2996. const allowOnPointerDown =
  2997. !this.state.penMode ||
  2998. event.pointerType !== "touch" ||
  2999. this.state.activeTool.type === "selection" ||
  3000. this.state.activeTool.type === "text" ||
  3001. this.state.activeTool.type === "image";
  3002. if (!allowOnPointerDown) {
  3003. return;
  3004. }
  3005. if (this.state.activeTool.type === "text") {
  3006. this.handleTextOnPointerDown(event, pointerDownState);
  3007. return;
  3008. } else if (
  3009. this.state.activeTool.type === "arrow" ||
  3010. this.state.activeTool.type === "line"
  3011. ) {
  3012. this.handleLinearElementOnPointerDown(
  3013. event,
  3014. this.state.activeTool.type,
  3015. pointerDownState,
  3016. );
  3017. } else if (this.state.activeTool.type === "image") {
  3018. // reset image preview on pointerdown
  3019. setCursor(this.canvas, CURSOR_TYPE.CROSSHAIR);
  3020. // retrieve the latest element as the state may be stale
  3021. const pendingImageElement =
  3022. this.state.pendingImageElementId &&
  3023. this.scene.getElement(this.state.pendingImageElementId);
  3024. if (!pendingImageElement) {
  3025. return;
  3026. }
  3027. this.setState({
  3028. draggingElement: pendingImageElement,
  3029. editingElement: pendingImageElement,
  3030. pendingImageElementId: null,
  3031. multiElement: null,
  3032. });
  3033. const { x, y } = viewportCoordsToSceneCoords(event, this.state);
  3034. mutateElement(pendingImageElement, {
  3035. x,
  3036. y,
  3037. });
  3038. } else if (this.state.activeTool.type === "freedraw") {
  3039. this.handleFreeDrawElementOnPointerDown(
  3040. event,
  3041. this.state.activeTool.type,
  3042. pointerDownState,
  3043. );
  3044. } else if (this.state.activeTool.type === "custom") {
  3045. setCursor(this.canvas, CURSOR_TYPE.AUTO);
  3046. } else if (this.state.activeTool.type !== "eraser") {
  3047. this.createGenericElementOnPointerDown(
  3048. this.state.activeTool.type,
  3049. pointerDownState,
  3050. );
  3051. }
  3052. this.props?.onPointerDown?.(this.state.activeTool, pointerDownState);
  3053. const onPointerMove =
  3054. this.onPointerMoveFromPointerDownHandler(pointerDownState);
  3055. const onPointerUp =
  3056. this.onPointerUpFromPointerDownHandler(pointerDownState);
  3057. const onKeyDown = this.onKeyDownFromPointerDownHandler(pointerDownState);
  3058. const onKeyUp = this.onKeyUpFromPointerDownHandler(pointerDownState);
  3059. lastPointerUp = onPointerUp;
  3060. if (!this.state.viewModeEnabled) {
  3061. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
  3062. window.addEventListener(EVENT.POINTER_UP, onPointerUp);
  3063. window.addEventListener(EVENT.KEYDOWN, onKeyDown);
  3064. window.addEventListener(EVENT.KEYUP, onKeyUp);
  3065. pointerDownState.eventListeners.onMove = onPointerMove;
  3066. pointerDownState.eventListeners.onUp = onPointerUp;
  3067. pointerDownState.eventListeners.onKeyUp = onKeyUp;
  3068. pointerDownState.eventListeners.onKeyDown = onKeyDown;
  3069. }
  3070. };
  3071. private handleCanvasPointerUp = (
  3072. event: React.PointerEvent<HTMLCanvasElement>,
  3073. ) => {
  3074. this.lastPointerUp = event;
  3075. if (this.device.isTouchScreen) {
  3076. const scenePointer = viewportCoordsToSceneCoords(
  3077. { clientX: event.clientX, clientY: event.clientY },
  3078. this.state,
  3079. );
  3080. const hitElement = this.getElementAtPosition(
  3081. scenePointer.x,
  3082. scenePointer.y,
  3083. );
  3084. this.hitLinkElement = this.getElementLinkAtPosition(
  3085. scenePointer,
  3086. hitElement,
  3087. );
  3088. }
  3089. if (
  3090. this.hitLinkElement &&
  3091. !this.state.selectedElementIds[this.hitLinkElement.id]
  3092. ) {
  3093. this.redirectToLink(event, this.device.isTouchScreen);
  3094. }
  3095. this.removePointer(event);
  3096. };
  3097. private maybeOpenContextMenuAfterPointerDownOnTouchDevices = (
  3098. event: React.PointerEvent<HTMLCanvasElement>,
  3099. ): void => {
  3100. // deal with opening context menu on touch devices
  3101. if (event.pointerType === "touch") {
  3102. invalidateContextMenu = false;
  3103. if (touchTimeout) {
  3104. // If there's already a touchTimeout, this means that there's another
  3105. // touch down and we are doing another touch, so we shouldn't open the
  3106. // context menu.
  3107. invalidateContextMenu = true;
  3108. } else {
  3109. // open the context menu with the first touch's clientX and clientY
  3110. // if the touch is not moving
  3111. touchTimeout = window.setTimeout(() => {
  3112. touchTimeout = 0;
  3113. if (!invalidateContextMenu) {
  3114. this.handleCanvasContextMenu(event);
  3115. }
  3116. }, TOUCH_CTX_MENU_TIMEOUT);
  3117. }
  3118. }
  3119. };
  3120. private resetContextMenuTimer = () => {
  3121. clearTimeout(touchTimeout);
  3122. touchTimeout = 0;
  3123. invalidateContextMenu = false;
  3124. };
  3125. private maybeCleanupAfterMissingPointerUp(
  3126. event: React.PointerEvent<HTMLCanvasElement>,
  3127. ): void {
  3128. if (lastPointerUp !== null) {
  3129. // Unfortunately, sometimes we don't get a pointerup after a pointerdown,
  3130. // this can happen when a contextual menu or alert is triggered. In order to avoid
  3131. // being in a weird state, we clean up on the next pointerdown
  3132. lastPointerUp(event);
  3133. }
  3134. }
  3135. // Returns whether the event is a panning
  3136. private handleCanvasPanUsingWheelOrSpaceDrag = (
  3137. event: React.PointerEvent<HTMLCanvasElement>,
  3138. ): boolean => {
  3139. if (
  3140. !(
  3141. gesture.pointers.size <= 1 &&
  3142. (event.button === POINTER_BUTTON.WHEEL ||
  3143. (event.button === POINTER_BUTTON.MAIN && isHoldingSpace) ||
  3144. this.state.viewModeEnabled)
  3145. ) ||
  3146. isTextElement(this.state.editingElement)
  3147. ) {
  3148. return false;
  3149. }
  3150. isPanning = true;
  3151. event.preventDefault();
  3152. let nextPastePrevented = false;
  3153. const isLinux = /Linux/.test(window.navigator.platform);
  3154. setCursor(this.canvas, CURSOR_TYPE.GRABBING);
  3155. let { clientX: lastX, clientY: lastY } = event;
  3156. const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
  3157. const deltaX = lastX - event.clientX;
  3158. const deltaY = lastY - event.clientY;
  3159. lastX = event.clientX;
  3160. lastY = event.clientY;
  3161. /*
  3162. * Prevent paste event if we move while middle clicking on Linux.
  3163. * See issue #1383.
  3164. */
  3165. if (
  3166. isLinux &&
  3167. !nextPastePrevented &&
  3168. (Math.abs(deltaX) > 1 || Math.abs(deltaY) > 1)
  3169. ) {
  3170. nextPastePrevented = true;
  3171. /* Prevent the next paste event */
  3172. const preventNextPaste = (event: ClipboardEvent) => {
  3173. document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
  3174. event.stopPropagation();
  3175. };
  3176. /*
  3177. * Reenable next paste in case of disabled middle click paste for
  3178. * any reason:
  3179. * - right click paste
  3180. * - empty clipboard
  3181. */
  3182. const enableNextPaste = () => {
  3183. setTimeout(() => {
  3184. document.body.removeEventListener(EVENT.PASTE, preventNextPaste);
  3185. window.removeEventListener(EVENT.POINTER_UP, enableNextPaste);
  3186. }, 100);
  3187. };
  3188. document.body.addEventListener(EVENT.PASTE, preventNextPaste);
  3189. window.addEventListener(EVENT.POINTER_UP, enableNextPaste);
  3190. }
  3191. this.setState({
  3192. scrollX: this.state.scrollX - deltaX / this.state.zoom.value,
  3193. scrollY: this.state.scrollY - deltaY / this.state.zoom.value,
  3194. });
  3195. });
  3196. const teardown = withBatchedUpdates(
  3197. (lastPointerUp = () => {
  3198. lastPointerUp = null;
  3199. isPanning = false;
  3200. if (!isHoldingSpace) {
  3201. if (this.state.viewModeEnabled) {
  3202. setCursor(this.canvas, CURSOR_TYPE.GRAB);
  3203. } else {
  3204. setCursorForShape(this.canvas, this.state);
  3205. }
  3206. }
  3207. this.setState({
  3208. cursorButton: "up",
  3209. });
  3210. this.savePointer(event.clientX, event.clientY, "up");
  3211. window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
  3212. window.removeEventListener(EVENT.POINTER_UP, teardown);
  3213. window.removeEventListener(EVENT.BLUR, teardown);
  3214. onPointerMove.flush();
  3215. }),
  3216. );
  3217. window.addEventListener(EVENT.BLUR, teardown);
  3218. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove, {
  3219. passive: true,
  3220. });
  3221. window.addEventListener(EVENT.POINTER_UP, teardown);
  3222. return true;
  3223. };
  3224. private updateGestureOnPointerDown(
  3225. event: React.PointerEvent<HTMLCanvasElement>,
  3226. ): void {
  3227. gesture.pointers.set(event.pointerId, {
  3228. x: event.clientX,
  3229. y: event.clientY,
  3230. });
  3231. if (gesture.pointers.size === 2) {
  3232. gesture.lastCenter = getCenter(gesture.pointers);
  3233. gesture.initialScale = this.state.zoom.value;
  3234. gesture.initialDistance = getDistance(
  3235. Array.from(gesture.pointers.values()),
  3236. );
  3237. }
  3238. }
  3239. private initialPointerDownState(
  3240. event: React.PointerEvent<HTMLCanvasElement>,
  3241. ): PointerDownState {
  3242. const origin = viewportCoordsToSceneCoords(event, this.state);
  3243. const selectedElements = getSelectedElements(
  3244. this.scene.getNonDeletedElements(),
  3245. this.state,
  3246. );
  3247. const [minX, minY, maxX, maxY] = getCommonBounds(selectedElements);
  3248. return {
  3249. origin,
  3250. withCmdOrCtrl: event[KEYS.CTRL_OR_CMD],
  3251. originInGrid: tupleToCoors(
  3252. getGridPoint(origin.x, origin.y, this.state.gridSize),
  3253. ),
  3254. scrollbars: isOverScrollBars(
  3255. currentScrollBars,
  3256. event.clientX - this.state.offsetLeft,
  3257. event.clientY - this.state.offsetTop,
  3258. ),
  3259. // we need to duplicate because we'll be updating this state
  3260. lastCoords: { ...origin },
  3261. originalElements: this.scene
  3262. .getNonDeletedElements()
  3263. .reduce((acc, element) => {
  3264. acc.set(element.id, deepCopyElement(element));
  3265. return acc;
  3266. }, new Map() as PointerDownState["originalElements"]),
  3267. resize: {
  3268. handleType: false,
  3269. isResizing: false,
  3270. offset: { x: 0, y: 0 },
  3271. arrowDirection: "origin",
  3272. center: { x: (maxX + minX) / 2, y: (maxY + minY) / 2 },
  3273. },
  3274. hit: {
  3275. element: null,
  3276. allHitElements: [],
  3277. wasAddedToSelection: false,
  3278. hasBeenDuplicated: false,
  3279. hasHitCommonBoundingBoxOfSelectedElements:
  3280. this.isHittingCommonBoundingBoxOfSelectedElements(
  3281. origin,
  3282. selectedElements,
  3283. ),
  3284. },
  3285. drag: {
  3286. hasOccurred: false,
  3287. offset: null,
  3288. },
  3289. eventListeners: {
  3290. onMove: null,
  3291. onUp: null,
  3292. onKeyUp: null,
  3293. onKeyDown: null,
  3294. },
  3295. boxSelection: {
  3296. hasOccurred: false,
  3297. },
  3298. elementIdsToErase: {},
  3299. };
  3300. }
  3301. // Returns whether the event is a dragging a scrollbar
  3302. private handleDraggingScrollBar(
  3303. event: React.PointerEvent<HTMLCanvasElement>,
  3304. pointerDownState: PointerDownState,
  3305. ): boolean {
  3306. if (
  3307. !(pointerDownState.scrollbars.isOverEither && !this.state.multiElement)
  3308. ) {
  3309. return false;
  3310. }
  3311. isDraggingScrollBar = true;
  3312. pointerDownState.lastCoords.x = event.clientX;
  3313. pointerDownState.lastCoords.y = event.clientY;
  3314. const onPointerMove = withBatchedUpdatesThrottled((event: PointerEvent) => {
  3315. const target = event.target;
  3316. if (!(target instanceof HTMLElement)) {
  3317. return;
  3318. }
  3319. this.handlePointerMoveOverScrollbars(event, pointerDownState);
  3320. });
  3321. const onPointerUp = withBatchedUpdates(() => {
  3322. isDraggingScrollBar = false;
  3323. setCursorForShape(this.canvas, this.state);
  3324. lastPointerUp = null;
  3325. this.setState({
  3326. cursorButton: "up",
  3327. });
  3328. this.savePointer(event.clientX, event.clientY, "up");
  3329. window.removeEventListener(EVENT.POINTER_MOVE, onPointerMove);
  3330. window.removeEventListener(EVENT.POINTER_UP, onPointerUp);
  3331. onPointerMove.flush();
  3332. });
  3333. lastPointerUp = onPointerUp;
  3334. window.addEventListener(EVENT.POINTER_MOVE, onPointerMove);
  3335. window.addEventListener(EVENT.POINTER_UP, onPointerUp);
  3336. return true;
  3337. }
  3338. private clearSelectionIfNotUsingSelection = (): void => {
  3339. if (this.state.activeTool.type !== "selection") {
  3340. this.setState({
  3341. selectedElementIds: {},
  3342. selectedGroupIds: {},
  3343. editingGroupId: null,
  3344. });
  3345. }
  3346. };
  3347. /**
  3348. * @returns whether the pointer event has been completely handled
  3349. */
  3350. private handleSelectionOnPointerDown = (
  3351. event: React.PointerEvent<HTMLCanvasElement>,
  3352. pointerDownState: PointerDownState,
  3353. ): boolean => {
  3354. if (this.state.activeTool.type === "selection") {
  3355. const elements = this.scene.getNonDeletedElements();
  3356. const selectedElements = getSelectedElements(elements, this.state);
  3357. if (selectedElements.length === 1 && !this.state.editingLinearElement) {
  3358. const elementWithTransformHandleType =
  3359. getElementWithTransformHandleType(
  3360. elements,
  3361. this.state,
  3362. pointerDownState.origin.x,
  3363. pointerDownState.origin.y,
  3364. this.state.zoom,
  3365. event.pointerType,
  3366. );
  3367. if (elementWithTransformHandleType != null) {
  3368. this.setState({
  3369. resizingElement: elementWithTransformHandleType.element,
  3370. });
  3371. pointerDownState.resize.handleType =
  3372. elementWithTransformHandleType.transformHandleType;
  3373. }
  3374. } else if (selectedElements.length > 1) {
  3375. pointerDownState.resize.handleType = getTransformHandleTypeFromCoords(
  3376. getCommonBounds(selectedElements),
  3377. pointerDownState.origin.x,
  3378. pointerDownState.origin.y,
  3379. this.state.zoom,
  3380. event.pointerType,
  3381. );
  3382. }
  3383. if (pointerDownState.resize.handleType) {
  3384. setCursor(
  3385. this.canvas,
  3386. getCursorForResizingElement({
  3387. transformHandleType: pointerDownState.resize.handleType,
  3388. }),
  3389. );
  3390. pointerDownState.resize.isResizing = true;
  3391. pointerDownState.resize.offset = tupleToCoors(
  3392. getResizeOffsetXY(
  3393. pointerDownState.resize.handleType,
  3394. selectedElements,
  3395. pointerDownState.origin.x,
  3396. pointerDownState.origin.y,
  3397. ),
  3398. );
  3399. if (
  3400. selectedElements.length === 1 &&
  3401. isLinearElement(selectedElements[0]) &&
  3402. selectedElements[0].points.length === 2
  3403. ) {
  3404. pointerDownState.resize.arrowDirection = getResizeArrowDirection(
  3405. pointerDownState.resize.handleType,
  3406. selectedElements[0],
  3407. );
  3408. }
  3409. } else {
  3410. if (this.state.selectedLinearElement) {
  3411. const linearElementEditor =
  3412. this.state.editingLinearElement || this.state.selectedLinearElement;
  3413. const ret = LinearElementEditor.handlePointerDown(
  3414. event,
  3415. this.state,
  3416. this.history,
  3417. pointerDownState.origin,
  3418. linearElementEditor,
  3419. );
  3420. if (ret.hitElement) {
  3421. pointerDownState.hit.element = ret.hitElement;
  3422. }
  3423. if (ret.linearElementEditor) {
  3424. this.setState({ selectedLinearElement: ret.linearElementEditor });
  3425. if (this.state.editingLinearElement) {
  3426. this.setState({ editingLinearElement: ret.linearElementEditor });
  3427. }
  3428. }
  3429. if (ret.didAddPoint && !ret.isMidPoint) {
  3430. return true;
  3431. }
  3432. }
  3433. // hitElement may already be set above, so check first
  3434. pointerDownState.hit.element =
  3435. pointerDownState.hit.element ??
  3436. this.getElementAtPosition(
  3437. pointerDownState.origin.x,
  3438. pointerDownState.origin.y,
  3439. );
  3440. if (pointerDownState.hit.element) {
  3441. // Early return if pointer is hitting link icon
  3442. const hitLinkElement = this.getElementLinkAtPosition(
  3443. {
  3444. x: pointerDownState.origin.x,
  3445. y: pointerDownState.origin.y,
  3446. },
  3447. pointerDownState.hit.element,
  3448. );
  3449. if (hitLinkElement) {
  3450. return false;
  3451. }
  3452. }
  3453. // For overlapped elements one position may hit
  3454. // multiple elements
  3455. pointerDownState.hit.allHitElements = this.getElementsAtPosition(
  3456. pointerDownState.origin.x,
  3457. pointerDownState.origin.y,
  3458. );
  3459. const hitElement = pointerDownState.hit.element;
  3460. const someHitElementIsSelected =
  3461. pointerDownState.hit.allHitElements.some((element) =>
  3462. this.isASelectedElement(element),
  3463. );
  3464. if (
  3465. (hitElement === null || !someHitElementIsSelected) &&
  3466. !event.shiftKey &&
  3467. !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
  3468. ) {
  3469. this.clearSelection(hitElement);
  3470. }
  3471. if (this.state.editingLinearElement) {
  3472. this.setState({
  3473. selectedElementIds: {
  3474. [this.state.editingLinearElement.elementId]: true,
  3475. },
  3476. });
  3477. // If we click on something
  3478. } else if (hitElement != null) {
  3479. // on CMD/CTRL, drill down to hit element regardless of groups etc.
  3480. if (event[KEYS.CTRL_OR_CMD]) {
  3481. if (!this.state.selectedElementIds[hitElement.id]) {
  3482. pointerDownState.hit.wasAddedToSelection = true;
  3483. }
  3484. this.setState((prevState) => ({
  3485. ...editGroupForSelectedElement(prevState, hitElement),
  3486. previousSelectedElementIds: this.state.selectedElementIds,
  3487. }));
  3488. // mark as not completely handled so as to allow dragging etc.
  3489. return false;
  3490. }
  3491. // deselect if item is selected
  3492. // if shift is not clicked, this will always return true
  3493. // otherwise, it will trigger selection based on current
  3494. // state of the box
  3495. if (!this.state.selectedElementIds[hitElement.id]) {
  3496. // if we are currently editing a group, exiting editing mode and deselect the group.
  3497. if (
  3498. this.state.editingGroupId &&
  3499. !isElementInGroup(hitElement, this.state.editingGroupId)
  3500. ) {
  3501. this.setState({
  3502. selectedElementIds: {},
  3503. selectedGroupIds: {},
  3504. editingGroupId: null,
  3505. });
  3506. }
  3507. // Add hit element to selection. At this point if we're not holding
  3508. // SHIFT the previously selected element(s) were deselected above
  3509. // (make sure you use setState updater to use latest state)
  3510. if (
  3511. !someHitElementIsSelected &&
  3512. !pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements
  3513. ) {
  3514. this.setState((prevState) => {
  3515. return selectGroupsForSelectedElements(
  3516. {
  3517. ...prevState,
  3518. selectedElementIds: {
  3519. ...prevState.selectedElementIds,
  3520. [hitElement.id]: true,
  3521. },
  3522. showHyperlinkPopup: hitElement.link ? "info" : false,
  3523. },
  3524. this.scene.getNonDeletedElements(),
  3525. );
  3526. });
  3527. pointerDownState.hit.wasAddedToSelection = true;
  3528. }
  3529. }
  3530. }
  3531. this.setState({
  3532. previousSelectedElementIds: this.state.selectedElementIds,
  3533. });
  3534. }
  3535. }
  3536. return false;
  3537. };
  3538. private isASelectedElement(hitElement: ExcalidrawElement | null): boolean {
  3539. return hitElement != null && this.state.selectedElementIds[hitElement.id];
  3540. }
  3541. private isHittingCommonBoundingBoxOfSelectedElements(
  3542. point: Readonly<{ x: number; y: number }>,
  3543. selectedElements: readonly ExcalidrawElement[],
  3544. ): boolean {
  3545. if (selectedElements.length < 2) {
  3546. return false;
  3547. }
  3548. // How many pixels off the shape boundary we still consider a hit
  3549. const threshold = 10 / this.state.zoom.value;
  3550. const [x1, y1, x2, y2] = getCommonBounds(selectedElements);
  3551. return (
  3552. point.x > x1 - threshold &&
  3553. point.x < x2 + threshold &&
  3554. point.y > y1 - threshold &&
  3555. point.y < y2 + threshold
  3556. );
  3557. }
  3558. private handleTextOnPointerDown = (
  3559. event: React.PointerEvent<HTMLCanvasElement>,
  3560. pointerDownState: PointerDownState,
  3561. ): void => {
  3562. // if we're currently still editing text, clicking outside
  3563. // should only finalize it, not create another (irrespective
  3564. // of state.activeTool.locked)
  3565. if (isTextElement(this.state.editingElement)) {
  3566. return;
  3567. }
  3568. let sceneX = pointerDownState.origin.x;
  3569. let sceneY = pointerDownState.origin.y;
  3570. const element = this.getElementAtPosition(sceneX, sceneY, {
  3571. includeBoundTextElement: true,
  3572. });
  3573. const canBindText = hasBoundTextElement(element);
  3574. if (canBindText) {
  3575. sceneX = element.x + element.width / 2;
  3576. sceneY = element.y + element.height / 2;
  3577. }
  3578. this.startTextEditing({
  3579. sceneX,
  3580. sceneY,
  3581. shouldBind: false,
  3582. insertAtParentCenter: !event.altKey,
  3583. });
  3584. resetCursor(this.canvas);
  3585. if (!this.state.activeTool.locked) {
  3586. this.setState({
  3587. activeTool: updateActiveTool(this.state, { type: "selection" }),
  3588. });
  3589. }
  3590. };
  3591. private handleFreeDrawElementOnPointerDown = (
  3592. event: React.PointerEvent<HTMLCanvasElement>,
  3593. elementType: ExcalidrawFreeDrawElement["type"],
  3594. pointerDownState: PointerDownState,
  3595. ) => {
  3596. // Begin a mark capture. This does not have to update state yet.
  3597. const [gridX, gridY] = getGridPoint(
  3598. pointerDownState.origin.x,
  3599. pointerDownState.origin.y,
  3600. null,
  3601. );
  3602. const element = newFreeDrawElement({
  3603. type: elementType,
  3604. x: gridX,
  3605. y: gridY,
  3606. strokeColor: this.state.currentItemStrokeColor,
  3607. backgroundColor: this.state.currentItemBackgroundColor,
  3608. fillStyle: this.state.currentItemFillStyle,
  3609. strokeWidth: this.state.currentItemStrokeWidth,
  3610. strokeStyle: this.state.currentItemStrokeStyle,
  3611. roughness: this.state.currentItemRoughness,
  3612. opacity: this.state.currentItemOpacity,
  3613. strokeSharpness: this.state.currentItemLinearStrokeSharpness,
  3614. simulatePressure: event.pressure === 0.5,
  3615. locked: false,
  3616. });
  3617. this.setState((prevState) => ({
  3618. selectedElementIds: {
  3619. ...prevState.selectedElementIds,
  3620. [element.id]: false,
  3621. },
  3622. }));
  3623. const pressures = element.simulatePressure
  3624. ? element.pressures
  3625. : [...element.pressures, event.pressure];
  3626. mutateElement(element, {
  3627. points: [[0, 0]],
  3628. pressures,
  3629. });
  3630. const boundElement = getHoveredElementForBinding(
  3631. pointerDownState.origin,
  3632. this.scene,
  3633. );
  3634. this.scene.replaceAllElements([
  3635. ...this.scene.getElementsIncludingDeleted(),
  3636. element,
  3637. ]);
  3638. this.setState({
  3639. draggingElement: element,
  3640. editingElement: element,
  3641. startBoundElement: boundElement,
  3642. suggestedBindings: [],
  3643. });
  3644. };
  3645. private createImageElement = ({
  3646. sceneX,
  3647. sceneY,
  3648. }: {
  3649. sceneX: number;
  3650. sceneY: number;
  3651. }) => {
  3652. const [gridX, gridY] = getGridPoint(sceneX, sceneY, this.state.gridSize);
  3653. const element = newImageElement({
  3654. type: "image",
  3655. x: gridX,
  3656. y: gridY,
  3657. strokeColor: this.state.currentItemStrokeColor,
  3658. backgroundColor: this.state.currentItemBackgroundColor,
  3659. fillStyle: this.state.currentItemFillStyle,
  3660. strokeWidth: this.state.currentItemStrokeWidth,
  3661. strokeStyle: this.state.currentItemStrokeStyle,
  3662. roughness: this.state.currentItemRoughness,
  3663. opacity: this.state.currentItemOpacity,
  3664. strokeSharpness: this.state.currentItemLinearStrokeSharpness,
  3665. locked: false,
  3666. });
  3667. return element;
  3668. };
  3669. private handleLinearElementOnPointerDown = (
  3670. event: React.PointerEvent<HTMLCanvasElement>,
  3671. elementType: ExcalidrawLinearElement["type"],
  3672. pointerDownState: PointerDownState,
  3673. ): void => {
  3674. if (this.state.multiElement) {
  3675. const { multiElement } = this.state;
  3676. // finalize if completing a loop
  3677. if (
  3678. multiElement.type === "line" &&
  3679. isPathALoop(multiElement.points, this.state.zoom.value)
  3680. ) {
  3681. mutateElement(multiElement, {
  3682. lastCommittedPoint:
  3683. multiElement.points[multiElement.points.length - 1],
  3684. });
  3685. this.actionManager.executeAction(actionFinalize);
  3686. return;
  3687. }
  3688. const { x: rx, y: ry, lastCommittedPoint } = multiElement;
  3689. // clicking inside commit zone → finalize arrow
  3690. if (
  3691. multiElement.points.length > 1 &&
  3692. lastCommittedPoint &&
  3693. distance2d(
  3694. pointerDownState.origin.x - rx,
  3695. pointerDownState.origin.y - ry,
  3696. lastCommittedPoint[0],
  3697. lastCommittedPoint[1],
  3698. ) < LINE_CONFIRM_THRESHOLD
  3699. ) {
  3700. this.actionManager.executeAction(actionFinalize);
  3701. return;
  3702. }
  3703. this.setState((prevState) => ({
  3704. selectedElementIds: {
  3705. ...prevState.selectedElementIds,
  3706. [multiElement.id]: true,
  3707. },
  3708. }));
  3709. // clicking outside commit zone → update reference for last committed
  3710. // point
  3711. mutateElement(multiElement, {
  3712. lastCommittedPoint: multiElement.points[multiElement.points.length - 1],
  3713. });
  3714. setCursor(this.canvas, CURSOR_TYPE.POINTER);
  3715. } else {
  3716. const [gridX, gridY] = getGridPoint(
  3717. pointerDownState.origin.x,
  3718. pointerDownState.origin.y,
  3719. this.state.gridSize,
  3720. );
  3721. /* If arrow is pre-arrowheads, it will have undefined for both start and end arrowheads.
  3722. If so, we want it to be null for start and "arrow" for end. If the linear item is not
  3723. an arrow, we want it to be null for both. Otherwise, we want it to use the
  3724. values from appState. */
  3725. const { currentItemStartArrowhead, currentItemEndArrowhead } = this.state;
  3726. const [startArrowhead, endArrowhead] =
  3727. elementType === "arrow"
  3728. ? [currentItemStartArrowhead, currentItemEndArrowhead]
  3729. : [null, null];
  3730. const element = newLinearElement({
  3731. type: elementType,
  3732. x: gridX,
  3733. y: gridY,
  3734. strokeColor: this.state.currentItemStrokeColor,
  3735. backgroundColor: this.state.currentItemBackgroundColor,
  3736. fillStyle: this.state.currentItemFillStyle,
  3737. strokeWidth: this.state.currentItemStrokeWidth,
  3738. strokeStyle: this.state.currentItemStrokeStyle,
  3739. roughness: this.state.currentItemRoughness,
  3740. opacity: this.state.currentItemOpacity,
  3741. strokeSharpness: this.state.currentItemLinearStrokeSharpness,
  3742. startArrowhead,
  3743. endArrowhead,
  3744. locked: false,
  3745. });
  3746. this.setState((prevState) => ({
  3747. selectedElementIds: {
  3748. ...prevState.selectedElementIds,
  3749. [element.id]: false,
  3750. },
  3751. }));
  3752. mutateElement(element, {
  3753. points: [...element.points, [0, 0]],
  3754. });
  3755. const boundElement = getHoveredElementForBinding(
  3756. pointerDownState.origin,
  3757. this.scene,
  3758. );
  3759. this.scene.replaceAllElements([
  3760. ...this.scene.getElementsIncludingDeleted(),
  3761. element,
  3762. ]);
  3763. this.setState({
  3764. draggingElement: element,
  3765. editingElement: element,
  3766. startBoundElement: boundElement,
  3767. suggestedBindings: [],
  3768. });
  3769. }
  3770. };
  3771. private createGenericElementOnPointerDown = (
  3772. elementType: ExcalidrawGenericElement["type"],
  3773. pointerDownState: PointerDownState,
  3774. ): void => {
  3775. const [gridX, gridY] = getGridPoint(
  3776. pointerDownState.origin.x,
  3777. pointerDownState.origin.y,
  3778. this.state.gridSize,
  3779. );
  3780. const element = newElement({
  3781. type: elementType,
  3782. x: gridX,
  3783. y: gridY,
  3784. strokeColor: this.state.currentItemStrokeColor,
  3785. backgroundColor: this.state.currentItemBackgroundColor,
  3786. fillStyle: this.state.currentItemFillStyle,
  3787. strokeWidth: this.state.currentItemStrokeWidth,
  3788. strokeStyle: this.state.currentItemStrokeStyle,
  3789. roughness: this.state.currentItemRoughness,
  3790. opacity: this.state.currentItemOpacity,
  3791. strokeSharpness: this.state.currentItemStrokeSharpness,
  3792. locked: false,
  3793. });
  3794. if (element.type === "selection") {
  3795. this.setState({
  3796. selectionElement: element,
  3797. draggingElement: element,
  3798. });
  3799. } else {
  3800. this.scene.replaceAllElements([
  3801. ...this.scene.getElementsIncludingDeleted(),
  3802. element,
  3803. ]);
  3804. this.setState({
  3805. multiElement: null,
  3806. draggingElement: element,
  3807. editingElement: element,
  3808. });
  3809. }
  3810. };
  3811. private onKeyDownFromPointerDownHandler(
  3812. pointerDownState: PointerDownState,
  3813. ): (event: KeyboardEvent) => void {
  3814. return withBatchedUpdates((event: KeyboardEvent) => {
  3815. if (this.maybeHandleResize(pointerDownState, event)) {
  3816. return;
  3817. }
  3818. this.maybeDragNewGenericElement(pointerDownState, event);
  3819. });
  3820. }
  3821. private onKeyUpFromPointerDownHandler(
  3822. pointerDownState: PointerDownState,
  3823. ): (event: KeyboardEvent) => void {
  3824. return withBatchedUpdates((event: KeyboardEvent) => {
  3825. // Prevents focus from escaping excalidraw tab
  3826. event.key === KEYS.ALT && event.preventDefault();
  3827. if (this.maybeHandleResize(pointerDownState, event)) {
  3828. return;
  3829. }
  3830. this.maybeDragNewGenericElement(pointerDownState, event);
  3831. });
  3832. }
  3833. private onPointerMoveFromPointerDownHandler(
  3834. pointerDownState: PointerDownState,
  3835. ) {
  3836. return withBatchedUpdatesThrottled((event: PointerEvent) => {
  3837. // We need to initialize dragOffsetXY only after we've updated
  3838. // `state.selectedElementIds` on pointerDown. Doing it here in pointerMove
  3839. // event handler should hopefully ensure we're already working with
  3840. // the updated state.
  3841. if (pointerDownState.drag.offset === null) {
  3842. pointerDownState.drag.offset = tupleToCoors(
  3843. getDragOffsetXY(
  3844. getSelectedElements(this.scene.getNonDeletedElements(), this.state),
  3845. pointerDownState.origin.x,
  3846. pointerDownState.origin.y,
  3847. ),
  3848. );
  3849. }
  3850. const target = event.target;
  3851. if (!(target instanceof HTMLElement)) {
  3852. return;
  3853. }
  3854. if (this.handlePointerMoveOverScrollbars(event, pointerDownState)) {
  3855. return;
  3856. }
  3857. const pointerCoords = viewportCoordsToSceneCoords(event, this.state);
  3858. if (isEraserActive(this.state)) {
  3859. this.handleEraser(event, pointerDownState, pointerCoords);
  3860. return;
  3861. }
  3862. const [gridX, gridY] = getGridPoint(
  3863. pointerCoords.x,
  3864. pointerCoords.y,
  3865. this.state.gridSize,
  3866. );
  3867. // for arrows/lines, don't start dragging until a given threshold
  3868. // to ensure we don't create a 2-point arrow by mistake when
  3869. // user clicks mouse in a way that it moves a tiny bit (thus
  3870. // triggering pointermove)
  3871. if (
  3872. !pointerDownState.drag.hasOccurred &&
  3873. (this.state.activeTool.type === "arrow" ||
  3874. this.state.activeTool.type === "line")
  3875. ) {
  3876. if (
  3877. distance2d(
  3878. pointerCoords.x,
  3879. pointerCoords.y,
  3880. pointerDownState.origin.x,
  3881. pointerDownState.origin.y,
  3882. ) < DRAGGING_THRESHOLD
  3883. ) {
  3884. return;
  3885. }
  3886. }
  3887. if (pointerDownState.resize.isResizing) {
  3888. pointerDownState.lastCoords.x = pointerCoords.x;
  3889. pointerDownState.lastCoords.y = pointerCoords.y;
  3890. if (this.maybeHandleResize(pointerDownState, event)) {
  3891. return true;
  3892. }
  3893. }
  3894. if (this.state.selectedLinearElement) {
  3895. const linearElementEditor =
  3896. this.state.editingLinearElement || this.state.selectedLinearElement;
  3897. const didDrag = LinearElementEditor.handlePointDragging(
  3898. event,
  3899. this.state,
  3900. pointerCoords.x,
  3901. pointerCoords.y,
  3902. (element, pointsSceneCoords) => {
  3903. this.maybeSuggestBindingsForLinearElementAtCoords(
  3904. element,
  3905. pointsSceneCoords,
  3906. );
  3907. },
  3908. linearElementEditor,
  3909. );
  3910. if (didDrag) {
  3911. pointerDownState.lastCoords.x = pointerCoords.x;
  3912. pointerDownState.lastCoords.y = pointerCoords.y;
  3913. pointerDownState.drag.hasOccurred = true;
  3914. if (
  3915. this.state.editingLinearElement &&
  3916. !this.state.editingLinearElement.isDragging
  3917. ) {
  3918. this.setState({
  3919. editingLinearElement: {
  3920. ...this.state.editingLinearElement,
  3921. isDragging: true,
  3922. },
  3923. });
  3924. }
  3925. if (!this.state.selectedLinearElement.isDragging) {
  3926. this.setState({
  3927. selectedLinearElement: {
  3928. ...this.state.selectedLinearElement,
  3929. isDragging: true,
  3930. },
  3931. });
  3932. }
  3933. return;
  3934. }
  3935. }
  3936. const hasHitASelectedElement = pointerDownState.hit.allHitElements.some(
  3937. (element) => this.isASelectedElement(element),
  3938. );
  3939. const isSelectingPointsInLineEditor =
  3940. this.state.editingLinearElement &&
  3941. event.shiftKey &&
  3942. this.state.editingLinearElement.elementId ===
  3943. pointerDownState.hit.element?.id;
  3944. if (
  3945. (hasHitASelectedElement ||
  3946. pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements) &&
  3947. !isSelectingPointsInLineEditor
  3948. ) {
  3949. const selectedElements = getSelectedElements(
  3950. this.scene.getNonDeletedElements(),
  3951. this.state,
  3952. );
  3953. if (selectedElements.every((element) => element.locked)) {
  3954. return;
  3955. }
  3956. // Marking that click was used for dragging to check
  3957. // if elements should be deselected on pointerup
  3958. pointerDownState.drag.hasOccurred = true;
  3959. // prevent dragging even if we're no longer holding cmd/ctrl otherwise
  3960. // it would have weird results (stuff jumping all over the screen)
  3961. if (selectedElements.length > 0 && !pointerDownState.withCmdOrCtrl) {
  3962. const [dragX, dragY] = getGridPoint(
  3963. pointerCoords.x - pointerDownState.drag.offset.x,
  3964. pointerCoords.y - pointerDownState.drag.offset.y,
  3965. this.state.gridSize,
  3966. );
  3967. const [dragDistanceX, dragDistanceY] = [
  3968. Math.abs(pointerCoords.x - pointerDownState.origin.x),
  3969. Math.abs(pointerCoords.y - pointerDownState.origin.y),
  3970. ];
  3971. // We only drag in one direction if shift is pressed
  3972. const lockDirection = event.shiftKey;
  3973. dragSelectedElements(
  3974. pointerDownState,
  3975. selectedElements,
  3976. dragX,
  3977. dragY,
  3978. lockDirection,
  3979. dragDistanceX,
  3980. dragDistanceY,
  3981. this.state,
  3982. );
  3983. this.maybeSuggestBindingForAll(selectedElements);
  3984. // We duplicate the selected element if alt is pressed on pointer move
  3985. if (event.altKey && !pointerDownState.hit.hasBeenDuplicated) {
  3986. // Move the currently selected elements to the top of the z index stack, and
  3987. // put the duplicates where the selected elements used to be.
  3988. // (the origin point where the dragging started)
  3989. pointerDownState.hit.hasBeenDuplicated = true;
  3990. const nextElements = [];
  3991. const elementsToAppend = [];
  3992. const groupIdMap = new Map();
  3993. const oldIdToDuplicatedId = new Map();
  3994. const hitElement = pointerDownState.hit.element;
  3995. const elements = this.scene.getElementsIncludingDeleted();
  3996. const selectedElementIds: Array<ExcalidrawElement["id"]> =
  3997. getSelectedElements(elements, this.state, true).map(
  3998. (element) => element.id,
  3999. );
  4000. for (const element of elements) {
  4001. if (
  4002. selectedElementIds.includes(element.id) ||
  4003. // case: the state.selectedElementIds might not have been
  4004. // updated yet by the time this mousemove event is fired
  4005. (element.id === hitElement?.id &&
  4006. pointerDownState.hit.wasAddedToSelection)
  4007. ) {
  4008. const duplicatedElement = duplicateElement(
  4009. this.state.editingGroupId,
  4010. groupIdMap,
  4011. element,
  4012. );
  4013. const [originDragX, originDragY] = getGridPoint(
  4014. pointerDownState.origin.x - pointerDownState.drag.offset.x,
  4015. pointerDownState.origin.y - pointerDownState.drag.offset.y,
  4016. this.state.gridSize,
  4017. );
  4018. mutateElement(duplicatedElement, {
  4019. x: duplicatedElement.x + (originDragX - dragX),
  4020. y: duplicatedElement.y + (originDragY - dragY),
  4021. });
  4022. nextElements.push(duplicatedElement);
  4023. elementsToAppend.push(element);
  4024. oldIdToDuplicatedId.set(element.id, duplicatedElement.id);
  4025. } else {
  4026. nextElements.push(element);
  4027. }
  4028. }
  4029. const nextSceneElements = [...nextElements, ...elementsToAppend];
  4030. bindTextToShapeAfterDuplication(
  4031. nextElements,
  4032. elementsToAppend,
  4033. oldIdToDuplicatedId,
  4034. );
  4035. fixBindingsAfterDuplication(
  4036. nextSceneElements,
  4037. elementsToAppend,
  4038. oldIdToDuplicatedId,
  4039. "duplicatesServeAsOld",
  4040. );
  4041. this.scene.replaceAllElements(nextSceneElements);
  4042. }
  4043. return;
  4044. }
  4045. }
  4046. // It is very important to read this.state within each move event,
  4047. // otherwise we would read a stale one!
  4048. const draggingElement = this.state.draggingElement;
  4049. if (!draggingElement) {
  4050. return;
  4051. }
  4052. if (draggingElement.type === "freedraw") {
  4053. const points = draggingElement.points;
  4054. const dx = pointerCoords.x - draggingElement.x;
  4055. const dy = pointerCoords.y - draggingElement.y;
  4056. const lastPoint = points.length > 0 && points[points.length - 1];
  4057. const discardPoint =
  4058. lastPoint && lastPoint[0] === dx && lastPoint[1] === dy;
  4059. if (!discardPoint) {
  4060. const pressures = draggingElement.simulatePressure
  4061. ? draggingElement.pressures
  4062. : [...draggingElement.pressures, event.pressure];
  4063. mutateElement(draggingElement, {
  4064. points: [...points, [dx, dy]],
  4065. pressures,
  4066. });
  4067. }
  4068. } else if (isLinearElement(draggingElement)) {
  4069. pointerDownState.drag.hasOccurred = true;
  4070. const points = draggingElement.points;
  4071. let dx = gridX - draggingElement.x;
  4072. let dy = gridY - draggingElement.y;
  4073. if (shouldRotateWithDiscreteAngle(event) && points.length === 2) {
  4074. ({ width: dx, height: dy } = getLockedLinearCursorAlignSize(
  4075. draggingElement.x,
  4076. draggingElement.y,
  4077. pointerCoords.x,
  4078. pointerCoords.y,
  4079. ));
  4080. }
  4081. if (points.length === 1) {
  4082. mutateElement(draggingElement, {
  4083. points: [...points, [dx, dy]],
  4084. });
  4085. } else if (points.length === 2) {
  4086. mutateElement(draggingElement, {
  4087. points: [...points.slice(0, -1), [dx, dy]],
  4088. });
  4089. }
  4090. if (isBindingElement(draggingElement, false)) {
  4091. // When creating a linear element by dragging
  4092. this.maybeSuggestBindingsForLinearElementAtCoords(
  4093. draggingElement,
  4094. [pointerCoords],
  4095. this.state.startBoundElement,
  4096. );
  4097. }
  4098. } else {
  4099. pointerDownState.lastCoords.x = pointerCoords.x;
  4100. pointerDownState.lastCoords.y = pointerCoords.y;
  4101. this.maybeDragNewGenericElement(pointerDownState, event);
  4102. }
  4103. if (this.state.activeTool.type === "selection") {
  4104. pointerDownState.boxSelection.hasOccurred = true;
  4105. const elements = this.scene.getNonDeletedElements();
  4106. if (
  4107. !event.shiftKey &&
  4108. // allows for box-selecting points (without shift)
  4109. !this.state.editingLinearElement &&
  4110. isSomeElementSelected(elements, this.state)
  4111. ) {
  4112. if (pointerDownState.withCmdOrCtrl && pointerDownState.hit.element) {
  4113. this.setState((prevState) =>
  4114. selectGroupsForSelectedElements(
  4115. {
  4116. ...prevState,
  4117. selectedElementIds: {
  4118. [pointerDownState.hit.element!.id]: true,
  4119. },
  4120. },
  4121. this.scene.getNonDeletedElements(),
  4122. ),
  4123. );
  4124. } else {
  4125. this.setState({
  4126. selectedElementIds: {},
  4127. selectedGroupIds: {},
  4128. editingGroupId: null,
  4129. });
  4130. }
  4131. }
  4132. // box-select line editor points
  4133. if (this.state.editingLinearElement) {
  4134. LinearElementEditor.handleBoxSelection(
  4135. event,
  4136. this.state,
  4137. this.setState.bind(this),
  4138. );
  4139. // regular box-select
  4140. } else {
  4141. const elementsWithinSelection = getElementsWithinSelection(
  4142. elements,
  4143. draggingElement,
  4144. );
  4145. this.setState((prevState) =>
  4146. selectGroupsForSelectedElements(
  4147. {
  4148. ...prevState,
  4149. selectedElementIds: {
  4150. ...prevState.selectedElementIds,
  4151. ...elementsWithinSelection.reduce(
  4152. (acc: Record<ExcalidrawElement["id"], true>, element) => {
  4153. acc[element.id] = true;
  4154. return acc;
  4155. },
  4156. {},
  4157. ),
  4158. ...(pointerDownState.hit.element
  4159. ? {
  4160. // if using ctrl/cmd, select the hitElement only if we
  4161. // haven't box-selected anything else
  4162. [pointerDownState.hit.element.id]:
  4163. !elementsWithinSelection.length,
  4164. }
  4165. : null),
  4166. },
  4167. showHyperlinkPopup:
  4168. elementsWithinSelection.length === 1 &&
  4169. elementsWithinSelection[0].link
  4170. ? "info"
  4171. : false,
  4172. // select linear element only when we haven't box-selected anything else
  4173. selectedLinearElement:
  4174. elementsWithinSelection.length === 1 &&
  4175. isLinearElement(elementsWithinSelection[0])
  4176. ? new LinearElementEditor(
  4177. elementsWithinSelection[0],
  4178. this.scene,
  4179. )
  4180. : null,
  4181. },
  4182. this.scene.getNonDeletedElements(),
  4183. ),
  4184. );
  4185. }
  4186. }
  4187. });
  4188. }
  4189. // Returns whether the pointer move happened over either scrollbar
  4190. private handlePointerMoveOverScrollbars(
  4191. event: PointerEvent,
  4192. pointerDownState: PointerDownState,
  4193. ): boolean {
  4194. if (pointerDownState.scrollbars.isOverHorizontal) {
  4195. const x = event.clientX;
  4196. const dx = x - pointerDownState.lastCoords.x;
  4197. this.setState({
  4198. scrollX: this.state.scrollX - dx / this.state.zoom.value,
  4199. });
  4200. pointerDownState.lastCoords.x = x;
  4201. return true;
  4202. }
  4203. if (pointerDownState.scrollbars.isOverVertical) {
  4204. const y = event.clientY;
  4205. const dy = y - pointerDownState.lastCoords.y;
  4206. this.setState({
  4207. scrollY: this.state.scrollY - dy / this.state.zoom.value,
  4208. });
  4209. pointerDownState.lastCoords.y = y;
  4210. return true;
  4211. }
  4212. return false;
  4213. }
  4214. private onPointerUpFromPointerDownHandler(
  4215. pointerDownState: PointerDownState,
  4216. ): (event: PointerEvent) => void {
  4217. return withBatchedUpdates((childEvent: PointerEvent) => {
  4218. const {
  4219. draggingElement,
  4220. resizingElement,
  4221. multiElement,
  4222. activeTool,
  4223. isResizing,
  4224. isRotating,
  4225. } = this.state;
  4226. this.setState({
  4227. isResizing: false,
  4228. isRotating: false,
  4229. resizingElement: null,
  4230. selectionElement: null,
  4231. cursorButton: "up",
  4232. // text elements are reset on finalize, and resetting on pointerup
  4233. // may cause issues with double taps
  4234. editingElement:
  4235. multiElement || isTextElement(this.state.editingElement)
  4236. ? this.state.editingElement
  4237. : null,
  4238. });
  4239. this.savePointer(childEvent.clientX, childEvent.clientY, "up");
  4240. // Handle end of dragging a point of a linear element, might close a loop
  4241. // and sets binding element
  4242. if (this.state.editingLinearElement) {
  4243. if (
  4244. !pointerDownState.boxSelection.hasOccurred &&
  4245. pointerDownState.hit?.element?.id !==
  4246. this.state.editingLinearElement.elementId
  4247. ) {
  4248. this.actionManager.executeAction(actionFinalize);
  4249. } else {
  4250. const editingLinearElement = LinearElementEditor.handlePointerUp(
  4251. childEvent,
  4252. this.state.editingLinearElement,
  4253. this.state,
  4254. );
  4255. if (editingLinearElement !== this.state.editingLinearElement) {
  4256. this.setState({
  4257. editingLinearElement,
  4258. suggestedBindings: [],
  4259. });
  4260. }
  4261. }
  4262. } else if (this.state.selectedLinearElement) {
  4263. if (
  4264. pointerDownState.hit?.element?.id !==
  4265. this.state.selectedLinearElement.elementId
  4266. ) {
  4267. const selectedELements = getSelectedElements(
  4268. this.scene.getNonDeletedElements(),
  4269. this.state,
  4270. );
  4271. // set selectedLinearElement to null if there is more than one element selected since we don't want to show linear element handles
  4272. if (selectedELements.length > 1) {
  4273. this.setState({ selectedLinearElement: null });
  4274. }
  4275. } else {
  4276. const linearElementEditor = LinearElementEditor.handlePointerUp(
  4277. childEvent,
  4278. this.state.selectedLinearElement,
  4279. this.state,
  4280. );
  4281. const { startBindingElement, endBindingElement } =
  4282. linearElementEditor;
  4283. const element = this.scene.getElement(linearElementEditor.elementId);
  4284. if (isBindingElement(element)) {
  4285. bindOrUnbindLinearElement(
  4286. element,
  4287. startBindingElement,
  4288. endBindingElement,
  4289. );
  4290. }
  4291. if (linearElementEditor !== this.state.selectedLinearElement) {
  4292. this.setState({
  4293. selectedLinearElement: {
  4294. ...linearElementEditor,
  4295. selectedPointsIndices: null,
  4296. },
  4297. suggestedBindings: [],
  4298. });
  4299. }
  4300. }
  4301. }
  4302. lastPointerUp = null;
  4303. if (pointerDownState.eventListeners.onMove) {
  4304. pointerDownState.eventListeners.onMove.flush();
  4305. }
  4306. window.removeEventListener(
  4307. EVENT.POINTER_MOVE,
  4308. pointerDownState.eventListeners.onMove!,
  4309. );
  4310. window.removeEventListener(
  4311. EVENT.POINTER_UP,
  4312. pointerDownState.eventListeners.onUp!,
  4313. );
  4314. window.removeEventListener(
  4315. EVENT.KEYDOWN,
  4316. pointerDownState.eventListeners.onKeyDown!,
  4317. );
  4318. window.removeEventListener(
  4319. EVENT.KEYUP,
  4320. pointerDownState.eventListeners.onKeyUp!,
  4321. );
  4322. if (this.state.pendingImageElementId) {
  4323. this.setState({ pendingImageElementId: null });
  4324. }
  4325. if (draggingElement?.type === "freedraw") {
  4326. const pointerCoords = viewportCoordsToSceneCoords(
  4327. childEvent,
  4328. this.state,
  4329. );
  4330. const points = draggingElement.points;
  4331. let dx = pointerCoords.x - draggingElement.x;
  4332. let dy = pointerCoords.y - draggingElement.y;
  4333. // Allows dots to avoid being flagged as infinitely small
  4334. if (dx === points[0][0] && dy === points[0][1]) {
  4335. dy += 0.0001;
  4336. dx += 0.0001;
  4337. }
  4338. const pressures = draggingElement.simulatePressure
  4339. ? []
  4340. : [...draggingElement.pressures, childEvent.pressure];
  4341. mutateElement(draggingElement, {
  4342. points: [...points, [dx, dy]],
  4343. pressures,
  4344. lastCommittedPoint: [dx, dy],
  4345. });
  4346. this.actionManager.executeAction(actionFinalize);
  4347. return;
  4348. }
  4349. if (isImageElement(draggingElement)) {
  4350. const imageElement = draggingElement;
  4351. try {
  4352. this.initializeImageDimensions(imageElement);
  4353. this.setState(
  4354. { selectedElementIds: { [imageElement.id]: true } },
  4355. () => {
  4356. this.actionManager.executeAction(actionFinalize);
  4357. },
  4358. );
  4359. } catch (error: any) {
  4360. console.error(error);
  4361. this.scene.replaceAllElements(
  4362. this.scene
  4363. .getElementsIncludingDeleted()
  4364. .filter((el) => el.id !== imageElement.id),
  4365. );
  4366. this.actionManager.executeAction(actionFinalize);
  4367. }
  4368. return;
  4369. }
  4370. if (isLinearElement(draggingElement)) {
  4371. if (draggingElement!.points.length > 1) {
  4372. this.history.resumeRecording();
  4373. }
  4374. const pointerCoords = viewportCoordsToSceneCoords(
  4375. childEvent,
  4376. this.state,
  4377. );
  4378. if (
  4379. !pointerDownState.drag.hasOccurred &&
  4380. draggingElement &&
  4381. !multiElement
  4382. ) {
  4383. mutateElement(draggingElement, {
  4384. points: [
  4385. ...draggingElement.points,
  4386. [
  4387. pointerCoords.x - draggingElement.x,
  4388. pointerCoords.y - draggingElement.y,
  4389. ],
  4390. ],
  4391. });
  4392. this.setState({
  4393. multiElement: draggingElement,
  4394. editingElement: this.state.draggingElement,
  4395. });
  4396. } else if (pointerDownState.drag.hasOccurred && !multiElement) {
  4397. if (
  4398. isBindingEnabled(this.state) &&
  4399. isBindingElement(draggingElement, false)
  4400. ) {
  4401. maybeBindLinearElement(
  4402. draggingElement,
  4403. this.state,
  4404. this.scene,
  4405. pointerCoords,
  4406. );
  4407. }
  4408. this.setState({ suggestedBindings: [], startBoundElement: null });
  4409. if (!activeTool.locked) {
  4410. resetCursor(this.canvas);
  4411. this.setState((prevState) => ({
  4412. draggingElement: null,
  4413. activeTool: updateActiveTool(this.state, {
  4414. type: "selection",
  4415. }),
  4416. selectedElementIds: {
  4417. ...prevState.selectedElementIds,
  4418. [draggingElement.id]: true,
  4419. },
  4420. selectedLinearElement: new LinearElementEditor(
  4421. draggingElement,
  4422. this.scene,
  4423. ),
  4424. }));
  4425. } else {
  4426. this.setState((prevState) => ({
  4427. draggingElement: null,
  4428. selectedElementIds: {
  4429. ...prevState.selectedElementIds,
  4430. [draggingElement.id]: true,
  4431. },
  4432. }));
  4433. }
  4434. }
  4435. return;
  4436. }
  4437. if (
  4438. activeTool.type !== "selection" &&
  4439. draggingElement &&
  4440. isInvisiblySmallElement(draggingElement)
  4441. ) {
  4442. // remove invisible element which was added in onPointerDown
  4443. this.scene.replaceAllElements(
  4444. this.scene.getElementsIncludingDeleted().slice(0, -1),
  4445. );
  4446. this.setState({
  4447. draggingElement: null,
  4448. });
  4449. return;
  4450. }
  4451. if (draggingElement) {
  4452. mutateElement(
  4453. draggingElement,
  4454. getNormalizedDimensions(draggingElement),
  4455. );
  4456. }
  4457. if (resizingElement) {
  4458. this.history.resumeRecording();
  4459. }
  4460. if (resizingElement && isInvisiblySmallElement(resizingElement)) {
  4461. this.scene.replaceAllElements(
  4462. this.scene
  4463. .getElementsIncludingDeleted()
  4464. .filter((el) => el.id !== resizingElement.id),
  4465. );
  4466. }
  4467. // Code below handles selection when element(s) weren't
  4468. // drag or added to selection on pointer down phase.
  4469. const hitElement = pointerDownState.hit.element;
  4470. if (
  4471. this.state.selectedLinearElement?.elementId !== hitElement?.id &&
  4472. isLinearElement(hitElement)
  4473. ) {
  4474. const selectedELements = getSelectedElements(
  4475. this.scene.getNonDeletedElements(),
  4476. this.state,
  4477. );
  4478. // set selectedLinearElement when no other element selected except
  4479. // the one we've hit
  4480. if (selectedELements.length === 1) {
  4481. this.setState({
  4482. selectedLinearElement: new LinearElementEditor(
  4483. hitElement,
  4484. this.scene,
  4485. ),
  4486. });
  4487. }
  4488. }
  4489. if (isEraserActive(this.state)) {
  4490. const draggedDistance = distance2d(
  4491. this.lastPointerDown!.clientX,
  4492. this.lastPointerDown!.clientY,
  4493. this.lastPointerUp!.clientX,
  4494. this.lastPointerUp!.clientY,
  4495. );
  4496. if (draggedDistance === 0) {
  4497. const scenePointer = viewportCoordsToSceneCoords(
  4498. {
  4499. clientX: this.lastPointerUp!.clientX,
  4500. clientY: this.lastPointerUp!.clientY,
  4501. },
  4502. this.state,
  4503. );
  4504. const hitElements = this.getElementsAtPosition(
  4505. scenePointer.x,
  4506. scenePointer.y,
  4507. );
  4508. hitElements.forEach(
  4509. (hitElement) =>
  4510. (pointerDownState.elementIdsToErase[hitElement.id] = {
  4511. erase: true,
  4512. opacity: hitElement.opacity,
  4513. }),
  4514. );
  4515. }
  4516. this.eraseElements(pointerDownState);
  4517. return;
  4518. } else if (Object.keys(pointerDownState.elementIdsToErase).length) {
  4519. this.restoreReadyToEraseElements(pointerDownState);
  4520. }
  4521. if (
  4522. hitElement &&
  4523. !pointerDownState.drag.hasOccurred &&
  4524. !pointerDownState.hit.wasAddedToSelection &&
  4525. // if we're editing a line, pointerup shouldn't switch selection if
  4526. // box selected
  4527. (!this.state.editingLinearElement ||
  4528. !pointerDownState.boxSelection.hasOccurred)
  4529. ) {
  4530. // when inside line editor, shift selects points instead
  4531. if (childEvent.shiftKey && !this.state.editingLinearElement) {
  4532. if (this.state.selectedElementIds[hitElement.id]) {
  4533. if (isSelectedViaGroup(this.state, hitElement)) {
  4534. // We want to unselect all groups hitElement is part of
  4535. // as well as all elements that are part of the groups
  4536. // hitElement is part of
  4537. const idsOfSelectedElementsThatAreInGroups = hitElement.groupIds
  4538. .flatMap((groupId) =>
  4539. getElementsInGroup(
  4540. this.scene.getNonDeletedElements(),
  4541. groupId,
  4542. ),
  4543. )
  4544. .map((element) => ({ [element.id]: false }))
  4545. .reduce((prevId, acc) => ({ ...prevId, ...acc }), {});
  4546. this.setState((_prevState) => ({
  4547. selectedGroupIds: {
  4548. ..._prevState.selectedElementIds,
  4549. ...hitElement.groupIds
  4550. .map((gId) => ({ [gId]: false }))
  4551. .reduce((prev, acc) => ({ ...prev, ...acc }), {}),
  4552. },
  4553. selectedElementIds: {
  4554. ..._prevState.selectedElementIds,
  4555. ...idsOfSelectedElementsThatAreInGroups,
  4556. },
  4557. }));
  4558. // if not gragging a linear element point (outside editor)
  4559. } else if (!this.state.selectedLinearElement?.isDragging) {
  4560. // remove element from selection while
  4561. // keeping prev elements selected
  4562. this.setState((prevState) => {
  4563. const newSelectedElementIds = {
  4564. ...prevState.selectedElementIds,
  4565. [hitElement!.id]: false,
  4566. };
  4567. const newSelectedElements = getSelectedElements(
  4568. this.scene.getNonDeletedElements(),
  4569. { ...prevState, selectedElementIds: newSelectedElementIds },
  4570. );
  4571. return selectGroupsForSelectedElements(
  4572. {
  4573. ...prevState,
  4574. selectedElementIds: newSelectedElementIds,
  4575. // set selectedLinearElement only if thats the only element selected
  4576. selectedLinearElement:
  4577. newSelectedElements.length === 1 &&
  4578. isLinearElement(newSelectedElements[0])
  4579. ? new LinearElementEditor(
  4580. newSelectedElements[0],
  4581. this.scene,
  4582. )
  4583. : prevState.selectedLinearElement,
  4584. },
  4585. this.scene.getNonDeletedElements(),
  4586. );
  4587. });
  4588. }
  4589. } else {
  4590. // add element to selection while
  4591. // keeping prev elements selected
  4592. this.setState((_prevState) => ({
  4593. selectedElementIds: {
  4594. ..._prevState.selectedElementIds,
  4595. [hitElement!.id]: true,
  4596. },
  4597. }));
  4598. }
  4599. } else {
  4600. this.setState((prevState) => ({
  4601. ...selectGroupsForSelectedElements(
  4602. {
  4603. ...prevState,
  4604. selectedElementIds: { [hitElement.id]: true },
  4605. selectedLinearElement:
  4606. isLinearElement(hitElement) &&
  4607. // Don't set `selectedLinearElement` if its same as the hitElement, this is mainly to prevent resetting the `hoverPointIndex` to -1.
  4608. // Future we should update the API to take care of setting the correct `hoverPointIndex` when initialized
  4609. prevState.selectedLinearElement?.elementId !== hitElement.id
  4610. ? new LinearElementEditor(hitElement, this.scene)
  4611. : prevState.selectedLinearElement,
  4612. },
  4613. this.scene.getNonDeletedElements(),
  4614. ),
  4615. }));
  4616. }
  4617. }
  4618. if (
  4619. !pointerDownState.drag.hasOccurred &&
  4620. !this.state.isResizing &&
  4621. ((hitElement &&
  4622. isHittingElementBoundingBoxWithoutHittingElement(
  4623. hitElement,
  4624. this.state,
  4625. pointerDownState.origin.x,
  4626. pointerDownState.origin.y,
  4627. )) ||
  4628. (!hitElement &&
  4629. pointerDownState.hit.hasHitCommonBoundingBoxOfSelectedElements))
  4630. ) {
  4631. if (this.state.editingLinearElement) {
  4632. this.setState({ editingLinearElement: null });
  4633. } else {
  4634. // Deselect selected elements
  4635. this.setState({
  4636. selectedElementIds: {},
  4637. selectedGroupIds: {},
  4638. editingGroupId: null,
  4639. });
  4640. }
  4641. return;
  4642. }
  4643. if (
  4644. !activeTool.locked &&
  4645. activeTool.type !== "freedraw" &&
  4646. draggingElement
  4647. ) {
  4648. this.setState((prevState) => ({
  4649. selectedElementIds: {
  4650. ...prevState.selectedElementIds,
  4651. [draggingElement.id]: true,
  4652. },
  4653. }));
  4654. }
  4655. if (
  4656. activeTool.type !== "selection" ||
  4657. isSomeElementSelected(this.scene.getNonDeletedElements(), this.state)
  4658. ) {
  4659. this.history.resumeRecording();
  4660. }
  4661. if (pointerDownState.drag.hasOccurred || isResizing || isRotating) {
  4662. (isBindingEnabled(this.state)
  4663. ? bindOrUnbindSelectedElements
  4664. : unbindLinearElements)(
  4665. getSelectedElements(this.scene.getNonDeletedElements(), this.state),
  4666. );
  4667. }
  4668. if (!activeTool.locked && activeTool.type !== "freedraw") {
  4669. resetCursor(this.canvas);
  4670. this.setState({
  4671. draggingElement: null,
  4672. suggestedBindings: [],
  4673. activeTool: updateActiveTool(this.state, { type: "selection" }),
  4674. });
  4675. } else {
  4676. this.setState({
  4677. draggingElement: null,
  4678. suggestedBindings: [],
  4679. });
  4680. }
  4681. });
  4682. }
  4683. private restoreReadyToEraseElements = (
  4684. pointerDownState: PointerDownState,
  4685. ) => {
  4686. const elements = this.scene.getElementsIncludingDeleted().map((ele) => {
  4687. if (
  4688. pointerDownState.elementIdsToErase[ele.id] &&
  4689. pointerDownState.elementIdsToErase[ele.id].erase
  4690. ) {
  4691. return newElementWith(ele, {
  4692. opacity: pointerDownState.elementIdsToErase[ele.id].opacity,
  4693. });
  4694. } else if (
  4695. isBoundToContainer(ele) &&
  4696. pointerDownState.elementIdsToErase[ele.containerId] &&
  4697. pointerDownState.elementIdsToErase[ele.containerId].erase
  4698. ) {
  4699. return newElementWith(ele, {
  4700. opacity: pointerDownState.elementIdsToErase[ele.containerId].opacity,
  4701. });
  4702. }
  4703. return ele;
  4704. });
  4705. this.scene.replaceAllElements(elements);
  4706. };
  4707. private eraseElements = (pointerDownState: PointerDownState) => {
  4708. const elements = this.scene.getElementsIncludingDeleted().map((ele) => {
  4709. if (
  4710. pointerDownState.elementIdsToErase[ele.id] &&
  4711. pointerDownState.elementIdsToErase[ele.id].erase
  4712. ) {
  4713. return newElementWith(ele, { isDeleted: true });
  4714. } else if (
  4715. isBoundToContainer(ele) &&
  4716. pointerDownState.elementIdsToErase[ele.containerId] &&
  4717. pointerDownState.elementIdsToErase[ele.containerId].erase
  4718. ) {
  4719. return newElementWith(ele, { isDeleted: true });
  4720. }
  4721. return ele;
  4722. });
  4723. this.history.resumeRecording();
  4724. this.scene.replaceAllElements(elements);
  4725. };
  4726. private initializeImage = async ({
  4727. imageFile,
  4728. imageElement: _imageElement,
  4729. showCursorImagePreview = false,
  4730. }: {
  4731. imageFile: File;
  4732. imageElement: ExcalidrawImageElement;
  4733. showCursorImagePreview?: boolean;
  4734. }) => {
  4735. // at this point this should be guaranteed image file, but we do this check
  4736. // to satisfy TS down the line
  4737. if (!isSupportedImageFile(imageFile)) {
  4738. throw new Error(t("errors.unsupportedFileType"));
  4739. }
  4740. const mimeType = imageFile.type;
  4741. setCursor(this.canvas, "wait");
  4742. if (mimeType === MIME_TYPES.svg) {
  4743. try {
  4744. imageFile = SVGStringToFile(
  4745. await normalizeSVG(await imageFile.text()),
  4746. imageFile.name,
  4747. );
  4748. } catch (error: any) {
  4749. console.warn(error);
  4750. throw new Error(t("errors.svgImageInsertError"));
  4751. }
  4752. }
  4753. // generate image id (by default the file digest) before any
  4754. // resizing/compression takes place to keep it more portable
  4755. const fileId = await ((this.props.generateIdForFile?.(
  4756. imageFile,
  4757. ) as Promise<FileId>) || generateIdFromFile(imageFile));
  4758. if (!fileId) {
  4759. console.warn(
  4760. "Couldn't generate file id or the supplied `generateIdForFile` didn't resolve to one.",
  4761. );
  4762. throw new Error(t("errors.imageInsertError"));
  4763. }
  4764. const existingFileData = this.files[fileId];
  4765. if (!existingFileData?.dataURL) {
  4766. try {
  4767. imageFile = await resizeImageFile(imageFile, {
  4768. maxWidthOrHeight: DEFAULT_MAX_IMAGE_WIDTH_OR_HEIGHT,
  4769. });
  4770. } catch (error: any) {
  4771. console.error("error trying to resing image file on insertion", error);
  4772. }
  4773. if (imageFile.size > MAX_ALLOWED_FILE_BYTES) {
  4774. throw new Error(
  4775. t("errors.fileTooBig", {
  4776. maxSize: `${Math.trunc(MAX_ALLOWED_FILE_BYTES / 1024 / 1024)}MB`,
  4777. }),
  4778. );
  4779. }
  4780. }
  4781. if (showCursorImagePreview) {
  4782. const dataURL = this.files[fileId]?.dataURL;
  4783. // optimization so that we don't unnecessarily resize the original
  4784. // full-size file for cursor preview
  4785. // (it's much faster to convert the resized dataURL to File)
  4786. const resizedFile = dataURL && dataURLToFile(dataURL);
  4787. this.setImagePreviewCursor(resizedFile || imageFile);
  4788. }
  4789. const dataURL =
  4790. this.files[fileId]?.dataURL || (await getDataURL(imageFile));
  4791. const imageElement = mutateElement(
  4792. _imageElement,
  4793. {
  4794. fileId,
  4795. },
  4796. false,
  4797. ) as NonDeleted<InitializedExcalidrawImageElement>;
  4798. return new Promise<NonDeleted<InitializedExcalidrawImageElement>>(
  4799. async (resolve, reject) => {
  4800. try {
  4801. this.files = {
  4802. ...this.files,
  4803. [fileId]: {
  4804. mimeType,
  4805. id: fileId,
  4806. dataURL,
  4807. created: Date.now(),
  4808. },
  4809. };
  4810. const cachedImageData = this.imageCache.get(fileId);
  4811. if (!cachedImageData) {
  4812. this.addNewImagesToImageCache();
  4813. await this.updateImageCache([imageElement]);
  4814. }
  4815. if (cachedImageData?.image instanceof Promise) {
  4816. await cachedImageData.image;
  4817. }
  4818. if (
  4819. this.state.pendingImageElementId !== imageElement.id &&
  4820. this.state.draggingElement?.id !== imageElement.id
  4821. ) {
  4822. this.initializeImageDimensions(imageElement, true);
  4823. }
  4824. resolve(imageElement);
  4825. } catch (error: any) {
  4826. console.error(error);
  4827. reject(new Error(t("errors.imageInsertError")));
  4828. } finally {
  4829. if (!showCursorImagePreview) {
  4830. resetCursor(this.canvas);
  4831. }
  4832. }
  4833. },
  4834. );
  4835. };
  4836. /**
  4837. * inserts image into elements array and rerenders
  4838. */
  4839. private insertImageElement = async (
  4840. imageElement: ExcalidrawImageElement,
  4841. imageFile: File,
  4842. showCursorImagePreview?: boolean,
  4843. ) => {
  4844. this.scene.replaceAllElements([
  4845. ...this.scene.getElementsIncludingDeleted(),
  4846. imageElement,
  4847. ]);
  4848. try {
  4849. await this.initializeImage({
  4850. imageFile,
  4851. imageElement,
  4852. showCursorImagePreview,
  4853. });
  4854. } catch (error: any) {
  4855. mutateElement(imageElement, {
  4856. isDeleted: true,
  4857. });
  4858. this.actionManager.executeAction(actionFinalize);
  4859. this.setState({
  4860. errorMessage: error.message || t("errors.imageInsertError"),
  4861. });
  4862. }
  4863. };
  4864. private setImagePreviewCursor = async (imageFile: File) => {
  4865. // mustn't be larger than 128 px
  4866. // https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Basic_User_Interface/Using_URL_values_for_the_cursor_property
  4867. const cursorImageSizePx = 96;
  4868. const imagePreview = await resizeImageFile(imageFile, {
  4869. maxWidthOrHeight: cursorImageSizePx,
  4870. });
  4871. let previewDataURL = await getDataURL(imagePreview);
  4872. // SVG cannot be resized via `resizeImageFile` so we resize by rendering to
  4873. // a small canvas
  4874. if (imageFile.type === MIME_TYPES.svg) {
  4875. const img = await loadHTMLImageElement(previewDataURL);
  4876. let height = Math.min(img.height, cursorImageSizePx);
  4877. let width = height * (img.width / img.height);
  4878. if (width > cursorImageSizePx) {
  4879. width = cursorImageSizePx;
  4880. height = width * (img.height / img.width);
  4881. }
  4882. const canvas = document.createElement("canvas");
  4883. canvas.height = height;
  4884. canvas.width = width;
  4885. const context = canvas.getContext("2d")!;
  4886. context.drawImage(img, 0, 0, width, height);
  4887. previewDataURL = canvas.toDataURL(MIME_TYPES.svg) as DataURL;
  4888. }
  4889. if (this.state.pendingImageElementId) {
  4890. setCursor(this.canvas, `url(${previewDataURL}) 4 4, auto`);
  4891. }
  4892. };
  4893. private onImageAction = async (
  4894. { insertOnCanvasDirectly } = { insertOnCanvasDirectly: false },
  4895. ) => {
  4896. try {
  4897. const clientX = this.state.width / 2 + this.state.offsetLeft;
  4898. const clientY = this.state.height / 2 + this.state.offsetTop;
  4899. const { x, y } = viewportCoordsToSceneCoords(
  4900. { clientX, clientY },
  4901. this.state,
  4902. );
  4903. const imageFile = await fileOpen({
  4904. description: "Image",
  4905. extensions: ["jpg", "png", "svg", "gif"],
  4906. });
  4907. const imageElement = this.createImageElement({
  4908. sceneX: x,
  4909. sceneY: y,
  4910. });
  4911. if (insertOnCanvasDirectly) {
  4912. this.insertImageElement(imageElement, imageFile);
  4913. this.initializeImageDimensions(imageElement);
  4914. this.setState(
  4915. {
  4916. selectedElementIds: { [imageElement.id]: true },
  4917. },
  4918. () => {
  4919. this.actionManager.executeAction(actionFinalize);
  4920. },
  4921. );
  4922. } else {
  4923. this.setState(
  4924. {
  4925. pendingImageElementId: imageElement.id,
  4926. },
  4927. () => {
  4928. this.insertImageElement(
  4929. imageElement,
  4930. imageFile,
  4931. /* showCursorImagePreview */ true,
  4932. );
  4933. },
  4934. );
  4935. }
  4936. } catch (error: any) {
  4937. if (error.name !== "AbortError") {
  4938. console.error(error);
  4939. } else {
  4940. console.warn(error);
  4941. }
  4942. this.setState(
  4943. {
  4944. pendingImageElementId: null,
  4945. editingElement: null,
  4946. activeTool: updateActiveTool(this.state, { type: "selection" }),
  4947. },
  4948. () => {
  4949. this.actionManager.executeAction(actionFinalize);
  4950. },
  4951. );
  4952. }
  4953. };
  4954. private initializeImageDimensions = (
  4955. imageElement: ExcalidrawImageElement,
  4956. forceNaturalSize = false,
  4957. ) => {
  4958. const image =
  4959. isInitializedImageElement(imageElement) &&
  4960. this.imageCache.get(imageElement.fileId)?.image;
  4961. if (!image || image instanceof Promise) {
  4962. if (
  4963. imageElement.width < DRAGGING_THRESHOLD / this.state.zoom.value &&
  4964. imageElement.height < DRAGGING_THRESHOLD / this.state.zoom.value
  4965. ) {
  4966. const placeholderSize = 100 / this.state.zoom.value;
  4967. mutateElement(imageElement, {
  4968. x: imageElement.x - placeholderSize / 2,
  4969. y: imageElement.y - placeholderSize / 2,
  4970. width: placeholderSize,
  4971. height: placeholderSize,
  4972. });
  4973. }
  4974. return;
  4975. }
  4976. if (
  4977. forceNaturalSize ||
  4978. // if user-created bounding box is below threshold, assume the
  4979. // intention was to click instead of drag, and use the image's
  4980. // intrinsic size
  4981. (imageElement.width < DRAGGING_THRESHOLD / this.state.zoom.value &&
  4982. imageElement.height < DRAGGING_THRESHOLD / this.state.zoom.value)
  4983. ) {
  4984. const minHeight = Math.max(this.state.height - 120, 160);
  4985. // max 65% of canvas height, clamped to <300px, vh - 120px>
  4986. const maxHeight = Math.min(
  4987. minHeight,
  4988. Math.floor(this.state.height * 0.5) / this.state.zoom.value,
  4989. );
  4990. const height = Math.min(image.naturalHeight, maxHeight);
  4991. const width = height * (image.naturalWidth / image.naturalHeight);
  4992. // add current imageElement width/height to account for previous centering
  4993. // of the placeholder image
  4994. const x = imageElement.x + imageElement.width / 2 - width / 2;
  4995. const y = imageElement.y + imageElement.height / 2 - height / 2;
  4996. mutateElement(imageElement, { x, y, width, height });
  4997. }
  4998. };
  4999. /** updates image cache, refreshing updated elements and/or setting status
  5000. to error for images that fail during <img> element creation */
  5001. private updateImageCache = async (
  5002. elements: readonly InitializedExcalidrawImageElement[],
  5003. files = this.files,
  5004. ) => {
  5005. const { updatedFiles, erroredFiles } = await _updateImageCache({
  5006. imageCache: this.imageCache,
  5007. fileIds: elements.map((element) => element.fileId),
  5008. files,
  5009. });
  5010. if (updatedFiles.size || erroredFiles.size) {
  5011. for (const element of elements) {
  5012. if (updatedFiles.has(element.fileId)) {
  5013. invalidateShapeForElement(element);
  5014. }
  5015. }
  5016. }
  5017. if (erroredFiles.size) {
  5018. this.scene.replaceAllElements(
  5019. this.scene.getElementsIncludingDeleted().map((element) => {
  5020. if (
  5021. isInitializedImageElement(element) &&
  5022. erroredFiles.has(element.fileId)
  5023. ) {
  5024. return newElementWith(element, {
  5025. status: "error",
  5026. });
  5027. }
  5028. return element;
  5029. }),
  5030. );
  5031. }
  5032. return { updatedFiles, erroredFiles };
  5033. };
  5034. /** adds new images to imageCache and re-renders if needed */
  5035. private addNewImagesToImageCache = async (
  5036. imageElements: InitializedExcalidrawImageElement[] = getInitializedImageElements(
  5037. this.scene.getNonDeletedElements(),
  5038. ),
  5039. files: BinaryFiles = this.files,
  5040. ) => {
  5041. const uncachedImageElements = imageElements.filter(
  5042. (element) => !element.isDeleted && !this.imageCache.has(element.fileId),
  5043. );
  5044. if (uncachedImageElements.length) {
  5045. const { updatedFiles } = await this.updateImageCache(
  5046. uncachedImageElements,
  5047. files,
  5048. );
  5049. if (updatedFiles.size) {
  5050. this.scene.informMutation();
  5051. }
  5052. }
  5053. };
  5054. /** generally you should use `addNewImagesToImageCache()` directly if you need
  5055. * to render new images. This is just a failsafe */
  5056. private scheduleImageRefresh = throttle(() => {
  5057. this.addNewImagesToImageCache();
  5058. }, IMAGE_RENDER_TIMEOUT);
  5059. private updateBindingEnabledOnPointerMove = (
  5060. event: React.PointerEvent<HTMLCanvasElement>,
  5061. ) => {
  5062. const shouldEnableBinding = shouldEnableBindingForPointerEvent(event);
  5063. if (this.state.isBindingEnabled !== shouldEnableBinding) {
  5064. this.setState({ isBindingEnabled: shouldEnableBinding });
  5065. }
  5066. };
  5067. private maybeSuggestBindingAtCursor = (pointerCoords: {
  5068. x: number;
  5069. y: number;
  5070. }): void => {
  5071. const hoveredBindableElement = getHoveredElementForBinding(
  5072. pointerCoords,
  5073. this.scene,
  5074. );
  5075. this.setState({
  5076. suggestedBindings:
  5077. hoveredBindableElement != null ? [hoveredBindableElement] : [],
  5078. });
  5079. };
  5080. private maybeSuggestBindingsForLinearElementAtCoords = (
  5081. linearElement: NonDeleted<ExcalidrawLinearElement>,
  5082. /** scene coords */
  5083. pointerCoords: {
  5084. x: number;
  5085. y: number;
  5086. }[],
  5087. // During line creation the start binding hasn't been written yet
  5088. // into `linearElement`
  5089. oppositeBindingBoundElement?: ExcalidrawBindableElement | null,
  5090. ): void => {
  5091. if (!pointerCoords.length) {
  5092. return;
  5093. }
  5094. const suggestedBindings = pointerCoords.reduce(
  5095. (acc: NonDeleted<ExcalidrawBindableElement>[], coords) => {
  5096. const hoveredBindableElement = getHoveredElementForBinding(
  5097. coords,
  5098. this.scene,
  5099. );
  5100. if (
  5101. hoveredBindableElement != null &&
  5102. !isLinearElementSimpleAndAlreadyBound(
  5103. linearElement,
  5104. oppositeBindingBoundElement?.id,
  5105. hoveredBindableElement,
  5106. )
  5107. ) {
  5108. acc.push(hoveredBindableElement);
  5109. }
  5110. return acc;
  5111. },
  5112. [],
  5113. );
  5114. this.setState({ suggestedBindings });
  5115. };
  5116. private maybeSuggestBindingForAll(
  5117. selectedElements: NonDeleted<ExcalidrawElement>[],
  5118. ): void {
  5119. const suggestedBindings = getEligibleElementsForBinding(selectedElements);
  5120. this.setState({ suggestedBindings });
  5121. }
  5122. private clearSelection(hitElement: ExcalidrawElement | null): void {
  5123. this.setState((prevState) => ({
  5124. selectedElementIds: {},
  5125. selectedGroupIds: {},
  5126. // Continue editing the same group if the user selected a different
  5127. // element from it
  5128. editingGroupId:
  5129. prevState.editingGroupId &&
  5130. hitElement != null &&
  5131. isElementInGroup(hitElement, prevState.editingGroupId)
  5132. ? prevState.editingGroupId
  5133. : null,
  5134. }));
  5135. this.setState({
  5136. selectedElementIds: {},
  5137. previousSelectedElementIds: this.state.selectedElementIds,
  5138. });
  5139. }
  5140. private handleCanvasRef = (canvas: HTMLCanvasElement) => {
  5141. // canvas is null when unmounting
  5142. if (canvas !== null) {
  5143. this.canvas = canvas;
  5144. this.rc = rough.canvas(this.canvas);
  5145. this.canvas.addEventListener(EVENT.WHEEL, this.handleWheel, {
  5146. passive: false,
  5147. });
  5148. this.canvas.addEventListener(EVENT.TOUCH_START, this.onTapStart);
  5149. this.canvas.addEventListener(EVENT.TOUCH_END, this.onTapEnd);
  5150. } else {
  5151. this.canvas?.removeEventListener(EVENT.WHEEL, this.handleWheel);
  5152. this.canvas?.removeEventListener(EVENT.TOUCH_START, this.onTapStart);
  5153. this.canvas?.removeEventListener(EVENT.TOUCH_END, this.onTapEnd);
  5154. }
  5155. };
  5156. private handleAppOnDrop = async (event: React.DragEvent<HTMLDivElement>) => {
  5157. // must be retrieved first, in the same frame
  5158. const { file, fileHandle } = await getFileFromEvent(event);
  5159. try {
  5160. if (isSupportedImageFile(file)) {
  5161. // first attempt to decode scene from the image if it's embedded
  5162. // ---------------------------------------------------------------------
  5163. if (file?.type === MIME_TYPES.png || file?.type === MIME_TYPES.svg) {
  5164. try {
  5165. const scene = await loadFromBlob(
  5166. file,
  5167. this.state,
  5168. this.scene.getElementsIncludingDeleted(),
  5169. fileHandle,
  5170. );
  5171. this.syncActionResult({
  5172. ...scene,
  5173. appState: {
  5174. ...(scene.appState || this.state),
  5175. isLoading: false,
  5176. },
  5177. replaceFiles: true,
  5178. commitToHistory: true,
  5179. });
  5180. return;
  5181. } catch (error: any) {
  5182. if (error.name !== "EncodingError") {
  5183. throw error;
  5184. }
  5185. }
  5186. }
  5187. // if no scene is embedded or we fail for whatever reason, fall back
  5188. // to importing as regular image
  5189. // ---------------------------------------------------------------------
  5190. const { x: sceneX, y: sceneY } = viewportCoordsToSceneCoords(
  5191. event,
  5192. this.state,
  5193. );
  5194. const imageElement = this.createImageElement({ sceneX, sceneY });
  5195. this.insertImageElement(imageElement, file);
  5196. this.initializeImageDimensions(imageElement);
  5197. this.setState({ selectedElementIds: { [imageElement.id]: true } });
  5198. return;
  5199. }
  5200. } catch (error: any) {
  5201. return this.setState({
  5202. isLoading: false,
  5203. errorMessage: error.message,
  5204. });
  5205. }
  5206. const libraryJSON = event.dataTransfer.getData(MIME_TYPES.excalidrawlib);
  5207. if (libraryJSON && typeof libraryJSON === "string") {
  5208. try {
  5209. const libraryItems = parseLibraryJSON(libraryJSON);
  5210. this.addElementsFromPasteOrLibrary({
  5211. elements: distributeLibraryItemsOnSquareGrid(libraryItems),
  5212. position: event,
  5213. files: null,
  5214. });
  5215. } catch (error: any) {
  5216. this.setState({ errorMessage: error.message });
  5217. }
  5218. return;
  5219. }
  5220. if (file) {
  5221. // atetmpt to parse an excalidraw/excalidrawlib file
  5222. await this.loadFileToCanvas(file, fileHandle);
  5223. }
  5224. };
  5225. loadFileToCanvas = async (
  5226. file: File,
  5227. fileHandle: FileSystemHandle | null,
  5228. ) => {
  5229. file = await normalizeFile(file);
  5230. try {
  5231. const ret = await loadSceneOrLibraryFromBlob(
  5232. file,
  5233. this.state,
  5234. this.scene.getElementsIncludingDeleted(),
  5235. fileHandle,
  5236. );
  5237. if (ret.type === MIME_TYPES.excalidraw) {
  5238. this.setState({ isLoading: true });
  5239. this.syncActionResult({
  5240. ...ret.data,
  5241. appState: {
  5242. ...(ret.data.appState || this.state),
  5243. isLoading: false,
  5244. },
  5245. replaceFiles: true,
  5246. commitToHistory: true,
  5247. });
  5248. } else if (ret.type === MIME_TYPES.excalidrawlib) {
  5249. await this.library
  5250. .updateLibrary({
  5251. libraryItems: file,
  5252. merge: true,
  5253. openLibraryMenu: true,
  5254. })
  5255. .catch((error) => {
  5256. console.error(error);
  5257. this.setState({ errorMessage: t("errors.importLibraryError") });
  5258. });
  5259. }
  5260. } catch (error: any) {
  5261. this.setState({ isLoading: false, errorMessage: error.message });
  5262. }
  5263. };
  5264. private handleCanvasContextMenu = (
  5265. event: React.PointerEvent<HTMLCanvasElement>,
  5266. ) => {
  5267. event.preventDefault();
  5268. if (
  5269. (event.nativeEvent.pointerType === "touch" ||
  5270. (event.nativeEvent.pointerType === "pen" &&
  5271. // always allow if user uses a pen secondary button
  5272. event.button !== POINTER_BUTTON.SECONDARY)) &&
  5273. this.state.activeTool.type !== "selection"
  5274. ) {
  5275. return;
  5276. }
  5277. const { x, y } = viewportCoordsToSceneCoords(event, this.state);
  5278. const element = this.getElementAtPosition(x, y, {
  5279. preferSelected: true,
  5280. includeLockedElements: true,
  5281. });
  5282. const type = element ? "element" : "canvas";
  5283. const container = this.excalidrawContainerRef.current!;
  5284. const { top: offsetTop, left: offsetLeft } =
  5285. container.getBoundingClientRect();
  5286. const left = event.clientX - offsetLeft;
  5287. const top = event.clientY - offsetTop;
  5288. if (element && !this.state.selectedElementIds[element.id]) {
  5289. this.setState(
  5290. selectGroupsForSelectedElements(
  5291. {
  5292. ...this.state,
  5293. selectedElementIds: { [element.id]: true },
  5294. selectedLinearElement: isLinearElement(element)
  5295. ? new LinearElementEditor(element, this.scene)
  5296. : null,
  5297. },
  5298. this.scene.getNonDeletedElements(),
  5299. ),
  5300. () => {
  5301. this._openContextMenu({ top, left }, type);
  5302. },
  5303. );
  5304. } else {
  5305. this._openContextMenu({ top, left }, type);
  5306. }
  5307. };
  5308. private maybeDragNewGenericElement = (
  5309. pointerDownState: PointerDownState,
  5310. event: MouseEvent | KeyboardEvent,
  5311. ): void => {
  5312. const draggingElement = this.state.draggingElement;
  5313. const pointerCoords = pointerDownState.lastCoords;
  5314. if (!draggingElement) {
  5315. return;
  5316. }
  5317. if (
  5318. draggingElement.type === "selection" &&
  5319. this.state.activeTool.type !== "eraser"
  5320. ) {
  5321. dragNewElement(
  5322. draggingElement,
  5323. this.state.activeTool.type,
  5324. pointerDownState.origin.x,
  5325. pointerDownState.origin.y,
  5326. pointerCoords.x,
  5327. pointerCoords.y,
  5328. distance(pointerDownState.origin.x, pointerCoords.x),
  5329. distance(pointerDownState.origin.y, pointerCoords.y),
  5330. shouldMaintainAspectRatio(event),
  5331. shouldResizeFromCenter(event),
  5332. );
  5333. } else {
  5334. const [gridX, gridY] = getGridPoint(
  5335. pointerCoords.x,
  5336. pointerCoords.y,
  5337. this.state.gridSize,
  5338. );
  5339. const image =
  5340. isInitializedImageElement(draggingElement) &&
  5341. this.imageCache.get(draggingElement.fileId)?.image;
  5342. const aspectRatio =
  5343. image && !(image instanceof Promise)
  5344. ? image.width / image.height
  5345. : null;
  5346. dragNewElement(
  5347. draggingElement,
  5348. this.state.activeTool.type,
  5349. pointerDownState.originInGrid.x,
  5350. pointerDownState.originInGrid.y,
  5351. gridX,
  5352. gridY,
  5353. distance(pointerDownState.originInGrid.x, gridX),
  5354. distance(pointerDownState.originInGrid.y, gridY),
  5355. isImageElement(draggingElement)
  5356. ? !shouldMaintainAspectRatio(event)
  5357. : shouldMaintainAspectRatio(event),
  5358. shouldResizeFromCenter(event),
  5359. aspectRatio,
  5360. );
  5361. this.maybeSuggestBindingForAll([draggingElement]);
  5362. }
  5363. };
  5364. private maybeHandleResize = (
  5365. pointerDownState: PointerDownState,
  5366. event: MouseEvent | KeyboardEvent,
  5367. ): boolean => {
  5368. const selectedElements = getSelectedElements(
  5369. this.scene.getNonDeletedElements(),
  5370. this.state,
  5371. );
  5372. const transformHandleType = pointerDownState.resize.handleType;
  5373. this.setState({
  5374. // TODO: rename this state field to "isScaling" to distinguish
  5375. // it from the generic "isResizing" which includes scaling and
  5376. // rotating
  5377. isResizing: transformHandleType && transformHandleType !== "rotation",
  5378. isRotating: transformHandleType === "rotation",
  5379. });
  5380. const pointerCoords = pointerDownState.lastCoords;
  5381. const [resizeX, resizeY] = getGridPoint(
  5382. pointerCoords.x - pointerDownState.resize.offset.x,
  5383. pointerCoords.y - pointerDownState.resize.offset.y,
  5384. this.state.gridSize,
  5385. );
  5386. if (
  5387. transformElements(
  5388. pointerDownState,
  5389. transformHandleType,
  5390. selectedElements,
  5391. pointerDownState.resize.arrowDirection,
  5392. shouldRotateWithDiscreteAngle(event),
  5393. shouldResizeFromCenter(event),
  5394. selectedElements.length === 1 && isImageElement(selectedElements[0])
  5395. ? !shouldMaintainAspectRatio(event)
  5396. : shouldMaintainAspectRatio(event),
  5397. resizeX,
  5398. resizeY,
  5399. pointerDownState.resize.center.x,
  5400. pointerDownState.resize.center.y,
  5401. )
  5402. ) {
  5403. this.maybeSuggestBindingForAll(selectedElements);
  5404. return true;
  5405. }
  5406. return false;
  5407. };
  5408. /** @private use this.handleCanvasContextMenu */
  5409. private _openContextMenu = (
  5410. {
  5411. left,
  5412. top,
  5413. }: {
  5414. left: number;
  5415. top: number;
  5416. },
  5417. type: "canvas" | "element",
  5418. ) => {
  5419. if (this.state.showHyperlinkPopup) {
  5420. this.setState({ showHyperlinkPopup: false });
  5421. }
  5422. this.contextMenuOpen = true;
  5423. const maybeGroupAction = actionGroup.contextItemPredicate!(
  5424. this.actionManager.getElementsIncludingDeleted(),
  5425. this.actionManager.getAppState(),
  5426. );
  5427. const maybeUngroupAction = actionUngroup.contextItemPredicate!(
  5428. this.actionManager.getElementsIncludingDeleted(),
  5429. this.actionManager.getAppState(),
  5430. );
  5431. const maybeFlipHorizontal = actionFlipHorizontal.contextItemPredicate!(
  5432. this.actionManager.getElementsIncludingDeleted(),
  5433. this.actionManager.getAppState(),
  5434. );
  5435. const maybeFlipVertical = actionFlipVertical.contextItemPredicate!(
  5436. this.actionManager.getElementsIncludingDeleted(),
  5437. this.actionManager.getAppState(),
  5438. );
  5439. const mayBeAllowUnbinding = actionUnbindText.contextItemPredicate(
  5440. this.actionManager.getElementsIncludingDeleted(),
  5441. this.actionManager.getAppState(),
  5442. );
  5443. const mayBeAllowBinding = actionBindText.contextItemPredicate(
  5444. this.actionManager.getElementsIncludingDeleted(),
  5445. this.actionManager.getAppState(),
  5446. );
  5447. const mayBeAllowToggleLineEditing =
  5448. actionToggleLinearEditor.contextItemPredicate(
  5449. this.actionManager.getElementsIncludingDeleted(),
  5450. this.actionManager.getAppState(),
  5451. );
  5452. const separator = "separator";
  5453. const elements = this.scene.getNonDeletedElements();
  5454. const selectedElements = getSelectedElements(
  5455. this.scene.getNonDeletedElements(),
  5456. this.state,
  5457. );
  5458. const options: ContextMenuOption[] = [];
  5459. if (probablySupportsClipboardBlob && elements.length > 0) {
  5460. options.push(actionCopyAsPng);
  5461. }
  5462. if (probablySupportsClipboardWriteText && elements.length > 0) {
  5463. options.push(actionCopyAsSvg);
  5464. }
  5465. if (
  5466. type === "element" &&
  5467. copyText.contextItemPredicate(elements, this.state) &&
  5468. probablySupportsClipboardWriteText
  5469. ) {
  5470. options.push(copyText);
  5471. }
  5472. if (type === "canvas") {
  5473. const viewModeOptions = [
  5474. ...options,
  5475. typeof this.props.gridModeEnabled === "undefined" &&
  5476. actionToggleGridMode,
  5477. typeof this.props.zenModeEnabled === "undefined" && actionToggleZenMode,
  5478. typeof this.props.viewModeEnabled === "undefined" &&
  5479. actionToggleViewMode,
  5480. actionToggleStats,
  5481. ];
  5482. if (this.state.viewModeEnabled) {
  5483. ContextMenu.push({
  5484. options: viewModeOptions,
  5485. top,
  5486. left,
  5487. actionManager: this.actionManager,
  5488. appState: this.state,
  5489. container: this.excalidrawContainerRef.current!,
  5490. elements,
  5491. });
  5492. } else {
  5493. ContextMenu.push({
  5494. options: [
  5495. this.device.isMobile &&
  5496. navigator.clipboard && {
  5497. trackEvent: false,
  5498. name: "paste",
  5499. perform: (elements, appStates) => {
  5500. this.pasteFromClipboard(null);
  5501. return {
  5502. commitToHistory: false,
  5503. };
  5504. },
  5505. contextItemLabel: "labels.paste",
  5506. },
  5507. this.device.isMobile && navigator.clipboard && separator,
  5508. probablySupportsClipboardBlob &&
  5509. elements.length > 0 &&
  5510. actionCopyAsPng,
  5511. probablySupportsClipboardWriteText &&
  5512. elements.length > 0 &&
  5513. actionCopyAsSvg,
  5514. probablySupportsClipboardWriteText &&
  5515. selectedElements.length > 0 &&
  5516. copyText,
  5517. ((probablySupportsClipboardBlob && elements.length > 0) ||
  5518. (probablySupportsClipboardWriteText && elements.length > 0)) &&
  5519. separator,
  5520. actionSelectAll,
  5521. separator,
  5522. typeof this.props.gridModeEnabled === "undefined" &&
  5523. actionToggleGridMode,
  5524. typeof this.props.zenModeEnabled === "undefined" &&
  5525. actionToggleZenMode,
  5526. typeof this.props.viewModeEnabled === "undefined" &&
  5527. actionToggleViewMode,
  5528. actionToggleStats,
  5529. ],
  5530. top,
  5531. left,
  5532. actionManager: this.actionManager,
  5533. appState: this.state,
  5534. container: this.excalidrawContainerRef.current!,
  5535. elements,
  5536. });
  5537. }
  5538. } else if (type === "element") {
  5539. if (this.state.viewModeEnabled) {
  5540. ContextMenu.push({
  5541. options: [navigator.clipboard && actionCopy, ...options],
  5542. top,
  5543. left,
  5544. actionManager: this.actionManager,
  5545. appState: this.state,
  5546. container: this.excalidrawContainerRef.current!,
  5547. elements,
  5548. });
  5549. } else {
  5550. ContextMenu.push({
  5551. options: [
  5552. this.device.isMobile && actionCut,
  5553. this.device.isMobile && navigator.clipboard && actionCopy,
  5554. this.device.isMobile &&
  5555. navigator.clipboard && {
  5556. name: "paste",
  5557. trackEvent: false,
  5558. perform: (elements, appStates) => {
  5559. this.pasteFromClipboard(null);
  5560. return {
  5561. commitToHistory: false,
  5562. };
  5563. },
  5564. contextItemLabel: "labels.paste",
  5565. },
  5566. this.device.isMobile && separator,
  5567. ...options,
  5568. separator,
  5569. actionCopyStyles,
  5570. actionPasteStyles,
  5571. separator,
  5572. maybeGroupAction && actionGroup,
  5573. mayBeAllowUnbinding && actionUnbindText,
  5574. mayBeAllowBinding && actionBindText,
  5575. maybeUngroupAction && actionUngroup,
  5576. (maybeGroupAction || maybeUngroupAction) && separator,
  5577. actionAddToLibrary,
  5578. separator,
  5579. actionSendBackward,
  5580. actionBringForward,
  5581. actionSendToBack,
  5582. actionBringToFront,
  5583. separator,
  5584. maybeFlipHorizontal && actionFlipHorizontal,
  5585. maybeFlipVertical && actionFlipVertical,
  5586. (maybeFlipHorizontal || maybeFlipVertical) && separator,
  5587. mayBeAllowToggleLineEditing && actionToggleLinearEditor,
  5588. actionLink.contextItemPredicate(elements, this.state) && actionLink,
  5589. actionDuplicateSelection,
  5590. actionToggleLock,
  5591. separator,
  5592. actionDeleteSelected,
  5593. ],
  5594. top,
  5595. left,
  5596. actionManager: this.actionManager,
  5597. appState: this.state,
  5598. container: this.excalidrawContainerRef.current!,
  5599. elements,
  5600. });
  5601. }
  5602. }
  5603. };
  5604. private handleWheel = withBatchedUpdates((event: WheelEvent) => {
  5605. event.preventDefault();
  5606. if (isPanning) {
  5607. return;
  5608. }
  5609. const { deltaX, deltaY } = event;
  5610. // note that event.ctrlKey is necessary to handle pinch zooming
  5611. if (event.metaKey || event.ctrlKey) {
  5612. const sign = Math.sign(deltaY);
  5613. const MAX_STEP = ZOOM_STEP * 100;
  5614. const absDelta = Math.abs(deltaY);
  5615. let delta = deltaY;
  5616. if (absDelta > MAX_STEP) {
  5617. delta = MAX_STEP * sign;
  5618. }
  5619. let newZoom = this.state.zoom.value - delta / 100;
  5620. // increase zoom steps the more zoomed-in we are (applies to >100% only)
  5621. newZoom +=
  5622. Math.log10(Math.max(1, this.state.zoom.value)) *
  5623. -sign *
  5624. // reduced amplification for small deltas (small movements on a trackpad)
  5625. Math.min(1, absDelta / 20);
  5626. this.setState((state) => ({
  5627. ...getStateForZoom(
  5628. {
  5629. viewportX: cursorX,
  5630. viewportY: cursorY,
  5631. nextZoom: getNormalizedZoom(newZoom),
  5632. },
  5633. state,
  5634. ),
  5635. shouldCacheIgnoreZoom: true,
  5636. }));
  5637. this.resetShouldCacheIgnoreZoomDebounced();
  5638. return;
  5639. }
  5640. // scroll horizontally when shift pressed
  5641. if (event.shiftKey) {
  5642. this.setState(({ zoom, scrollX }) => ({
  5643. // on Mac, shift+wheel tends to result in deltaX
  5644. scrollX: scrollX - (deltaY || deltaX) / zoom.value,
  5645. }));
  5646. return;
  5647. }
  5648. this.setState(({ zoom, scrollX, scrollY }) => ({
  5649. scrollX: scrollX - deltaX / zoom.value,
  5650. scrollY: scrollY - deltaY / zoom.value,
  5651. }));
  5652. });
  5653. private getTextWysiwygSnappedToCenterPosition(
  5654. x: number,
  5655. y: number,
  5656. appState: AppState,
  5657. canvas: HTMLCanvasElement | null,
  5658. scale: number,
  5659. ) {
  5660. const elementClickedInside = getTextBindableContainerAtPosition(
  5661. this.scene
  5662. .getElementsIncludingDeleted()
  5663. .filter((element) => !isTextElement(element)),
  5664. x,
  5665. y,
  5666. );
  5667. if (elementClickedInside) {
  5668. const elementCenterX =
  5669. elementClickedInside.x + elementClickedInside.width / 2;
  5670. const elementCenterY =
  5671. elementClickedInside.y + elementClickedInside.height / 2;
  5672. const distanceToCenter = Math.hypot(
  5673. x - elementCenterX,
  5674. y - elementCenterY,
  5675. );
  5676. const isSnappedToCenter =
  5677. distanceToCenter < TEXT_TO_CENTER_SNAP_THRESHOLD;
  5678. if (isSnappedToCenter) {
  5679. const { x: viewportX, y: viewportY } = sceneCoordsToViewportCoords(
  5680. { sceneX: elementCenterX, sceneY: elementCenterY },
  5681. appState,
  5682. );
  5683. return { viewportX, viewportY, elementCenterX, elementCenterY };
  5684. }
  5685. }
  5686. }
  5687. private savePointer = (x: number, y: number, button: "up" | "down") => {
  5688. if (!x || !y) {
  5689. return;
  5690. }
  5691. const pointer = viewportCoordsToSceneCoords(
  5692. { clientX: x, clientY: y },
  5693. this.state,
  5694. );
  5695. if (isNaN(pointer.x) || isNaN(pointer.y)) {
  5696. // sometimes the pointer goes off screen
  5697. }
  5698. this.props.onPointerUpdate?.({
  5699. pointer,
  5700. button,
  5701. pointersMap: gesture.pointers,
  5702. });
  5703. };
  5704. private resetShouldCacheIgnoreZoomDebounced = debounce(() => {
  5705. if (!this.unmounted) {
  5706. this.setState({ shouldCacheIgnoreZoom: false });
  5707. }
  5708. }, 300);
  5709. private updateDOMRect = (cb?: () => void) => {
  5710. if (this.excalidrawContainerRef?.current) {
  5711. const excalidrawContainer = this.excalidrawContainerRef.current;
  5712. const {
  5713. width,
  5714. height,
  5715. left: offsetLeft,
  5716. top: offsetTop,
  5717. } = excalidrawContainer.getBoundingClientRect();
  5718. const {
  5719. width: currentWidth,
  5720. height: currentHeight,
  5721. offsetTop: currentOffsetTop,
  5722. offsetLeft: currentOffsetLeft,
  5723. } = this.state;
  5724. if (
  5725. width === currentWidth &&
  5726. height === currentHeight &&
  5727. offsetLeft === currentOffsetLeft &&
  5728. offsetTop === currentOffsetTop
  5729. ) {
  5730. if (cb) {
  5731. cb();
  5732. }
  5733. return;
  5734. }
  5735. this.setState(
  5736. {
  5737. width,
  5738. height,
  5739. offsetLeft,
  5740. offsetTop,
  5741. },
  5742. () => {
  5743. cb && cb();
  5744. },
  5745. );
  5746. }
  5747. };
  5748. public refresh = () => {
  5749. this.setState({ ...this.getCanvasOffsets() });
  5750. };
  5751. private getCanvasOffsets(): Pick<AppState, "offsetTop" | "offsetLeft"> {
  5752. if (this.excalidrawContainerRef?.current) {
  5753. const excalidrawContainer = this.excalidrawContainerRef.current;
  5754. const { left, top } = excalidrawContainer.getBoundingClientRect();
  5755. return {
  5756. offsetLeft: left,
  5757. offsetTop: top,
  5758. };
  5759. }
  5760. return {
  5761. offsetLeft: 0,
  5762. offsetTop: 0,
  5763. };
  5764. }
  5765. private async updateLanguage() {
  5766. const currentLang =
  5767. languages.find((lang) => lang.code === this.props.langCode) ||
  5768. defaultLang;
  5769. await setLanguage(currentLang);
  5770. this.setAppState({});
  5771. }
  5772. }
  5773. // -----------------------------------------------------------------------------
  5774. // TEST HOOKS
  5775. // -----------------------------------------------------------------------------
  5776. declare global {
  5777. interface Window {
  5778. h: {
  5779. elements: readonly ExcalidrawElement[];
  5780. state: AppState;
  5781. setState: React.Component<any, AppState>["setState"];
  5782. app: InstanceType<typeof App>;
  5783. history: History;
  5784. };
  5785. }
  5786. }
  5787. if (
  5788. process.env.NODE_ENV === ENV.TEST ||
  5789. process.env.NODE_ENV === ENV.DEVELOPMENT
  5790. ) {
  5791. window.h = window.h || ({} as Window["h"]);
  5792. Object.defineProperties(window.h, {
  5793. elements: {
  5794. configurable: true,
  5795. get() {
  5796. return this.app?.scene.getElementsIncludingDeleted();
  5797. },
  5798. set(elements: ExcalidrawElement[]) {
  5799. return this.app?.scene.replaceAllElements(elements);
  5800. },
  5801. },
  5802. });
  5803. }
  5804. export default App;