App.tsx 75 KB

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