App.tsx 78 KB

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