App.tsx 160 KB

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