App.tsx 160 KB

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