App.tsx 79 KB

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