App.tsx 169 KB

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