App.tsx 159 KB

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