App.tsx 129 KB

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