Skip to content

armgit / ente

Public Imported from GitHub
0

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

[web][photos] Unify confirmation dialogs

AswinAsok233f05e08dca
diff --git a/web/apps/photos/src/components/Collections/AllAlbums.tsx b/web/apps/photos/src/components/Collections/AllAlbums.tsx
index 872009ec0e..876257fdfe 100644
--- a/web/apps/photos/src/components/Collections/AllAlbums.tsx
+++ b/web/apps/photos/src/components/Collections/AllAlbums.tsx
@@ -1,4 +1,3 @@
-import { TrashFilesDialog } from "@/components/gallery/TrashFilesDialog";
// TODO: Audit this file.
import {
CreateAlbumTile,
@@ -105,11 +104,8 @@ export const AllAlbums: React.FC<AllAlbums> = ({
onClose();
};
- const {
- handleDeleteEmptyAlbums,
- hasEnoughEmptyAlbums,
- deleteEmptyAlbumsDialogProps,
- } = useDeleteEmptyAlbums(collectionSummaries, onRemotePull);
+ const { handleDeleteEmptyAlbums, hasEnoughEmptyAlbums } =
+ useDeleteEmptyAlbums(collectionSummaries, onRemotePull);
const showDeleteEmptyAlbums =
showAlbumFilters &&
@@ -254,7 +250,6 @@ export const AllAlbums: React.FC<AllAlbums> = ({
</Box>
)}
</Dialog>
- <TrashFilesDialog {...deleteEmptyAlbumsDialogProps} />
</>
);
};
diff --git a/web/apps/photos/src/components/Collections/useDeleteEmptyAlbums.ts b/web/apps/photos/src/components/Collections/useDeleteEmptyAlbums.ts
index b7707e4a7a..4a9f727cd5 100644
--- a/web/apps/photos/src/components/Collections/useDeleteEmptyAlbums.ts
+++ b/web/apps/photos/src/components/Collections/useDeleteEmptyAlbums.ts
@@ -1,5 +1,6 @@
import type { RemotePullOpts } from "@/components/gallery";
import { ensureLocalUser } from "ente-accounts/services/user";
+import { useBaseContext } from "ente-base/context";
import {
deleteCollection,
isArchivedCollection,
@@ -15,13 +16,13 @@ import {
} from "ente-new/photos/services/photos-fdb";
import { usePhotosAppContext } from "ente-new/photos/types/context";
import { t } from "i18next";
-import { useState } from "react";
+import { trashFilesDialogAttributes } from "../utils/dialog-attributes";
export const useDeleteEmptyAlbums = (
collectionSummaries: CollectionSummary[],
onRemotePull: (opts?: RemotePullOpts) => Promise<void>,
) => {
- const [candidateIDs, setCandidateIDs] = useState<number[]>();
+ const { showMiniDialog } = useBaseContext();
const { showNotification } = usePhotosAppContext();
const emptyAlbumCandidates = collectionSummaries.filter(
isBulkDeletableEmptyAlbum,
@@ -98,22 +99,22 @@ export const useDeleteEmptyAlbums = (
};
const handleDeleteEmptyAlbums = () => {
- setCandidateIDs(emptyAlbumCandidates.map((cs) => cs.id));
+ const candidateIDs = emptyAlbumCandidates.map((cs) => cs.id);
+ const attributes = trashFilesDialogAttributes(candidateIDs.length, () =>
+ deleteEmptyAlbums(candidateIDs),
+ );
+ showMiniDialog({
+ ...attributes,
+ title: t("delete_empty_albums_title"),
+ message: t("delete_empty_albums_message", {
+ count: candidateIDs.length,
+ }),
+ continue: { ...attributes.continue, text: t("delete") },
+ });
};
return {
handleDeleteEmptyAlbums,
- deleteEmptyAlbumsDialogProps: {
- open: candidateIDs !== undefined,
- onClose: () => setCandidateIDs(undefined),
- count: candidateIDs?.length ?? 0,
- title: t("delete_empty_albums_title"),
- message: t("delete_empty_albums_message", {
- count: candidateIDs?.length ?? 0,
- }),
- confirmText: t("delete"),
- onConfirm: () => deleteEmptyAlbums(candidateIDs ?? []),
- },
hasEnoughEmptyAlbums: emptyAlbumCandidates.length >= 3,
};
};
diff --git a/web/apps/photos/src/components/gallery/TrashFilesDialog.tsx b/web/apps/photos/src/components/gallery/TrashFilesDialog.tsx
deleted file mode 100644
index 162dd0397e..0000000000
--- a/web/apps/photos/src/components/gallery/TrashFilesDialog.tsx
+++ /dev/null
@@ -1,157 +0,0 @@
-import CloseIcon from "@mui/icons-material/Close";
-import {
- Box,
- Dialog,
- DialogContent,
- DialogTitle,
- IconButton,
- Stack,
- Typography,
-} from "@mui/material";
-import { InlineErrorIndicator } from "ente-base/components/ErrorIndicator";
-import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
-import { LoadingButton } from "ente-base/components/mui/LoadingButton";
-import type { ModalVisibilityProps } from "ente-base/components/utils/modal";
-import log from "ente-base/log";
-import { t } from "i18next";
-import { useId, useState } from "react";
-
-type TrashFilesDialogProps = ModalVisibilityProps & {
- count: number;
- title?: string;
- message?: string;
- confirmText?: string;
- onConfirm: () => void | Promise<void>;
-};
-
-export const TrashFilesDialog: React.FC<TrashFilesDialogProps> = ({
- open,
- onClose,
- count,
- title,
- message,
- confirmText,
- onConfirm,
-}) => {
- const [phase, setPhase] = useState<"loading" | "failed" | undefined>();
- const titleID = useId();
- const messageID = useId();
-
- const resetAndClose = () => {
- setPhase(undefined);
- onClose();
- };
-
- const handleClose = () => {
- if (phase !== "loading") resetAndClose();
- };
-
- const handleConfirm = async () => {
- setPhase("loading");
- try {
- await onConfirm();
- resetAndClose();
- } catch (e) {
- log.error(e);
- setPhase("failed");
- }
- };
-
- return (
- <Dialog
- open={open}
- onClose={handleClose}
- aria-labelledby={titleID}
- aria-describedby={messageID}
- fullWidth
- slotProps={{
- paper: {
- sx: {
- maxWidth: "440px",
- borderRadius: "24px",
- position: "relative",
- textAlign: "center",
- "& .MuiButton-root": {
- fontWeight: 500,
- minHeight: "48px",
- padding: "14px 24px",
- borderRadius: "20px",
- },
- },
- },
- }}
- >
- <IconButton
- aria-label={t("close")}
- disabled={phase === "loading"}
- onClick={handleClose}
- sx={{
- position: "absolute",
- top: 16,
- right: 16,
- width: 36,
- height: 36,
- backgroundColor: "fill.faint",
- }}
- >
- <CloseIcon sx={{ fontSize: 20 }} />
- </IconButton>
- <Stack sx={{ alignItems: "center", pt: "38px", px: 3.5 }}>
- <Box
- component="img"
- src="/images/warning-red.png"
- alt=""
- sx={{ width: 68, height: 64, objectFit: "contain" }}
- />
- <DialogTitle
- id={titleID}
- sx={{ "&&&": { p: 0, mt: 3 }, fontSize: 20 }}
- >
- {title ??
- t("trash_items_title", {
- count,
- fallbackLng: false,
- defaultValue: t(
- count === 1
- ? "trash_file_title"
- : "trash_files_title",
- ),
- })}
- </DialogTitle>
- </Stack>
- <DialogContent sx={{ padding: "16px 28px 24px" }}>
- <Typography id={messageID} sx={{ color: "text.muted" }}>
- {message ??
- t("trash_items_message", {
- count,
- fallbackLng: false,
- defaultValue: t(
- count === 1
- ? "trash_file_message"
- : "trash_files_message",
- ),
- })}
- </Typography>
- <Stack sx={{ pt: 3, gap: 1 }}>
- {phase === "failed" && <InlineErrorIndicator />}
- <LoadingButton
- loading={phase === "loading"}
- fullWidth
- color="critical"
- onClick={handleConfirm}
- >
- {confirmText ?? t("move_to_trash")}
- </LoadingButton>
- <FocusVisibleButton
- fullWidth
- color="secondary"
- disabled={phase === "loading"}
- onClick={handleClose}
- >
- {t("cancel")}
- </FocusVisibleButton>
- </Stack>
- </DialogContent>
- </Dialog>
- );
-};
diff --git a/web/apps/photos/src/components/sidebar/Sidebar.tsx b/web/apps/photos/src/components/sidebar/Sidebar.tsx
index 50ca767aae..fb9829cf9f 100644
--- a/web/apps/photos/src/components/sidebar/Sidebar.tsx
+++ b/web/apps/photos/src/components/sidebar/Sidebar.tsx
@@ -338,18 +338,7 @@ export const Sidebar: React.FC<SidebarProps> = ({
>
<AttributedMiniDialog
{...downloadAppDialogProps}
- sx={(theme) => ({
- "& .MuiDialog-paper": { borderRadius: "20px" },
- "& .MuiDialog-paper > .MuiStack-root": {
- p: "24px 24px 8px",
- },
- "& .MuiDialogContent-root": { p: "16px 24px 24px" },
- "& .MuiDialogTitle-root": theme.typography.h2,
- "& .MuiButton-root": {
- borderRadius: "12px",
- minHeight: 48,
- },
- })}
+ appearance="centered"
/>
{open && exportVisibilityProps.open && (
<Export
diff --git a/web/apps/photos/src/components/utils/dialog-attributes.tsx b/web/apps/photos/src/components/utils/dialog-attributes.tsx
index 4b67f97cb5..4ee4f42d8b 100644
--- a/web/apps/photos/src/components/utils/dialog-attributes.tsx
+++ b/web/apps/photos/src/components/utils/dialog-attributes.tsx
@@ -1,6 +1,44 @@
import InfoOutlinedIcon from "@mui/icons-material/InfoOutlined";
+import { Box } from "@mui/material";
+import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
import { t } from "i18next";
+export const trashFilesDialogAttributes = (
+ count: number,
+ onConfirm: () => void | Promise<void>,
+): MiniDialogAttributes => ({
+ title: t("trash_items_title", {
+ count,
+ fallbackLng: false,
+ defaultValue: t(count === 1 ? "trash_file_title" : "trash_files_title"),
+ }),
+ message: t("trash_items_message", {
+ count,
+ fallbackLng: false,
+ defaultValue: t(
+ count === 1 ? "trash_file_message" : "trash_files_message",
+ ),
+ }),
+ illustration: (
+ <Box
+ component="img"
+ src="/images/warning-red.png"
+ alt=""
+ sx={{
+ width: 68,
+ height: 64,
+ objectFit: "contain",
+ display: "block",
+ }}
+ />
+ ),
+ continue: {
+ text: t("move_to_trash"),
+ color: "critical",
+ action: onConfirm,
+ },
+});
+
export const notifyOthersFilesDialogAttributes = () => ({
title: t("note"),
icon: <InfoOutlinedIcon />,
diff --git a/web/apps/photos/src/pages/_app.tsx b/web/apps/photos/src/pages/_app.tsx
index 317203109e..ede279c3a6 100644
--- a/web/apps/photos/src/pages/_app.tsx
+++ b/web/apps/photos/src/pages/_app.tsx
@@ -170,7 +170,7 @@ const App: React.FC<PhotosAppProps> = ({ Component, pageProps }) => {
<CssBaseline enableColorScheme />
<ThemedLoadingBar ref={loadingBarRef} />
- <AttributedMiniDialog {...miniDialogProps} />
+ <AttributedMiniDialog {...miniDialogProps} appearance="centered" />
<Notification {...notificationProps} />
{isDesktop && (
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index f41b185bc9..c067ca1847 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -39,7 +39,6 @@ import { DuplicatesView } from "@/components/gallery/DuplicatesView";
import { LargeFilesView } from "@/components/gallery/LargeFilesView";
import { PeopleOverview } from "@/components/gallery/PeopleOverview";
import { PhotosNavigationShell } from "@/components/gallery/PhotosNavigationShell";
-import { TrashFilesDialog } from "@/components/gallery/TrashFilesDialog";
import {
albumShortcutCollectionID,
findCollectionCreatingIfNeeded,
@@ -54,6 +53,7 @@ import { Sidebar } from "@/components/sidebar/Sidebar";
import {
notifyOthersFilesDialogAttributes,
notifyUnsupportedSharedFavoritesDialogAttributes,
+ trashFilesDialogAttributes,
} from "@/components/utils/dialog-attributes";
import { useIsOffline } from "@/components/utils/use-is-offline";
import { shouldShowWhatsNew } from "@/services/changelog";
@@ -205,14 +205,6 @@ const Page: React.FC = () => {
const isCleanupViewOpen = cleanupView !== undefined;
const [isFirstLoad, setIsFirstLoad] = useState(false);
const [isContextMenuOpen, setIsContextMenuOpen] = useState(false);
- const [trashFilesDialog, setTrashFilesDialog] = useState<{
- count: number;
- onConfirm: () => void;
- }>();
- const {
- show: showTrashFilesDialog,
- props: trashFilesDialogVisibilityProps,
- } = useModalVisibility();
const [suppressContextSelectionBar, setSuppressContextSelectionBar] =
useState(false);
const [selected, setSelected] = useState<SelectedState>({
@@ -1247,7 +1239,7 @@ const Page: React.FC = () => {
const createFileOpHandler =
(op: FileOp, options?: { suppressSelectionBar?: boolean }) => () => {
- void (async () => {
+ return (async () => {
if (options?.suppressSelectionBar) {
setSuppressContextSelectionBar(true);
}
@@ -1352,7 +1344,9 @@ const Page: React.FC = () => {
clearSelection();
await remotePull({ silent: true, source: `file-op:${op}` });
} catch (e) {
- if (op == "sendLink") {
+ if (op == "trash") {
+ throw e;
+ } else if (op == "sendLink") {
onSendLinkError(e);
} else {
onGenericError(e);
@@ -1714,15 +1708,14 @@ const Page: React.FC = () => {
const handleDeleteFiles = useCallback(
(suppressSelectionBar = false) => {
if (selectedOwnCount === 0) return;
- setTrashFilesDialog({
- count: selectedOwnCount,
- onConfirm: createFileOpHandler("trash", {
- suppressSelectionBar,
- }),
- });
- showTrashFilesDialog();
+ showMiniDialog(
+ trashFilesDialogAttributes(
+ selectedOwnCount,
+ createFileOpHandler("trash", { suppressSelectionBar }),
+ ),
+ );
},
- [selectedOwnCount, createFileOpHandler, showTrashFilesDialog],
+ [selectedOwnCount, createFileOpHandler, showMiniDialog],
);
const selectedFavoriteCount = useMemo(
() => countSelectedFavorites(selected, favoriteFileIDs),
@@ -1773,32 +1766,44 @@ const Page: React.FC = () => {
const suppressSelectionBar = !!meta?.isEphemeralSingleSelection;
switch (action) {
case "sendLink":
- createFileOpHandler("sendLink", { suppressSelectionBar })();
+ void createFileOpHandler("sendLink", {
+ suppressSelectionBar,
+ })();
break;
case "download":
- createFileOpHandler("download", { suppressSelectionBar })();
+ void createFileOpHandler("download", {
+ suppressSelectionBar,
+ })();
break;
case "favorite":
- createFileOpHandler("favorite", { suppressSelectionBar })();
+ void createFileOpHandler("favorite", {
+ suppressSelectionBar,
+ })();
break;
case "unfavorite":
- createFileOpHandler("unfavorite", {
+ void createFileOpHandler("unfavorite", {
suppressSelectionBar,
})();
break;
case "archive":
- createFileOpHandler("archive", { suppressSelectionBar })();
+ void createFileOpHandler("archive", {
+ suppressSelectionBar,
+ })();
break;
case "unarchive":
- createFileOpHandler("unarchive", {
+ void createFileOpHandler("unarchive", {
suppressSelectionBar,
})();
break;
case "hide":
- createFileOpHandler("hide", { suppressSelectionBar })();
+ void createFileOpHandler("hide", {
+ suppressSelectionBar,
+ })();
break;
case "fixTime":
- createFileOpHandler("fixTime", { suppressSelectionBar })();
+ void createFileOpHandler("fixTime", {
+ suppressSelectionBar,
+ })();
break;
case "trash":
handleDeleteFiles(suppressSelectionBar);
@@ -2075,12 +2080,6 @@ const Page: React.FC = () => {
files={fixCreationTimeFiles}
onRemotePull={remotePull}
/>
- {trashFilesDialog && (
- <TrashFilesDialog
- {...trashFilesDialogVisibilityProps}
- {...trashFilesDialog}
- />
- )}
<PhotosNavigationShell
showRail
showNormalNavigation={showNormalNavigation}
diff --git a/web/apps/photos/tests/delete-empty-albums.test.ts b/web/apps/photos/tests/delete-empty-albums.test.ts
index 0f39dc3e31..287324e103 100644
--- a/web/apps/photos/tests/delete-empty-albums.test.ts
+++ b/web/apps/photos/tests/delete-empty-albums.test.ts
@@ -1,9 +1,10 @@
+import type { MiniDialogAttributes } from "ente-base/components/MiniDialog";
import type { CollectionSummary } from "ente-new/photos/services/collection-summary";
import { beforeEach, describe, expect, test, vi } from "vitest";
import { useDeleteEmptyAlbums } from "../src/components/Collections/useDeleteEmptyAlbums";
const mocks = vi.hoisted(() => ({
- candidateIDs: undefined as number[] | undefined,
+ showMiniDialog: vi.fn<(attributes: MiniDialogAttributes) => void>(),
notify: vi.fn<
(notification: { title: { key: string; opts?: unknown } }) => void
>(),
@@ -12,13 +13,8 @@ const mocks = vi.hoisted(() => ({
files: vi.fn(),
remove: vi.fn(),
}));
-vi.mock("react", () => ({
- useState: () => [
- mocks.candidateIDs,
- (ids: number[] | undefined) => {
- mocks.candidateIDs = ids;
- },
- ],
+vi.mock("ente-base/context", () => ({
+ useBaseContext: () => ({ showMiniDialog: mocks.showMiniDialog }),
}));
vi.mock("ente-new/photos/types/context", () => ({
usePhotosAppContext: () => ({ showNotification: mocks.notify }),
@@ -60,12 +56,10 @@ const collection = (id: number) => ({
const start = (ids = [1, 2, 3]) => {
const result = useDeleteEmptyAlbums(ids.map(summary), mocks.pull);
result.handleDeleteEmptyAlbums();
- return useDeleteEmptyAlbums(ids.map(summary), mocks.pull)
- .deleteEmptyAlbumsDialogProps;
+ return mocks.showMiniDialog.mock.calls.at(-1)![0];
};
beforeEach(() => {
vi.resetAllMocks();
- mocks.candidateIDs = undefined;
mocks.pull.mockResolvedValue(undefined);
mocks.collections.mockResolvedValue([1, 2, 3].map(collection));
mocks.files.mockResolvedValue([]);
@@ -74,19 +68,19 @@ beforeEach(() => {
describe("shared empty album deletion", () => {
test("confirms the candidate count and does nothing until confirmed", () => {
const dialog = start();
- expect(dialog.open).toBe(true);
- expect(dialog.count).toBe(3);
+ expect(mocks.showMiniDialog).toHaveBeenCalledOnce();
+ expect(dialog.illustration).toBeDefined();
+ expect(dialog.continue?.text).toEqual({
+ key: "delete",
+ opts: undefined,
+ });
+ expect(dialog.continue?.color).toBe("critical");
expect(dialog.message).toEqual({
key: "delete_empty_albums_message",
opts: { count: 3 },
});
expect(mocks.pull).not.toHaveBeenCalled();
expect(mocks.remove).not.toHaveBeenCalled();
- dialog.onClose();
- expect(
- useDeleteEmptyAlbums([summary(1)], mocks.pull)
- .deleteEmptyAlbumsDialogProps.open,
- ).toBe(false);
expect(
useDeleteEmptyAlbums([summary(1), summary(2)], mocks.pull)
.hasEnoughEmptyAlbums,
@@ -105,7 +99,7 @@ describe("shared empty album deletion", () => {
collection(9),
]);
mocks.files.mockResolvedValue([{ collectionID: 2 }]);
- await start([1, 2, 3, 4, 5, 6, 7, 8]).onConfirm();
+ await start([1, 2, 3, 4, 5, 6, 7, 8]).continue?.action?.();
expect(mocks.remove.mock.calls).toEqual([[1, { keepFiles: true }]]);
expect(mocks.pull.mock.calls).toEqual([
[{ strict: true }],
@@ -114,7 +108,7 @@ describe("shared empty album deletion", () => {
});
test("aborts on initial sync failure", async () => {
mocks.pull.mockRejectedValueOnce(new Error("sync"));
- await start().onConfirm();
+ await start().continue?.action?.();
expect(mocks.remove).not.toHaveBeenCalled();
expect(mocks.notify.mock.calls[0]![0].title).toEqual({
key: "delete_empty_albums_failed",
@@ -123,7 +117,7 @@ describe("shared empty album deletion", () => {
});
test("continues after a deletion failure and reports the failed count", async () => {
mocks.remove.mockRejectedValueOnce(new Error("delete"));
- await start().onConfirm();
+ await start().continue?.action?.();
expect(mocks.remove).toHaveBeenCalledTimes(3);
expect(mocks.pull).toHaveBeenCalledTimes(2);
expect(mocks.notify.mock.calls[0]![0].title).toEqual({
@@ -135,7 +129,7 @@ describe("shared empty album deletion", () => {
mocks.pull
.mockResolvedValueOnce(undefined)
.mockRejectedValueOnce(new Error("refresh"));
- await start().onConfirm();
+ await start().continue?.action?.();
expect(mocks.notify.mock.calls[0]![0].title.key).toBe(
"delete_empty_albums_refresh_failed",
);
diff --git a/web/apps/photos/tests/mini-dialog.test.ts b/web/apps/photos/tests/mini-dialog.test.ts
new file mode 100644
index 0000000000..703e2167b3
--- /dev/null
+++ b/web/apps/photos/tests/mini-dialog.test.ts
@@ -0,0 +1,93 @@
+import { miniDialogReducer } from "ente-base/components/utils/mini-dialog-state";
+import { describe, expect, test, vi } from "vitest";
+import { trashFilesDialogAttributes } from "../src/components/utils/dialog-attributes";
+
+vi.mock("i18next", () => ({
+ t: (key: string, options?: { count?: number }) =>
+ options?.count === undefined ? key : `${key}:${options.count}`,
+}));
+
+describe("mini dialog lifecycle", () => {
+ test("an earlier action cannot close a follow-up notice", () => {
+ const first = miniDialogReducer(
+ { open: false, id: 0 },
+ { type: "show", attributes: { title: "Delete?" } },
+ );
+ const notice = miniDialogReducer(first, {
+ type: "show",
+ attributes: { title: "Some files belong to others" },
+ });
+ expect(miniDialogReducer(notice, { type: "close", id: first.id })).toBe(
+ notice,
+ );
+ expect(notice.open).toBe(true);
+ expect(notice.id).not.toBe(first.id);
+ });
+
+ test("non-replaceable prompts block replacement only while open", () => {
+ const locked = miniDialogReducer(
+ { open: false, id: 0 },
+ { type: "show", attributes: { nonReplaceable: true } },
+ );
+ const show = { type: "show", attributes: { title: "Next" } } as const;
+ expect(miniDialogReducer(locked, show)).toBe(locked);
+ const closed = miniDialogReducer(locked, {
+ type: "close",
+ id: locked.id,
+ });
+ expect(closed.open).toBe(false);
+ const next = miniDialogReducer(closed, show);
+ expect(next.open).toBe(true);
+ expect(next.attributes?.title).toBe("Next");
+ expect(next.id).not.toBe(locked.id);
+ });
+
+ test("showing the same attributes again creates fresh component state", () => {
+ const attributes = { title: "Retry" };
+ const first = miniDialogReducer(
+ { open: false, id: 0 },
+ { type: "show", attributes },
+ );
+ const next = miniDialogReducer(first, { type: "show", attributes });
+ expect(next.id).toBe(first.id + 1);
+ });
+});
+
+describe("trash confirmation attributes", () => {
+ test.each([1, 12])(
+ "uses the owned count %i and a critical action",
+ (count) => {
+ const attributes = trashFilesDialogAttributes(count, vi.fn());
+ expect(attributes.title).toBe(`trash_items_title:${count}`);
+ expect(attributes.message).toBe(`trash_items_message:${count}`);
+ expect(attributes.illustration).toBeDefined();
+ expect(attributes.continue?.color).toBe("critical");
+ expect(attributes.continue?.text).toBe("move_to_trash");
+ },
+ );
+
+ test("keeps the action pending until the operation finishes", async () => {
+ let finish!: () => void;
+ const operation = new Promise<void>((resolve) => {
+ finish = resolve;
+ });
+ const attributes = trashFilesDialogAttributes(1, () => operation);
+ const completed = vi.fn();
+ const result = Promise.resolve(attributes.continue?.action?.()).then(
+ completed,
+ );
+ await Promise.resolve();
+ expect(completed).not.toHaveBeenCalled();
+ finish();
+ await result;
+ expect(completed).toHaveBeenCalledOnce();
+ });
+
+ test("passes failures through for the inline retry state", async () => {
+ const failure = new Error("Trash failed");
+ const attributes = trashFilesDialogAttributes(1, () =>
+ Promise.reject(failure),
+ );
+ await expect(attributes.continue?.action?.()).rejects.toBe(failure);
+ });
+});
diff --git a/web/apps/photos/vitest.config.ts b/web/apps/photos/vitest.config.ts
new file mode 100644
index 0000000000..df521d1935
--- /dev/null
+++ b/web/apps/photos/vitest.config.ts
@@ -0,0 +1,6 @@
+import { defineConfig } from "vitest/config";
+
+export default defineConfig({
+ // Next preserves JSX for its own compiler; component tests need it compiled.
+ oxc: { jsx: { runtime: "automatic" } },
+});
diff --git a/web/packages/base/components/MiniDialog.tsx b/web/packages/base/components/MiniDialog.tsx
index 2506167e9e..59266b1b15 100644
--- a/web/packages/base/components/MiniDialog.tsx
+++ b/web/packages/base/components/MiniDialog.tsx
@@ -1,9 +1,11 @@
-import type { ButtonProps, ModalProps } from "@mui/material";
+import CloseIcon from "@mui/icons-material/Close";
+import type { ButtonProps } from "@mui/material";
import {
Box,
Dialog,
DialogContent,
DialogTitle,
+ IconButton,
Stack,
Typography,
type DialogProps,
@@ -11,13 +13,14 @@ import {
import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
import { LoadingButton } from "ente-base/components/mui/LoadingButton";
import { t } from "i18next";
-import React, { useState } from "react";
+import React, { useId, useState } from "react";
import log from "../log";
import { InlineErrorIndicator } from "./ErrorIndicator";
export interface MiniDialogAttributes {
title?: React.ReactNode;
icon?: React.ReactNode;
+ illustration?: React.ReactNode;
message?: React.ReactNode;
nonClosable?: boolean;
nonReplaceable?: boolean;
@@ -37,13 +40,27 @@ export interface MiniDialogAttributes {
}
type MiniDialogProps = Pick<DialogProps, "open" | "sx"> & {
+ appearance?: "default" | "centered";
+ /** A new request remounts the content to reset pending/error state. */
+ dialogID?: number;
onClose: () => void;
attributes?: MiniDialogAttributes;
};
export const AttributedMiniDialog: React.FC<
React.PropsWithChildren<MiniDialogProps>
-> = ({ open, onClose, attributes, children, sx }) => {
+> = ({ dialogID, ...props }) => <MiniDialogContent key={dialogID} {...props} />;
+
+const MiniDialogContent: React.FC<React.PropsWithChildren<MiniDialogProps>> = ({
+ open,
+ onClose,
+ attributes,
+ children,
+ sx,
+ appearance = "default",
+}) => {
+ const titleID = useId();
+ const messageID = useId();
const [phase, setPhase] = useState<
"loading" | "secondary-loading" | "failed" | undefined
>();
@@ -52,12 +69,16 @@ export const AttributedMiniDialog: React.FC<
return <></>;
}
+ const centered = appearance === "centered";
+ const busy = phase === "loading" || phase === "secondary-loading";
+ const artwork = attributes.illustration ?? attributes.icon;
+
const resetPhaseAndClose = () => {
setPhase(undefined);
onClose();
};
- const handleClose: ModalProps["onClose"] = () => {
+ const handleClose = () => {
if (attributes.nonClosable) return;
if (phase == "loading" || phase == "secondary-loading") return;
resetPhaseAndClose();
@@ -140,9 +161,76 @@ export const AttributedMiniDialog: React.FC<
{...{ open, sx }}
onClose={handleClose}
fullWidth
- slotProps={{ paper: { sx: { maxWidth: "360px" } } }}
+ aria-labelledby={attributes.title ? titleID : undefined}
+ aria-describedby={attributes.message ? messageID : undefined}
+ aria-busy={busy}
+ slotProps={{
+ paper: {
+ sx: centered
+ ? {
+ maxWidth: "440px",
+ borderRadius: "24px",
+ position: "relative",
+ textAlign: "center",
+ "& .MuiButton-root": {
+ fontWeight: 500,
+ minHeight: "48px",
+ padding: "14px 24px",
+ borderRadius: "20px",
+ },
+ }
+ : { maxWidth: "360px" },
+ },
+ }}
>
- {(attributes.icon ?? attributes.title) ? (
+ {centered && !attributes.nonClosable && (
+ <IconButton
+ aria-label={t("close")}
+ disabled={busy}
+ onClick={handleClose}
+ sx={{
+ position: "absolute",
+ top: 16,
+ right: 16,
+ width: 36,
+ height: 36,
+ backgroundColor: "fill.faint",
+ }}
+ >
+ <CloseIcon sx={{ fontSize: 20 }} />
+ </IconButton>
+ )}
+ {centered ? (
+ <Stack
+ sx={{
+ alignItems: "center",
+ pt: artwork ? "38px" : "64px",
+ px: 3.5,
+ }}
+ >
+ {artwork && (
+ <Box
+ sx={{
+ mb: 3,
+ "& > svg": {
+ fontSize: 48,
+ color: "stroke.faint",
+ },
+ }}
+ >
+ {artwork}
+ </Box>
+ )}
+ {attributes.title && (
+ <DialogTitle
+ id={titleID}
+ sx={{ "&&&": { p: 0 }, fontSize: 20 }}
+ >
+ {attributes.title}
+ </DialogTitle>
+ )}
+ </Stack>
+ ) : (attributes.icon ?? attributes.title) ? (
<Stack
direction="row"
sx={[
@@ -161,6 +249,7 @@ export const AttributedMiniDialog: React.FC<
>
{attributes.title && (
<DialogTitle
+ id={titleID}
sx={{ "&&&": { padding: 0 }, flexShrink: 1 }}
>
{attributes.title}
@@ -171,9 +260,12 @@ export const AttributedMiniDialog: React.FC<
) : (
<Box sx={{ height: "8px" }} />
)}
- <DialogContent>
+ <DialogContent
+ sx={centered ? { padding: "16px 28px 24px" } : undefined}
+ >
{attributes.message && (
<Typography
+ id={messageID}
component={
typeof attributes.message == "string" ? "p" : "div"
}
@@ -187,7 +279,19 @@ export const AttributedMiniDialog: React.FC<
sx={{ pt: 3, gap: 1 }}
direction={attributes.buttonDirection ?? "column"}
>
- {phase == "failed" && <InlineErrorIndicator />}
+ {phase == "failed" &&
+ (centered ? (
+ <Box
+ sx={{
+ display: "flex",
+ justifyContent: "center",
+ }}
+ >
+ <InlineErrorIndicator />
+ </Box>
+ ) : (
+ <InlineErrorIndicator />
+ ))}
{attributes.buttonDirection == "row" ? (
<>
{cancelButton}
diff --git a/web/packages/base/components/utils/dialog.tsx b/web/packages/base/components/utils/dialog.tsx
index 1c765e6316..221dac0253 100644
--- a/web/packages/base/components/utils/dialog.tsx
+++ b/web/packages/base/components/utils/dialog.tsx
@@ -1,30 +1,34 @@
import ErrorOutlinedIcon from "@mui/icons-material/ErrorOutlined";
import { t } from "i18next";
-import { useCallback, useState } from "react";
+import { useCallback, useReducer } from "react";
import type { MiniDialogAttributes } from "../MiniDialog";
+import { miniDialogReducer } from "./mini-dialog-state";
export const useAttributedMiniDialog = () => {
- const [attributes, setAttributes] = useState<
- MiniDialogAttributes | undefined
- >(undefined);
-
- const [open, setOpen] = useState(false);
+ const [dialog, dispatch] = useReducer(miniDialogReducer, {
+ open: false,
+ id: 0,
+ });
const showMiniDialog = useCallback(
(newAttributes: MiniDialogAttributes) => {
- setAttributes((attributes) =>
- attributes?.nonReplaceable ? attributes : newAttributes,
- );
- setOpen(true);
+ dispatch({ type: "show", attributes: newAttributes });
},
[],
);
- const handleClose = useCallback(() => setOpen(false), []);
+ const handleClose = useCallback(() => {
+ dispatch({ type: "close", id: dialog.id });
+ }, [dialog.id]);
return {
showMiniDialog,
- miniDialogProps: { open, onClose: handleClose, attributes },
+ miniDialogProps: {
+ dialogID: dialog.id,
+ open: dialog.open,
+ onClose: handleClose,
+ attributes: dialog.attributes,
+ },
};
};
diff --git a/web/packages/base/components/utils/mini-dialog-state.ts b/web/packages/base/components/utils/mini-dialog-state.ts
new file mode 100644
index 0000000000..a2cc93811f
--- /dev/null
+++ b/web/packages/base/components/utils/mini-dialog-state.ts
@@ -0,0 +1,23 @@
+import type { MiniDialogAttributes } from "../MiniDialog";
+
+export interface MiniDialogState {
+ open: boolean;
+ attributes?: MiniDialogAttributes;
+ id: number;
+}
+
+type MiniDialogAction =
+ | { type: "show"; attributes: MiniDialogAttributes }
+ | { type: "close"; id: number };
+
+export const miniDialogReducer = (
+ current: MiniDialogState,
+ action: MiniDialogAction,
+): MiniDialogState => {
+ if (action.type === "close") {
+ // An older async action must not dismiss a replacement prompt.
+ return current.id === action.id ? { ...current, open: false } : current;
+ }
+ if (current.open && current.attributes?.nonReplaceable) return current;
+ return { open: true, attributes: action.attributes, id: current.id + 1 };
+};