App.tsx 178 KB

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