App.tsx 81 KB

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