App.tsx 104 KB

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