Skip to content

armgit / ente

Public Imported from GitHub
0

💚 End-to-end encrypted cloud for everything.

fix(locker):confirm-before-discarding-unsaved-changes

Aswin Asok5c05c95ac1f7
diff --git a/web/apps/locker/src/components/create-item/CreateItemDialog.tsx b/web/apps/locker/src/components/create-item/CreateItemDialog.tsx
index 444499ca20..a0e99c9b5a 100644
--- a/web/apps/locker/src/components/create-item/CreateItemDialog.tsx
+++ b/web/apps/locker/src/components/create-item/CreateItemDialog.tsx
@@ -14,6 +14,7 @@ import {
createDocumentIconConfig,
lockerItemIconConfig,
} from "@/components/items/locker-item-icons";
+import { LockerConfirmDialog } from "@/components/ui/LockerConfirmDialog";
import type { LockerUploadLimitState } from "@/services/locker-limits";
import type { LockerUploadProgress } from "@/services/uploads";
import {
@@ -135,6 +136,7 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
canSave,
canUpload,
completedFileKeys,
+ collectionName,
customCollectionNames,
displayCollections,
error,
@@ -143,6 +145,8 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
formType,
handleClose,
handleDialogClose,
+ handleDiscard,
+ handleKeepEditing,
handleFieldChange,
handleFileSelect,
handleSave,
@@ -151,6 +155,7 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
handleUpload,
isEditMode,
isFileMode,
+ pendingExit,
saving,
savedUploadCount,
selectedCollectionIDs,
@@ -159,6 +164,7 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
selectedType,
selectedUploadItems,
setCustomCollectionNames,
+ setCollectionName,
setSelectedCollectionIDs,
setSelectedCollectionNamesByFileKey,
setSelectedUploadItems,
@@ -189,355 +195,381 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
});
return (
- <Dialog
- open={open}
- onClose={handleDialogClose}
- fullWidth
- maxWidth="sm"
- sx={(theme) => ({
- "& .MuiBackdrop-root": { backgroundColor: "rgba(0 0 0 / 0.6)" },
- "& .MuiDialogTitle-root": { padding: 0 },
- "& .MuiDialogContent-root": {
- padding: 0,
- paddingTop: "16px",
- paddingRight: isFileMode ? 0 : "14px",
- marginRight: isFileMode ? 0 : "-14px",
- },
- [theme.breakpoints.down("sm")]: {
- "& .MuiDialog-container": { alignItems: "flex-end" },
- },
- })}
- slotProps={{
- paper: {
- sx: (theme) => ({
- display: "flex",
- flexDirection: "column",
- maxHeight: "min(720px, 90vh)",
- width: "min(100%, 440px)",
- borderRadius: "24px",
- backgroundColor: theme.vars.palette.background.default,
- padding: "20px",
- margin: "16px",
- [theme.breakpoints.down("sm")]: {
- width: "100%",
- maxWidth: "100%",
- margin: 0,
- borderRadius: "20px 20px 0 0",
- paddingBottom:
- "max(34px, env(safe-area-inset-bottom))",
- maxHeight: "90vh",
- },
- }),
- },
- }}
- >
- <Box
- sx={{
- display: "flex",
- alignItems: "center",
- gap: "12px",
- minHeight: 38,
- flexShrink: 0,
+ <>
+ <Dialog
+ open={open}
+ onClose={handleDialogClose}
+ fullWidth
+ maxWidth="sm"
+ sx={(theme) => ({
+ "& .MuiBackdrop-root": {
+ backgroundColor: "rgba(0 0 0 / 0.6)",
+ },
+ "& .MuiDialogTitle-root": { padding: 0 },
+ "& .MuiDialogContent-root": {
+ padding: 0,
+ paddingTop: "16px",
+ paddingRight: isFileMode ? 0 : "14px",
+ marginRight: isFileMode ? 0 : "-14px",
+ },
+ [theme.breakpoints.down("sm")]: {
+ "& .MuiDialog-container": { alignItems: "flex-end" },
+ },
+ })}
+ slotProps={{
+ paper: {
+ sx: (theme) => ({
+ display: "flex",
+ flexDirection: "column",
+ maxHeight: "min(720px, 90vh)",
+ width: "min(100%, 440px)",
+ borderRadius: "24px",
+ backgroundColor:
+ theme.vars.palette.background.default,
+ padding: "20px",
+ margin: "16px",
+ [theme.breakpoints.down("sm")]: {
+ width: "100%",
+ maxWidth: "100%",
+ margin: 0,
+ borderRadius: "20px 20px 0 0",
+ paddingBottom:
+ "max(34px, env(safe-area-inset-bottom))",
+ maxHeight: "90vh",
+ },
+ }),
+ },
}}
>
- {!isEditMode &&
- selectedOption !== null &&
- !(isFileMode && selectedUploadItems.length > 0) && (
- <IconButton
- onClick={handleStepBackToOptions}
- disabled={saving || uploading}
- aria-label={t("go_back")}
- sx={lockerHeaderIconButtonSx}
- >
- <HugeiconsIcon
- icon={ArrowLeft01Icon}
- size={18}
- strokeWidth={1.5}
- />
- </IconButton>
- )}
- <DialogTitle
+ <Box
sx={{
- flex: 1,
- minWidth: 0,
- fontSize: 18,
- lineHeight: "24px",
- fontWeight: 600,
- whiteSpace: "nowrap",
- overflow: "hidden",
- textOverflow: "ellipsis",
+ display: "flex",
+ alignItems: "center",
+ gap: "12px",
+ minHeight: 38,
+ flexShrink: 0,
}}
>
- {isEditMode
- ? t("editItem")
- : isFileMode
- ? selectedUploadItems.length > 1
- ? t("saveDocumentsTitle")
- : t("saveDocumentTitle")
- : selectedType
- ? typeDisplayName(selectedType)
- : t("saveToLocker")}
- </DialogTitle>
- <IconButton
- onClick={handleClose}
- disabled={saving || uploading}
- aria-label={t("close")}
- sx={lockerHeaderIconButtonSx}
- >
- <HugeiconsIcon
- icon={Cancel01Icon}
- size={18}
- strokeWidth={1.5}
- />
- </IconButton>
- </Box>
-
- <DialogContent
- sx={(theme) => ({
- ...(isFileMode
- ? {
- display: "flex",
- flexDirection: "column",
- flex: 1,
- minHeight: 0,
- overflow: "hidden",
- }
- : lockerScrollAreaSx(theme)),
- })}
- >
- {shouldShowDialogErrorCard && (
- <Box
+ {!isEditMode &&
+ selectedOption !== null &&
+ !(isFileMode && selectedUploadItems.length > 0) && (
+ <IconButton
+ onClick={handleStepBackToOptions}
+ disabled={saving || uploading}
+ aria-label={t("go_back")}
+ sx={lockerHeaderIconButtonSx}
+ >
+ <HugeiconsIcon
+ icon={ArrowLeft01Icon}
+ size={18}
+ strokeWidth={1.5}
+ />
+ </IconButton>
+ )}
+ <DialogTitle
sx={{
- display: "flex",
- alignItems: "center",
- gap: "16px",
- minHeight: 66,
- px: "16px",
- py: "12px",
- mb: "16px",
- borderRadius: "20px",
- backgroundColor: "background.paper",
- flexShrink: 0,
+ flex: 1,
+ minWidth: 0,
+ fontSize: 18,
+ lineHeight: "24px",
+ fontWeight: 600,
+ whiteSpace: "nowrap",
+ overflow: "hidden",
+ textOverflow: "ellipsis",
}}
>
+ {isEditMode
+ ? t("editItem")
+ : isFileMode
+ ? selectedUploadItems.length > 1
+ ? t("saveDocumentsTitle")
+ : t("saveDocumentTitle")
+ : selectedType
+ ? typeDisplayName(selectedType)
+ : t("saveToLocker")}
+ </DialogTitle>
+ <IconButton
+ onClick={handleClose}
+ disabled={saving || uploading}
+ aria-label={t("close")}
+ sx={lockerHeaderIconButtonSx}
+ >
+ <HugeiconsIcon
+ icon={Cancel01Icon}
+ size={18}
+ strokeWidth={1.5}
+ />
+ </IconButton>
+ </Box>
+
+ <DialogContent
+ sx={(theme) => ({
+ ...(isFileMode
+ ? {
+ display: "flex",
+ flexDirection: "column",
+ flex: 1,
+ minHeight: 0,
+ overflow: "hidden",
+ }
+ : lockerScrollAreaSx(theme)),
+ })}
+ >
+ {shouldShowDialogErrorCard && (
<Box
sx={{
- color: "critical.main",
- flexShrink: 0,
display: "flex",
+ alignItems: "center",
+ gap: "16px",
+ minHeight: 66,
+ px: "16px",
+ py: "12px",
+ mb: "16px",
+ borderRadius: "20px",
+ backgroundColor: "background.paper",
+ flexShrink: 0,
}}
>
- <HugeiconsIcon
- icon={CancelCircleIcon}
- size={24}
- strokeWidth={1.5}
- />
- </Box>
- <Typography
- variant="mini"
- sx={{ color: "text.muted", minWidth: 0 }}
- >
- {upgradeCTAType === "fileCountLimit" ? (
- <Trans
- i18nKey="uploadFileCountLimitErrorBodyWithUpgrade"
- components={{
- cta: (
- <Link
- href="https://photos.ente.com"
- target="_blank"
- rel="noopener"
- underline="always"
- sx={{
- color: "accent.main",
- fontWeight: 600,
- }}
- />
- ),
- }}
- />
- ) : (
- error
- )}
- </Typography>
- </Box>
- )}
-
- {!isEditMode && !selectedOption && (
- <Stack sx={{ gap: "24px" }}>
- <Typography
- variant="small"
- sx={{ color: "text.muted" }}
- >
- {t("informationDescription")}
- </Typography>
- <Stack sx={{ gap: "16px" }}>
- {CREATABLE_TYPES.map((option) => (
- <TypeCard
- key={option.type}
- label={t(option.labelKey)}
- description={t(option.descriptionKey)}
- icon={option.icon}
- onClick={() =>
- handleSelectOption(option.type)
- }
+ <Box
+ sx={{
+ color: "critical.main",
+ flexShrink: 0,
+ display: "flex",
+ }}
+ >
+ <HugeiconsIcon
+ icon={CancelCircleIcon}
+ size={24}
+ strokeWidth={1.5}
/>
- ))}
- </Stack>
- </Stack>
- )}
+ </Box>
+ <Typography
+ variant="mini"
+ sx={{ color: "text.muted", minWidth: 0 }}
+ >
+ {upgradeCTAType === "fileCountLimit" ? (
+ <Trans
+ i18nKey="uploadFileCountLimitErrorBodyWithUpgrade"
+ components={{
+ cta: (
+ <Link
+ href="https://photos.ente.com"
+ target="_blank"
+ rel="noopener"
+ underline="always"
+ sx={{
+ color: "accent.main",
+ fontWeight: 600,
+ }}
+ />
+ ),
+ }}
+ />
+ ) : (
+ error
+ )}
+ </Typography>
+ </Box>
+ )}
- {isFileMode && !isEditMode && (
- <>
- {showUploadCounter && (
+ {!isEditMode && !selectedOption && (
+ <Stack sx={{ gap: "24px" }}>
<Typography
variant="small"
- sx={{
- color: "text.muted",
- mb: "16px",
- flexShrink: 0,
- }}
+ sx={{ color: "text.muted" }}
>
- {savedUploadCount} / {totalUploadCount}{" "}
- {t("saved")}
+ {t("informationDescription")}
</Typography>
- )}
- <FileUploadSection
- fileInputRef={fileInputRef}
- selectedUploadItems={selectedUploadItems}
- collections={displayCollections}
- availableCollectionNames={customCollectionNames}
- selectedCollectionNamesByFileKey={
- selectedCollectionNamesByFileKey
- }
- completedFileKeys={completedFileKeys}
- failedFileKeys={failedFileKeys}
- uploadingFileKeys={uploadingFileKeys}
- uploadProgressByFileKey={uploadProgressByFileKey}
- uploadCapByFileKey={uploadCapByFileKey}
- uploading={uploading}
- canUpload={canUpload}
- onFileSelect={handleFileSelect}
- onToggleCollectionName={(fileKey, name) =>
- setSelectedCollectionNamesByFileKey(
- (current) => ({
- ...current,
- [fileKey]: toggleCollectionName(
- current[fileKey] ?? [],
- name,
- ),
- }),
- )
- }
- onAddCollectionName={(fileKey, name) => {
- setCustomCollectionNames((current) =>
- addCollectionName(current, name),
- );
- setSelectedCollectionNamesByFileKey(
- (current) => ({
- ...current,
- [fileKey]: addCollectionName(
- current[fileKey] ?? [],
- name,
+ <Stack sx={{ gap: "16px" }}>
+ {CREATABLE_TYPES.map((option) => (
+ <TypeCard
+ key={option.type}
+ label={t(option.labelKey)}
+ description={t(option.descriptionKey)}
+ icon={option.icon}
+ onClick={() =>
+ handleSelectOption(option.type)
+ }
+ />
+ ))}
+ </Stack>
+ </Stack>
+ )}
+
+ {isFileMode && !isEditMode && (
+ <>
+ {showUploadCounter && (
+ <Typography
+ variant="small"
+ sx={{
+ color: "text.muted",
+ mb: "16px",
+ flexShrink: 0,
+ }}
+ >
+ {savedUploadCount} / {totalUploadCount}{" "}
+ {t("saved")}
+ </Typography>
+ )}
+ <FileUploadSection
+ fileInputRef={fileInputRef}
+ selectedUploadItems={selectedUploadItems}
+ collections={displayCollections}
+ availableCollectionNames={customCollectionNames}
+ selectedCollectionNamesByFileKey={
+ selectedCollectionNamesByFileKey
+ }
+ completedFileKeys={completedFileKeys}
+ failedFileKeys={failedFileKeys}
+ uploadingFileKeys={uploadingFileKeys}
+ uploadProgressByFileKey={
+ uploadProgressByFileKey
+ }
+ uploadCapByFileKey={uploadCapByFileKey}
+ uploading={uploading}
+ canUpload={canUpload}
+ onFileSelect={handleFileSelect}
+ onToggleCollectionName={(fileKey, name) =>
+ setSelectedCollectionNamesByFileKey(
+ (current) => ({
+ ...current,
+ [fileKey]: toggleCollectionName(
+ current[fileKey] ?? [],
+ name,
+ ),
+ }),
+ )
+ }
+ onAddCollectionName={(fileKey, name) => {
+ setCustomCollectionNames((current) =>
+ addCollectionName(current, name),
+ );
+ setSelectedCollectionNamesByFileKey(
+ (current) => ({
+ ...current,
+ [fileKey]: addCollectionName(
+ current[fileKey] ?? [],
+ name,
+ ),
+ }),
+ );
+ }}
+ onAddAvailableCollectionName={(name) =>
+ setCustomCollectionNames((current) =>
+ addCollectionName(current, name),
+ )
+ }
+ onSetCollectionNamesForAllItems={(names) =>
+ setSelectedCollectionNamesByFileKey(
+ Object.fromEntries(
+ selectedUploadItems.map((item) => [
+ uploadQueueItemKey(item),
+ names,
+ ]),
),
- }),
- );
- }}
- onAddAvailableCollectionName={(name) =>
- setCustomCollectionNames((current) =>
- addCollectionName(current, name),
- )
- }
- onSetCollectionNamesForAllItems={(names) =>
- setSelectedCollectionNamesByFileKey(
- Object.fromEntries(
- selectedUploadItems.map((item) => [
- uploadQueueItemKey(item),
- names,
- ]),
- ),
- )
- }
- onRemoveItem={(fileKey) => {
- setSelectedUploadItems((current) =>
- current.filter(
- (item) =>
- uploadQueueItemKey(item) !==
- fileKey,
- ),
- );
- setSelectedCollectionNamesByFileKey((current) =>
- Object.fromEntries(
- Object.entries(current).filter(
- ([key]) => key !== fileKey,
+ )
+ }
+ onRemoveItem={(fileKey) => {
+ setSelectedUploadItems((current) =>
+ current.filter(
+ (item) =>
+ uploadQueueItemKey(item) !==
+ fileKey,
),
- ),
- );
- }}
- onUpload={handleUpload}
- />
- </>
- )}
+ );
+ setSelectedCollectionNamesByFileKey(
+ (current) =>
+ Object.fromEntries(
+ Object.entries(current).filter(
+ ([key]) => key !== fileKey,
+ ),
+ ),
+ );
+ }}
+ onUpload={handleUpload}
+ />
+ </>
+ )}
- {formType && (!isFileMode || isEditMode) && (
- <Stack sx={{ gap: "24px" }}>
- <ItemFormFields
- type={formType}
- data={formData}
- onChange={handleFieldChange}
- showPassword={showPassword}
- onTogglePassword={() =>
- setShowPassword((value) => !value)
- }
- />
+ {formType && (!isFileMode || isEditMode) && (
+ <Stack sx={{ gap: "24px" }}>
+ <ItemFormFields
+ type={formType}
+ data={formData}
+ onChange={handleFieldChange}
+ showPassword={showPassword}
+ onTogglePassword={() =>
+ setShowPassword((value) => !value)
+ }
+ />
- <CollectionSelector
- key={`${open ? "open" : "closed"}:${
- editItem?.id ?? "create"
- }:${formType}`}
- collections={displayCollections}
- selectedIDs={selectedCollectionIDs}
- initialSelectedIDs={
- isEditMode ? editItem?.collectionIDs : undefined
- }
- onToggle={(collectionID) =>
- setSelectedCollectionIDs((current) =>
- current.includes(collectionID)
- ? current.filter(
- (id) => id !== collectionID,
- )
- : [...current, collectionID],
- )
- }
- onCreateCollection={onCreateCollection}
- />
+ <CollectionSelector
+ createName={collectionName}
+ onCreateNameChange={setCollectionName}
+ key={`${open ? "open" : "closed"}:${
+ editItem?.id ?? "create"
+ }:${formType}`}
+ collections={displayCollections}
+ selectedIDs={selectedCollectionIDs}
+ initialSelectedIDs={
+ isEditMode
+ ? editItem?.collectionIDs
+ : undefined
+ }
+ onToggle={(collectionID) =>
+ setSelectedCollectionIDs((current) =>
+ current.includes(collectionID)
+ ? current.filter(
+ (id) => id !== collectionID,
+ )
+ : [...current, collectionID],
+ )
+ }
+ onCreateCollection={onCreateCollection}
+ />
- {error && upgradeCTAType !== "fileCountLimit" && (
- <Typography
- variant="small"
- sx={{ color: "critical.main" }}
- >
- {error}
- </Typography>
- )}
+ {error && upgradeCTAType !== "fileCountLimit" && (
+ <Typography
+ variant="small"
+ sx={{ color: "critical.main" }}
+ >
+ {error}
+ </Typography>
+ )}
- <LoadingButton
- fullWidth
- color="accent"
- loading={saving}
- disabled={!canSave}
- onClick={() => void handleSave()}
- sx={(theme) =>
- lockerPrimaryButtonSx(theme, {
- loading: saving,
- })
- }
- >
- {t("saveRecord")}
- </LoadingButton>
- </Stack>
+ <LoadingButton
+ fullWidth
+ color="accent"
+ loading={saving}
+ disabled={!canSave}
+ onClick={() => void handleSave()}
+ sx={(theme) =>
+ lockerPrimaryButtonSx(theme, {
+ loading: saving,
+ })
+ }
+ >
+ {t("saveRecord")}
+ </LoadingButton>
+ </Stack>
+ )}
+ </DialogContent>
+ </Dialog>
+ <LockerConfirmDialog
+ open={open && pendingExit !== null}
+ illustration="/images/warning-grey.png"
+ title={t("discardUnsavedChangesTitle")}
+ body={t(
+ isFileMode && !isEditMode
+ ? "discardPendingUploadsBody"
+ : "discardUnsavedChangesBody",
)}
- </DialogContent>
- </Dialog>
+ confirmLabel={t("discard")}
+ cancelLabel={t("keepEditing")}
+ onClose={handleKeepEditing}
+ onConfirm={handleDiscard}
+ />
+ </>
);
};
diff --git a/web/apps/locker/src/components/create-item/ItemFormFields.tsx b/web/apps/locker/src/components/create-item/ItemFormFields.tsx
index 742abbadc4..43b25f4791 100644
--- a/web/apps/locker/src/components/create-item/ItemFormFields.tsx
+++ b/web/apps/locker/src/components/create-item/ItemFormFields.tsx
@@ -195,17 +195,20 @@ export const CollectionSelector: React.FC<{
collections: LockerCollection[];
selectedIDs: number[];
initialSelectedIDs?: number[];
+ createName: string;
+ onCreateNameChange: (name: string) => void;
onToggle: (id: number) => void;
onCreateCollection?: (name: string) => Promise<number>;
}> = ({
collections,
selectedIDs,
initialSelectedIDs,
+ createName,
+ onCreateNameChange: setCreateName,
onToggle,
onCreateCollection,
}) => {
const [createOpen, setCreateOpen] = useState(false);
- const [createName, setCreateName] = useState("");
const [creating, setCreating] = useState(false);
const [createError, setCreateError] = useState<string | null>(null);
const [newlyCreatedCollectionIDs, setNewlyCreatedCollectionIDs] = useState<
@@ -267,7 +270,7 @@ export const CollectionSelector: React.FC<{
} finally {
setCreating(false);
}
- }, [createName, onCreateCollection, onToggle]);
+ }, [createName, onCreateCollection, onToggle, setCreateName]);
return (
<Box>
diff --git a/web/apps/locker/src/components/create-item/unsaved-changes.ts b/web/apps/locker/src/components/create-item/unsaved-changes.ts
new file mode 100644
index 0000000000..8440322a53
--- /dev/null
+++ b/web/apps/locker/src/components/create-item/unsaved-changes.ts
@@ -0,0 +1,33 @@
+import type { LockerUploadCandidate } from "@/types";
+import { uploadQueueItemKey } from "./file-upload-helpers";
+
+/** Compare drafts without treating absent optional fields or ordering as edits. */
+export function hasUnsavedItemChanges(
+ data: Record<string, string>,
+ initialData: Record<string, string>,
+ collectionIDs: number[],
+ initialCollectionIDs: number[],
+ collectionName: string,
+): boolean {
+ const fields = new Set([...Object.keys(data), ...Object.keys(initialData)]);
+ const collections = new Set(collectionIDs);
+ const initialCollections = new Set(initialCollectionIDs);
+
+ return (
+ collectionName !== "" ||
+ [...fields].some(
+ (field) => (data[field] ?? "") !== (initialData[field] ?? ""),
+ ) ||
+ collections.size !== initialCollections.size ||
+ [...collections].some((id) => !initialCollections.has(id))
+ );
+}
+
+export function hasPendingUploads(
+ items: LockerUploadCandidate[],
+ completedFileKeys: Set<string>,
+): boolean {
+ return items.some(
+ (item) => !completedFileKeys.has(uploadQueueItemKey(item)),
+ );
+}
diff --git a/web/apps/locker/src/components/create-item/use-create-item-dialog-state.ts b/web/apps/locker/src/components/create-item/use-create-item-dialog-state.ts
index 1c2f178e45..af66f18852 100644
--- a/web/apps/locker/src/components/create-item/use-create-item-dialog-state.ts
+++ b/web/apps/locker/src/components/create-item/use-create-item-dialog-state.ts
@@ -22,12 +22,12 @@ import { useCallback, useEffect, useMemo, useRef, useState } from "react";
import {
collectionNamesByUploadItem,
filterNonEmptyUploadItems,
- uploadQueueItemKey,
} from "./file-upload-helpers";
import {
getRequiredFields,
itemFormDataForSave,
} from "./item-form-fields-utils";
+import { hasPendingUploads, hasUnsavedItemChanges } from "./unsaved-changes";
import { useUploadQueue, type LockerUploadCallbacks } from "./use-upload-queue";
export type CreateOption = LockerItemType;
@@ -140,6 +140,10 @@ export const useCreateItemDialogState = ({
editFormData(editItem),
);
const [showPassword, setShowPassword] = useState(false);
+ const [collectionName, setCollectionName] = useState("");
+ const [pendingExit, setPendingExit] = useState<"close" | "back" | null>(
+ null,
+ );
const [selectedUploadItems, setSelectedUploadItems] = useState<
LockerUploadCandidate[]
>(filterNonEmptyUploadItems(initialItems ?? []));
@@ -196,6 +200,7 @@ export const useCreateItemDialogState = ({
);
useEffect(() => {
+ setPendingExit(null);
if (!open) {
return;
}
@@ -226,6 +231,7 @@ export const useCreateItemDialogState = ({
),
);
setFormData(editFormData(editItem));
+ setCollectionName("");
setShowPassword(false);
const filteredInitialItems = filterNonEmptyUploadItems(
initialItems ?? [],
@@ -298,25 +304,88 @@ export const useCreateItemDialogState = ({
selectedCollectionIDs.length,
]);
- const handleClose = useCallback(() => {
- if (saving || uploading) {
- return;
- }
+ const handleSelectOption = useCallback(
+ (option: CreateOption | null) => {
+ setSelectedOption(option);
+ setFormData({});
+ setCollectionName("");
+ setSelectedUploadItems([]);
+ setCustomCollectionNames([]);
+ setSelectedCollectionNamesByFileKey({});
+ resetUploadState();
+ setError(null);
+ setUpgradeCTAType(null);
+ },
+ [resetUploadState],
+ );
- onClose();
- }, [onClose, saving, uploading]);
+ const resetToOptions = useCallback(() => {
+ handleSelectOption(null);
+ setSelectedCollectionIDs(
+ normalizeSelectedCollectionIDs(
+ defaultCollectionID !== null &&
+ defaultCollectionID !== undefined
+ ? [defaultCollectionID]
+ : [],
+ ),
+ );
+ setShowPassword(false);
+ }, [
+ defaultCollectionID,
+ handleSelectOption,
+ normalizeSelectedCollectionIDs,
+ ]);
+ const pendingUploads = hasPendingUploads(
+ selectedUploadItems,
+ completedFileKeys,
+ );
+ const hasUnsavedChanges =
+ isFileMode && !isEditMode
+ ? pendingUploads
+ : hasUnsavedItemChanges(
+ formData,
+ editFormData(editItem),
+ selectedCollectionIDs,
+ normalizeSelectedCollectionIDs(
+ isEditMode
+ ? editCollectionIDs
+ : defaultCollectionID !== null &&
+ defaultCollectionID !== undefined
+ ? [defaultCollectionID]
+ : [],
+ ),
+ collectionName,
+ );
+
+ const requestExit = useCallback(
+ (action: "close" | "back") => {
+ if (saving || uploading) return;
+ if (hasUnsavedChanges) {
+ setPendingExit(action);
+ } else if (action === "back") {
+ resetToOptions();
+ } else {
+ onClose();
+ }
+ },
+ [hasUnsavedChanges, onClose, resetToOptions, saving, uploading],
+ );
+
+ const handleClose = useCallback(() => requestExit("close"), [requestExit]);
const handleStepBackToOptions = useCallback(() => {
- if (isEditMode || saving || uploading) {
- return;
+ if (!isEditMode) requestExit("back");
+ }, [isEditMode, requestExit]);
+ const handleKeepEditing = useCallback(() => setPendingExit(null), []);
+ const handleDiscard = useCallback(() => {
+ if (saving || uploading || !pendingExit) return;
+ setPendingExit(null);
+ if (pendingExit === "back") {
+ resetToOptions();
+ } else {
+ onClose();
}
-
- setSelectedOption(null);
- setFormData({});
- setShowPassword(false);
- setError(null);
- setUpgradeCTAType(null);
- }, [isEditMode, saving, uploading]);
+ }, [onClose, pendingExit, resetToOptions, saving, uploading]);
const handleDialogClose = useCallback(
(_event: object, reason?: "backdropClick" | "escapeKeyDown") => {
@@ -334,20 +403,6 @@ export const useCreateItemDialogState = ({
[handleClose, handleStepBackToOptions, isEditMode, selectedType],
);
- const handleSelectOption = useCallback(
- (option: CreateOption) => {
- setSelectedOption(option);
- setFormData({});
- setSelectedUploadItems([]);
- setCustomCollectionNames([]);
- setSelectedCollectionNamesByFileKey({});
- resetUploadState();
- setError(null);
- setUpgradeCTAType(null);
- },
- [resetUploadState],
- );
-
const handleFieldChange = useCallback((field: string, value: string) => {
setFormData((previous) => ({ ...previous, [field]: value }));
setError(null);
@@ -407,7 +462,8 @@ export const useCreateItemDialogState = ({
try {
const cleanData = itemFormDataForSave(formType, formData);
await onSave(formType, cleanData, selectedCollectionIDs);
- handleClose();
+ // Successful persistence must bypass the unsaved-changes guard.
+ onClose();
} catch (error) {
log.error("Failed to save Locker item", error);
setError(await formatLockerMutationError(error, "createItem"));
@@ -415,12 +471,9 @@ export const useCreateItemDialogState = ({
} finally {
setSaving(false);
}
- }, [formData, formType, handleClose, onSave, selectedCollectionIDs]);
+ }, [formData, formType, onClose, onSave, selectedCollectionIDs]);
- const handleUpload = useCallback(
- () => upload(handleClose),
- [upload, handleClose],
- );
+ const handleUpload = useCallback(() => upload(onClose), [upload, onClose]);
const canSave =
formType !== null &&
@@ -428,12 +481,7 @@ export const useCreateItemDialogState = ({
(field) =>
typeof formData[field] === "string" && formData[field].trim(),
);
- const canUpload =
- isFileMode &&
- selectedUploadItems.length > 0 &&
- selectedUploadItems.some(
- (item) => !completedFileKeys.has(uploadQueueItemKey(item)),
- );
+ const canUpload = isFileMode && pendingUploads;
const savedUploadCount = completedFileKeys.size;
const totalUploadCount = selectedUploadItems.length;
const showUploadCounter = isFileMode && totalUploadCount > 0;
@@ -444,6 +492,7 @@ export const useCreateItemDialogState = ({
canSave,
canUpload,
completedFileKeys,
+ collectionName,
customCollectionNames,
displayCollections,
error,
@@ -451,6 +500,8 @@ export const useCreateItemDialogState = ({
formType,
handleClose,
handleDialogClose,
+ handleDiscard,
+ handleKeepEditing,
handleFieldChange,
handleFileSelect,
handleSave,
@@ -459,6 +510,7 @@ export const useCreateItemDialogState = ({
handleUpload,
isEditMode,
isFileMode,
+ pendingExit,
saving,
savedUploadCount,
selectedCollectionIDs,
@@ -467,6 +519,7 @@ export const useCreateItemDialogState = ({
selectedType,
selectedUploadItems,
setCustomCollectionNames,
+ setCollectionName,
setSelectedCollectionIDs,
setSelectedCollectionNamesByFileKey,
setSelectedUploadItems,
diff --git a/web/apps/locker/src/components/ui/LockerConfirmDialog.tsx b/web/apps/locker/src/components/ui/LockerConfirmDialog.tsx
index a65e6f56a5..d33fabca79 100644
--- a/web/apps/locker/src/components/ui/LockerConfirmDialog.tsx
+++ b/web/apps/locker/src/components/ui/LockerConfirmDialog.tsx
@@ -10,6 +10,7 @@ import { Cancel01Icon } from "@hugeicons/core-free-icons";
import { HugeiconsIcon } from "@hugeicons/react";
import {
Box,
+ Button,
Checkbox,
Dialog,
FormControlLabel,
@@ -27,6 +28,7 @@ interface LockerConfirmDialogProps {
title: string;
body: React.ReactNode;
confirmLabel: string;
+ cancelLabel?: string;
tone?: "critical" | "primary";
loading?: boolean;
error?: string;
@@ -45,6 +47,7 @@ export function LockerConfirmDialog({
title,
body,
confirmLabel,
+ cancelLabel,
tone = "critical",
loading,
error,
@@ -205,6 +208,23 @@ export function LockerConfirmDialog({
>
{confirmLabel}
</LoadingButton>
+ {cancelLabel && (
+ <Button
+ fullWidth
+ autoFocus
+ disabled={loading}
+ onClick={handleClose}
+ sx={{
+ ...lockerTextBodyBoldSx,
+ mt: 1,
+ minHeight: 52,
+ borderRadius: "20px",
+ textTransform: "none",
+ }}
+ >
+ {cancelLabel}
+ </Button>
+ )}
</Stack>
</Dialog>
);
diff --git a/web/apps/locker/src/locales/en-US/translation.json b/web/apps/locker/src/locales/en-US/translation.json
index e8bc53b4ec..d6906145bc 100644
--- a/web/apps/locker/src/locales/en-US/translation.json
+++ b/web/apps/locker/src/locales/en-US/translation.json
@@ -1,4 +1,8 @@
{
+ "discardUnsavedChangesTitle": "Discard unsaved changes?",
+ "discardUnsavedChangesBody": "You have unsaved changes. Discarding will lose them.",
+ "discardPendingUploadsBody": "Files that haven’t been uploaded will be removed from this queue. Files already uploaded will stay in Locker.",
+ "keepEditing": "Keep editing",
"refresh": "Refresh",
"saveToLocker": "Save to Locker",
"informationDescription": "Save and share information with loved ones.",
diff --git a/web/apps/locker/tests/unsaved-changes.test.ts b/web/apps/locker/tests/unsaved-changes.test.ts
new file mode 100644
index 0000000000..53a752f500
--- /dev/null
+++ b/web/apps/locker/tests/unsaved-changes.test.ts
@@ -0,0 +1,127 @@
+import { describe, expect, test } from "vitest";
+import { uploadQueueItemKey } from "../src/components/create-item/file-upload-helpers";
+import {
+ hasPendingUploads,
+ hasUnsavedItemChanges,
+} from "../src/components/create-item/unsaved-changes";
+import type { LockerUploadCandidate } from "../src/types";
+
+describe("unsaved item changes", () => {
+ test("an empty new form and its default collection are clean", () => {
+ expect(hasUnsavedItemChanges({}, {}, [1], [1], "")).toBe(false);
+ expect(
+ hasUnsavedItemChanges({ title: "", content: "" }, {}, [], [], ""),
+ ).toBe(false);
+ });
+
+ test.each<Record<string, string>>([
+ { title: "Incomplete note" },
+ { content: "My instructions" },
+ { password: "unsaved password" },
+ { location: "Spare key location" },
+ { contactDetails: "New contact details" },
+ { name: "Document title" },
+ ])(
+ "protects edits even when required fields are incomplete: %j",
+ (data) => {
+ expect(hasUnsavedItemChanges(data, {}, [], [], "")).toBe(true);
+ },
+ );
+
+ test("an unchanged existing item or reverted edit is clean", () => {
+ const initial = { title: "Title", content: "Content" };
+ expect(
+ hasUnsavedItemChanges(
+ { ...initial, notes: "" },
+ initial,
+ [2, 1],
+ [1, 2],
+ "",
+ ),
+ ).toBe(false);
+ expect(
+ hasUnsavedItemChanges(
+ { ...initial, content: "Changed" },
+ initial,
+ [1],
+ [1],
+ "",
+ ),
+ ).toBe(true);
+ expect(
+ hasUnsavedItemChanges({ ...initial }, initial, [1], [1], ""),
+ ).toBe(false);
+ });
+
+ test("clearing an existing field or changing whitespace is an edit", () => {
+ expect(
+ hasUnsavedItemChanges({}, { name: "Original" }, [], [], ""),
+ ).toBe(true);
+ expect(hasUnsavedItemChanges({ content: " " }, {}, [], [], "")).toBe(
+ true,
+ );
+ expect(
+ hasUnsavedItemChanges(
+ { content: "Text " },
+ { content: "Text" },
+ [],
+ [],
+ "",
+ ),
+ ).toBe(true);
+ });
+
+ test("collection membership changes count, but order and duplicates do not", () => {
+ expect(hasUnsavedItemChanges({}, {}, [2], [1], "")).toBe(true);
+ expect(hasUnsavedItemChanges({}, {}, [], [1], "")).toBe(true);
+ expect(hasUnsavedItemChanges({}, {}, [1, 2], [1], "")).toBe(true);
+ expect(hasUnsavedItemChanges({}, {}, [2, 1, 1], [1, 2], "")).toBe(
+ false,
+ );
+ });
+
+ test("an unfinished collection name is protected until cleared", () => {
+ expect(hasUnsavedItemChanges({}, {}, [], [], "New collection")).toBe(
+ true,
+ );
+ expect(hasUnsavedItemChanges({}, {}, [], [], "")).toBe(false);
+ });
+});
+
+describe("pending uploads", () => {
+ const first: LockerUploadCandidate = {
+ file: new File(["First"], "first.txt"),
+ suggestedCollectionNames: [],
+ };
+ const second: LockerUploadCandidate = {
+ file: new File(["Second"], "second.txt"),
+ suggestedCollectionNames: ["Documents"],
+ };
+
+ test("an empty queue is clean", () => {
+ expect(hasPendingUploads([], new Set())).toBe(false);
+ });
+
+ test("selected or prefilled files need confirmation before any upload", () => {
+ expect(hasPendingUploads([first], new Set())).toBe(true);
+ });
+
+ test("a partial upload with pending or failed files remains protected", () => {
+ expect(
+ hasPendingUploads(
+ [first, second],
+ new Set([uploadQueueItemKey(first)]),
+ ),
+ ).toBe(true);
+ });
+
+ test("completed files alone are clean, including after removing failed files", () => {
+ const completed = new Set([
+ uploadQueueItemKey(first),
+ uploadQueueItemKey(second),
+ ]);
+ expect(hasPendingUploads([first, second], completed)).toBe(false);
+ expect(hasPendingUploads([first], completed)).toBe(false);
+ expect(hasPendingUploads([], completed)).toBe(false);
+ });
+});