App.tsx 75 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484
  1. import React from "react";
  2. import socketIOClient from "socket.io-client";
  3. import rough from "roughjs/bin/rough";
  4. import { RoughCanvas } from "roughjs/bin/canvas";
  5. import {
  6. newElement,
  7. newTextElement,
  8. duplicateElement,
  9. resizeTest,
  10. normalizeResizeHandle,
  11. isInvisiblySmallElement,
  12. isTextElement,
  13. textWysiwyg,
  14. getCommonBounds,
  15. getCursorForResizingElement,
  16. getPerfectElementSize,
  17. normalizeDimensions,
  18. getElementMap,
  19. getDrawingVersion,
  20. getSyncableElements,
  21. hasNonDeletedElements,
  22. newLinearElement,
  23. } from "../element";
  24. import {
  25. deleteSelectedElements,
  26. getElementsWithinSelection,
  27. isOverScrollBars,
  28. getElementAtPosition,
  29. getElementContainingPosition,
  30. getNormalizedZoom,
  31. getSelectedElements,
  32. globalSceneState,
  33. isSomeElementSelected,
  34. } from "../scene";
  35. import {
  36. decryptAESGEM,
  37. encryptAESGEM,
  38. saveToLocalStorage,
  39. loadScene,
  40. loadFromBlob,
  41. SOCKET_SERVER,
  42. SocketUpdateDataSource,
  43. exportCanvas,
  44. } from "../data";
  45. import { restore } from "../data/restore";
  46. import { renderScene } from "../renderer";
  47. import { AppState, GestureEvent, Gesture } from "../types";
  48. import { ExcalidrawElement, ExcalidrawLinearElement } from "../element/types";
  49. import {
  50. isWritableElement,
  51. isInputLike,
  52. isToolIcon,
  53. debounce,
  54. distance,
  55. distance2d,
  56. resetCursor,
  57. viewportCoordsToSceneCoords,
  58. sceneCoordsToViewportCoords,
  59. } from "../utils";
  60. import { KEYS, isArrowKey } from "../keys";
  61. import { findShapeByKey, shapesShortcutKeys } from "../shapes";
  62. import { createHistory, SceneHistory } from "../history";
  63. import ContextMenu from "./ContextMenu";
  64. import { getElementWithResizeHandler } from "../element/resizeTest";
  65. import { ActionManager } from "../actions/manager";
  66. import "../actions";
  67. import { actions } from "../actions/register";
  68. import { ActionResult } from "../actions/types";
  69. import { getDefaultAppState } from "../appState";
  70. import { t, getLanguage } from "../i18n";
  71. import {
  72. copyToAppClipboard,
  73. getClipboardContent,
  74. probablySupportsClipboardBlob,
  75. } from "../clipboard";
  76. import { normalizeScroll } from "../scene";
  77. import { getCenter, getDistance } from "../gesture";
  78. import { createUndoAction, createRedoAction } from "../actions/actionHistory";
  79. import {
  80. CURSOR_TYPE,
  81. ELEMENT_SHIFT_TRANSLATE_AMOUNT,
  82. ELEMENT_TRANSLATE_AMOUNT,
  83. POINTER_BUTTON,
  84. DRAGGING_THRESHOLD,
  85. TEXT_TO_CENTER_SNAP_THRESHOLD,
  86. ARROW_CONFIRM_THRESHOLD,
  87. } from "../constants";
  88. import { LayerUI } from "./LayerUI";
  89. import { ScrollBars } from "../scene/types";
  90. import { generateCollaborationLink, getCollaborationLinkData } from "../data";
  91. import { mutateElement, newElementWith } from "../element/mutateElement";
  92. import { invalidateShapeForElement } from "../renderer/renderElement";
  93. import { unstable_batchedUpdates } from "react-dom";
  94. import { SceneStateCallbackRemover } from "../scene/globalScene";
  95. import { isLinearElement } from "../element/typeChecks";
  96. import { rescalePoints } from "../points";
  97. import { actionFinalize } from "../actions";
  98. /**
  99. * @param func handler taking at most single parameter (event).
  100. */
  101. function withBatchedUpdates<
  102. TFunction extends ((event: any) => void) | (() => void)
  103. >(func: Parameters<TFunction>["length"] extends 0 | 1 ? TFunction : never) {
  104. return ((event) => {
  105. unstable_batchedUpdates(func as TFunction, event);
  106. }) as TFunction;
  107. }
  108. const { history } = createHistory();
  109. let cursorX = 0;
  110. let cursorY = 0;
  111. let isHoldingSpace: boolean = false;
  112. let isPanning: boolean = false;
  113. let isDraggingScrollBar: boolean = false;
  114. let currentScrollBars: ScrollBars = { horizontal: null, vertical: null };
  115. let lastPointerUp: ((event: any) => void) | null = null;
  116. const gesture: Gesture = {
  117. pointers: new Map(),
  118. lastCenter: null,
  119. initialDistance: null,
  120. initialScale: null,
  121. };
  122. function setCursorForShape(shape: string) {
  123. if (shape === "selection") {
  124. resetCursor();
  125. } else {
  126. document.documentElement.style.cursor =
  127. shape === "text" ? CURSOR_TYPE.TEXT : CURSOR_TYPE.CROSSHAIR;
  128. }
  129. }
  130. export class App extends React.Component<any, AppState> {
  131. canvas: HTMLCanvasElement | null = null;
  132. rc: RoughCanvas | null = null;
  133. socket: SocketIOClient.Socket | null = null;
  134. socketInitialized: boolean = false; // we don't want the socket to emit any updates until it is fully initalized
  135. roomID: string | null = null;
  136. roomKey: string | null = null;
  137. lastBroadcastedOrReceivedSceneVersion: number = -1;
  138. removeSceneCallback: SceneStateCallbackRemover | null = null;
  139. actionManager: ActionManager;
  140. canvasOnlyActions = ["selectAll"];
  141. constructor(props: any) {
  142. super(props);
  143. this.actionManager = new ActionManager(
  144. this.syncActionResult,
  145. () => this.state,
  146. () => globalSceneState.getAllElements(),
  147. );
  148. this.actionManager.registerAll(actions);
  149. this.actionManager.registerAction(createUndoAction(history));
  150. this.actionManager.registerAction(createRedoAction(history));
  151. }
  152. public render() {
  153. const canvasDOMWidth = window.innerWidth;
  154. const canvasDOMHeight = window.innerHeight;
  155. const canvasScale = window.devicePixelRatio;
  156. const canvasWidth = canvasDOMWidth * canvasScale;
  157. const canvasHeight = canvasDOMHeight * canvasScale;
  158. return (
  159. <div className="container">
  160. <LayerUI
  161. canvas={this.canvas}
  162. appState={this.state}
  163. setAppState={this.setAppState}
  164. actionManager={this.actionManager}
  165. elements={globalSceneState.getAllElements().filter((element) => {
  166. return !element.isDeleted;
  167. })}
  168. setElements={this.setElements}
  169. language={getLanguage()}
  170. onRoomCreate={this.createRoom}
  171. onRoomDestroy={this.destroyRoom}
  172. onToggleLock={this.toggleLock}
  173. />
  174. <main>
  175. <canvas
  176. id="canvas"
  177. style={{
  178. width: canvasDOMWidth,
  179. height: canvasDOMHeight,
  180. }}
  181. width={canvasWidth}
  182. height={canvasHeight}
  183. ref={(canvas) => {
  184. // canvas is null when unmounting
  185. if (canvas !== null) {
  186. this.canvas = canvas;
  187. this.rc = rough.canvas(this.canvas);
  188. this.canvas.addEventListener("wheel", this.handleWheel, {
  189. passive: false,
  190. });
  191. } else {
  192. this.canvas?.removeEventListener("wheel", this.handleWheel);
  193. }
  194. }}
  195. onContextMenu={this.handleCanvasContextMenu}
  196. onPointerDown={this.handleCanvasPointerDown}
  197. onDoubleClick={this.handleCanvasDoubleClick}
  198. onPointerMove={this.handleCanvasPointerMove}
  199. onPointerUp={this.removePointer}
  200. onPointerCancel={this.removePointer}
  201. onDrop={(event) => {
  202. const file = event.dataTransfer.files[0];
  203. if (
  204. file?.type === "application/json" ||
  205. file?.name.endsWith(".excalidraw")
  206. ) {
  207. loadFromBlob(file)
  208. .then(({ elements, appState }) =>
  209. this.syncActionResult({
  210. elements,
  211. appState,
  212. commitToHistory: false,
  213. }),
  214. )
  215. .catch((error) => console.error(error));
  216. }
  217. }}
  218. >
  219. {t("labels.drawingCanvas")}
  220. </canvas>
  221. </main>
  222. </div>
  223. );
  224. }
  225. private syncActionResult = withBatchedUpdates((res: ActionResult) => {
  226. if (this.unmounted) {
  227. return;
  228. }
  229. if (res.elements) {
  230. globalSceneState.replaceAllElements(res.elements);
  231. if (res.commitToHistory) {
  232. history.resumeRecording();
  233. }
  234. }
  235. if (res.appState) {
  236. if (res.commitToHistory) {
  237. history.resumeRecording();
  238. }
  239. this.setState((state) => ({
  240. ...res.appState,
  241. isCollaborating: state.isCollaborating,
  242. collaborators: state.collaborators,
  243. }));
  244. }
  245. });
  246. // Lifecycle
  247. private onUnload = withBatchedUpdates(() => {
  248. isHoldingSpace = false;
  249. this.saveDebounced();
  250. this.saveDebounced.flush();
  251. });
  252. private disableEvent: EventHandlerNonNull = (event) => {
  253. event.preventDefault();
  254. };
  255. private unmounted = false;
  256. public async componentDidMount() {
  257. if (
  258. process.env.NODE_ENV === "test" ||
  259. process.env.NODE_ENV === "development"
  260. ) {
  261. const setState = this.setState.bind(this);
  262. Object.defineProperties(window.h, {
  263. state: {
  264. configurable: true,
  265. get: () => {
  266. return this.state;
  267. },
  268. },
  269. setState: {
  270. configurable: true,
  271. value: (...args: Parameters<typeof setState>) => {
  272. return this.setState(...args);
  273. },
  274. },
  275. });
  276. }
  277. this.removeSceneCallback = globalSceneState.addCallback(
  278. this.onSceneUpdated,
  279. );
  280. document.addEventListener("copy", this.onCopy);
  281. document.addEventListener("paste", this.pasteFromClipboard);
  282. document.addEventListener("cut", this.onCut);
  283. document.addEventListener("keydown", this.onKeyDown, false);
  284. document.addEventListener("keyup", this.onKeyUp, { passive: true });
  285. document.addEventListener("mousemove", this.updateCurrentCursorPosition);
  286. window.addEventListener("resize", this.onResize, false);
  287. window.addEventListener("unload", this.onUnload, false);
  288. window.addEventListener("blur", this.onUnload, false);
  289. window.addEventListener("dragover", this.disableEvent, false);
  290. window.addEventListener("drop", this.disableEvent, false);
  291. // Safari-only desktop pinch zoom
  292. document.addEventListener(
  293. "gesturestart",
  294. this.onGestureStart as any,
  295. false,
  296. );
  297. document.addEventListener(
  298. "gesturechange",
  299. this.onGestureChange as any,
  300. false,
  301. );
  302. document.addEventListener("gestureend", this.onGestureEnd as any, false);
  303. const searchParams = new URLSearchParams(window.location.search);
  304. const id = searchParams.get("id");
  305. if (id) {
  306. // Backwards compatibility with legacy url format
  307. const scene = await loadScene(id);
  308. this.syncActionResult(scene);
  309. }
  310. const jsonMatch = window.location.hash.match(
  311. /^#json=([0-9]+),([a-zA-Z0-9_-]+)$/,
  312. );
  313. if (jsonMatch) {
  314. const scene = await loadScene(jsonMatch[1], jsonMatch[2]);
  315. this.syncActionResult(scene);
  316. return;
  317. }
  318. const scene = await loadScene(null);
  319. this.syncActionResult(scene);
  320. const roomMatch = getCollaborationLinkData(window.location.href);
  321. if (roomMatch) {
  322. this.initializeSocketClient();
  323. return;
  324. }
  325. window.addEventListener("beforeunload", this.beforeUnload);
  326. }
  327. public componentWillUnmount() {
  328. this.unmounted = true;
  329. this.removeSceneCallback!();
  330. document.removeEventListener("copy", this.onCopy);
  331. document.removeEventListener("paste", this.pasteFromClipboard);
  332. document.removeEventListener("cut", this.onCut);
  333. document.removeEventListener("keydown", this.onKeyDown, false);
  334. document.removeEventListener(
  335. "mousemove",
  336. this.updateCurrentCursorPosition,
  337. false,
  338. );
  339. document.removeEventListener("keyup", this.onKeyUp);
  340. window.removeEventListener("resize", this.onResize, false);
  341. window.removeEventListener("unload", this.onUnload, false);
  342. window.removeEventListener("blur", this.onUnload, false);
  343. window.removeEventListener("dragover", this.disableEvent, false);
  344. window.removeEventListener("drop", this.disableEvent, false);
  345. document.removeEventListener(
  346. "gesturestart",
  347. this.onGestureStart as any,
  348. false,
  349. );
  350. document.removeEventListener(
  351. "gesturechange",
  352. this.onGestureChange as any,
  353. false,
  354. );
  355. document.removeEventListener("gestureend", this.onGestureEnd as any, false);
  356. window.removeEventListener("beforeunload", this.beforeUnload);
  357. }
  358. private onResize = withBatchedUpdates(() => {
  359. globalSceneState
  360. .getAllElements()
  361. .forEach((element) => invalidateShapeForElement(element));
  362. this.setState({});
  363. });
  364. private beforeUnload = withBatchedUpdates((event: BeforeUnloadEvent) => {
  365. if (
  366. this.state.isCollaborating &&
  367. hasNonDeletedElements(globalSceneState.getAllElements())
  368. ) {
  369. event.preventDefault();
  370. // NOTE: modern browsers no longer allow showing a custom message here
  371. event.returnValue = "";
  372. }
  373. });
  374. componentDidUpdate() {
  375. if (this.state.isCollaborating && !this.socket) {
  376. this.initializeSocketClient();
  377. }
  378. const pointerViewportCoords: {
  379. [id: string]: { x: number; y: number };
  380. } = {};
  381. this.state.collaborators.forEach((user, socketID) => {
  382. if (!user.pointer) {
  383. return;
  384. }
  385. pointerViewportCoords[socketID] = sceneCoordsToViewportCoords(
  386. {
  387. sceneX: user.pointer.x,
  388. sceneY: user.pointer.y,
  389. },
  390. this.state,
  391. this.canvas,
  392. window.devicePixelRatio,
  393. );
  394. });
  395. const { atLeastOneVisibleElement, scrollBars } = renderScene(
  396. globalSceneState.getAllElements(),
  397. this.state,
  398. this.state.selectionElement,
  399. window.devicePixelRatio,
  400. this.rc!,
  401. this.canvas!,
  402. {
  403. scrollX: this.state.scrollX,
  404. scrollY: this.state.scrollY,
  405. viewBackgroundColor: this.state.viewBackgroundColor,
  406. zoom: this.state.zoom,
  407. remotePointerViewportCoords: pointerViewportCoords,
  408. },
  409. {
  410. renderOptimizations: true,
  411. },
  412. );
  413. if (scrollBars) {
  414. currentScrollBars = scrollBars;
  415. }
  416. const scrolledOutside =
  417. !atLeastOneVisibleElement &&
  418. hasNonDeletedElements(globalSceneState.getAllElements());
  419. if (this.state.scrolledOutside !== scrolledOutside) {
  420. this.setState({ scrolledOutside: scrolledOutside });
  421. }
  422. this.saveDebounced();
  423. if (
  424. getDrawingVersion(globalSceneState.getAllElements()) >
  425. this.lastBroadcastedOrReceivedSceneVersion
  426. ) {
  427. this.broadcastSceneUpdate();
  428. }
  429. history.record(this.state, globalSceneState.getAllElements());
  430. }
  431. // Copy/paste
  432. private onCut = withBatchedUpdates((event: ClipboardEvent) => {
  433. if (isWritableElement(event.target)) {
  434. return;
  435. }
  436. copyToAppClipboard(globalSceneState.getAllElements(), this.state);
  437. const { elements: nextElements, appState } = deleteSelectedElements(
  438. globalSceneState.getAllElements(),
  439. this.state,
  440. );
  441. globalSceneState.replaceAllElements(nextElements);
  442. history.resumeRecording();
  443. this.setState({ ...appState });
  444. event.preventDefault();
  445. });
  446. private onCopy = withBatchedUpdates((event: ClipboardEvent) => {
  447. if (isWritableElement(event.target)) {
  448. return;
  449. }
  450. copyToAppClipboard(globalSceneState.getAllElements(), this.state);
  451. event.preventDefault();
  452. });
  453. private copyToAppClipboard = () => {
  454. copyToAppClipboard(globalSceneState.getAllElements(), this.state);
  455. };
  456. private copyToClipboardAsPng = () => {
  457. const selectedElements = getSelectedElements(
  458. globalSceneState.getAllElements(),
  459. this.state,
  460. );
  461. exportCanvas(
  462. "clipboard",
  463. selectedElements.length
  464. ? selectedElements
  465. : globalSceneState.getAllElements(),
  466. this.state,
  467. this.canvas!,
  468. this.state,
  469. );
  470. };
  471. private pasteFromClipboard = withBatchedUpdates(
  472. async (event: ClipboardEvent | null) => {
  473. // #686
  474. const target = document.activeElement;
  475. const elementUnderCursor = document.elementFromPoint(cursorX, cursorY);
  476. if (
  477. // if no ClipboardEvent supplied, assume we're pasting via contextMenu
  478. // thus these checks don't make sense
  479. !event ||
  480. (elementUnderCursor instanceof HTMLCanvasElement &&
  481. !isWritableElement(target))
  482. ) {
  483. const data = await getClipboardContent(event);
  484. if (data.elements) {
  485. this.addElementsFromPaste(data.elements);
  486. } else if (data.text) {
  487. const { x, y } = viewportCoordsToSceneCoords(
  488. { clientX: cursorX, clientY: cursorY },
  489. this.state,
  490. this.canvas,
  491. window.devicePixelRatio,
  492. );
  493. const element = newTextElement({
  494. x: x,
  495. y: y,
  496. strokeColor: this.state.currentItemStrokeColor,
  497. backgroundColor: this.state.currentItemBackgroundColor,
  498. fillStyle: this.state.currentItemFillStyle,
  499. strokeWidth: this.state.currentItemStrokeWidth,
  500. roughness: this.state.currentItemRoughness,
  501. opacity: this.state.currentItemOpacity,
  502. text: data.text,
  503. font: this.state.currentItemFont,
  504. });
  505. globalSceneState.replaceAllElements([
  506. ...globalSceneState.getAllElements(),
  507. element,
  508. ]);
  509. this.setState({ selectedElementIds: { [element.id]: true } });
  510. history.resumeRecording();
  511. }
  512. this.selectShapeTool("selection");
  513. event?.preventDefault();
  514. }
  515. },
  516. );
  517. private addElementsFromPaste = (
  518. clipboardElements: readonly ExcalidrawElement[],
  519. ) => {
  520. const [minX, minY, maxX, maxY] = getCommonBounds(clipboardElements);
  521. const elementsCenterX = distance(minX, maxX) / 2;
  522. const elementsCenterY = distance(minY, maxY) / 2;
  523. const { x, y } = viewportCoordsToSceneCoords(
  524. { clientX: cursorX, clientY: cursorY },
  525. this.state,
  526. this.canvas,
  527. window.devicePixelRatio,
  528. );
  529. const dx = x - elementsCenterX;
  530. const dy = y - elementsCenterY;
  531. const newElements = clipboardElements.map((element) =>
  532. duplicateElement(element, {
  533. x: element.x + dx - minX,
  534. y: element.y + dy - minY,
  535. }),
  536. );
  537. globalSceneState.replaceAllElements([
  538. ...globalSceneState.getAllElements(),
  539. ...newElements,
  540. ]);
  541. history.resumeRecording();
  542. this.setState({
  543. selectedElementIds: newElements.reduce((map, element) => {
  544. map[element.id] = true;
  545. return map;
  546. }, {} as any),
  547. });
  548. };
  549. // Collaboration
  550. setAppState = (obj: any) => {
  551. this.setState(obj);
  552. };
  553. removePointer = (event: React.PointerEvent<HTMLElement>) => {
  554. gesture.pointers.delete(event.pointerId);
  555. };
  556. createRoom = async () => {
  557. window.history.pushState(
  558. {},
  559. "Excalidraw",
  560. await generateCollaborationLink(),
  561. );
  562. this.initializeSocketClient();
  563. };
  564. destroyRoom = () => {
  565. window.history.pushState({}, "Excalidraw", window.location.origin);
  566. this.destroySocketClient();
  567. };
  568. toggleLock = () => {
  569. this.setState((prevState) => ({
  570. elementLocked: !prevState.elementLocked,
  571. elementType: prevState.elementLocked
  572. ? "selection"
  573. : prevState.elementType,
  574. }));
  575. };
  576. private destroySocketClient = () => {
  577. this.setState({
  578. isCollaborating: false,
  579. collaborators: new Map(),
  580. });
  581. if (this.socket) {
  582. this.socket.close();
  583. this.socket = null;
  584. this.roomID = null;
  585. this.roomKey = null;
  586. }
  587. };
  588. private initializeSocketClient = () => {
  589. if (this.socket) {
  590. return;
  591. }
  592. const roomMatch = getCollaborationLinkData(window.location.href);
  593. if (roomMatch) {
  594. this.setState({
  595. isCollaborating: true,
  596. });
  597. this.socket = socketIOClient(SOCKET_SERVER);
  598. this.roomID = roomMatch[1];
  599. this.roomKey = roomMatch[2];
  600. this.socket.on("init-room", () => {
  601. this.socket && this.socket.emit("join-room", this.roomID);
  602. });
  603. this.socket.on(
  604. "client-broadcast",
  605. async (encryptedData: ArrayBuffer, iv: Uint8Array) => {
  606. if (!this.roomKey) {
  607. return;
  608. }
  609. const decryptedData = await decryptAESGEM(
  610. encryptedData,
  611. this.roomKey,
  612. iv,
  613. );
  614. switch (decryptedData.type) {
  615. case "INVALID_RESPONSE":
  616. return;
  617. case "SCENE_UPDATE":
  618. const { elements: remoteElements } = decryptedData.payload;
  619. const restoredState = restore(remoteElements || [], null, {
  620. scrollToContent: true,
  621. });
  622. // Perform reconciliation - in collaboration, if we encounter
  623. // elements with more staler versions than ours, ignore them
  624. // and keep ours.
  625. if (
  626. globalSceneState.getAllElements() == null ||
  627. globalSceneState.getAllElements().length === 0
  628. ) {
  629. globalSceneState.replaceAllElements(restoredState.elements);
  630. } else {
  631. // create a map of ids so we don't have to iterate
  632. // over the array more than once.
  633. const localElementMap = getElementMap(
  634. globalSceneState.getAllElements(),
  635. );
  636. // Reconcile
  637. globalSceneState.replaceAllElements(
  638. restoredState.elements
  639. .reduce((elements, element) => {
  640. // if the remote element references one that's currently
  641. // edited on local, skip it (it'll be added in the next
  642. // step)
  643. if (
  644. element.id === this.state.editingElement?.id ||
  645. element.id === this.state.resizingElement?.id ||
  646. element.id === this.state.draggingElement?.id
  647. ) {
  648. return elements;
  649. }
  650. if (
  651. localElementMap.hasOwnProperty(element.id) &&
  652. localElementMap[element.id].version > element.version
  653. ) {
  654. elements.push(localElementMap[element.id]);
  655. delete localElementMap[element.id];
  656. } else if (
  657. localElementMap.hasOwnProperty(element.id) &&
  658. localElementMap[element.id].version ===
  659. element.version &&
  660. localElementMap[element.id].versionNonce !==
  661. element.versionNonce
  662. ) {
  663. // resolve conflicting edits deterministically by taking the one with the lowest versionNonce
  664. if (
  665. localElementMap[element.id].versionNonce <
  666. element.versionNonce
  667. ) {
  668. elements.push(localElementMap[element.id]);
  669. } else {
  670. // it should be highly unlikely that the two versionNonces are the same. if we are
  671. // really worried about this, we can replace the versionNonce with the socket id.
  672. elements.push(element);
  673. }
  674. delete localElementMap[element.id];
  675. } else {
  676. elements.push(element);
  677. delete localElementMap[element.id];
  678. }
  679. return elements;
  680. }, [] as Mutable<typeof restoredState.elements>)
  681. // add local elements that weren't deleted or on remote
  682. .concat(...Object.values(localElementMap)),
  683. );
  684. }
  685. this.lastBroadcastedOrReceivedSceneVersion = getDrawingVersion(
  686. globalSceneState.getAllElements(),
  687. );
  688. // We haven't yet implemented multiplayer undo functionality, so we clear the undo stack
  689. // when we receive any messages from another peer. This UX can be pretty rough -- if you
  690. // undo, a user makes a change, and then try to redo, your element(s) will be lost. However,
  691. // right now we think this is the right tradeoff.
  692. history.clear();
  693. if (this.socketInitialized === false) {
  694. this.socketInitialized = true;
  695. }
  696. break;
  697. case "MOUSE_LOCATION":
  698. const { socketID, pointerCoords } = decryptedData.payload;
  699. this.setState((state) => {
  700. if (!state.collaborators.has(socketID)) {
  701. state.collaborators.set(socketID, {});
  702. }
  703. const user = state.collaborators.get(socketID)!;
  704. user.pointer = pointerCoords;
  705. state.collaborators.set(socketID, user);
  706. return state;
  707. });
  708. break;
  709. }
  710. },
  711. );
  712. this.socket.on("first-in-room", () => {
  713. if (this.socket) {
  714. this.socket.off("first-in-room");
  715. }
  716. this.socketInitialized = true;
  717. });
  718. this.socket.on("room-user-change", (clients: string[]) => {
  719. this.setState((state) => {
  720. const collaborators: typeof state.collaborators = new Map();
  721. for (const socketID of clients) {
  722. if (state.collaborators.has(socketID)) {
  723. collaborators.set(socketID, state.collaborators.get(socketID)!);
  724. } else {
  725. collaborators.set(socketID, {});
  726. }
  727. }
  728. return {
  729. ...state,
  730. collaborators,
  731. };
  732. });
  733. });
  734. this.socket.on("new-user", async (socketID: string) => {
  735. this.broadcastSceneUpdate();
  736. });
  737. }
  738. };
  739. private broadcastMouseLocation = (payload: {
  740. pointerCoords: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["pointerCoords"];
  741. }) => {
  742. if (this.socket?.id) {
  743. const data: SocketUpdateDataSource["MOUSE_LOCATION"] = {
  744. type: "MOUSE_LOCATION",
  745. payload: {
  746. socketID: this.socket.id,
  747. pointerCoords: payload.pointerCoords,
  748. },
  749. };
  750. return this._broadcastSocketData(
  751. data as typeof data & { _brand: "socketUpdateData" },
  752. );
  753. }
  754. };
  755. private broadcastSceneUpdate = () => {
  756. const data: SocketUpdateDataSource["SCENE_UPDATE"] = {
  757. type: "SCENE_UPDATE",
  758. payload: {
  759. elements: getSyncableElements(globalSceneState.getAllElements()),
  760. },
  761. };
  762. this.lastBroadcastedOrReceivedSceneVersion = Math.max(
  763. this.lastBroadcastedOrReceivedSceneVersion,
  764. getDrawingVersion(globalSceneState.getAllElements()),
  765. );
  766. return this._broadcastSocketData(
  767. data as typeof data & { _brand: "socketUpdateData" },
  768. );
  769. };
  770. // Low-level. Use type-specific broadcast* method.
  771. private async _broadcastSocketData(
  772. data: SocketUpdateDataSource[keyof SocketUpdateDataSource] & {
  773. _brand: "socketUpdateData";
  774. },
  775. ) {
  776. if (this.socketInitialized && this.socket && this.roomID && this.roomKey) {
  777. const json = JSON.stringify(data);
  778. const encoded = new TextEncoder().encode(json);
  779. const encrypted = await encryptAESGEM(encoded, this.roomKey);
  780. this.socket.emit(
  781. "server-broadcast",
  782. this.roomID,
  783. encrypted.data,
  784. encrypted.iv,
  785. );
  786. }
  787. }
  788. private onSceneUpdated = () => {
  789. this.setState({});
  790. };
  791. public state: AppState = getDefaultAppState();
  792. private updateCurrentCursorPosition = withBatchedUpdates(
  793. (event: MouseEvent) => {
  794. cursorX = event.x;
  795. cursorY = event.y;
  796. },
  797. );
  798. // Input handling
  799. private onKeyDown = withBatchedUpdates((event: KeyboardEvent) => {
  800. if (
  801. (isWritableElement(event.target) && event.key !== KEYS.ESCAPE) ||
  802. // case: using arrows to move between buttons
  803. (isArrowKey(event.key) && isInputLike(event.target))
  804. ) {
  805. return;
  806. }
  807. if (event.code === "KeyC" && event.altKey && event.shiftKey) {
  808. this.copyToClipboardAsPng();
  809. event.preventDefault();
  810. return;
  811. }
  812. if (this.actionManager.handleKeyDown(event)) {
  813. return;
  814. }
  815. const shape = findShapeByKey(event.key);
  816. if (isArrowKey(event.key)) {
  817. const step = event.shiftKey
  818. ? ELEMENT_SHIFT_TRANSLATE_AMOUNT
  819. : ELEMENT_TRANSLATE_AMOUNT;
  820. globalSceneState.replaceAllElements(
  821. globalSceneState.getAllElements().map((el) => {
  822. if (this.state.selectedElementIds[el.id]) {
  823. const update: { x?: number; y?: number } = {};
  824. if (event.key === KEYS.ARROW_LEFT) {
  825. update.x = el.x - step;
  826. } else if (event.key === KEYS.ARROW_RIGHT) {
  827. update.x = el.x + step;
  828. } else if (event.key === KEYS.ARROW_UP) {
  829. update.y = el.y - step;
  830. } else if (event.key === KEYS.ARROW_DOWN) {
  831. update.y = el.y + step;
  832. }
  833. return newElementWith(el, update);
  834. }
  835. return el;
  836. }),
  837. );
  838. event.preventDefault();
  839. } else if (
  840. !event.ctrlKey &&
  841. !event.altKey &&
  842. !event.metaKey &&
  843. this.state.draggingElement === null
  844. ) {
  845. if (shapesShortcutKeys.includes(event.key.toLowerCase())) {
  846. this.selectShapeTool(shape);
  847. } else if (event.key === "q") {
  848. this.toggleLock();
  849. }
  850. }
  851. if (event.key === KEYS.SPACE && gesture.pointers.size === 0) {
  852. isHoldingSpace = true;
  853. document.documentElement.style.cursor = CURSOR_TYPE.GRABBING;
  854. }
  855. });
  856. private onKeyUp = withBatchedUpdates((event: KeyboardEvent) => {
  857. if (event.key === KEYS.SPACE) {
  858. if (this.state.elementType === "selection") {
  859. resetCursor();
  860. } else {
  861. document.documentElement.style.cursor =
  862. this.state.elementType === "text"
  863. ? CURSOR_TYPE.TEXT
  864. : CURSOR_TYPE.CROSSHAIR;
  865. this.setState({ selectedElementIds: {} });
  866. }
  867. isHoldingSpace = false;
  868. }
  869. });
  870. private selectShapeTool(elementType: AppState["elementType"]) {
  871. if (!isHoldingSpace) {
  872. setCursorForShape(elementType);
  873. }
  874. if (isToolIcon(document.activeElement)) {
  875. document.activeElement.blur();
  876. }
  877. if (elementType !== "selection") {
  878. this.setState({ elementType, selectedElementIds: {} });
  879. } else {
  880. this.setState({ elementType });
  881. }
  882. }
  883. private onGestureStart = withBatchedUpdates((event: GestureEvent) => {
  884. event.preventDefault();
  885. gesture.initialScale = this.state.zoom;
  886. });
  887. private onGestureChange = withBatchedUpdates((event: GestureEvent) => {
  888. event.preventDefault();
  889. this.setState({
  890. zoom: getNormalizedZoom(gesture.initialScale! * event.scale),
  891. });
  892. });
  893. private onGestureEnd = withBatchedUpdates((event: GestureEvent) => {
  894. event.preventDefault();
  895. gesture.initialScale = null;
  896. });
  897. private setElements = (elements: readonly ExcalidrawElement[]) => {
  898. globalSceneState.replaceAllElements(elements);
  899. };
  900. private handleCanvasDoubleClick = (
  901. event: React.MouseEvent<HTMLCanvasElement>,
  902. ) => {
  903. // case: double-clicking with arrow/line tool selected would both create
  904. // text and enter multiElement mode
  905. if (this.state.multiElement) {
  906. return;
  907. }
  908. resetCursor();
  909. const { x, y } = viewportCoordsToSceneCoords(
  910. event,
  911. this.state,
  912. this.canvas,
  913. window.devicePixelRatio,
  914. );
  915. const elementAtPosition = getElementAtPosition(
  916. globalSceneState.getAllElements(),
  917. this.state,
  918. x,
  919. y,
  920. this.state.zoom,
  921. );
  922. const element =
  923. elementAtPosition && isTextElement(elementAtPosition)
  924. ? elementAtPosition
  925. : newTextElement({
  926. x: x,
  927. y: y,
  928. strokeColor: this.state.currentItemStrokeColor,
  929. backgroundColor: this.state.currentItemBackgroundColor,
  930. fillStyle: this.state.currentItemFillStyle,
  931. strokeWidth: this.state.currentItemStrokeWidth,
  932. roughness: this.state.currentItemRoughness,
  933. opacity: this.state.currentItemOpacity,
  934. text: "",
  935. font: this.state.currentItemFont,
  936. });
  937. this.setState({ editingElement: element });
  938. let textX = event.clientX;
  939. let textY = event.clientY;
  940. if (elementAtPosition && isTextElement(elementAtPosition)) {
  941. globalSceneState.replaceAllElements(
  942. globalSceneState
  943. .getAllElements()
  944. .filter((element) => element.id !== elementAtPosition.id),
  945. );
  946. const centerElementX = elementAtPosition.x + elementAtPosition.width / 2;
  947. const centerElementY = elementAtPosition.y + elementAtPosition.height / 2;
  948. const {
  949. x: centerElementXInViewport,
  950. y: centerElementYInViewport,
  951. } = sceneCoordsToViewportCoords(
  952. { sceneX: centerElementX, sceneY: centerElementY },
  953. this.state,
  954. this.canvas,
  955. window.devicePixelRatio,
  956. );
  957. textX = centerElementXInViewport;
  958. textY = centerElementYInViewport;
  959. // x and y will change after calling newTextElement function
  960. mutateElement(element, {
  961. x: centerElementX,
  962. y: centerElementY,
  963. });
  964. } else if (!event.altKey) {
  965. const snappedToCenterPosition = this.getTextWysiwygSnappedToCenterPosition(
  966. x,
  967. y,
  968. );
  969. if (snappedToCenterPosition) {
  970. mutateElement(element, {
  971. x: snappedToCenterPosition.elementCenterX,
  972. y: snappedToCenterPosition.elementCenterY,
  973. });
  974. textX = snappedToCenterPosition.wysiwygX;
  975. textY = snappedToCenterPosition.wysiwygY;
  976. }
  977. }
  978. const resetSelection = () => {
  979. this.setState({
  980. draggingElement: null,
  981. editingElement: null,
  982. });
  983. };
  984. // deselect all other elements when inserting text
  985. this.setState({ selectedElementIds: {} });
  986. textWysiwyg({
  987. initText: element.text,
  988. x: textX,
  989. y: textY,
  990. strokeColor: element.strokeColor,
  991. font: element.font,
  992. opacity: this.state.currentItemOpacity,
  993. zoom: this.state.zoom,
  994. onSubmit: (text) => {
  995. if (text) {
  996. globalSceneState.replaceAllElements([
  997. ...globalSceneState.getAllElements(),
  998. // we need to recreate the element to update dimensions & position
  999. newTextElement({ ...element, text, font: element.font }),
  1000. ]);
  1001. }
  1002. this.setState((prevState) => ({
  1003. selectedElementIds: {
  1004. ...prevState.selectedElementIds,
  1005. [element.id]: true,
  1006. },
  1007. }));
  1008. history.resumeRecording();
  1009. resetSelection();
  1010. },
  1011. onCancel: () => {
  1012. resetSelection();
  1013. },
  1014. });
  1015. };
  1016. private handleCanvasPointerMove = (
  1017. event: React.PointerEvent<HTMLCanvasElement>,
  1018. ) => {
  1019. const pointerCoords = viewportCoordsToSceneCoords(
  1020. event,
  1021. this.state,
  1022. this.canvas,
  1023. window.devicePixelRatio,
  1024. );
  1025. this.savePointer(pointerCoords);
  1026. if (gesture.pointers.has(event.pointerId)) {
  1027. gesture.pointers.set(event.pointerId, {
  1028. x: event.clientX,
  1029. y: event.clientY,
  1030. });
  1031. }
  1032. if (gesture.pointers.size === 2) {
  1033. const center = getCenter(gesture.pointers);
  1034. const deltaX = center.x - gesture.lastCenter!.x;
  1035. const deltaY = center.y - gesture.lastCenter!.y;
  1036. gesture.lastCenter = center;
  1037. const distance = getDistance(Array.from(gesture.pointers.values()));
  1038. const scaleFactor = distance / gesture.initialDistance!;
  1039. this.setState({
  1040. scrollX: normalizeScroll(this.state.scrollX + deltaX / this.state.zoom),
  1041. scrollY: normalizeScroll(this.state.scrollY + deltaY / this.state.zoom),
  1042. zoom: getNormalizedZoom(gesture.initialScale! * scaleFactor),
  1043. });
  1044. } else {
  1045. gesture.lastCenter = gesture.initialDistance = gesture.initialScale = null;
  1046. }
  1047. if (isHoldingSpace || isPanning || isDraggingScrollBar) {
  1048. return;
  1049. }
  1050. const {
  1051. isOverHorizontalScrollBar,
  1052. isOverVerticalScrollBar,
  1053. } = isOverScrollBars(currentScrollBars, event.clientX, event.clientY);
  1054. const isOverScrollBar =
  1055. isOverVerticalScrollBar || isOverHorizontalScrollBar;
  1056. if (!this.state.draggingElement && !this.state.multiElement) {
  1057. if (isOverScrollBar) {
  1058. resetCursor();
  1059. } else {
  1060. setCursorForShape(this.state.elementType);
  1061. }
  1062. }
  1063. const { x, y } = viewportCoordsToSceneCoords(
  1064. event,
  1065. this.state,
  1066. this.canvas,
  1067. window.devicePixelRatio,
  1068. );
  1069. if (this.state.multiElement) {
  1070. const { multiElement } = this.state;
  1071. const { x: rx, y: ry } = multiElement;
  1072. const { points, lastCommittedPoint } = multiElement;
  1073. const lastPoint = points[points.length - 1];
  1074. setCursorForShape(this.state.elementType);
  1075. if (lastPoint === lastCommittedPoint) {
  1076. // if we haven't yet created a temp point and we're beyond commit-zone
  1077. // threshold, add a point
  1078. if (
  1079. distance2d(x - rx, y - ry, lastPoint[0], lastPoint[1]) >=
  1080. ARROW_CONFIRM_THRESHOLD
  1081. ) {
  1082. mutateElement(multiElement, {
  1083. points: [...points, [x - rx, y - ry]],
  1084. });
  1085. } else {
  1086. document.documentElement.style.cursor = CURSOR_TYPE.POINTER;
  1087. // in this branch, we're inside the commit zone, and no uncommitted
  1088. // point exists. Thus do nothing (don't add/remove points).
  1089. }
  1090. } else {
  1091. // cursor moved inside commit zone, and there's uncommitted point,
  1092. // thus remove it
  1093. if (
  1094. points.length > 2 &&
  1095. lastCommittedPoint &&
  1096. distance2d(
  1097. x - rx,
  1098. y - ry,
  1099. lastCommittedPoint[0],
  1100. lastCommittedPoint[1],
  1101. ) < ARROW_CONFIRM_THRESHOLD
  1102. ) {
  1103. document.documentElement.style.cursor = CURSOR_TYPE.POINTER;
  1104. mutateElement(multiElement, {
  1105. points: points.slice(0, -1),
  1106. });
  1107. } else {
  1108. // update last uncommitted point
  1109. mutateElement(multiElement, {
  1110. points: [...points.slice(0, -1), [x - rx, y - ry]],
  1111. });
  1112. }
  1113. }
  1114. return;
  1115. }
  1116. const hasDeselectedButton = Boolean(event.buttons);
  1117. if (hasDeselectedButton || this.state.elementType !== "selection") {
  1118. return;
  1119. }
  1120. const selectedElements = getSelectedElements(
  1121. globalSceneState.getAllElements(),
  1122. this.state,
  1123. );
  1124. if (selectedElements.length === 1 && !isOverScrollBar) {
  1125. const resizeElement = getElementWithResizeHandler(
  1126. globalSceneState.getAllElements(),
  1127. this.state,
  1128. { x, y },
  1129. this.state.zoom,
  1130. event.pointerType,
  1131. );
  1132. if (resizeElement && resizeElement.resizeHandle) {
  1133. document.documentElement.style.cursor = getCursorForResizingElement(
  1134. resizeElement,
  1135. );
  1136. return;
  1137. }
  1138. }
  1139. const hitElement = getElementAtPosition(
  1140. globalSceneState.getAllElements(),
  1141. this.state,
  1142. x,
  1143. y,
  1144. this.state.zoom,
  1145. );
  1146. document.documentElement.style.cursor =
  1147. hitElement && !isOverScrollBar ? "move" : "";
  1148. };
  1149. private handleCanvasPointerDown = (
  1150. event: React.PointerEvent<HTMLCanvasElement>,
  1151. ) => {
  1152. if (lastPointerUp !== null) {
  1153. // Unfortunately, sometimes we don't get a pointerup after a pointerdown,
  1154. // this can happen when a contextual menu or alert is triggered. In order to avoid
  1155. // being in a weird state, we clean up on the next pointerdown
  1156. lastPointerUp(event);
  1157. }
  1158. if (isPanning) {
  1159. return;
  1160. }
  1161. this.setState({ lastPointerDownWith: event.pointerType });
  1162. // pan canvas on wheel button drag or space+drag
  1163. if (
  1164. gesture.pointers.size === 0 &&
  1165. (event.button === POINTER_BUTTON.WHEEL ||
  1166. (event.button === POINTER_BUTTON.MAIN && isHoldingSpace))
  1167. ) {
  1168. isPanning = true;
  1169. document.documentElement.style.cursor = CURSOR_TYPE.GRABBING;
  1170. let { clientX: lastX, clientY: lastY } = event;
  1171. const onPointerMove = withBatchedUpdates((event: PointerEvent) => {
  1172. const deltaX = lastX - event.clientX;
  1173. const deltaY = lastY - event.clientY;
  1174. lastX = event.clientX;
  1175. lastY = event.clientY;
  1176. this.setState({
  1177. scrollX: normalizeScroll(
  1178. this.state.scrollX - deltaX / this.state.zoom,
  1179. ),
  1180. scrollY: normalizeScroll(
  1181. this.state.scrollY - deltaY / this.state.zoom,
  1182. ),
  1183. });
  1184. });
  1185. const teardown = withBatchedUpdates(
  1186. (lastPointerUp = () => {
  1187. lastPointerUp = null;
  1188. isPanning = false;
  1189. if (!isHoldingSpace) {
  1190. setCursorForShape(this.state.elementType);
  1191. }
  1192. window.removeEventListener("pointermove", onPointerMove);
  1193. window.removeEventListener("pointerup", teardown);
  1194. window.removeEventListener("blur", teardown);
  1195. }),
  1196. );
  1197. window.addEventListener("blur", teardown);
  1198. window.addEventListener("pointermove", onPointerMove, {
  1199. passive: true,
  1200. });
  1201. window.addEventListener("pointerup", teardown);
  1202. return;
  1203. }
  1204. // only handle left mouse button or touch
  1205. if (
  1206. event.button !== POINTER_BUTTON.MAIN &&
  1207. event.button !== POINTER_BUTTON.TOUCH
  1208. ) {
  1209. return;
  1210. }
  1211. gesture.pointers.set(event.pointerId, {
  1212. x: event.clientX,
  1213. y: event.clientY,
  1214. });
  1215. if (gesture.pointers.size === 2) {
  1216. gesture.lastCenter = getCenter(gesture.pointers);
  1217. gesture.initialScale = this.state.zoom;
  1218. gesture.initialDistance = getDistance(
  1219. Array.from(gesture.pointers.values()),
  1220. );
  1221. }
  1222. // fixes pointermove causing selection of UI texts #32
  1223. event.preventDefault();
  1224. // Preventing the event above disables default behavior
  1225. // of defocusing potentially focused element, which is what we
  1226. // want when clicking inside the canvas.
  1227. if (document.activeElement instanceof HTMLElement) {
  1228. document.activeElement.blur();
  1229. }
  1230. // don't select while panning
  1231. if (gesture.pointers.size > 1) {
  1232. return;
  1233. }
  1234. // Handle scrollbars dragging
  1235. const {
  1236. isOverHorizontalScrollBar,
  1237. isOverVerticalScrollBar,
  1238. } = isOverScrollBars(currentScrollBars, event.clientX, event.clientY);
  1239. const { x, y } = viewportCoordsToSceneCoords(
  1240. event,
  1241. this.state,
  1242. this.canvas,
  1243. window.devicePixelRatio,
  1244. );
  1245. let lastX = x;
  1246. let lastY = y;
  1247. if (
  1248. (isOverHorizontalScrollBar || isOverVerticalScrollBar) &&
  1249. !this.state.multiElement
  1250. ) {
  1251. isDraggingScrollBar = true;
  1252. lastX = event.clientX;
  1253. lastY = event.clientY;
  1254. const onPointerMove = withBatchedUpdates((event: PointerEvent) => {
  1255. const target = event.target;
  1256. if (!(target instanceof HTMLElement)) {
  1257. return;
  1258. }
  1259. if (isOverHorizontalScrollBar) {
  1260. const x = event.clientX;
  1261. const dx = x - lastX;
  1262. this.setState({
  1263. scrollX: normalizeScroll(this.state.scrollX - dx / this.state.zoom),
  1264. });
  1265. lastX = x;
  1266. return;
  1267. }
  1268. if (isOverVerticalScrollBar) {
  1269. const y = event.clientY;
  1270. const dy = y - lastY;
  1271. this.setState({
  1272. scrollY: normalizeScroll(this.state.scrollY - dy / this.state.zoom),
  1273. });
  1274. lastY = y;
  1275. }
  1276. });
  1277. const onPointerUp = withBatchedUpdates(() => {
  1278. isDraggingScrollBar = false;
  1279. setCursorForShape(this.state.elementType);
  1280. lastPointerUp = null;
  1281. window.removeEventListener("pointermove", onPointerMove);
  1282. window.removeEventListener("pointerup", onPointerUp);
  1283. });
  1284. lastPointerUp = onPointerUp;
  1285. window.addEventListener("pointermove", onPointerMove);
  1286. window.addEventListener("pointerup", onPointerUp);
  1287. return;
  1288. }
  1289. const originX = x;
  1290. const originY = y;
  1291. type ResizeTestType = ReturnType<typeof resizeTest>;
  1292. let resizeHandle: ResizeTestType = false;
  1293. let isResizingElements = false;
  1294. let draggingOccurred = false;
  1295. let hitElement: ExcalidrawElement | null = null;
  1296. let hitElementWasAddedToSelection = false;
  1297. if (this.state.elementType === "selection") {
  1298. const resizeElement = getElementWithResizeHandler(
  1299. globalSceneState.getAllElements(),
  1300. this.state,
  1301. { x, y },
  1302. this.state.zoom,
  1303. event.pointerType,
  1304. );
  1305. const selectedElements = getSelectedElements(
  1306. globalSceneState.getAllElements(),
  1307. this.state,
  1308. );
  1309. if (selectedElements.length === 1 && resizeElement) {
  1310. this.setState({
  1311. resizingElement: resizeElement ? resizeElement.element : null,
  1312. });
  1313. resizeHandle = resizeElement.resizeHandle;
  1314. document.documentElement.style.cursor = getCursorForResizingElement(
  1315. resizeElement,
  1316. );
  1317. isResizingElements = true;
  1318. } else {
  1319. hitElement = getElementAtPosition(
  1320. globalSceneState.getAllElements(),
  1321. this.state,
  1322. x,
  1323. y,
  1324. this.state.zoom,
  1325. );
  1326. // clear selection if shift is not clicked
  1327. if (
  1328. !(hitElement && this.state.selectedElementIds[hitElement.id]) &&
  1329. !event.shiftKey
  1330. ) {
  1331. this.setState({ selectedElementIds: {} });
  1332. }
  1333. // If we click on something
  1334. if (hitElement) {
  1335. // deselect if item is selected
  1336. // if shift is not clicked, this will always return true
  1337. // otherwise, it will trigger selection based on current
  1338. // state of the box
  1339. if (!this.state.selectedElementIds[hitElement.id]) {
  1340. this.setState((prevState) => ({
  1341. selectedElementIds: {
  1342. ...prevState.selectedElementIds,
  1343. [hitElement!.id]: true,
  1344. },
  1345. }));
  1346. globalSceneState.replaceAllElements(
  1347. globalSceneState.getAllElements(),
  1348. );
  1349. hitElementWasAddedToSelection = true;
  1350. }
  1351. // We duplicate the selected element if alt is pressed on pointer down
  1352. if (event.altKey) {
  1353. // Move the currently selected elements to the top of the z index stack, and
  1354. // put the duplicates where the selected elements used to be.
  1355. const nextElements = [];
  1356. const elementsToAppend = [];
  1357. for (const element of globalSceneState.getAllElements()) {
  1358. if (
  1359. this.state.selectedElementIds[element.id] ||
  1360. (element.id === hitElement.id && hitElementWasAddedToSelection)
  1361. ) {
  1362. nextElements.push(duplicateElement(element));
  1363. elementsToAppend.push(element);
  1364. } else {
  1365. nextElements.push(element);
  1366. }
  1367. }
  1368. globalSceneState.replaceAllElements([
  1369. ...nextElements,
  1370. ...elementsToAppend,
  1371. ]);
  1372. }
  1373. }
  1374. }
  1375. } else {
  1376. this.setState({ selectedElementIds: {} });
  1377. }
  1378. if (this.state.elementType === "text") {
  1379. // if we're currently still editing text, clicking outside
  1380. // should only finalize it, not create another (irrespective
  1381. // of state.elementLocked)
  1382. if (this.state.editingElement?.type === "text") {
  1383. return;
  1384. }
  1385. const snappedToCenterPosition = event.altKey
  1386. ? null
  1387. : this.getTextWysiwygSnappedToCenterPosition(x, y);
  1388. const element = newTextElement({
  1389. x: snappedToCenterPosition?.elementCenterX ?? x,
  1390. y: snappedToCenterPosition?.elementCenterY ?? y,
  1391. strokeColor: this.state.currentItemStrokeColor,
  1392. backgroundColor: this.state.currentItemBackgroundColor,
  1393. fillStyle: this.state.currentItemFillStyle,
  1394. strokeWidth: this.state.currentItemStrokeWidth,
  1395. roughness: this.state.currentItemRoughness,
  1396. opacity: this.state.currentItemOpacity,
  1397. text: "",
  1398. font: this.state.currentItemFont,
  1399. });
  1400. const resetSelection = () => {
  1401. this.setState({
  1402. draggingElement: null,
  1403. editingElement: null,
  1404. });
  1405. };
  1406. textWysiwyg({
  1407. initText: "",
  1408. x: snappedToCenterPosition?.wysiwygX ?? event.clientX,
  1409. y: snappedToCenterPosition?.wysiwygY ?? event.clientY,
  1410. strokeColor: this.state.currentItemStrokeColor,
  1411. opacity: this.state.currentItemOpacity,
  1412. font: this.state.currentItemFont,
  1413. zoom: this.state.zoom,
  1414. onSubmit: (text) => {
  1415. if (text) {
  1416. globalSceneState.replaceAllElements([
  1417. ...globalSceneState.getAllElements(),
  1418. newTextElement({
  1419. ...element,
  1420. text,
  1421. font: this.state.currentItemFont,
  1422. }),
  1423. ]);
  1424. }
  1425. this.setState((prevState) => ({
  1426. selectedElementIds: {
  1427. ...prevState.selectedElementIds,
  1428. [element.id]: true,
  1429. },
  1430. }));
  1431. if (this.state.elementLocked) {
  1432. setCursorForShape(this.state.elementType);
  1433. }
  1434. history.resumeRecording();
  1435. resetSelection();
  1436. },
  1437. onCancel: () => {
  1438. resetSelection();
  1439. },
  1440. });
  1441. resetCursor();
  1442. if (!this.state.elementLocked) {
  1443. this.setState({
  1444. editingElement: element,
  1445. elementType: "selection",
  1446. });
  1447. } else {
  1448. this.setState({
  1449. editingElement: element,
  1450. });
  1451. }
  1452. return;
  1453. } else if (
  1454. this.state.elementType === "arrow" ||
  1455. this.state.elementType === "line"
  1456. ) {
  1457. if (this.state.multiElement) {
  1458. const { multiElement } = this.state;
  1459. const { x: rx, y: ry, lastCommittedPoint } = multiElement;
  1460. // clicking inside commit zone → finalize arrow
  1461. if (
  1462. multiElement.points.length > 1 &&
  1463. lastCommittedPoint &&
  1464. distance2d(
  1465. x - rx,
  1466. y - ry,
  1467. lastCommittedPoint[0],
  1468. lastCommittedPoint[1],
  1469. ) < ARROW_CONFIRM_THRESHOLD
  1470. ) {
  1471. this.actionManager.executeAction(actionFinalize);
  1472. return;
  1473. }
  1474. this.setState((prevState) => ({
  1475. selectedElementIds: {
  1476. ...prevState.selectedElementIds,
  1477. [multiElement.id]: true,
  1478. },
  1479. }));
  1480. // clicking outside commit zone → update reference for last committed
  1481. // point
  1482. mutateElement(multiElement, {
  1483. lastCommittedPoint:
  1484. multiElement.points[multiElement.points.length - 1],
  1485. });
  1486. document.documentElement.style.cursor = CURSOR_TYPE.POINTER;
  1487. } else {
  1488. const element = newLinearElement({
  1489. type: this.state.elementType,
  1490. x: x,
  1491. y: y,
  1492. strokeColor: this.state.currentItemStrokeColor,
  1493. backgroundColor: this.state.currentItemBackgroundColor,
  1494. fillStyle: this.state.currentItemFillStyle,
  1495. strokeWidth: this.state.currentItemStrokeWidth,
  1496. roughness: this.state.currentItemRoughness,
  1497. opacity: this.state.currentItemOpacity,
  1498. });
  1499. this.setState((prevState) => ({
  1500. selectedElementIds: {
  1501. ...prevState.selectedElementIds,
  1502. [element.id]: false,
  1503. },
  1504. }));
  1505. mutateElement(element, {
  1506. points: [...element.points, [0, 0]],
  1507. });
  1508. globalSceneState.replaceAllElements([
  1509. ...globalSceneState.getAllElements(),
  1510. element,
  1511. ]);
  1512. this.setState({
  1513. draggingElement: element,
  1514. editingElement: element,
  1515. });
  1516. }
  1517. } else {
  1518. const element = newElement({
  1519. type: this.state.elementType,
  1520. x: x,
  1521. y: y,
  1522. strokeColor: this.state.currentItemStrokeColor,
  1523. backgroundColor: this.state.currentItemBackgroundColor,
  1524. fillStyle: this.state.currentItemFillStyle,
  1525. strokeWidth: this.state.currentItemStrokeWidth,
  1526. roughness: this.state.currentItemRoughness,
  1527. opacity: this.state.currentItemOpacity,
  1528. });
  1529. if (element.type === "selection") {
  1530. this.setState({
  1531. selectionElement: element,
  1532. draggingElement: element,
  1533. });
  1534. } else {
  1535. globalSceneState.replaceAllElements([
  1536. ...globalSceneState.getAllElements(),
  1537. element,
  1538. ]);
  1539. this.setState({
  1540. multiElement: null,
  1541. draggingElement: element,
  1542. editingElement: element,
  1543. });
  1544. }
  1545. }
  1546. let resizeArrowFn:
  1547. | ((
  1548. element: ExcalidrawLinearElement,
  1549. pointIndex: number,
  1550. deltaX: number,
  1551. deltaY: number,
  1552. pointerX: number,
  1553. pointerY: number,
  1554. perfect: boolean,
  1555. ) => void)
  1556. | null = null;
  1557. const arrowResizeOrigin = (
  1558. element: ExcalidrawLinearElement,
  1559. pointIndex: number,
  1560. deltaX: number,
  1561. deltaY: number,
  1562. pointerX: number,
  1563. pointerY: number,
  1564. perfect: boolean,
  1565. ) => {
  1566. const p1 = element.points[pointIndex];
  1567. if (perfect) {
  1568. const absPx = p1[0] + element.x;
  1569. const absPy = p1[1] + element.y;
  1570. const { width, height } = getPerfectElementSize(
  1571. element.type,
  1572. pointerX - element.x - p1[0],
  1573. pointerY - element.y - p1[1],
  1574. );
  1575. const dx = element.x + width + p1[0];
  1576. const dy = element.y + height + p1[1];
  1577. mutateElement(element, {
  1578. x: dx,
  1579. y: dy,
  1580. points: element.points.map((point, i) =>
  1581. i === pointIndex
  1582. ? ([absPx - element.x, absPy - element.y] as const)
  1583. : point,
  1584. ),
  1585. });
  1586. } else {
  1587. mutateElement(element, {
  1588. x: element.x + deltaX,
  1589. y: element.y + deltaY,
  1590. points: element.points.map((point, i) =>
  1591. i === pointIndex
  1592. ? ([p1[0] - deltaX, p1[1] - deltaY] as const)
  1593. : point,
  1594. ),
  1595. });
  1596. }
  1597. };
  1598. const arrowResizeEnd = (
  1599. element: ExcalidrawLinearElement,
  1600. pointIndex: number,
  1601. deltaX: number,
  1602. deltaY: number,
  1603. pointerX: number,
  1604. pointerY: number,
  1605. perfect: boolean,
  1606. ) => {
  1607. const p1 = element.points[pointIndex];
  1608. if (perfect) {
  1609. const { width, height } = getPerfectElementSize(
  1610. element.type,
  1611. pointerX - element.x,
  1612. pointerY - element.y,
  1613. );
  1614. mutateElement(element, {
  1615. points: element.points.map((point, i) =>
  1616. i === pointIndex ? ([width, height] as const) : point,
  1617. ),
  1618. });
  1619. } else {
  1620. mutateElement(element, {
  1621. points: element.points.map((point, i) =>
  1622. i === pointIndex
  1623. ? ([p1[0] + deltaX, p1[1] + deltaY] as const)
  1624. : point,
  1625. ),
  1626. });
  1627. }
  1628. };
  1629. const onPointerMove = withBatchedUpdates((event: PointerEvent) => {
  1630. const target = event.target;
  1631. if (!(target instanceof HTMLElement)) {
  1632. return;
  1633. }
  1634. if (isOverHorizontalScrollBar) {
  1635. const x = event.clientX;
  1636. const dx = x - lastX;
  1637. this.setState({
  1638. scrollX: normalizeScroll(this.state.scrollX - dx / this.state.zoom),
  1639. });
  1640. lastX = x;
  1641. return;
  1642. }
  1643. if (isOverVerticalScrollBar) {
  1644. const y = event.clientY;
  1645. const dy = y - lastY;
  1646. this.setState({
  1647. scrollY: normalizeScroll(this.state.scrollY - dy / this.state.zoom),
  1648. });
  1649. lastY = y;
  1650. return;
  1651. }
  1652. // for arrows, don't start dragging until a given threshold
  1653. // to ensure we don't create a 2-point arrow by mistake when
  1654. // user clicks mouse in a way that it moves a tiny bit (thus
  1655. // triggering pointermove)
  1656. if (
  1657. !draggingOccurred &&
  1658. (this.state.elementType === "arrow" ||
  1659. this.state.elementType === "line")
  1660. ) {
  1661. const { x, y } = viewportCoordsToSceneCoords(
  1662. event,
  1663. this.state,
  1664. this.canvas,
  1665. window.devicePixelRatio,
  1666. );
  1667. if (distance2d(x, y, originX, originY) < DRAGGING_THRESHOLD) {
  1668. return;
  1669. }
  1670. }
  1671. if (isResizingElements && this.state.resizingElement) {
  1672. this.setState({ isResizing: true });
  1673. const el = this.state.resizingElement;
  1674. const selectedElements = getSelectedElements(
  1675. globalSceneState.getAllElements(),
  1676. this.state,
  1677. );
  1678. if (selectedElements.length === 1) {
  1679. const { x, y } = viewportCoordsToSceneCoords(
  1680. event,
  1681. this.state,
  1682. this.canvas,
  1683. window.devicePixelRatio,
  1684. );
  1685. const deltaX = x - lastX;
  1686. const deltaY = y - lastY;
  1687. const element = selectedElements[0];
  1688. switch (resizeHandle) {
  1689. case "nw":
  1690. if (isLinearElement(element) && element.points.length === 2) {
  1691. const [, p1] = element.points;
  1692. if (!resizeArrowFn) {
  1693. if (p1[0] < 0 || p1[1] < 0) {
  1694. resizeArrowFn = arrowResizeEnd;
  1695. } else {
  1696. resizeArrowFn = arrowResizeOrigin;
  1697. }
  1698. }
  1699. resizeArrowFn(element, 1, deltaX, deltaY, x, y, event.shiftKey);
  1700. } else {
  1701. mutateElement(element, {
  1702. x: element.x + deltaX,
  1703. y: event.shiftKey
  1704. ? element.y + element.height - element.width
  1705. : element.y + deltaY,
  1706. width: element.width - deltaX,
  1707. height: event.shiftKey
  1708. ? element.width
  1709. : element.height - deltaY,
  1710. });
  1711. }
  1712. break;
  1713. case "ne":
  1714. if (isLinearElement(element) && element.points.length === 2) {
  1715. const [, p1] = element.points;
  1716. if (!resizeArrowFn) {
  1717. if (p1[0] >= 0) {
  1718. resizeArrowFn = arrowResizeEnd;
  1719. } else {
  1720. resizeArrowFn = arrowResizeOrigin;
  1721. }
  1722. }
  1723. resizeArrowFn(element, 1, deltaX, deltaY, x, y, event.shiftKey);
  1724. } else {
  1725. const nextWidth = element.width + deltaX;
  1726. mutateElement(element, {
  1727. y: event.shiftKey
  1728. ? element.y + element.height - nextWidth
  1729. : element.y + deltaY,
  1730. width: nextWidth,
  1731. height: event.shiftKey ? nextWidth : element.height - deltaY,
  1732. });
  1733. }
  1734. break;
  1735. case "sw":
  1736. if (isLinearElement(element) && element.points.length === 2) {
  1737. const [, p1] = element.points;
  1738. if (!resizeArrowFn) {
  1739. if (p1[0] <= 0) {
  1740. resizeArrowFn = arrowResizeEnd;
  1741. } else {
  1742. resizeArrowFn = arrowResizeOrigin;
  1743. }
  1744. }
  1745. resizeArrowFn(element, 1, deltaX, deltaY, x, y, event.shiftKey);
  1746. } else {
  1747. mutateElement(element, {
  1748. x: element.x + deltaX,
  1749. width: element.width - deltaX,
  1750. height: event.shiftKey
  1751. ? element.width
  1752. : element.height + deltaY,
  1753. });
  1754. }
  1755. break;
  1756. case "se":
  1757. if (isLinearElement(element) && element.points.length === 2) {
  1758. const [, p1] = element.points;
  1759. if (!resizeArrowFn) {
  1760. if (p1[0] > 0 || p1[1] > 0) {
  1761. resizeArrowFn = arrowResizeEnd;
  1762. } else {
  1763. resizeArrowFn = arrowResizeOrigin;
  1764. }
  1765. }
  1766. resizeArrowFn(element, 1, deltaX, deltaY, x, y, event.shiftKey);
  1767. } else {
  1768. mutateElement(element, {
  1769. width: element.width + deltaX,
  1770. height: event.shiftKey
  1771. ? element.width
  1772. : element.height + deltaY,
  1773. });
  1774. }
  1775. break;
  1776. case "n": {
  1777. const height = element.height - deltaY;
  1778. if (isLinearElement(element)) {
  1779. if (element.points.length > 2 && height <= 0) {
  1780. // Someday we should implement logic to flip the shape.
  1781. // But for now, just stop.
  1782. break;
  1783. }
  1784. mutateElement(element, {
  1785. height,
  1786. y: element.y + deltaY,
  1787. points: rescalePoints(1, height, element.points),
  1788. });
  1789. } else {
  1790. mutateElement(element, {
  1791. height,
  1792. y: element.y + deltaY,
  1793. });
  1794. }
  1795. break;
  1796. }
  1797. case "w": {
  1798. const width = element.width - deltaX;
  1799. if (isLinearElement(element)) {
  1800. if (element.points.length > 2 && width <= 0) {
  1801. // Someday we should implement logic to flip the shape.
  1802. // But for now, just stop.
  1803. break;
  1804. }
  1805. mutateElement(element, {
  1806. width,
  1807. x: element.x + deltaX,
  1808. points: rescalePoints(0, width, element.points),
  1809. });
  1810. } else {
  1811. mutateElement(element, {
  1812. width,
  1813. x: element.x + deltaX,
  1814. });
  1815. }
  1816. break;
  1817. }
  1818. case "s": {
  1819. const height = element.height + deltaY;
  1820. if (isLinearElement(element)) {
  1821. if (element.points.length > 2 && height <= 0) {
  1822. // Someday we should implement logic to flip the shape.
  1823. // But for now, just stop.
  1824. break;
  1825. }
  1826. mutateElement(element, {
  1827. height,
  1828. points: rescalePoints(1, height, element.points),
  1829. });
  1830. } else {
  1831. mutateElement(element, {
  1832. height,
  1833. });
  1834. }
  1835. break;
  1836. }
  1837. case "e": {
  1838. const width = element.width + deltaX;
  1839. if (isLinearElement(element)) {
  1840. if (element.points.length > 2 && width <= 0) {
  1841. // Someday we should implement logic to flip the shape.
  1842. // But for now, just stop.
  1843. break;
  1844. }
  1845. mutateElement(element, {
  1846. width,
  1847. points: rescalePoints(0, width, element.points),
  1848. });
  1849. } else {
  1850. mutateElement(element, {
  1851. width,
  1852. });
  1853. }
  1854. break;
  1855. }
  1856. }
  1857. if (resizeHandle) {
  1858. resizeHandle = normalizeResizeHandle(element, resizeHandle);
  1859. }
  1860. normalizeDimensions(element);
  1861. document.documentElement.style.cursor = getCursorForResizingElement({
  1862. element,
  1863. resizeHandle,
  1864. });
  1865. mutateElement(el, {
  1866. x: element.x,
  1867. y: element.y,
  1868. });
  1869. lastX = x;
  1870. lastY = y;
  1871. return;
  1872. }
  1873. }
  1874. if (hitElement && this.state.selectedElementIds[hitElement.id]) {
  1875. // Marking that click was used for dragging to check
  1876. // if elements should be deselected on pointerup
  1877. draggingOccurred = true;
  1878. const selectedElements = getSelectedElements(
  1879. globalSceneState.getAllElements(),
  1880. this.state,
  1881. );
  1882. if (selectedElements.length > 0) {
  1883. const { x, y } = viewportCoordsToSceneCoords(
  1884. event,
  1885. this.state,
  1886. this.canvas,
  1887. window.devicePixelRatio,
  1888. );
  1889. selectedElements.forEach((element) => {
  1890. mutateElement(element, {
  1891. x: element.x + x - lastX,
  1892. y: element.y + y - lastY,
  1893. });
  1894. });
  1895. lastX = x;
  1896. lastY = y;
  1897. return;
  1898. }
  1899. }
  1900. // It is very important to read this.state within each move event,
  1901. // otherwise we would read a stale one!
  1902. const draggingElement = this.state.draggingElement;
  1903. if (!draggingElement) {
  1904. return;
  1905. }
  1906. const { x, y } = viewportCoordsToSceneCoords(
  1907. event,
  1908. this.state,
  1909. this.canvas,
  1910. window.devicePixelRatio,
  1911. );
  1912. let width = distance(originX, x);
  1913. let height = distance(originY, y);
  1914. if (isLinearElement(draggingElement)) {
  1915. draggingOccurred = true;
  1916. const points = draggingElement.points;
  1917. let dx = x - draggingElement.x;
  1918. let dy = y - draggingElement.y;
  1919. if (event.shiftKey && points.length === 2) {
  1920. ({ width: dx, height: dy } = getPerfectElementSize(
  1921. this.state.elementType,
  1922. dx,
  1923. dy,
  1924. ));
  1925. }
  1926. if (points.length === 1) {
  1927. mutateElement(draggingElement, { points: [...points, [dx, dy]] });
  1928. } else if (points.length > 1) {
  1929. mutateElement(draggingElement, {
  1930. points: [...points.slice(0, -1), [dx, dy]],
  1931. });
  1932. }
  1933. } else {
  1934. if (event.shiftKey) {
  1935. ({ width, height } = getPerfectElementSize(
  1936. this.state.elementType,
  1937. width,
  1938. y < originY ? -height : height,
  1939. ));
  1940. if (height < 0) {
  1941. height = -height;
  1942. }
  1943. }
  1944. mutateElement(draggingElement, {
  1945. x: x < originX ? originX - width : originX,
  1946. y: y < originY ? originY - height : originY,
  1947. width: width,
  1948. height: height,
  1949. });
  1950. }
  1951. if (this.state.elementType === "selection") {
  1952. if (
  1953. !event.shiftKey &&
  1954. isSomeElementSelected(globalSceneState.getAllElements(), this.state)
  1955. ) {
  1956. this.setState({ selectedElementIds: {} });
  1957. }
  1958. const elementsWithinSelection = getElementsWithinSelection(
  1959. globalSceneState.getAllElements(),
  1960. draggingElement,
  1961. );
  1962. this.setState((prevState) => ({
  1963. selectedElementIds: {
  1964. ...prevState.selectedElementIds,
  1965. ...elementsWithinSelection.reduce((map, element) => {
  1966. map[element.id] = true;
  1967. return map;
  1968. }, {} as any),
  1969. },
  1970. }));
  1971. }
  1972. });
  1973. const onPointerUp = withBatchedUpdates((event: PointerEvent) => {
  1974. const {
  1975. draggingElement,
  1976. resizingElement,
  1977. multiElement,
  1978. elementType,
  1979. elementLocked,
  1980. } = this.state;
  1981. this.setState({
  1982. isResizing: false,
  1983. resizingElement: null,
  1984. selectionElement: null,
  1985. editingElement: multiElement ? this.state.editingElement : null,
  1986. });
  1987. resizeArrowFn = null;
  1988. lastPointerUp = null;
  1989. window.removeEventListener("pointermove", onPointerMove);
  1990. window.removeEventListener("pointerup", onPointerUp);
  1991. if (isLinearElement(draggingElement)) {
  1992. if (draggingElement!.points.length > 1) {
  1993. history.resumeRecording();
  1994. }
  1995. if (!draggingOccurred && draggingElement && !multiElement) {
  1996. const { x, y } = viewportCoordsToSceneCoords(
  1997. event,
  1998. this.state,
  1999. this.canvas,
  2000. window.devicePixelRatio,
  2001. );
  2002. mutateElement(draggingElement, {
  2003. points: [
  2004. ...draggingElement.points,
  2005. [x - draggingElement.x, y - draggingElement.y],
  2006. ],
  2007. });
  2008. this.setState({
  2009. multiElement: draggingElement,
  2010. editingElement: this.state.draggingElement,
  2011. });
  2012. } else if (draggingOccurred && !multiElement) {
  2013. if (!elementLocked) {
  2014. resetCursor();
  2015. this.setState((prevState) => ({
  2016. draggingElement: null,
  2017. elementType: "selection",
  2018. selectedElementIds: {
  2019. ...prevState.selectedElementIds,
  2020. [this.state.draggingElement!.id]: true,
  2021. },
  2022. }));
  2023. } else {
  2024. this.setState((prevState) => ({
  2025. draggingElement: null,
  2026. selectedElementIds: {
  2027. ...prevState.selectedElementIds,
  2028. [this.state.draggingElement!.id]: true,
  2029. },
  2030. }));
  2031. }
  2032. }
  2033. return;
  2034. }
  2035. if (
  2036. elementType !== "selection" &&
  2037. draggingElement &&
  2038. isInvisiblySmallElement(draggingElement)
  2039. ) {
  2040. // remove invisible element which was added in onPointerDown
  2041. globalSceneState.replaceAllElements(
  2042. globalSceneState.getAllElements().slice(0, -1),
  2043. );
  2044. this.setState({
  2045. draggingElement: null,
  2046. });
  2047. return;
  2048. }
  2049. normalizeDimensions(draggingElement);
  2050. if (resizingElement) {
  2051. history.resumeRecording();
  2052. }
  2053. if (resizingElement && isInvisiblySmallElement(resizingElement)) {
  2054. globalSceneState.replaceAllElements(
  2055. globalSceneState
  2056. .getAllElements()
  2057. .filter((el) => el.id !== resizingElement.id),
  2058. );
  2059. }
  2060. // If click occurred on already selected element
  2061. // it is needed to remove selection from other elements
  2062. // or if SHIFT or META key pressed remove selection
  2063. // from hitted element
  2064. //
  2065. // If click occurred and elements were dragged or some element
  2066. // was added to selection (on pointerdown phase) we need to keep
  2067. // selection unchanged
  2068. if (hitElement && !draggingOccurred && !hitElementWasAddedToSelection) {
  2069. if (event.shiftKey) {
  2070. this.setState((prevState) => ({
  2071. selectedElementIds: {
  2072. ...prevState.selectedElementIds,
  2073. [hitElement!.id]: false,
  2074. },
  2075. }));
  2076. } else {
  2077. this.setState((prevState) => ({
  2078. selectedElementIds: { [hitElement!.id]: true },
  2079. }));
  2080. }
  2081. }
  2082. if (draggingElement === null) {
  2083. // if no element is clicked, clear the selection and redraw
  2084. this.setState({ selectedElementIds: {} });
  2085. return;
  2086. }
  2087. if (!elementLocked) {
  2088. this.setState((prevState) => ({
  2089. selectedElementIds: {
  2090. ...prevState.selectedElementIds,
  2091. [draggingElement.id]: true,
  2092. },
  2093. }));
  2094. }
  2095. if (
  2096. elementType !== "selection" ||
  2097. isSomeElementSelected(globalSceneState.getAllElements(), this.state)
  2098. ) {
  2099. history.resumeRecording();
  2100. }
  2101. if (!elementLocked) {
  2102. resetCursor();
  2103. this.setState({
  2104. draggingElement: null,
  2105. elementType: "selection",
  2106. });
  2107. } else {
  2108. this.setState({
  2109. draggingElement: null,
  2110. });
  2111. }
  2112. });
  2113. lastPointerUp = onPointerUp;
  2114. window.addEventListener("pointermove", onPointerMove);
  2115. window.addEventListener("pointerup", onPointerUp);
  2116. };
  2117. private handleCanvasContextMenu = (
  2118. event: React.PointerEvent<HTMLCanvasElement>,
  2119. ) => {
  2120. event.preventDefault();
  2121. const { x, y } = viewportCoordsToSceneCoords(
  2122. event,
  2123. this.state,
  2124. this.canvas,
  2125. window.devicePixelRatio,
  2126. );
  2127. const element = getElementAtPosition(
  2128. globalSceneState.getAllElements(),
  2129. this.state,
  2130. x,
  2131. y,
  2132. this.state.zoom,
  2133. );
  2134. if (!element) {
  2135. ContextMenu.push({
  2136. options: [
  2137. navigator.clipboard && {
  2138. label: t("labels.paste"),
  2139. action: () => this.pasteFromClipboard(null),
  2140. },
  2141. probablySupportsClipboardBlob &&
  2142. hasNonDeletedElements(globalSceneState.getAllElements()) && {
  2143. label: t("labels.copyAsPng"),
  2144. action: this.copyToClipboardAsPng,
  2145. },
  2146. ...this.actionManager.getContextMenuItems((action) =>
  2147. this.canvasOnlyActions.includes(action.name),
  2148. ),
  2149. ],
  2150. top: event.clientY,
  2151. left: event.clientX,
  2152. });
  2153. return;
  2154. }
  2155. if (!this.state.selectedElementIds[element.id]) {
  2156. this.setState({ selectedElementIds: { [element.id]: true } });
  2157. }
  2158. ContextMenu.push({
  2159. options: [
  2160. navigator.clipboard && {
  2161. label: t("labels.copy"),
  2162. action: this.copyToAppClipboard,
  2163. },
  2164. navigator.clipboard && {
  2165. label: t("labels.paste"),
  2166. action: () => this.pasteFromClipboard(null),
  2167. },
  2168. probablySupportsClipboardBlob && {
  2169. label: t("labels.copyAsPng"),
  2170. action: this.copyToClipboardAsPng,
  2171. },
  2172. ...this.actionManager.getContextMenuItems(
  2173. (action) => !this.canvasOnlyActions.includes(action.name),
  2174. ),
  2175. ],
  2176. top: event.clientY,
  2177. left: event.clientX,
  2178. });
  2179. };
  2180. private handleWheel = withBatchedUpdates((event: WheelEvent) => {
  2181. event.preventDefault();
  2182. const { deltaX, deltaY } = event;
  2183. // note that event.ctrlKey is necessary to handle pinch zooming
  2184. if (event.metaKey || event.ctrlKey) {
  2185. const sign = Math.sign(deltaY);
  2186. const MAX_STEP = 10;
  2187. let delta = Math.abs(deltaY);
  2188. if (delta > MAX_STEP) {
  2189. delta = MAX_STEP;
  2190. }
  2191. delta *= sign;
  2192. this.setState(({ zoom }) => ({
  2193. zoom: getNormalizedZoom(zoom - delta / 100),
  2194. }));
  2195. return;
  2196. }
  2197. this.setState(({ zoom, scrollX, scrollY }) => ({
  2198. scrollX: normalizeScroll(scrollX - deltaX / zoom),
  2199. scrollY: normalizeScroll(scrollY - deltaY / zoom),
  2200. }));
  2201. });
  2202. private getTextWysiwygSnappedToCenterPosition(x: number, y: number) {
  2203. const elementClickedInside = getElementContainingPosition(
  2204. globalSceneState.getAllElements(),
  2205. x,
  2206. y,
  2207. );
  2208. if (elementClickedInside) {
  2209. const elementCenterX =
  2210. elementClickedInside.x + elementClickedInside.width / 2;
  2211. const elementCenterY =
  2212. elementClickedInside.y + elementClickedInside.height / 2;
  2213. const distanceToCenter = Math.hypot(
  2214. x - elementCenterX,
  2215. y - elementCenterY,
  2216. );
  2217. const isSnappedToCenter =
  2218. distanceToCenter < TEXT_TO_CENTER_SNAP_THRESHOLD;
  2219. if (isSnappedToCenter) {
  2220. const wysiwygX =
  2221. this.state.scrollX +
  2222. elementClickedInside.x +
  2223. elementClickedInside.width / 2;
  2224. const wysiwygY =
  2225. this.state.scrollY +
  2226. elementClickedInside.y +
  2227. elementClickedInside.height / 2;
  2228. return { wysiwygX, wysiwygY, elementCenterX, elementCenterY };
  2229. }
  2230. }
  2231. }
  2232. private savePointer = (pointerCoords: { x: number; y: number }) => {
  2233. if (isNaN(pointerCoords.x) || isNaN(pointerCoords.y)) {
  2234. // sometimes the pointer goes off screen
  2235. return;
  2236. }
  2237. this.socket && this.broadcastMouseLocation({ pointerCoords });
  2238. };
  2239. private saveDebounced = debounce(() => {
  2240. saveToLocalStorage(globalSceneState.getAllElements(), this.state);
  2241. }, 300);
  2242. }
  2243. // -----------------------------------------------------------------------------
  2244. // TEST HOOKS
  2245. // -----------------------------------------------------------------------------
  2246. declare global {
  2247. interface Window {
  2248. h: {
  2249. elements: readonly ExcalidrawElement[];
  2250. state: AppState;
  2251. history: SceneHistory;
  2252. };
  2253. }
  2254. }
  2255. if (process.env.NODE_ENV === "test" || process.env.NODE_ENV === "development") {
  2256. window.h = {} as Window["h"];
  2257. Object.defineProperties(window.h, {
  2258. elements: {
  2259. get() {
  2260. return globalSceneState.getAllElements();
  2261. },
  2262. set(elements: ExcalidrawElement[]) {
  2263. return globalSceneState.replaceAllElements(elements);
  2264. },
  2265. },
  2266. history: {
  2267. get() {
  2268. return history;
  2269. },
  2270. },
  2271. });
  2272. }
  2273. // -----------------------------------------------------------------------------