Browse Source

chore: Minor refactoring for consistency (#2425)

Lipis 4 years ago
parent
commit
b21fd49412

+ 2 - 0
.eslintrc.json

@@ -24,6 +24,8 @@
     "no-unused-expressions": "warn",
     "no-unused-vars": "warn",
     "no-useless-return": "warn",
+    "no-var": "warn",
+    "object-shorthand": "warn",
     "one-var": ["warn", "never"],
     "prefer-arrow-callback": "warn",
     "prefer-const": [

+ 3 - 3
scripts/build-node.js

@@ -9,9 +9,9 @@
 //   node build/static/js/build-node.js
 //   open test.png
 
-var rewire = require("rewire");
-var defaults = rewire("react-scripts/scripts/build.js");
-var config = defaults.__get__("config");
+const rewire = require("rewire");
+const defaults = rewire("react-scripts/scripts/build.js");
+const config = defaults.__get__("config");
 
 // Disable multiple chunks
 config.optimization.runtimeChunk = false;

+ 1 - 1
src/actions/actionDeleteSelected.tsx

@@ -98,7 +98,7 @@ export const actionDeleteSelected = register({
       LinearElementEditor.movePoint(element, activePointIndex, "delete");
 
       return {
-        elements: elements,
+        elements,
         appState: {
           ...appState,
           editingLinearElement: {

+ 1 - 1
src/actions/actionExport.tsx

@@ -156,7 +156,7 @@ export const actionLoadScene = register({
       onClick={() => {
         loadFromJSON(appState)
           .then(({ elements, appState }) => {
-            updateData({ elements: elements, appState: appState });
+            updateData({ elements, appState });
           })
           .catch(muteFSAbortError)
           .catch((error) => {

+ 7 - 7
src/charts.ts

@@ -159,7 +159,7 @@ export const renderSpreadsheet = (
   const range = max - min;
 
   const minYLabel = newTextElement({
-    x: x,
+    x,
     y: y + BAR_HEIGHT,
     strokeColor: appState.currentItemStrokeColor,
     backgroundColor: appState.currentItemBackgroundColor,
@@ -177,8 +177,8 @@ export const renderSpreadsheet = (
   });
 
   const maxYLabel = newTextElement({
-    x: x,
-    y: y,
+    x,
+    y,
     strokeColor: appState.currentItemStrokeColor,
     backgroundColor: appState.currentItemBackgroundColor,
     fillStyle: appState.currentItemFillStyle,
@@ -194,11 +194,11 @@ export const renderSpreadsheet = (
     verticalAlign: DEFAULT_VERTICAL_ALIGN,
   });
 
-  const bars = spreadsheet.values.map((value, i) => {
+  const bars = spreadsheet.values.map((value, index) => {
     const valueBarHeight = value - min;
     const percentBarHeight = valueBarHeight / range;
     const barHeight = percentBarHeight * BAR_HEIGHT;
-    const barX = i * (BAR_WIDTH + BAR_SPACING) + LABEL_SPACING;
+    const barX = index * (BAR_WIDTH + BAR_SPACING) + LABEL_SPACING;
     const barY = BAR_HEIGHT - barHeight;
     return newElement({
       type: "rectangle",
@@ -218,9 +218,9 @@ export const renderSpreadsheet = (
   });
 
   const xLabels =
-    spreadsheet.labels?.map((label, i) => {
+    spreadsheet.labels?.map((label, index) => {
       const labelX =
-        i * (BAR_WIDTH + BAR_SPACING) + LABEL_SPACING + BAR_SPACING;
+        index * (BAR_WIDTH + BAR_SPACING) + LABEL_SPACING + BAR_SPACING;
       const labelY = BAR_HEIGHT + BAR_SPACING;
       return newTextElement({
         text: label.length > 8 ? `${label.slice(0, 5)}...` : label,

+ 14 - 22
src/components/App.tsx

@@ -47,7 +47,6 @@ import {
   loadScene,
   loadFromBlob,
   SOCKET_SERVER,
-  SocketUpdateDataSource,
   exportCanvas,
 } from "../data";
 import Portal from "./Portal";
@@ -505,7 +504,7 @@ class App extends React.Component<ExcalidrawProps, AppState> {
       return false;
     }
 
-    const roomID = roomMatch[1];
+    const roomId = roomMatch[1];
 
     let collabForceLoadFlag;
     try {
@@ -524,7 +523,7 @@ class App extends React.Component<ExcalidrawProps, AppState> {
         );
         // if loading same room as the one previously unloaded within 15sec
         // force reload without prompting
-        if (previousRoom === roomID && Date.now() - timestamp < 15000) {
+        if (previousRoom === roomId && Date.now() - timestamp < 15000) {
           return true;
         }
       } catch {}
@@ -828,13 +827,13 @@ class App extends React.Component<ExcalidrawProps, AppState> {
   }
 
   private beforeUnload = withBatchedUpdates((event: BeforeUnloadEvent) => {
-    if (this.state.isCollaborating && this.portal.roomID) {
+    if (this.state.isCollaborating && this.portal.roomId) {
       try {
         localStorage?.setItem(
           LOCAL_STORAGE_KEY_COLLAB_FORCE_FLAG,
           JSON.stringify({
             timestamp: Date.now(),
-            room: this.portal.roomID,
+            room: this.portal.roomId,
           }),
         );
       } catch {}
@@ -962,7 +961,7 @@ class App extends React.Component<ExcalidrawProps, AppState> {
         zoom: this.state.zoom,
         remotePointerViewportCoords: pointerViewportCoords,
         remotePointerButton: cursorButton,
-        remoteSelectedElementIds: remoteSelectedElementIds,
+        remoteSelectedElementIds,
         remotePointerUsernames: pointerUsernames,
         shouldCacheIgnoreZoom: this.state.shouldCacheIgnoreZoom,
       },
@@ -979,7 +978,7 @@ class App extends React.Component<ExcalidrawProps, AppState> {
         ? false
         : !atLeastOneVisibleElement && elements.length > 0;
     if (this.state.scrolledOutside !== scrolledOutside) {
-      this.setState({ scrolledOutside: scrolledOutside });
+      this.setState({ scrolledOutside });
     }
 
     if (
@@ -1205,8 +1204,8 @@ class App extends React.Component<ExcalidrawProps, AppState> {
     );
 
     const element = newTextElement({
-      x: x,
-      y: y,
+      x,
+      y,
       strokeColor: this.state.currentItemStrokeColor,
       backgroundColor: this.state.currentItemBackgroundColor,
       fillStyle: this.state.currentItemFillStyle,
@@ -1215,7 +1214,7 @@ class App extends React.Component<ExcalidrawProps, AppState> {
       roughness: this.state.currentItemRoughness,
       opacity: this.state.currentItemOpacity,
       strokeSharpness: this.state.currentItemStrokeSharpness,
-      text: text,
+      text,
       fontSize: this.state.currentItemFontSize,
       fontFamily: this.state.currentItemFontFamily,
       textAlign: this.state.currentItemTextAlign,
@@ -1376,7 +1375,7 @@ class App extends React.Component<ExcalidrawProps, AppState> {
 
     const roomMatch = getCollaborationLinkData(window.location.href);
     if (roomMatch) {
-      const roomID = roomMatch[1];
+      const roomId = roomMatch[1];
       const roomKey = roomMatch[2];
 
       // fallback in case you're not alone in the room but still don't receive
@@ -1386,11 +1385,9 @@ class App extends React.Component<ExcalidrawProps, AppState> {
         INITIAL_SCENE_UPDATE_TIMEOUT,
       );
 
-      const { default: socketIOClient }: any = await import(
-        /* webpackChunkName: "socketIoClient" */ "socket.io-client"
-      );
+      const { default: socketIOClient }: any = await import("socket.io-client");
 
-      this.portal.open(socketIOClient(SOCKET_SERVER), roomID, roomKey);
+      this.portal.open(socketIOClient(SOCKET_SERVER), roomId, roomKey);
 
       // All socket listeners are moving to Portal
       this.portal.socket!.on(
@@ -1420,17 +1417,12 @@ class App extends React.Component<ExcalidrawProps, AppState> {
               break;
             case "MOUSE_LOCATION": {
               const {
+                socketId,
                 pointer,
                 button,
                 username,
                 selectedElementIds,
               } = decryptedData.payload;
-
-              const socketId: SocketUpdateDataSource["MOUSE_LOCATION"]["payload"]["socketId"] =
-                decryptedData.payload.socketId ||
-                // @ts-ignore legacy, see #2094 (#2097)
-                decryptedData.payload.socketID;
-
               // NOTE purposefully mutating collaborators map in case of
               // pointer updates so as not to trigger LayerUI rerender
               this.setState((state) => {
@@ -1463,7 +1455,7 @@ class App extends React.Component<ExcalidrawProps, AppState> {
       });
 
       try {
-        const elements = await loadFromFirebase(roomID, roomKey);
+        const elements = await loadFromFirebase(roomId, roomKey);
         if (elements) {
           this.handleRemoteSceneUpdate(elements, { initFromSnapshot: true });
         }

+ 1 - 1
src/components/Popover.tsx

@@ -49,7 +49,7 @@ export const Popover = ({
   }, [onCloseRequest]);
 
   return (
-    <div className="popover" style={{ top: top, left: left }} ref={popoverRef}>
+    <div className="popover" style={{ top, left }} ref={popoverRef}>
       {children}
     </div>
   );

+ 6 - 6
src/components/Portal.tsx

@@ -14,7 +14,7 @@ class Portal {
   app: App;
   socket: SocketIOClient.Socket | null = null;
   socketInitialized: boolean = false; // we don't want the socket to emit any updates until it is fully initialized
-  roomID: string | null = null;
+  roomId: string | null = null;
   roomKey: string | null = null;
   broadcastedElementVersions: Map<string, number> = new Map();
 
@@ -24,13 +24,13 @@ class Portal {
 
   open(socket: SocketIOClient.Socket, id: string, key: string) {
     this.socket = socket;
-    this.roomID = id;
+    this.roomId = id;
     this.roomKey = key;
 
     // Initialize socket listeners (moving from App)
     this.socket.on("init-room", () => {
       if (this.socket) {
-        this.socket.emit("join-room", this.roomID);
+        this.socket.emit("join-room", this.roomId);
       }
     });
     this.socket.on("new-user", async (_socketId: string) => {
@@ -47,7 +47,7 @@ class Portal {
     }
     this.socket.close();
     this.socket = null;
-    this.roomID = null;
+    this.roomId = null;
     this.roomKey = null;
     this.socketInitialized = false;
     this.broadcastedElementVersions = new Map();
@@ -57,7 +57,7 @@ class Portal {
     return !!(
       this.socketInitialized &&
       this.socket &&
-      this.roomID &&
+      this.roomId &&
       this.roomKey
     );
   }
@@ -72,7 +72,7 @@ class Portal {
       const encrypted = await encryptAESGEM(encoded, this.roomKey!);
       this.socket!.emit(
         volatile ? BROADCAST.SERVER_VOLATILE : BROADCAST.SERVER,
-        this.roomID,
+        this.roomId,
         encrypted.data,
         encrypted.iv,
       );

+ 6 - 6
src/data/firebase.ts

@@ -83,7 +83,7 @@ export const isSavedToFirebase = (
   portal: Portal,
   elements: readonly ExcalidrawElement[],
 ): boolean => {
-  if (portal.socket && portal.roomID && portal.roomKey) {
+  if (portal.socket && portal.roomId && portal.roomKey) {
     const sceneVersion = getSceneVersion(elements);
     return firebaseSceneVersionCache.get(portal.socket) === sceneVersion;
   }
@@ -96,11 +96,11 @@ export const saveToFirebase = async (
   portal: Portal,
   elements: readonly ExcalidrawElement[],
 ) => {
-  const { roomID, roomKey, socket } = portal;
+  const { roomId, roomKey, socket } = portal;
   if (
     // if no room exists, consider the room saved because there's nothing we can
     // do at this point
-    !roomID ||
+    !roomId ||
     !roomKey ||
     !socket ||
     isSavedToFirebase(portal, elements)
@@ -121,7 +121,7 @@ export const saveToFirebase = async (
   } as FirebaseStoredScene;
 
   const db = firebase.firestore();
-  const docRef = db.collection("scenes").doc(roomID);
+  const docRef = db.collection("scenes").doc(roomId);
   const didUpdate = await db.runTransaction(async (transaction) => {
     const doc = await transaction.get(docRef);
     if (!doc.exists) {
@@ -146,13 +146,13 @@ export const saveToFirebase = async (
 };
 
 export const loadFromFirebase = async (
-  roomID: string,
+  roomId: string,
   roomKey: string,
 ): Promise<readonly ExcalidrawElement[] | null> => {
   const firebase = await getFirebase();
   const db = firebase.firestore();
 
-  const docRef = db.collection("scenes").doc(roomID);
+  const docRef = db.collection("scenes").doc(roomId);
   const doc = await docRef.get();
   if (!doc.exists) {
     return null;

+ 3 - 3
src/data/index.ts

@@ -153,7 +153,7 @@ export const decryptAESGEM = async (
     const decrypted = await window.crypto.subtle.decrypt(
       {
         name: "AES-GCM",
-        iv: iv,
+        iv,
       },
       importedKey,
       data,
@@ -195,7 +195,7 @@ export const exportToBackend = async (
   const encrypted = await window.crypto.subtle.encrypt(
     {
       name: "AES-GCM",
-      iv: iv,
+      iv,
     },
     key,
     encoded,
@@ -248,7 +248,7 @@ const importFromBackend = async (
       const decrypted = await window.crypto.subtle.decrypt(
         {
           name: "AES-GCM",
-          iv: iv,
+          iv,
         },
         key,
         buffer,

+ 6 - 6
src/disitrubte.ts

@@ -44,24 +44,24 @@ export const distributeElements = (
     // rather than from gaps. Buckle up, this is a weird one.
 
     // Get indices of boxes that define start and end of our bounding box
-    const i0 = groups.findIndex((g) => g[1][start] === bounds[start]);
-    const i1 = groups.findIndex((g) => g[1][end] === bounds[end]);
+    const index0 = groups.findIndex((g) => g[1][start] === bounds[start]);
+    const index1 = groups.findIndex((g) => g[1][end] === bounds[end]);
 
     // Get our step, based on the distance between the center points of our
     // start and end boxes
     const step =
-      (groups[i1][1][mid] - groups[i0][1][mid]) / (groups.length - 1);
+      (groups[index1][1][mid] - groups[index0][1][mid]) / (groups.length - 1);
 
-    let pos = groups[i0][1][mid];
+    let pos = groups[index0][1][mid];
 
-    return groups.flatMap(([group, box], i) => {
+    return groups.flatMap(([group, box], index) => {
       const translation = {
         x: 0,
         y: 0,
       };
 
       // Don't move our start and end boxes
-      if (i !== i0 && i !== i1) {
+      if (index !== index0 && index !== index1) {
         pos += step;
         translation[distribution.axis] = pos - box[mid];
       }

+ 2 - 2
src/element/dragElements.ts

@@ -91,8 +91,8 @@ export const dragNewElement = (
     mutateElement(draggingElement, {
       x: newX,
       y: newY,
-      width: width,
-      height: height,
+      width,
+      height,
     });
   }
 };

+ 4 - 4
src/element/mutateElement.ts

@@ -44,10 +44,10 @@ export const mutateElement = <TElement extends Mutable<ExcalidrawElement>>(
         const nextPoints = value;
         if (prevPoints.length === nextPoints.length) {
           let didChangePoints = false;
-          let i = prevPoints.length;
-          while (--i) {
-            const prevPoint: Point = prevPoints[i];
-            const nextPoint: Point = nextPoints[i];
+          let index = prevPoints.length;
+          while (--index) {
+            const prevPoint: Point = prevPoints[index];
+            const nextPoint: Point = nextPoints[index];
             if (
               prevPoint[0] !== nextPoint[0] ||
               prevPoint[1] !== nextPoint[1]

+ 1 - 1
src/element/textWysiwyg.tsx

@@ -74,7 +74,7 @@ export const textWysiwyg = ({
           angle,
           appState,
         ),
-        textAlign: textAlign,
+        textAlign,
         color: updatedElement.strokeColor,
         opacity: updatedElement.opacity / 100,
         filter: "var(--appearance-filter)",

+ 2 - 2
src/groups.ts

@@ -127,8 +127,8 @@ export const getNewGroupIdsForDuplication = (
     : -1;
   const endIndex =
     positionOfEditingGroupId > -1 ? positionOfEditingGroupId : groupIds.length;
-  for (let i = 0; i < endIndex; i++) {
-    copy[i] = mapper(copy[i]);
+  for (let index = 0; index < endIndex; index++) {
+    copy[index] = mapper(copy[index]);
   }
 
   return copy;

+ 3 - 3
src/i18n.ts

@@ -89,8 +89,8 @@ export const setLanguageFirstTime = async () => {
 export const getLanguage = () => currentLanguage;
 
 const findPartsForData = (data: any, parts: string[]) => {
-  for (var i = 0; i < parts.length; ++i) {
-    const part = parts[i];
+  for (let index = 0; index < parts.length; ++index) {
+    const part = parts[index];
     if (data[part] === undefined) {
       return undefined;
     }
@@ -112,7 +112,7 @@ export const t = (path: string, replacement?: { [key: string]: string }) => {
   }
 
   if (replacement) {
-    for (var key in replacement) {
+    for (const key in replacement) {
       translation = translation.replace(`{{${key}}}`, replacement[key]);
     }
   }

+ 3 - 3
src/renderer/renderElement.ts

@@ -147,11 +147,11 @@ const drawElementOnCanvas = (
             : element.textAlign === "right"
             ? element.width
             : 0;
-        for (let i = 0; i < lines.length; i++) {
+        for (let index = 0; index < lines.length; index++) {
           context.fillText(
-            lines[i],
+            lines[index],
             horizontalOffset,
-            (i + 1) * lineHeight - verticalOffset,
+            (index + 1) * lineHeight - verticalOffset,
           );
         }
         context.fillStyle = fillStyle;

+ 3 - 3
src/renderer/renderScene.ts

@@ -620,13 +620,13 @@ const renderSelectionBorder = (
   context.translate(sceneState.scrollX, sceneState.scrollY);
 
   const count = selectionColors.length;
-  for (var i = 0; i < count; ++i) {
-    context.strokeStyle = selectionColors[i];
+  for (let index = 0; index < count; ++index) {
+    context.strokeStyle = selectionColors[index];
     context.setLineDash([
       dashWidth,
       spaceWidth + (dashWidth + spaceWidth) * (count - 1),
     ]);
-    context.lineDashOffset = (dashWidth + spaceWidth) * i;
+    context.lineDashOffset = (dashWidth + spaceWidth) * index;
     strokeRectWithRotation(
       context,
       elementX1 - dashedLinePadding,

+ 6 - 6
src/scene/comparisons.ts

@@ -36,8 +36,8 @@ export const getElementAtPosition = (
   // We need to to hit testing from front (end of the array) to back (beginning of the array)
   // because array is ordered from lower z-index to highest and we want element z-index
   // with higher z-index
-  for (let i = elements.length - 1; i >= 0; --i) {
-    const element = elements[i];
+  for (let index = elements.length - 1; index >= 0; --index) {
+    const element = elements[index];
     if (element.isDeleted) {
       continue;
     }
@@ -68,13 +68,13 @@ export const getElementContainingPosition = (
 ) => {
   let hitElement = null;
   // We need to to hit testing from front (end of the array) to back (beginning of the array)
-  for (let i = elements.length - 1; i >= 0; --i) {
-    if (elements[i].isDeleted) {
+  for (let index = elements.length - 1; index >= 0; --index) {
+    if (elements[index].isDeleted) {
       continue;
     }
-    const [x1, y1, x2, y2] = getElementAbsoluteCoords(elements[i]);
+    const [x1, y1, x2, y2] = getElementAbsoluteCoords(elements[index]);
     if (x1 < x && x < x2 && y1 < y && y < y2) {
-      hitElement = elements[i];
+      hitElement = elements[index];
       break;
     }
   }

+ 1 - 1
src/scene/index.ts

@@ -16,4 +16,4 @@ export {
   hasText,
   getElementsAtPosition,
 } from "./comparisons";
-export { normalizeZoomValue as getNormalizedZoom, getNewZoom } from "./zoom";
+export { getNormalizedZoom, getNewZoom } from "./zoom";

+ 1 - 1
src/scene/zoom.ts

@@ -20,7 +20,7 @@ export const getNewZoom = (
   };
 };
 
-export const normalizeZoomValue = (zoom: number): NormalizedZoomValue => {
+export const getNormalizedZoom = (zoom: number): NormalizedZoomValue => {
   const normalizedZoom = parseFloat(zoom.toFixed(2));
   const clampedZoom = Math.max(0.1, Math.min(normalizedZoom, 2));
   return clampedZoom as NormalizedZoomValue;