Skip to content

armgit / ente

Public Imported from GitHub
0

πŸ’š End-to-end encrypted cloud for everything.

Stable identity of context functions to prevent unnecessary rerenders

Manav Rathid15f8451fef3
diff --git a/web/apps/photos/src/components/Collections/CollectionHeader.tsx b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
index 2647a31a82..505a557c84 100644
--- a/web/apps/photos/src/components/Collections/CollectionHeader.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
@@ -141,7 +141,7 @@ const CollectionOptions: React.FC<CollectionOptionsProps> = ({
setFilesDownloadProgressAttributesCreator,
isActiveCollectionDownloadInProgress,
}) => {
- const { startLoading, finishLoading, setDialogMessage } =
+ const { showLoadingBar, hideLoadingBar, setDialogMessage } =
useContext(AppContext);
const { syncWithRemote } = useContext(GalleryContext);
const overFlowMenuIconRef = useRef<SVGSVGElement>(null);
@@ -169,19 +169,19 @@ const CollectionOptions: React.FC<CollectionOptionsProps> = ({
const wrap = useCallback(
(f: () => Promise<void>) => {
const wrapped = async () => {
- startLoading();
+ showLoadingBar();
try {
await f();
} catch (e) {
handleError(e);
} finally {
void syncWithRemote(false, true);
- finishLoading();
+ hideLoadingBar();
}
};
return (): void => void wrapped();
},
- [handleError, syncWithRemote, startLoading, finishLoading],
+ [handleError, syncWithRemote, showLoadingBar, hideLoadingBar],
);
const showRenameCollectionModal = () => {
diff --git a/web/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageEmailShare.tsx b/web/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageEmailShare.tsx
index caf6e732a5..cd2cb17e75 100644
--- a/web/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageEmailShare.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionShare/emailShare/ManageEmailShare.tsx
@@ -41,7 +41,7 @@ export default function ManageEmailShare({
onRootClose,
peopleCount,
}: Iprops) {
- const appContext = useContext(AppContext);
+ const { showLoadingBar, hideLoadingBar } = useContext(AppContext);
const galleryContext = useContext(GalleryContext);
const [addParticipantView, setAddParticipantView] = useState(false);
@@ -80,11 +80,11 @@ export default function ManageEmailShare({
const collectionUnshare = async (email: string) => {
try {
- appContext.startLoading();
+ showLoadingBar();
await unshareCollection(collection, email);
await galleryContext.syncWithRemote(false, true);
} finally {
- appContext.finishLoading();
+ hideLoadingBar();
}
};
diff --git a/web/apps/photos/src/components/PhotoViewer/index.tsx b/web/apps/photos/src/components/PhotoViewer/index.tsx
index 961201b46d..366a377545 100644
--- a/web/apps/photos/src/components/PhotoViewer/index.tsx
+++ b/web/apps/photos/src/components/PhotoViewer/index.tsx
@@ -118,7 +118,8 @@ export interface PhotoViewerProps {
function PhotoViewer(props: PhotoViewerProps) {
const galleryContext = useContext(GalleryContext);
- const appContext = useContext(AppContext);
+ const { showLoadingBar, hideLoadingBar, setDialogMessage } =
+ useContext(AppContext);
const publicCollectionGalleryContext = useContext(
PublicCollectionGalleryContext,
);
@@ -537,9 +538,12 @@ function PhotoViewer(props: PhotoViewerProps) {
const trashFile = async (file: EnteFile) => {
try {
- appContext.startLoading();
- await trashFiles([file]);
- appContext.finishLoading();
+ showLoadingBar();
+ try {
+ await trashFiles([file]);
+ } finally {
+ hideLoadingBar();
+ }
markTempDeleted?.([file]);
updateItems(props.items.filter((item) => item.id !== file.id));
needUpdate.current = true;
@@ -552,7 +556,7 @@ function PhotoViewer(props: PhotoViewerProps) {
if (!file || !isOwnFile || props.isTrashCollection) {
return;
}
- appContext.setDialogMessage(getTrashFileMessage(() => trashFile(file)));
+ setDialogMessage(getTrashFileMessage(() => trashFile(file)));
};
const handleArrowClick = (
@@ -683,9 +687,9 @@ function PhotoViewer(props: PhotoViewerProps) {
const copyToClipboardHelper = async (file: EnteFile) => {
if (file && props.enableDownload && shouldShowCopyOption) {
- appContext.startLoading();
+ showLoadingBar();
await copyFileToClipboard(file.src);
- appContext.finishLoading();
+ hideLoadingBar();
}
};
diff --git a/web/apps/photos/src/components/Sidebar/index.tsx b/web/apps/photos/src/components/Sidebar/index.tsx
index 1ae907e4d1..d5ca9fb601 100644
--- a/web/apps/photos/src/components/Sidebar/index.tsx
+++ b/web/apps/photos/src/components/Sidebar/index.tsx
@@ -426,15 +426,13 @@ interface UtilitySectionProps {
const UtilitySection: React.FC<UtilitySectionProps> = ({ closeSidebar }) => {
const router = useRouter();
- const appContext = useContext(AppContext);
const {
- startLoading,
watchFolderView,
setWatchFolderView,
themeColor,
setThemeColor,
showMiniDialog,
- } = appContext;
+ } = useAppContext();
const { show: showRecoveryKey, props: recoveryKeyVisibilityProps } =
useModalVisibility();
@@ -536,7 +534,6 @@ const UtilitySection: React.FC<UtilitySectionProps> = ({ closeSidebar }) => {
<TwoFactorModal
{...twoFactorVisibilityProps}
closeSidebar={closeSidebar}
- setLoading={startLoading}
/>
{isElectron() && (
<WatchFolder
diff --git a/web/apps/photos/src/components/TwoFactor/Modal/index.tsx b/web/apps/photos/src/components/TwoFactor/Modal/index.tsx
index bebd1810d4..da65c7e73b 100644
--- a/web/apps/photos/src/components/TwoFactor/Modal/index.tsx
+++ b/web/apps/photos/src/components/TwoFactor/Modal/index.tsx
@@ -5,7 +5,6 @@ import { Dialog, DialogContent, styled } from "@mui/material";
import { t } from "i18next";
import { useEffect, useState } from "react";
import { getTwoFactorStatus } from "services/userService";
-import { SetLoading } from "types/gallery";
import TwoFactorModalManageSection from "./Manage";
import TwoFactorModalSetupSection from "./Setup";
@@ -16,7 +15,6 @@ const TwoFactorDialog = styled(Dialog)(({ theme }) => ({
}));
type Props = ModalVisibilityProps & {
- setLoading: SetLoading;
closeSidebar: () => void;
};
diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsx
index ff9996b407..36c43c7420 100644
--- a/web/apps/photos/src/pages/_app.tsx
+++ b/web/apps/photos/src/pages/_app.tsx
@@ -18,6 +18,7 @@ import {
updateAvailableForDownloadDialogAttributes,
updateReadyToInstallDialogAttributes,
} from "@/new/photos/components/utils/download";
+import { useLoadingBar } from "@/new/photos/components/utils/use-loading-bar";
import { photosDialogZIndex } from "@/new/photos/components/utils/z-index";
import DownloadManager from "@/new/photos/services/download";
import { runMigrations } from "@/new/photos/services/migrations";
@@ -51,7 +52,7 @@ import isElectron from "is-electron";
import type { AppProps } from "next/app";
import { useRouter } from "next/router";
import "photoswipe/dist/photoswipe.css";
-import { useCallback, useEffect, useRef, useState } from "react";
+import { useCallback, useEffect, useState } from "react";
import LoadingBar from "react-top-loading-bar";
import { resumeExportsIfNeeded } from "services/export";
import { photosLogout } from "services/logout";
@@ -71,8 +72,6 @@ export default function App({ Component, pageProps }: AppProps) {
);
const [showNavbar, setShowNavBar] = useState(false);
const [mapEnabled, setMapEnabled] = useState(false);
- const isLoadingBarRunning = useRef(false);
- const loadingBar = useRef(null);
const [dialogMessage, setDialogMessage] = useState<DialogBoxAttributes>();
const [messageDialogView, setMessageDialogView] = useState(false);
const [watchFolderView, setWatchFolderView] = useState(false);
@@ -83,6 +82,7 @@ export default function App({ Component, pageProps }: AppProps) {
useState<NotificationAttributes>(null);
const { showMiniDialog, miniDialogProps } = useAttributedMiniDialog();
+ const { loadingBarRef, showLoadingBar, hideLoadingBar } = useLoadingBar();
const [themeColor, setThemeColor] = useLocalState(
LS_KEYS.THEME,
THEME_COLOR.DARK,
@@ -213,15 +213,6 @@ export default function App({ Component, pageProps }: AppProps) {
setMapEnabled(enabled);
};
- const startLoading = () => {
- !isLoadingBarRunning.current && loadingBar.current?.continuousStart();
- isLoadingBarRunning.current = true;
- };
- const finishLoading = () => {
- isLoadingBarRunning.current && loadingBar.current?.complete();
- isLoadingBarRunning.current = false;
- };
-
// Use `onGenericError` instead.
const somethingWentWrong = useCallback(
() =>
@@ -244,8 +235,8 @@ export default function App({ Component, pageProps }: AppProps) {
const appContext = {
showNavBar,
- startLoading, // <- changes on each render (TODO Fix)
- finishLoading, // <- changes on each render
+ showLoadingBar,
+ hideLoadingBar,
setDialogMessage,
watchFolderView,
setWatchFolderView,
@@ -276,7 +267,7 @@ export default function App({ Component, pageProps }: AppProps) {
<MessageContainer>
{isI18nReady && offline && t("OFFLINE_MSG")}
</MessageContainer>
- <LoadingBar color="#51cd7c" ref={loadingBar} />
+ <LoadingBar color="#51cd7c" ref={loadingBarRef} />
<DialogBox
sx={{ zIndex: photosDialogZIndex }}
diff --git a/web/apps/photos/src/pages/deduplicate.tsx b/web/apps/photos/src/pages/deduplicate.tsx
index c9ce265619..14fd616a47 100644
--- a/web/apps/photos/src/pages/deduplicate.tsx
+++ b/web/apps/photos/src/pages/deduplicate.tsx
@@ -3,7 +3,7 @@ import { ActivityIndicator } from "@/base/components/mui/ActivityIndicator";
import { ALL_SECTION } from "@/new/photos/services/collection";
import { createFileCollectionIDs } from "@/new/photos/services/file";
import { getLocalFiles } from "@/new/photos/services/files";
-import { AppContext } from "@/new/photos/types/context";
+import { useAppContext } from "@/new/photos/types/context";
import { VerticallyCentered } from "@ente/shared/components/Container";
import { PHOTOS_PAGES as PAGES } from "@ente/shared/constants/pages";
import { ApiError } from "@ente/shared/error";
@@ -16,7 +16,7 @@ import DeduplicateOptions from "components/pages/dedupe/SelectedFileOptions";
import PhotoFrame from "components/PhotoFrame";
import { t } from "i18next";
import { default as Router, default as router } from "next/router";
-import { createContext, useContext, useEffect, useState } from "react";
+import { createContext, useEffect, useState } from "react";
import {
getAllLatestCollections,
getLocalCollections,
@@ -40,8 +40,8 @@ export const Info = styled("div")`
`;
export default function Deduplicate() {
- const { setDialogMessage, startLoading, finishLoading, showNavBar } =
- useContext(AppContext);
+ const { showNavBar, showLoadingBar, hideLoadingBar, setDialogMessage } =
+ useAppContext();
const [duplicates, setDuplicates] = useState<Duplicate[]>(null);
const [collectionNameMap, setCollectionNameMap] = useState(
new Map<number, string>(),
@@ -70,42 +70,48 @@ export default function Deduplicate() {
}, []);
const syncWithRemote = async () => {
- startLoading();
- const collections = await getLocalCollections();
- const collectionNameMap = new Map<number, string>();
- for (const collection of collections) {
- collectionNameMap.set(collection.id, collection.name);
- }
- setCollectionNameMap(collectionNameMap);
- const files = await getLocalFiles();
- const duplicateFiles = await getDuplicates(files, collectionNameMap);
- const currFileSizeMap = new Map<number, number>();
- let toSelectFileIDs: number[] = [];
- let count = 0;
- for (const dupe of duplicateFiles) {
- // select all except first file
- toSelectFileIDs = [
- ...toSelectFileIDs,
- ...dupe.files.slice(1).map((f) => f.id),
- ];
- count += dupe.files.length - 1;
+ showLoadingBar();
+ try {
+ const collections = await getLocalCollections();
+ const collectionNameMap = new Map<number, string>();
+ for (const collection of collections) {
+ collectionNameMap.set(collection.id, collection.name);
+ }
+ setCollectionNameMap(collectionNameMap);
+ const files = await getLocalFiles();
+ const duplicateFiles = await getDuplicates(
+ files,
+ collectionNameMap,
+ );
+ const currFileSizeMap = new Map<number, number>();
+ let toSelectFileIDs: number[] = [];
+ let count = 0;
+ for (const dupe of duplicateFiles) {
+ // select all except first file
+ toSelectFileIDs = [
+ ...toSelectFileIDs,
+ ...dupe.files.slice(1).map((f) => f.id),
+ ];
+ count += dupe.files.length - 1;
- for (const file of dupe.files) {
- currFileSizeMap.set(file.id, dupe.size);
+ for (const file of dupe.files) {
+ currFileSizeMap.set(file.id, dupe.size);
+ }
}
+ setDuplicates(duplicateFiles);
+ const selectedFiles = {
+ count: count,
+ ownCount: count,
+ collectionID: ALL_SECTION,
+ context: undefined,
+ };
+ for (const fileID of toSelectFileIDs) {
+ selectedFiles[fileID] = true;
+ }
+ setSelected(selectedFiles);
+ } finally {
+ hideLoadingBar();
}
- setDuplicates(duplicateFiles);
- const selectedFiles = {
- count: count,
- ownCount: count,
- collectionID: ALL_SECTION,
- context: undefined,
- };
- for (const fileID of toSelectFileIDs) {
- selectedFiles[fileID] = true;
- }
- setSelected(selectedFiles);
- finishLoading();
};
const duplicateFiles = useMemoSingleThreaded(() => {
@@ -120,7 +126,7 @@ export default function Deduplicate() {
const deleteFileHelper = async () => {
try {
- startLoading();
+ showLoadingBar();
const selectedFiles = getSelectedFiles(selected, duplicateFiles);
await trashFiles(selectedFiles);
@@ -160,7 +166,7 @@ export default function Deduplicate() {
}
} finally {
await syncWithRemote();
- finishLoading();
+ hideLoadingBar();
}
};
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 48081a92c1..044e99046d 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -43,7 +43,7 @@ import {
setSearchCollectionsAndFiles,
} from "@/new/photos/services/search";
import type { SearchOption } from "@/new/photos/services/search/types";
-import { AppContext } from "@/new/photos/types/context";
+import { useAppContext } from "@/new/photos/types/context";
import { splitByPredicate } from "@/utils/array";
import { ensure } from "@/utils/ensure";
import {
@@ -100,14 +100,7 @@ import PlanSelector from "components/pages/gallery/PlanSelector";
import SelectedFileOptions from "components/pages/gallery/SelectedFileOptions";
import { t } from "i18next";
import { useRouter } from "next/router";
-import {
- createContext,
- useCallback,
- useContext,
- useEffect,
- useRef,
- useState,
-} from "react";
+import { createContext, useCallback, useEffect, useRef, useState } from "react";
import { useDropzone } from "react-dropzone";
import {
constructEmailList,
@@ -231,12 +224,12 @@ export default function Gallery() {
const resync = useRef<{ force: boolean; silent: boolean }>();
const {
- startLoading,
- finishLoading,
+ showLoadingBar,
+ hideLoadingBar,
setDialogMessage,
logout,
...appContext
- } = useContext(AppContext);
+ } = useAppContext();
const [userIDToEmailMap, setUserIDToEmailMap] =
useState<Map<number, string>>(null);
const [emailList, setEmailList] = useState<string[]>(null);
@@ -574,7 +567,7 @@ export default function Gallery() {
if (!tokenValid) {
throw new Error(CustomError.SESSION_EXPIRED);
}
- !silent && startLoading();
+ !silent && showLoadingBar();
await preFileInfoSync();
const allCollections = await getAllLatestCollections();
const [hiddenCollections, collections] = splitByPredicate(
@@ -626,7 +619,7 @@ export default function Gallery() {
} finally {
dispatch({ type: "clearTempDeleted" });
dispatch({ type: "clearTempHidden" });
- !silent && finishLoading();
+ !silent && hideLoadingBar();
}
syncInProgress.current = false;
if (resync.current) {
@@ -690,7 +683,7 @@ export default function Gallery() {
const collectionOpsHelper =
(ops: COLLECTION_OPS_TYPE) => async (collection: Collection) => {
- startLoading();
+ showLoadingBar();
try {
setOpenCollectionSelector(false);
const selectedFiles = getSelectedFiles(selected, filteredFiles);
@@ -719,12 +712,12 @@ export default function Gallery() {
content: t("generic_error_retry"),
});
} finally {
- finishLoading();
+ hideLoadingBar();
}
};
const fileOpsHelper = (ops: FILE_OPS_TYPE) => async () => {
- startLoading();
+ showLoadingBar();
try {
// passing files here instead of filteredData for hide ops because we want to move all files copies to hidden collection
const selectedFiles = getSelectedFiles(
@@ -758,14 +751,14 @@ export default function Gallery() {
content: t("generic_error_retry"),
});
} finally {
- finishLoading();
+ hideLoadingBar();
}
};
const showCreateCollectionModal = (ops: COLLECTION_OPS_TYPE) => {
const callback = async (collectionName: string) => {
try {
- startLoading();
+ showLoadingBar();
const collection = await createAlbum(collectionName);
await collectionOpsHelper(ops)(collection);
} catch (e) {
@@ -777,7 +770,7 @@ export default function Gallery() {
content: t("generic_error_retry"),
});
} finally {
- finishLoading();
+ hideLoadingBar();
}
};
return () =>
diff --git a/web/packages/new/photos/components/utils/use-loading-bar.ts b/web/packages/new/photos/components/utils/use-loading-bar.ts
new file mode 100644
index 0000000000..4c83a42349
--- /dev/null
+++ b/web/packages/new/photos/components/utils/use-loading-bar.ts
@@ -0,0 +1,26 @@
+import { useCallback, useRef } from "react";
+import { type LoadingBarRef } from "react-top-loading-bar";
+
+/**
+ * A convenience hook for returning stable functions tied to a
+ * {@link LoadingBar} ref.
+ *
+ * The {@link LoadingBar} component comes from the "react-top-loading-bar"
+ * library. To control it, we keep a ref. We want to allow components in our
+ * React tree to be able to also control the loading bar, but instead of
+ * exposing the ref directly, we export wrapper functions to start and stop the
+ * loading bar. This hook returns these functions (and the ref).
+ */
+export const useLoadingBar = () => {
+ const loadingBarRef = useRef<LoadingBarRef>();
+
+ const showLoadingBar = useCallback(() => {
+ loadingBarRef.current?.continuousStart();
+ }, []);
+
+ const hideLoadingBar = useCallback(() => {
+ loadingBarRef.current?.complete();
+ }, []);
+
+ return { loadingBarRef, showLoadingBar, hideLoadingBar };
+};
diff --git a/web/packages/new/photos/components/utils/use-wrap-async.ts b/web/packages/new/photos/components/utils/use-wrap-async.ts
index 473cd78dd6..bd77821586 100644
--- a/web/packages/new/photos/components/utils/use-wrap-async.ts
+++ b/web/packages/new/photos/components/utils/use-wrap-async.ts
@@ -15,18 +15,18 @@ import { useAppContext } from "../../types/context";
export const useWrapAsyncOperation = <T extends unknown[]>(
f: (...args: T) => Promise<void>,
) => {
- const { startLoading, finishLoading, onGenericError } = useAppContext();
+ const { showLoadingBar, hideLoadingBar, onGenericError } = useAppContext();
return useCallback(
async (...args: T) => {
- startLoading();
+ showLoadingBar();
try {
await f(...args);
} catch (e) {
onGenericError(e);
} finally {
- finishLoading();
+ hideLoadingBar();
}
},
- [f, startLoading, finishLoading, onGenericError],
+ [f, showLoadingBar, hideLoadingBar, onGenericError],
);
};
diff --git a/web/packages/new/photos/types/context.ts b/web/packages/new/photos/types/context.ts
index 1d156e1cce..40c679583b 100644
--- a/web/packages/new/photos/types/context.ts
+++ b/web/packages/new/photos/types/context.ts
@@ -10,13 +10,14 @@ import type { SetNotificationAttributes } from "./notification";
*/
export type AppContextT = AccountsContextT & {
/**
- * Show the global activity indicator (a green bar at the top of the page).
+ * Show the global activity indicator (a loading bar at the top of the
+ * page).
*/
- startLoading: () => void;
+ showLoadingBar: () => void;
/**
- * Hide the global activity indicator.
+ * Hide the global activity indicator bar.
*/
- finishLoading: () => void;
+ hideLoadingBar: () => void;
/**
* Show a generic error dialog, and log the given error.
*/