App.tsx 156 KB

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