App.tsx 116 KB

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