App.tsx 75 KB

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