App.tsx 189 KB

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