Skip to content

armgit / ente

Public Imported from GitHub
0

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

Nested items

vishnukvmd4bc22f4d867e
diff --git a/web/apps/locker/src/components/CreateItemDialog.tsx b/web/apps/locker/src/components/CreateItemDialog.tsx
index a05b33a0b7..edd4657f2d 100644
--- a/web/apps/locker/src/components/CreateItemDialog.tsx
+++ b/web/apps/locker/src/components/CreateItemDialog.tsx
@@ -1,8 +1,5 @@
import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
import ChevronRightRoundedIcon from "@mui/icons-material/ChevronRightRounded";
-import CloudUploadOutlinedIcon from "@mui/icons-material/CloudUploadOutlined";
-import ErrorOutlineRoundedIcon from "@mui/icons-material/ErrorOutlineRounded";
-import ScheduleRoundedIcon from "@mui/icons-material/ScheduleRounded";
import VisibilityIcon from "@mui/icons-material/Visibility";
import VisibilityOffIcon from "@mui/icons-material/VisibilityOff";
import {
@@ -13,11 +10,19 @@ import {
DialogTitle,
IconButton,
InputAdornment,
- LinearProgress,
Stack,
TextField,
Typography,
} from "@mui/material";
+import { FileUploadSection } from "components/createItemDialog/FileUploadSection";
+import {
+ addCollectionName,
+ collectionNamesByUploadItem,
+ dedupeCollectionNames,
+ normalizeCollectionName,
+ toggleCollectionName,
+ uploadQueueItemKey,
+} from "components/createItemDialog/fileUploadHelpers";
import { lockerDialogPaperSx } from "components/lockerDialogStyles";
import {
createDocumentIcon,
@@ -39,7 +44,11 @@ import React, {
} from "react";
import { formatLockerMutationError } from "services/locker-errors";
import type { LockerUploadProgress } from "services/remote";
-import type { LockerCollection, LockerItemType } from "types";
+import type {
+ LockerCollection,
+ LockerItemType,
+ LockerUploadCandidate,
+} from "types";
import { isCollectionOwner, visibleLockerCollections } from "types";
type CreateOption = LockerItemType | "file";
@@ -106,8 +115,11 @@ interface CreateItemDialogProps {
onUploadItemComplete?: () => void;
onUploadsFinished?: (uploadedCount: number) => Promise<void>;
onCreateCollection?: (name: string) => Promise<number>;
+ onEnsureCollections?: (
+ names: string[],
+ ) => Promise<Map<string, number> | Record<string, number>>;
defaultCollectionID?: number | null;
- initialFiles?: File[];
+ initialItems?: LockerUploadCandidate[];
editItem?: {
id: number;
type: LockerItemType;
@@ -116,6 +128,24 @@ interface CreateItemDialogProps {
} | null;
}
+interface UploadState {
+ completedFileKeys: Set<string>;
+ failedFileKeys: Set<string>;
+ uploadingFileKeys: Set<string>;
+ uploadProgressByFileKey: Record<string, LockerUploadProgress | null>;
+ uploadCapByFileKey: Record<string, number>;
+ finalizingStartedAtByFileKey: Record<string, number>;
+}
+
+const emptyUploadState = (): UploadState => ({
+ completedFileKeys: new Set(),
+ failedFileKeys: new Set(),
+ uploadingFileKeys: new Set(),
+ uploadProgressByFileKey: {},
+ uploadCapByFileKey: {},
+ finalizingStartedAtByFileKey: {},
+});
+
export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
open,
onClose,
@@ -125,8 +155,9 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
onUploadItemComplete,
onUploadsFinished,
onCreateCollection,
+ onEnsureCollections,
defaultCollectionID,
- initialFiles,
+ initialItems,
editItem,
}) => {
const isEditMode = !!editItem;
@@ -152,7 +183,13 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
editItem ? (editItem.data as Record<string, string>) : {},
);
const [showPassword, setShowPassword] = useState(false);
- const [selectedFiles, setSelectedFiles] = useState<File[]>([]);
+ const [selectedUploadItems, setSelectedUploadItems] = useState<
+ LockerUploadCandidate[]
+ >([]);
+ const [
+ selectedCollectionNamesByFileKey,
+ setSelectedCollectionNamesByFileKey,
+ ] = useState<Record<string, string[]>>({});
const [completedFileKeys, setCompletedFileKeys] = useState<Set<string>>(
() => new Set(),
);
@@ -194,14 +231,30 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
[],
);
+ const resetUploadState = useCallback(() => {
+ const nextState = emptyUploadState();
+ setCompletedFileKeys(nextState.completedFileKeys);
+ setFailedFileKeys(nextState.failedFileKeys);
+ setUploadingFileKeys(nextState.uploadingFileKeys);
+ setUploadProgressByFileKey(nextState.uploadProgressByFileKey);
+ setUploadCapByFileKey(nextState.uploadCapByFileKey);
+ setFinalizingStartedAtByFileKey(nextState.finalizingStartedAtByFileKey);
+ }, []);
+
useEffect(() => {
if (!open) {
return;
}
setSelectedOption(
- editItem?.type ?? (initialFiles?.length ? "file" : null),
+ editItem?.type ?? (initialItems?.length ? "file" : null),
);
+ const defaultCollectionName =
+ defaultCollectionID !== null && defaultCollectionID !== undefined
+ ? displayCollectionsRef.current.find(
+ (collection) => collection.id === defaultCollectionID,
+ )?.name
+ : undefined;
setSelectedCollectionIDs(
isEditMode
? editCollectionID
@@ -216,22 +269,24 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
);
setFormData(editItem ? (editItem.data as Record<string, string>) : {});
setShowPassword(false);
- setSelectedFiles(initialFiles ?? []);
- setCompletedFileKeys(new Set());
- setFailedFileKeys(new Set());
- setUploadingFileKeys(new Set());
+ setSelectedUploadItems(initialItems ?? []);
+ setSelectedCollectionNamesByFileKey(
+ collectionNamesByUploadItem(
+ initialItems ?? [],
+ defaultCollectionName,
+ ),
+ );
+ resetUploadState();
setError(null);
- setUploadProgressByFileKey({});
- setUploadCapByFileKey({});
- setFinalizingStartedAtByFileKey({});
}, [
defaultCollectionID,
editCollectionID,
editItem,
- initialFiles,
+ initialItems,
isEditMode,
normalizeSelectedCollectionIDs,
open,
+ resetUploadState,
]);
useEffect(() => {
@@ -275,28 +330,23 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
setError(null);
setShowPassword(false);
- setSelectedFiles([]);
- setCompletedFileKeys(new Set());
- setFailedFileKeys(new Set());
- setUploadingFileKeys(new Set());
- setUploadProgressByFileKey({});
- setUploadCapByFileKey({});
- setFinalizingStartedAtByFileKey({});
+ setSelectedUploadItems([]);
+ setSelectedCollectionNamesByFileKey({});
+ resetUploadState();
onClose();
- }, [onClose, saving, uploading]);
+ }, [onClose, resetUploadState, saving, uploading]);
- const handleSelectOption = useCallback((option: CreateOption) => {
- setSelectedOption(option);
- setFormData({});
- setSelectedFiles([]);
- setCompletedFileKeys(new Set());
- setFailedFileKeys(new Set());
- setUploadingFileKeys(new Set());
- setUploadProgressByFileKey({});
- setUploadCapByFileKey({});
- setFinalizingStartedAtByFileKey({});
- setError(null);
- }, []);
+ const handleSelectOption = useCallback(
+ (option: CreateOption) => {
+ setSelectedOption(option);
+ setFormData({});
+ setSelectedUploadItems([]);
+ setSelectedCollectionNamesByFileKey({});
+ resetUploadState();
+ setError(null);
+ },
+ [resetUploadState],
+ );
const handleFieldChange = useCallback((field: string, value: string) => {
setFormData((previous) => ({ ...previous, [field]: value }));
@@ -307,17 +357,26 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
(event: React.ChangeEvent<HTMLInputElement>) => {
const files = Array.from(event.target.files ?? []);
if (files.length > 0) {
- setSelectedFiles(files);
- setCompletedFileKeys(new Set());
- setFailedFileKeys(new Set());
- setUploadingFileKeys(new Set());
- setUploadProgressByFileKey({});
- setUploadCapByFileKey({});
- setFinalizingStartedAtByFileKey({});
+ const defaultCollectionName =
+ selectedCollectionIDs.length > 0
+ ? displayCollectionsRef.current.find((collection) =>
+ selectedCollectionIDs.includes(collection.id),
+ )?.name
+ : undefined;
+ const items = files.map((file) => ({
+ file,
+ relativePath: file.webkitRelativePath || file.name,
+ suggestedCollectionNames: [],
+ }));
+ setSelectedUploadItems(items);
+ setSelectedCollectionNamesByFileKey(
+ collectionNamesByUploadItem(items, defaultCollectionName),
+ );
+ resetUploadState();
setError(null);
}
},
- [],
+ [resetUploadState, selectedCollectionIDs],
);
const handleSave = useCallback(async () => {
@@ -351,34 +410,69 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
}, [formData, handleClose, onSave, selectedCollectionIDs, selectedType]);
const handleUpload = useCallback(async () => {
- if (
- selectedFiles.length === 0 ||
- selectedCollectionIDs.length === 0 ||
- !onUploadProgress
- ) {
+ if (selectedUploadItems.length === 0 || !onUploadProgress) {
return;
}
setUploading(true);
setError(null);
- setCompletedFileKeys(new Set());
- setFailedFileKeys(new Set());
- setUploadingFileKeys(new Set());
- setUploadProgressByFileKey({});
- setUploadCapByFileKey({});
- setFinalizingStartedAtByFileKey({});
+ resetUploadState();
let uploadedCount = 0;
try {
+ const existingNormalizedNameToID = new Map(
+ displayCollections.map((collection) => [
+ normalizeCollectionName(collection.name),
+ collection.id,
+ ]),
+ );
+ const normalizedNameToIDResult = await onEnsureCollections?.(
+ dedupeCollectionNames(
+ Object.values(selectedCollectionNamesByFileKey).flat(),
+ ),
+ );
+ const normalizedNameToID = new Map(existingNormalizedNameToID);
+ if (normalizedNameToIDResult instanceof Map) {
+ for (const [name, id] of normalizedNameToIDResult.entries()) {
+ normalizedNameToID.set(normalizeCollectionName(name), id);
+ }
+ } else {
+ for (const [name, id] of Object.entries(
+ normalizedNameToIDResult ?? {},
+ )) {
+ normalizedNameToID.set(normalizeCollectionName(name), id);
+ }
+ }
+ const uploadTargets = selectedUploadItems.map((item) => {
+ const fileKey = uploadQueueItemKey(item);
+ const collectionIDs = dedupeCollectionNames(
+ selectedCollectionNamesByFileKey[fileKey] ?? [],
+ )
+ .map((name) =>
+ normalizedNameToID.get(normalizeCollectionName(name)),
+ )
+ .filter((id): id is number => typeof id === "number");
+ return { item, fileKey, collectionIDs };
+ });
+
+ if (
+ uploadTargets.some(
+ ({ collectionIDs }) => collectionIDs.length === 0,
+ )
+ ) {
+ setError(t("required_field"));
+ return;
+ }
+
let nextIndex = 0;
const worker = async () => {
while (true) {
- const file = selectedFiles[nextIndex];
+ const target = uploadTargets[nextIndex];
nextIndex += 1;
- if (!file) {
+ if (!target) {
return;
}
- const fileKey = uploadQueueItemKey(file);
+ const { item, fileKey, collectionIDs } = target;
setUploadingFileKeys((current) =>
new Set(current).add(fileKey),
);
@@ -393,8 +487,8 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
try {
await onUploadProgress(
- file,
- selectedCollectionIDs,
+ item.file,
+ collectionIDs,
(progress) => {
if (progress.phase === "finalizing") {
setFinalizingStartedAtByFileKey(
@@ -447,7 +541,7 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
Array.from({
length: Math.min(
MAX_PARALLEL_UPLOADS,
- selectedFiles.length,
+ selectedUploadItems.length,
),
}).map(() => worker()),
);
@@ -455,7 +549,7 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
if (uploadedCount > 0) {
await onUploadsFinished?.(uploadedCount);
}
- if (uploadedCount === selectedFiles.length) {
+ if (uploadedCount === selectedUploadItems.length) {
handleClose();
}
} catch (error) {
@@ -466,11 +560,14 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
}
}, [
handleClose,
+ displayCollections,
+ onEnsureCollections,
onUploadProgress,
onUploadItemComplete,
onUploadsFinished,
- selectedCollectionIDs,
- selectedFiles,
+ resetUploadState,
+ selectedCollectionNamesByFileKey,
+ selectedUploadItems,
]);
const canSave =
@@ -482,9 +579,14 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
const canUpload =
isFileMode &&
- selectedCollectionIDs.length > 0 &&
- selectedFiles.length > 0 &&
- completedFileKeys.size + failedFileKeys.size !== selectedFiles.length;
+ selectedUploadItems.length > 0 &&
+ selectedUploadItems.every(
+ (item) =>
+ (selectedCollectionNamesByFileKey[uploadQueueItemKey(item)]
+ ?.length ?? 0) > 0,
+ ) &&
+ completedFileKeys.size + failedFileKeys.size !==
+ selectedUploadItems.length;
return (
<Dialog
@@ -513,7 +615,9 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
{isEditMode
? t("editItem")
: isFileMode
- ? t("saveDocumentTitle")
+ ? selectedUploadItems.length > 1
+ ? t("saveDocumentsTitle")
+ : t("saveDocumentTitle")
: selectedType
? typeDisplayName(selectedType)
: t("saveToLocker")}
@@ -545,259 +649,72 @@ export const CreateItemDialog: React.FC<CreateItemDialogProps> = ({
)}
{isFileMode && (
- <Stack sx={{ gap: 2.5, pt: 0.5 }}>
- <input
- ref={fileInputRef}
- type="file"
- multiple
- hidden
- onChange={handleFileSelect}
- />
-
- {selectedFiles.length === 0 ? (
- <ButtonBase
- onClick={() => fileInputRef.current?.click()}
- sx={(theme) => ({
- display: "flex",
- flexDirection: "column",
- alignItems: "center",
- gap: 1.5,
- p: 4,
- borderRadius: "16px",
- border: `2px dashed ${theme.vars.palette.divider}`,
- backgroundColor:
- theme.vars.palette.fill.faint,
- transition: "background-color 0.15s",
- "&:hover": {
- backgroundColor:
- theme.vars.palette.fill.faintHover,
- },
- })}
- >
- <CloudUploadOutlinedIcon
- sx={{ fontSize: 40, color: "text.faint" }}
- />
- <Typography
- variant="body"
- sx={{ color: "text.muted" }}
- >
- {t("clickHereToUpload")}
- </Typography>
- </ButtonBase>
- ) : (
- <Stack sx={{ gap: 1.25 }}>
- {selectedFiles.map((file) => {
- const fileKey = uploadQueueItemKey(file);
- const isDone =
- completedFileKeys.has(fileKey);
- const isFailed =
- failedFileKeys.has(fileKey);
- const isUploading =
- uploadingFileKeys.has(fileKey);
- const isQueued =
- !isDone &&
- !isFailed &&
- !isUploading &&
- uploading;
- const uploadProgress =
- uploadProgressByFileKey[fileKey];
- const uploadCap =
- uploadCapByFileKey[fileKey] ?? 95;
- const finalizingStartedAt =
- finalizingStartedAtByFileKey[fileKey];
- return (
- <Stack
- key={fileKey}
- sx={{
- borderRadius: "12px",
- backgroundColor: (theme) =>
- theme.vars.palette.fill
- .faint,
- overflow: "hidden",
- }}
- >
- <Stack
- direction="row"
- sx={{
- alignItems: "center",
- gap: 1.5,
- p: 2,
- }}
- >
- <Box
- sx={{
- display: "flex",
- alignItems: "center",
- justifyContent:
- "center",
- width: 48,
- height: 48,
- borderRadius: "12px",
- backgroundColor:
- lockerItemIconConfig(
- "file",
- file.name,
- ).backgroundColor,
- flexShrink: 0,
- }}
- >
- {lockerItemIcon("file", {
- fileName: file.name,
- size: 24,
- strokeWidth: 1.9,
- })}
- </Box>
- <Box
- sx={{
- flex: 1,
- minWidth: 0,
- }}
- >
- <Typography
- variant="body"
- noWrap
- >
- {file.name}
- </Typography>
- <Typography
- variant="small"
- sx={{
- color: "text.faint",
- }}
- >
- {formatFileSize(
- file.size,
- )}
- </Typography>
- </Box>
- {isDone && (
- <Box
- sx={(theme) => ({
- width: 24,
- height: 24,
- borderRadius: "50%",
- display: "flex",
- alignItems:
- "center",
- justifyContent:
- "center",
- backgroundColor:
- theme.vars
- .palette
- .primary
- .main,
- color: theme.vars
- .palette.primary
- .contrastText,
- flexShrink: 0,
- })}
- >
- <CheckRoundedIcon
- sx={{
- fontSize: 16,
- }}
- />
- </Box>
- )}
- {isFailed && (
- <ErrorOutlineRoundedIcon
- sx={{
- color: "critical.main",
- fontSize: 20,
- flexShrink: 0,
- }}
- />
- )}
- {isQueued && (
- <ScheduleRoundedIcon
- sx={{
- color: "text.muted",
- fontSize: 20,
- flexShrink: 0,
- }}
- />
- )}
- </Stack>
- <Box sx={{ height: 4 }}>
- <LinearProgress
- variant="determinate"
- value={
- isUploading
- ? uploadProgressValue(
- uploadProgress,
- uploadCap,
- finalizingStartedAt,
- progressTick,
- )
- : isDone
- ? 100
- : 0
- }
- sx={{
- height: 4,
- borderRadius: 0,
- opacity:
- isUploading ||
- isDone
- ? 1
- : 0,
- }}
- />
- </Box>
- </Stack>
- );
- })}
- </Stack>
- )}
-
- {!isEditMode && (
- <CollectionSelector
- collections={displayCollections}
- selectedIDs={selectedCollectionIDs}
- onToggle={(collectionID) =>
- setSelectedCollectionIDs((current) =>
- current.includes(collectionID)
- ? current.filter(
- (id) => id !== collectionID,
- )
- : [...current, collectionID],
- )
- }
- onCreateCollection={onCreateCollection}
- />
- )}
-
- {error && (
- <Typography
- variant="small"
- sx={{ color: "critical.main" }}
- >
- {error}
- </Typography>
- )}
-
- <Stack direction="row" sx={{ gap: 1, pt: 1 }}>
- <FocusVisibleButton
- fullWidth
- color="secondary"
- onClick={handleClose}
- disabled={uploading}
- sx={{ borderRadius: "16px", py: 1.25 }}
- >
- {t("cancel")}
- </FocusVisibleButton>
- <LoadingButton
- fullWidth
- color="accent"
- loading={uploading}
- disabled={!canUpload}
- sx={{ borderRadius: "16px", py: 1.25 }}
- onClick={() => void handleUpload()}
- >
- {t("upload")}
- </LoadingButton>
- </Stack>
- </Stack>
+ <FileUploadSection
+ fileInputRef={fileInputRef}
+ selectedUploadItems={selectedUploadItems}
+ collections={displayCollections}
+ selectedCollectionNamesByFileKey={
+ selectedCollectionNamesByFileKey
+ }
+ completedFileKeys={completedFileKeys}
+ failedFileKeys={failedFileKeys}
+ uploadingFileKeys={uploadingFileKeys}
+ uploadProgressByFileKey={uploadProgressByFileKey}
+ uploadCapByFileKey={uploadCapByFileKey}
+ finalizingStartedAtByFileKey={
+ finalizingStartedAtByFileKey
+ }
+ progressTick={progressTick}
+ uploading={uploading}
+ error={error}
+ canUpload={canUpload}
+ onFileSelect={handleFileSelect}
+ onToggleCollectionName={(fileKey, name) =>
+ setSelectedCollectionNamesByFileKey((current) => ({
+ ...current,
+ [fileKey]: toggleCollectionName(
+ current[fileKey] ?? [],
+ name,
+ ),
+ }))
+ }
+ onAddCollectionName={(fileKey, name) =>
+ setSelectedCollectionNamesByFileKey((current) => ({
+ ...current,
+ [fileKey]: addCollectionName(
+ current[fileKey] ?? [],
+ 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,
+ ),
+ ),
+ );
+ }}
+ onClose={handleClose}
+ onUpload={handleUpload}
+ />
)}
{selectedType && (
@@ -1130,40 +1047,6 @@ const typeDisplayName = (type: LockerItemType): string => {
}
};
-const uploadQueueItemKey = (file: File) =>
- `${file.name}:${file.size}:${file.lastModified}`;
-
-const uploadProgressValue = (
- progress: LockerUploadProgress | null | undefined,
- uploadCap: number,
- finalizingStartedAt?: number,
- now = Date.now(),
-) => {
- if (!progress) {
- return 0;
- }
-
- if (progress.phase === "uploading") {
- return Math.min(
- uploadCap,
- (progress.loaded / Math.max(progress.total, 1)) * uploadCap,
- );
- }
-
- if (progress.phase === "finalizing") {
- const start = finalizingStartedAt ?? now;
- const elapsed = Math.max(0, now - start);
- const finalTarget = 99;
- const easedFraction = 1 - Math.exp(-elapsed / 2200);
- return Math.min(
- finalTarget,
- uploadCap + (finalTarget - uploadCap) * easedFraction,
- );
- }
-
- return 0;
-};
-
const CollectionSelector: React.FC<{
collections: LockerCollection[];
selectedIDs: number[];
@@ -1339,16 +1222,3 @@ const CollectionSelector: React.FC<{
</Box>
);
};
-
-const formatFileSize = (bytes: number) => {
- if (bytes < 1024) {
- return `${bytes} B`;
- }
- if (bytes < 1024 * 1024) {
- return `${(bytes / 1024).toFixed(1)} KB`;
- }
- if (bytes < 1024 * 1024 * 1024) {
- return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
- }
- return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
-};
diff --git a/web/apps/locker/src/components/createItemDialog/FileUploadSection.tsx b/web/apps/locker/src/components/createItemDialog/FileUploadSection.tsx
new file mode 100644
index 0000000000..faaed49094
--- /dev/null
+++ b/web/apps/locker/src/components/createItemDialog/FileUploadSection.tsx
@@ -0,0 +1,594 @@
+import CheckRoundedIcon from "@mui/icons-material/CheckRounded";
+import CloudUploadOutlinedIcon from "@mui/icons-material/CloudUploadOutlined";
+import DeleteOutlineRoundedIcon from "@mui/icons-material/DeleteOutlineRounded";
+import ErrorOutlineRoundedIcon from "@mui/icons-material/ErrorOutlineRounded";
+import ScheduleRoundedIcon from "@mui/icons-material/ScheduleRounded";
+import {
+ Box,
+ ButtonBase,
+ IconButton,
+ LinearProgress,
+ Stack,
+ TextField,
+ Typography,
+} from "@mui/material";
+import {
+ lockerItemIcon,
+ lockerItemIconConfig,
+} from "components/lockerItemIcons";
+import { FocusVisibleButton } from "ente-base/components/mui/FocusVisibleButton";
+import { LoadingButton } from "ente-base/components/mui/LoadingButton";
+import { t } from "i18next";
+import React, { useCallback, useMemo, useState } from "react";
+import type { LockerUploadProgress } from "services/remote";
+import type { LockerCollection, LockerUploadCandidate } from "types";
+
+import {
+ addCollectionName,
+ dedupeCollectionNames,
+ formatFileSize,
+ normalizeCollectionName,
+ toggleCollectionName,
+ uploadItemParentPath,
+ uploadProgressValue,
+ uploadQueueItemKey,
+} from "./fileUploadHelpers";
+
+interface FileUploadSectionProps {
+ fileInputRef: React.RefObject<HTMLInputElement | null>;
+ selectedUploadItems: LockerUploadCandidate[];
+ collections: LockerCollection[];
+ selectedCollectionNamesByFileKey: Record<string, string[]>;
+ completedFileKeys: Set<string>;
+ failedFileKeys: Set<string>;
+ uploadingFileKeys: Set<string>;
+ uploadProgressByFileKey: Record<string, LockerUploadProgress | null>;
+ uploadCapByFileKey: Record<string, number>;
+ finalizingStartedAtByFileKey: Record<string, number>;
+ progressTick: number;
+ uploading: boolean;
+ error: string | null;
+ canUpload: boolean;
+ onFileSelect: (event: React.ChangeEvent<HTMLInputElement>) => void;
+ onToggleCollectionName: (fileKey: string, name: string) => void;
+ onAddCollectionName: (fileKey: string, name: string) => void;
+ onSetCollectionNamesForAllItems: (names: string[]) => void;
+ onRemoveItem: (fileKey: string) => void;
+ onClose: () => void;
+ onUpload: () => Promise<void>;
+}
+
+export function FileUploadSection({
+ fileInputRef,
+ selectedUploadItems,
+ collections,
+ selectedCollectionNamesByFileKey,
+ completedFileKeys,
+ failedFileKeys,
+ uploadingFileKeys,
+ uploadProgressByFileKey,
+ uploadCapByFileKey,
+ finalizingStartedAtByFileKey,
+ progressTick,
+ uploading,
+ error,
+ canUpload,
+ onFileSelect,
+ onToggleCollectionName,
+ onAddCollectionName,
+ onSetCollectionNamesForAllItems,
+ onRemoveItem,
+ onClose,
+ onUpload,
+}: FileUploadSectionProps) {
+ const shouldShowPerItemCollectionSelector = useMemo(() => {
+ const uniqueParentPaths = new Set(
+ selectedUploadItems.map(uploadItemParentPath),
+ );
+ return uniqueParentPaths.size > 1;
+ }, [selectedUploadItems]);
+ const sharedSelectedCollectionNames =
+ selectedUploadItems.length > 0
+ ? (selectedCollectionNamesByFileKey[
+ uploadQueueItemKey(selectedUploadItems[0]!)
+ ] ?? [])
+ : [];
+ const sharedSuggestedCollectionNames = useMemo(
+ () =>
+ dedupeCollectionNames(
+ selectedUploadItems.flatMap(
+ (item) => item.suggestedCollectionNames,
+ ),
+ ),
+ [selectedUploadItems],
+ );
+
+ return (
+ <Stack sx={{ gap: 2.5, pt: 0.5 }}>
+ <input
+ ref={fileInputRef}
+ type="file"
+ multiple
+ hidden
+ onChange={onFileSelect}
+ />
+
+ {selectedUploadItems.length === 0 ? (
+ <ButtonBase
+ onClick={() => fileInputRef.current?.click()}
+ sx={(theme) => ({
+ display: "flex",
+ flexDirection: "column",
+ alignItems: "center",
+ gap: 1.5,
+ p: 4,
+ borderRadius: "16px",
+ border: `2px dashed ${theme.vars.palette.divider}`,
+ backgroundColor: theme.vars.palette.fill.faint,
+ transition: "background-color 0.15s",
+ "&:hover": {
+ backgroundColor: theme.vars.palette.fill.faintHover,
+ },
+ })}
+ >
+ <CloudUploadOutlinedIcon
+ sx={{ fontSize: 40, color: "text.faint" }}
+ />
+ <Typography variant="body" sx={{ color: "text.muted" }}>
+ {t("clickHereToUpload")}
+ </Typography>
+ </ButtonBase>
+ ) : (
+ <Stack sx={{ gap: 1.25 }}>
+ {selectedUploadItems.map((item) => {
+ const fileKey = uploadQueueItemKey(item);
+ return (
+ <UploadItemCard
+ key={fileKey}
+ item={item}
+ collections={collections}
+ selectedCollectionNames={
+ selectedCollectionNamesByFileKey[fileKey] ??
+ []
+ }
+ suggestedCollectionNames={
+ item.suggestedCollectionNames
+ }
+ showCollectionSelector={
+ shouldShowPerItemCollectionSelector
+ }
+ isDone={completedFileKeys.has(fileKey)}
+ isFailed={failedFileKeys.has(fileKey)}
+ isUploading={uploadingFileKeys.has(fileKey)}
+ isQueued={
+ !completedFileKeys.has(fileKey) &&
+ !failedFileKeys.has(fileKey) &&
+ !uploadingFileKeys.has(fileKey) &&
+ uploading
+ }
+ uploadProgress={
+ uploadProgressByFileKey[fileKey]
+ }
+ uploadCap={uploadCapByFileKey[fileKey] ?? 95}
+ finalizingStartedAt={
+ finalizingStartedAtByFileKey[fileKey]
+ }
+ progressTick={progressTick}
+ uploadInFlight={uploading}
+ onToggleCollectionName={(name) =>
+ onToggleCollectionName(fileKey, name)
+ }
+ onAddCollectionName={(name) =>
+ onAddCollectionName(fileKey, name)
+ }
+ canRemove={!uploading}
+ onRemove={() => onRemoveItem(fileKey)}
+ />
+ );
+ })}
+ </Stack>
+ )}
+
+ {!shouldShowPerItemCollectionSelector &&
+ selectedUploadItems.length > 0 && (
+ <CollectionNameSelector
+ collections={collections}
+ selectedNames={sharedSelectedCollectionNames}
+ suggestedNames={sharedSuggestedCollectionNames}
+ onToggleName={(name) =>
+ onSetCollectionNamesForAllItems(
+ toggleCollectionName(
+ sharedSelectedCollectionNames,
+ name,
+ ),
+ )
+ }
+ onAddCollectionName={(name) =>
+ onSetCollectionNamesForAllItems(
+ addCollectionName(
+ sharedSelectedCollectionNames,
+ name,
+ ),
+ )
+ }
+ disabled={uploading}
+ />
+ )}
+
+ {error && (
+ <Typography variant="small" sx={{ color: "critical.main" }}>
+ {error}
+ </Typography>
+ )}
+
+ <Stack direction="row" sx={{ gap: 1, pt: 1 }}>
+ <FocusVisibleButton
+ fullWidth
+ color="secondary"
+ onClick={onClose}
+ disabled={uploading}
+ sx={{ borderRadius: "16px", py: 1.25 }}
+ >
+ {t("cancel")}
+ </FocusVisibleButton>
+ <LoadingButton
+ fullWidth
+ color="accent"
+ loading={uploading}
+ disabled={!canUpload}
+ sx={{ borderRadius: "16px", py: 1.25 }}
+ onClick={() => void onUpload()}
+ >
+ {t("upload")}
+ </LoadingButton>
+ </Stack>
+ </Stack>
+ );
+}
+
+const UploadItemCard: React.FC<{
+ item: LockerUploadCandidate;
+ collections: LockerCollection[];
+ selectedCollectionNames: string[];
+ suggestedCollectionNames: string[];
+ showCollectionSelector: boolean;
+ isDone: boolean;
+ isFailed: boolean;
+ isUploading: boolean;
+ isQueued: boolean;
+ uploadProgress: LockerUploadProgress | null | undefined;
+ uploadCap: number;
+ finalizingStartedAt?: number;
+ progressTick: number;
+ uploadInFlight: boolean;
+ onToggleCollectionName: (name: string) => void;
+ onAddCollectionName: (name: string) => void;
+ canRemove: boolean;
+ onRemove: () => void;
+}> = ({
+ item,
+ collections,
+ selectedCollectionNames,
+ suggestedCollectionNames,
+ showCollectionSelector,
+ isDone,
+ isFailed,
+ isUploading,
+ isQueued,
+ uploadProgress,
+ uploadCap,
+ finalizingStartedAt,
+ progressTick,
+ uploadInFlight,
+ onToggleCollectionName,
+ onAddCollectionName,
+ canRemove,
+ onRemove,
+}) => (
+ <Stack
+ sx={{
+ borderRadius: "12px",
+ backgroundColor: (theme) => theme.vars.palette.fill.faint,
+ overflow: "hidden",
+ }}
+ >
+ <Stack
+ direction="row"
+ sx={{ alignItems: "center", gap: 1.5, p: 2, position: "relative" }}
+ >
+ <Box
+ sx={{
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ width: 48,
+ height: 48,
+ borderRadius: "12px",
+ backgroundColor: lockerItemIconConfig(
+ "file",
+ item.file.name,
+ ).backgroundColor,
+ flexShrink: 0,
+ }}
+ >
+ {lockerItemIcon("file", {
+ fileName: item.file.name,
+ size: 24,
+ strokeWidth: 1.9,
+ })}
+ </Box>
+ <Box sx={{ flex: 1, minWidth: 0, pr: canRemove ? 5 : 0 }}>
+ <Typography variant="body" noWrap>
+ {item.file.name}
+ </Typography>
+ <Typography variant="small" sx={{ color: "text.faint" }}>
+ {formatFileSize(item.file.size)}
+ </Typography>
+ </Box>
+ {isDone && (
+ <Box
+ sx={(theme) => ({
+ width: 24,
+ height: 24,
+ borderRadius: "50%",
+ display: "flex",
+ alignItems: "center",
+ justifyContent: "center",
+ backgroundColor: theme.vars.palette.primary.main,
+ color: theme.vars.palette.primary.contrastText,
+ flexShrink: 0,
+ })}
+ >
+ <CheckRoundedIcon sx={{ fontSize: 16 }} />
+ </Box>
+ )}
+ {isFailed && (
+ <ErrorOutlineRoundedIcon
+ sx={{ color: "critical.main", fontSize: 20, flexShrink: 0 }}
+ />
+ )}
+ {isQueued && (
+ <ScheduleRoundedIcon
+ sx={{ color: "text.muted", fontSize: 20, flexShrink: 0 }}
+ />
+ )}
+ {canRemove && (
+ <IconButton
+ aria-label={t("delete")}
+ onClick={onRemove}
+ size="small"
+ sx={(theme) => ({
+ position: "absolute",
+ top: 12,
+ right: 12,
+ width: 30,
+ height: 30,
+ borderRadius: "10px",
+ backgroundColor: "transparent",
+ color: theme.vars.palette.text.muted,
+ flexShrink: 0,
+ "&:hover": {
+ backgroundColor: theme.vars.palette.fill.faintHover,
+ color: theme.vars.palette.text.base,
+ },
+ })}
+ >
+ <DeleteOutlineRoundedIcon sx={{ fontSize: 16 }} />
+ </IconButton>
+ )}
+ </Stack>
+ <Box sx={{ height: 4 }}>
+ <LinearProgress
+ variant="determinate"
+ value={
+ isUploading
+ ? uploadProgressValue(
+ uploadProgress,
+ uploadCap,
+ finalizingStartedAt,
+ progressTick,
+ )
+ : isDone
+ ? 100
+ : 0
+ }
+ sx={{
+ height: 4,
+ borderRadius: 0,
+ opacity: isUploading || isDone ? 1 : 0,
+ }}
+ />
+ </Box>
+ {showCollectionSelector && (
+ <Box sx={{ px: 2, pt: 1.5, pb: 2 }}>
+ <CollectionNameSelector
+ collections={collections}
+ selectedNames={selectedCollectionNames}
+ suggestedNames={suggestedCollectionNames}
+ onToggleName={onToggleCollectionName}
+ onAddCollectionName={onAddCollectionName}
+ disabled={uploadInFlight}
+ />
+ </Box>
+ )}
+ </Stack>
+);
+
+const CollectionNameSelector: React.FC<{
+ collections: LockerCollection[];
+ selectedNames: string[];
+ suggestedNames: string[];
+ onToggleName: (name: string) => void;
+ onAddCollectionName: (name: string) => void;
+ disabled?: boolean;
+}> = ({
+ collections,
+ selectedNames,
+ suggestedNames,
+ onToggleName,
+ onAddCollectionName,
+ disabled,
+}) => {
+ const [createOpen, setCreateOpen] = useState(false);
+ const [createName, setCreateName] = useState("");
+ const selectedNameMap = useMemo(
+ () =>
+ new Map(
+ selectedNames.map((name) => [
+ normalizeCollectionName(name),
+ name,
+ ]),
+ ),
+ [selectedNames],
+ );
+ const displayNames = useMemo(
+ () =>
+ dedupeCollectionNames([
+ ...collections.map((collection) => collection.name),
+ ...suggestedNames,
+ ...selectedNames,
+ ]),
+ [collections, selectedNames, suggestedNames],
+ );
+
+ const handleAddCollectionName = useCallback(() => {
+ const trimmedName = createName.trim();
+ if (!trimmedName) {
+ return;
+ }
+
+ onAddCollectionName(trimmedName);
+ setCreateName("");
+ setCreateOpen(false);
+ }, [createName, onAddCollectionName]);
+
+ return (
+ <Box>
+ <Stack
+ direction="row"
+ sx={{
+ alignItems: "center",
+ justifyContent: "space-between",
+ gap: 1,
+ mb: 1.25,
+ }}
+ >
+ <Typography
+ variant="small"
+ sx={{
+ color: "text.faint",
+ fontWeight: "bold",
+ textTransform: "uppercase",
+ letterSpacing: "0.08em",
+ display: "block",
+ }}
+ >
+ {t("collections")}
+ </Typography>
+ </Stack>
+
+ {displayNames.length > 0 ? (
+ <Stack direction="row" sx={{ gap: 1, flexWrap: "wrap" }}>
+ {displayNames.map((name) => {
+ const isSelected = selectedNameMap.has(
+ normalizeCollectionName(name),
+ );
+ return (
+ <ButtonBase
+ key={name}
+ onClick={() => onToggleName(name)}
+ disabled={disabled}
+ sx={(theme) => ({
+ borderRadius: "999px",
+ px: 1.5,
+ py: 0.875,
+ backgroundColor: isSelected
+ ? theme.vars.palette.primary.main
+ : theme.vars.palette.fill.faint,
+ color: isSelected
+ ? theme.vars.palette.primary
+ .contrastText
+ : theme.vars.palette.text.base,
+ })}
+ >
+ <Typography variant="small">{name}</Typography>
+ </ButtonBase>
+ );
+ })}
+ <ButtonBase
+ onClick={() => setCreateOpen((open) => !open)}
+ disabled={disabled}
+ sx={(theme) => ({
+ borderRadius: "999px",
+ px: 1.5,
+ py: 0.875,
+ border: `1px dotted ${theme.vars.palette.stroke.muted}`,
+ color: theme.vars.palette.text.muted,
+ backgroundColor: createOpen
+ ? theme.vars.palette.fill.faint
+ : "transparent",
+ })}
+ >
+ <Typography variant="small">
+ + {t("collection")}
+ </Typography>
+ </ButtonBase>
+ </Stack>
+ ) : (
+ <Typography variant="body" sx={{ color: "text.muted" }}>
+ {t("noCollectionsAvailableForSelection")}
+ </Typography>
+ )}
+
+ {createOpen && (
+ <Stack sx={{ gap: 1, mt: 1.25 }}>
+ <Stack
+ direction="row"
+ sx={{ gap: 1, alignItems: "center" }}
+ >
+ <TextField
+ size="small"
+ fullWidth
+ autoFocus
+ placeholder={t("enterCollectionName")}
+ sx={{
+ "& .MuiInputBase-root": {
+ height: 44,
+ borderRadius: "14px",
+ },
+ "& .MuiInputBase-input": { pt: 1, pb: 0.5 },
+ }}
+ value={createName}
+ onChange={(event) =>
+ setCreateName(event.target.value)
+ }
+ onKeyDown={(event) => {
+ if (event.key === "Enter") {
+ event.preventDefault();
+ handleAddCollectionName();
+ }
+ }}
+ disabled={disabled}
+ />
+ <LoadingButton
+ color="accent"
+ disabled={!createName.trim() || disabled}
+ aria-label={t("create")}
+ onClick={handleAddCollectionName}
+ sx={{
+ minWidth: 0,
+ width: 44,
+ height: 44,
+ p: 0,
+ borderRadius: "14px",
+ flexShrink: 0,
+ }}
+ >
+ <CheckRoundedIcon />
+ </LoadingButton>
+ </Stack>
+ </Stack>
+ )}
+ </Box>
+ );
+};
diff --git a/web/apps/locker/src/components/createItemDialog/fileUploadHelpers.ts b/web/apps/locker/src/components/createItemDialog/fileUploadHelpers.ts
new file mode 100644
index 0000000000..fb78144b34
--- /dev/null
+++ b/web/apps/locker/src/components/createItemDialog/fileUploadHelpers.ts
@@ -0,0 +1,106 @@
+import type { LockerUploadProgress } from "services/remote";
+import type { LockerUploadCandidate } from "types";
+
+export const normalizeCollectionName = (name: string) =>
+ name.trim().toLocaleLowerCase();
+
+export const dedupeCollectionNames = (names: string[]) => {
+ const seen = new Set<string>();
+ return names.filter((name) => {
+ const trimmedName = name.trim();
+ const normalizedName = normalizeCollectionName(trimmedName);
+ if (!normalizedName || seen.has(normalizedName)) {
+ return false;
+ }
+ seen.add(normalizedName);
+ return true;
+ });
+};
+
+export const addCollectionName = (names: string[], name: string) =>
+ dedupeCollectionNames([...names, name.trim()]);
+
+export const toggleCollectionName = (names: string[], name: string) => {
+ const normalizedName = normalizeCollectionName(name);
+ if (!normalizedName) {
+ return names;
+ }
+
+ return names.some(
+ (candidate) => normalizeCollectionName(candidate) === normalizedName,
+ )
+ ? names.filter(
+ (candidate) =>
+ normalizeCollectionName(candidate) !== normalizedName,
+ )
+ : addCollectionName(names, name);
+};
+
+export const uploadQueueItemKey = (item: LockerUploadCandidate) =>
+ `${item.relativePath ?? item.file.name}:${item.file.size}:${item.file.lastModified}`;
+
+export const uploadItemParentPath = (item: LockerUploadCandidate) => {
+ const segments = (item.relativePath ?? item.file.name)
+ .split("/")
+ .filter(Boolean);
+ return segments.slice(0, -1).join("/");
+};
+
+export const collectionNamesByUploadItem = (
+ items: LockerUploadCandidate[],
+ defaultCollectionName?: string,
+) =>
+ Object.fromEntries(
+ items.map((item) => [
+ uploadQueueItemKey(item),
+ item.suggestedCollectionNames.length > 0
+ ? dedupeCollectionNames(item.suggestedCollectionNames)
+ : defaultCollectionName
+ ? [defaultCollectionName]
+ : [],
+ ]),
+ );
+
+export const uploadProgressValue = (
+ progress: LockerUploadProgress | null | undefined,
+ uploadCap: number,
+ finalizingStartedAt?: number,
+ now = Date.now(),
+) => {
+ if (!progress) {
+ return 0;
+ }
+
+ if (progress.phase === "uploading") {
+ return Math.min(
+ uploadCap,
+ (progress.loaded / Math.max(progress.total, 1)) * uploadCap,
+ );
+ }
+
+ if (progress.phase === "finalizing") {
+ const start = finalizingStartedAt ?? now;
+ const elapsed = Math.max(0, now - start);
+ const finalTarget = 99;
+ const easedFraction = 1 - Math.exp(-elapsed / 2200);
+ return Math.min(
+ finalTarget,
+ uploadCap + (finalTarget - uploadCap) * easedFraction,
+ );
+ }
+
+ return 0;
+};
+
+export const formatFileSize = (bytes: number) => {
+ if (bytes < 1024) {
+ return `${bytes} B`;
+ }
+ if (bytes < 1024 * 1024) {
+ return `${(bytes / 1024).toFixed(1)} KB`;
+ }
+ if (bytes < 1024 * 1024 * 1024) {
+ return `${(bytes / (1024 * 1024)).toFixed(1)} MB`;
+ }
+ return `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`;
+};
diff --git a/web/apps/locker/src/locales/en-US/translation.json b/web/apps/locker/src/locales/en-US/translation.json
index 550a25fbd7..6c6c092b79 100644
--- a/web/apps/locker/src/locales/en-US/translation.json
+++ b/web/apps/locker/src/locales/en-US/translation.json
@@ -2,6 +2,7 @@
"saveToLocker": "Save to Locker",
"informationDescription": "Save and share information with loved ones.",
"saveDocumentTitle": "Document",
+ "saveDocumentsTitle": "Documents",
"saveDocumentDescription": "Upload important docs.",
"personalNote": "Note",
"personalNoteDescription": "Write down thoughts and instructions.",
diff --git a/web/apps/locker/src/locales/fr-FR/translation.json b/web/apps/locker/src/locales/fr-FR/translation.json
index ca39aba159..e7921f1f39 100644
--- a/web/apps/locker/src/locales/fr-FR/translation.json
+++ b/web/apps/locker/src/locales/fr-FR/translation.json
@@ -1,5 +1,6 @@
{
"saveToLocker": "Enregistrer dans Locker",
+ "saveDocumentsTitle": "Documents",
"informationDescription": "Enregistre et partage des informations avec tes proches.",
"saveDocumentDescription": "Televerse des documents importants.",
"personalNoteDescription": "Note tes pensees et instructions.",
diff --git a/web/apps/locker/src/locales/ja-JP/translation.json b/web/apps/locker/src/locales/ja-JP/translation.json
index 70f2cfcdb2..914e051ace 100644
--- a/web/apps/locker/src/locales/ja-JP/translation.json
+++ b/web/apps/locker/src/locales/ja-JP/translation.json
@@ -2,6 +2,7 @@
"saveToLocker": "Lockerに保存",
"informationDescription": "ε€§εˆ‡γͺδΊΊγ¨ζƒ…ε ±γ‚’δΏε­˜γƒ»ε…±ζœ‰γ—γΎγ™γ€‚",
"saveDocumentTitle": "ドキγƒ₯γƒ‘γƒ³γƒˆ",
+ "saveDocumentsTitle": "ドキγƒ₯γƒ‘γƒ³γƒˆ",
"saveDocumentDescription": "重要γͺドキγƒ₯γƒ‘γƒ³γƒˆγ‚’γ‚’γƒƒγƒ—γƒ­γƒΌγƒ‰γ—γΎγ™γ€‚",
"personalNote": "パヒ",
"personalNoteDescription": "θ€ƒγˆγ‚„ζŒ‡η€Ίγ‚’ζ›Έγη•™γ‚γΎγ™γ€‚",
diff --git a/web/apps/locker/src/pages/locker.tsx b/web/apps/locker/src/pages/locker.tsx
index c47bbdea62..00e583d166 100644
--- a/web/apps/locker/src/pages/locker.tsx
+++ b/web/apps/locker/src/pages/locker.tsx
@@ -46,7 +46,12 @@ import {
uploadLockerFile,
type LockerUploadProgress,
} from "services/remote";
-import type { LockerCollection, LockerItem, LockerItemType } from "types";
+import type {
+ LockerCollection,
+ LockerItem,
+ LockerItemType,
+ LockerUploadCandidate,
+} from "types";
import { getItemTitle } from "types";
/** Subset of /users/details/v2 we need for the sidebar. */
@@ -122,17 +127,44 @@ const readDirectoryEntries = (entry: FileSystemDirectoryEntry) =>
readBatch();
});
-const filesFromEntry = async (entry: FileSystemEntry): Promise<File[]> => {
+const collectionNamesFromRelativePath = (relativePath?: string) => [
+ ...new Set((relativePath?.split("/").slice(0, -1) ?? []).filter(Boolean)),
+];
+
+const uploadCandidateFromFile = (
+ file: File,
+ relativePath?: string,
+): LockerUploadCandidate => ({
+ file,
+ relativePath,
+ suggestedCollectionNames: collectionNamesFromRelativePath(relativePath),
+});
+
+const uploadCandidatesFromEntry = async (
+ entry: FileSystemEntry,
+ parentPath = "",
+): Promise<LockerUploadCandidate[]> => {
if (entry.isFile) {
- return [await fileFromEntry(entry as FileSystemFileEntry)];
+ const file = await fileFromEntry(entry as FileSystemFileEntry);
+ const relativePath = parentPath
+ ? `${parentPath}/${file.name}`
+ : file.name;
+ return [uploadCandidateFromFile(file, relativePath)];
}
if (entry.isDirectory) {
+ const directoryPath = parentPath
+ ? `${parentPath}/${entry.name}`
+ : entry.name;
const entries = await readDirectoryEntries(
entry as FileSystemDirectoryEntry,
);
- const files = await Promise.all(entries.map(filesFromEntry));
- return files.flat();
+ const items = await Promise.all(
+ entries.map((childEntry) =>
+ uploadCandidatesFromEntry(childEntry, directoryPath),
+ ),
+ );
+ return items.flat();
}
return [];
@@ -203,9 +235,9 @@ export const LockerPage: React.FC = () => {
// Create/Edit dialog state
const [createDialogOpen, setCreateDialogOpen] = useState(false);
- const [prefilledUploadFiles, setPrefilledUploadFiles] = useState<File[]>(
- [],
- );
+ const [prefilledUploadItems, setPrefilledUploadItems] = useState<
+ LockerUploadCandidate[]
+ >([]);
const [editItem, setEditItem] = useState<{
id: number;
type: LockerItemType;
@@ -666,18 +698,53 @@ export const LockerPage: React.FC = () => {
[masterKey, refreshData],
);
+ const ensureCollectionsExist = useCallback(
+ async (names: string[]) => {
+ if (!masterKey) throw new Error("No master key");
+
+ const normalizedNameToID = new Map(
+ collections.map((collection) => [
+ collection.name.trim().toLocaleLowerCase(),
+ collection.id,
+ ]),
+ );
+ let createdCollection = false;
+
+ for (const name of names) {
+ const normalizedName = name.trim().toLocaleLowerCase();
+ if (!normalizedName || normalizedNameToID.has(normalizedName)) {
+ continue;
+ }
+
+ const id = await createCollectionAPI(name, masterKey);
+ normalizedNameToID.set(normalizedName, id);
+ createdCollection = true;
+ }
+
+ if (createdCollection) {
+ await refreshData();
+ }
+
+ return normalizedNameToID;
+ },
+ [collections, masterKey, refreshData],
+ );
+
const handleCreateDialogClose = useCallback(() => {
setCreateDialogOpen(false);
- setPrefilledUploadFiles([]);
+ setPrefilledUploadItems([]);
}, []);
- const openUploadDialogForFiles = useCallback((files: File[]) => {
- setPrefilledUploadFiles(files);
- setCreateDialogOpen(true);
- }, []);
+ const openUploadDialogForItems = useCallback(
+ (items: LockerUploadCandidate[]) => {
+ setPrefilledUploadItems(items);
+ setCreateDialogOpen(true);
+ },
+ [],
+ );
const openCreateDialog = useCallback(() => {
- setPrefilledUploadFiles([]);
+ setPrefilledUploadItems([]);
setCreateDialogOpen(true);
}, []);
@@ -731,7 +798,7 @@ export const LockerPage: React.FC = () => {
const droppedItems = Array.from(
event.dataTransfer.items,
) as DragDataTransferItem[];
- const entryFiles = (
+ const entryItems = (
await Promise.all(
droppedItems
.filter((item) => item.kind === "file")
@@ -739,34 +806,49 @@ export const LockerPage: React.FC = () => {
const entry = item.webkitGetAsEntry();
if (!entry) {
const file = item.getAsFile();
- return file ? [file] : [];
+ return file
+ ? [
+ uploadCandidateFromFile(
+ file,
+ file.webkitRelativePath ||
+ file.name,
+ ),
+ ]
+ : [];
}
- return filesFromEntry(entry);
+ return uploadCandidatesFromEntry(entry);
}),
)
).flat();
- const droppedFiles =
- entryFiles.length > 0
- ? entryFiles
- : Array.from(event.dataTransfer.files);
- const uniqueFiles = droppedFiles.filter(
- (file, index, files) =>
- files.findIndex(
+ const droppedItemsList =
+ entryItems.length > 0
+ ? entryItems
+ : Array.from(event.dataTransfer.files).map((file) =>
+ uploadCandidateFromFile(
+ file,
+ file.webkitRelativePath || file.name,
+ ),
+ );
+ const uniqueItems = droppedItemsList.filter(
+ (item, index, items) =>
+ items.findIndex(
(candidate) =>
- candidate.name === file.name &&
- candidate.size === file.size &&
- candidate.lastModified === file.lastModified,
+ (candidate.relativePath ?? candidate.file.name) ===
+ (item.relativePath ?? item.file.name) &&
+ candidate.file.size === item.file.size &&
+ candidate.file.lastModified ===
+ item.file.lastModified,
) === index,
);
- if (uniqueFiles.length === 0) {
+ if (uniqueItems.length === 0) {
return;
}
- openUploadDialogForFiles(uniqueFiles);
+ openUploadDialogForItems(uniqueItems);
},
- [openUploadDialogForFiles],
+ [openUploadDialogForItems],
);
const handleRenameCollection = useCallback(
@@ -995,8 +1077,9 @@ export const LockerPage: React.FC = () => {
onUploadItemComplete={handleUploadItemComplete}
onUploadsFinished={handleUploadsFinished}
onCreateCollection={handleCreateCollection}
+ onEnsureCollections={ensureCollectionsExist}
defaultCollectionID={selectedCollectionID}
- initialFiles={prefilledUploadFiles}
+ initialItems={prefilledUploadItems}
/>
{/* Edit dialog */}
diff --git a/web/apps/locker/src/types.ts b/web/apps/locker/src/types.ts
index 4074627d1b..763a8aeb4b 100644
--- a/web/apps/locker/src/types.ts
+++ b/web/apps/locker/src/types.ts
@@ -127,6 +127,12 @@ export interface LockerCollection {
isShared: boolean;
}
+export interface LockerUploadCandidate {
+ file: File;
+ relativePath?: string;
+ suggestedCollectionNames: string[];
+}
+
const IMPORTANT_COLLECTION_TYPE = "favorites";
const UNCATEGORIZED_COLLECTION_TYPE = "uncategorized";