App.tsx 77 KB

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