App.tsx 92 KB

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