App.tsx 81 KB

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