App.tsx 75 KB

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