App.tsx 152 KB

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