Skip to content

armgit / ente

Public Imported from GitHub
0

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

feat(photos):add-album-filename-sorting

Aswin Asok2e1b2a79187f
diff --git a/web/apps/albums/src/public-album/components/FileList.tsx b/web/apps/albums/src/public-album/components/FileList.tsx
index a7eb1cbfd8..ab3597a007 100644
--- a/web/apps/albums/src/public-album/components/FileList.tsx
+++ b/web/apps/albums/src/public-album/components/FileList.tsx
@@ -99,6 +99,7 @@ export interface FileListProps {
width: number;
annotatedFiles: FileListAnnotatedFile[];
layout?: "grid" | "masonry";
+ disableGrouping?: boolean;
header?: FileListHeaderOrFooter;
footer?: FileListHeaderOrFooter;
enableSelect?: boolean;
@@ -115,6 +116,7 @@ export const FileList: React.FC<FileListProps> = ({
height,
width,
layout = "grid",
+ disableGrouping,
header,
footer,
annotatedFiles,
@@ -205,34 +207,42 @@ export const FileList: React.FC<FileListProps> = ({
}
};
- const spaceBetweenDatesToImageContainerWidthRatio = 0.244;
-
- let pendingSplits = new Array<FileListAnnotatedFile[]>();
- for (const split of splitByDate(annotatedFiles)) {
- const filledColumns = pendingSplits.reduce(
- (a, s) => a + s.length,
- 0,
+ if (disableGrouping) {
+ items.push(
+ ...batch(annotatedFiles, columns).map((files) =>
+ createFileItem([files]),
+ ),
);
- const incomingColumns = split.length;
-
- if (
- !isSmallerLayout &&
- filledColumns +
- incomingColumns +
- Math.ceil(
- pendingSplits.length *
- spaceBetweenDatesToImageContainerWidthRatio,
- ) <=
- columns
- ) {
- pendingSplits.push(split);
- continue;
- }
+ } else {
+ const spaceBetweenDatesToImageContainerWidthRatio = 0.244;
+ let pendingSplits = new Array<FileListAnnotatedFile[]>();
+ for (const split of splitByDate(annotatedFiles)) {
+ const filledColumns = pendingSplits.reduce(
+ (a, s) => a + s.length,
+ 0,
+ );
+ const incomingColumns = split.length;
+
+ if (
+ !isSmallerLayout &&
+ filledColumns +
+ incomingColumns +
+ Math.ceil(
+ pendingSplits.length *
+ spaceBetweenDatesToImageContainerWidthRatio,
+ ) <=
+ columns
+ ) {
+ pendingSplits.push(split);
+ continue;
+ }
+
+ if (pendingSplits.length) pushItemsFromSplits(pendingSplits);
+ pendingSplits = [split];
+ }
if (pendingSplits.length) pushItemsFromSplits(pendingSplits);
- pendingSplits = [split];
}
- if (pendingSplits.length) pushItemsFromSplits(pendingSplits);
if (!annotatedFiles.length) {
items.push({
@@ -267,6 +277,7 @@ export const FileList: React.FC<FileListProps> = ({
footer,
annotatedFiles,
shouldUseMasonry,
+ disableGrouping,
layoutParams,
emptyStateAction,
]);
diff --git a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx b/web/apps/albums/src/public-album/components/FileListWithViewer.tsx
index 7a25beb035..42dd8377c8 100644
--- a/web/apps/albums/src/public-album/components/FileListWithViewer.tsx
+++ b/web/apps/albums/src/public-album/components/FileListWithViewer.tsx
@@ -33,6 +33,7 @@ export type FileListWithViewerProps = {
} & Pick<
FileListProps,
| "layout"
+ | "disableGrouping"
| "header"
| "footer"
| "enableSelect"
@@ -52,6 +53,7 @@ export type FileListWithViewerProps = {
export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
layout,
+ disableGrouping,
header,
footer,
files,
@@ -156,6 +158,7 @@ export const FileListWithViewer: React.FC<FileListWithViewerProps> = ({
{...{ width, height, annotatedFiles }}
{...{
layout,
+ disableGrouping,
header,
footer,
enableSelect,
diff --git a/web/apps/albums/src/public-album/media/utils/sort-files.ts b/web/apps/albums/src/public-album/media/utils/sort-files.ts
deleted file mode 100644
index ac09375a56..0000000000
--- a/web/apps/albums/src/public-album/media/utils/sort-files.ts
+++ /dev/null
@@ -1,22 +0,0 @@
-import type { EnteFile } from "ente-media/file";
-import { fileCreationPhotoSortTime } from "ente-media/file-metadata";
-
-export const sortFiles = (files: EnteFile[], sortAsc = false) => {
- const factor = sortAsc ? -1 : 1;
- const sortTimeByFile = new Map<EnteFile, number>();
- const sortTimeForFile = (file: EnteFile) => {
- const cached = sortTimeByFile.get(file);
- if (cached != undefined) return cached;
- const t = fileCreationPhotoSortTime(file);
- sortTimeByFile.set(file, t);
- return t;
- };
- return files.sort((a, b) => {
- const at = sortTimeForFile(a);
- const bt = sortTimeForFile(b);
- return at == bt
- ? factor *
- (b.metadata.modificationTime - a.metadata.modificationTime)
- : factor * (bt - at);
- });
-};
diff --git a/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx
index 9d79e2f3d5..338dce0c46 100644
--- a/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx
+++ b/web/apps/albums/src/public-album/page/PublicAlbumPage.tsx
@@ -19,7 +19,6 @@ import { setPublicAlbumsCredentials } from "@/public-album/data/auth/public-link
import { ActiveDownloadStatusNotifications } from "@/public-album/download/components/ActiveDownloadStatusNotifications";
import { downloadManager } from "@/public-album/download/services/download-manager";
import { thumbnailManager } from "@/public-album/media/thumbnails/thumbnail-manager";
-import { sortFiles } from "@/public-album/media/utils/sort-files";
import type { UploadProps } from "@/public-album/upload/components/Upload";
import {
getSelectedFiles,
@@ -71,6 +70,10 @@ import {
quickLinkDateRangeForFiles,
} from "ente-gallery/utils/quick-link";
import type { Collection } from "ente-media/collection";
+import {
+ collectionSortBy,
+ sortCollectionFiles,
+} from "ente-media/collection-sort";
import type { EnteFile } from "ente-media/file";
import { fileCreationTime, fileFileName } from "ente-media/file-metadata";
import { FileType } from "ente-media/file-type";
@@ -694,7 +697,13 @@ export default function PublicAlbumPage() {
);
}
- const layout = publicAlbumLayout;
+ const disableGrouping =
+ collectionSortBy(publicCollection?.pubMagicMetadata?.data) === "name";
+ // Trip sections group by date/location, which would break filename order.
+ const layout =
+ disableGrouping && publicAlbumLayout === "trip"
+ ? "masonry"
+ : publicAlbumLayout;
const quickLinkDateRange = quickLinkDateRangeForFiles(publicFiles);
const isSingleFileAlbum = publicFiles.length === 1;
const isQuickLinkAlbum =
@@ -787,6 +796,7 @@ export default function PublicAlbumPage() {
</NavbarBase>
<FileListWithViewer
files={publicFiles}
+ disableGrouping={disableGrouping}
layout={layout === "masonry" ? "masonry" : "grid"}
header={fileListHeader}
footer={fileListFooter}
@@ -861,7 +871,7 @@ export default function PublicAlbumPage() {
}
const sortFilesForCollection = (files: EnteFile[], collection?: Collection) =>
- sortFiles(files, collection?.pubMagicMetadata?.data.asc ?? false);
+ sortCollectionFiles(files, collection?.pubMagicMetadata?.data);
type PublicAlbumLayout = "masonry" | "grouped" | "trip";
diff --git a/web/apps/embed/src/pages/index.tsx b/web/apps/embed/src/pages/index.tsx
index 292d80b196..e14f24a36d 100644
--- a/web/apps/embed/src/pages/index.tsx
+++ b/web/apps/embed/src/pages/index.tsx
@@ -16,8 +16,8 @@ import log from "ente-base/log";
import { apiOrigin, isCustomAPIOrigin } from "ente-base/origins";
import { downloadManager } from "ente-gallery/services/download";
import { extractCollectionKeyFromShareURL } from "ente-gallery/services/share";
-import { sortFiles } from "ente-gallery/utils/file";
import type { Collection } from "ente-media/collection";
+import { sortCollectionFiles } from "ente-media/collection-sort";
import type { EnteFile } from "ente-media/file";
import { usePhotosAppContext } from "ente-new/photos/types/context";
import { t } from "i18next";
@@ -270,7 +270,7 @@ export default function EmbedGallery() {
}
const sortFilesForCollection = (files: EnteFile[], collection?: Collection) =>
- sortFiles(files, collection?.pubMagicMetadata?.data.asc ?? false);
+ sortCollectionFiles(files, collection?.pubMagicMetadata?.data);
const EmbedContainer = styled("div")({
width: "100%",
diff --git a/web/apps/photos/src/components/Collections/CollectionHeader.tsx b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
index 6fc0af57b1..e259d30c3a 100644
--- a/web/apps/photos/src/components/Collections/CollectionHeader.tsx
+++ b/web/apps/photos/src/components/Collections/CollectionHeader.tsx
@@ -41,6 +41,10 @@ import {
CollectionSubType,
type Collection,
} from "ente-media/collection";
+import {
+ collectionSortBy,
+ type CollectionSortBy,
+} from "ente-media/collection-sort";
import { ItemVisibility } from "ente-media/file-metadata";
import {
GalleryItemsHeaderAdapter,
@@ -417,15 +421,12 @@ const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({
await deleteShareURL(activeCollection.id);
});
- const changeSortOrderAsc = wrap(async () => {
- if (!activeCollection) return;
- await updateCollectionSortOrder(activeCollection, true);
- });
-
- const changeSortOrderDesc = wrap(async () => {
- if (!activeCollection) return;
- await updateCollectionSortOrder(activeCollection, false);
- });
+ const changeSortOrder = (sortBy: CollectionSortBy, asc: boolean) => {
+ wrap(async () => {
+ if (!activeCollection) return;
+ await updateCollectionSortOrder(activeCollection, asc, sortBy);
+ })();
+ };
let menuOptions: React.ReactNode[] = [];
// MUI rejects fragments here, so return keyed arrays.
@@ -717,8 +718,10 @@ const CollectionHeaderOptions: React.FC<CollectionHeaderProps> = ({
{...sortOrderMenuVisibilityProps}
overflowMenuIconRef={overflowMenuIconRef}
sortAsc={activeCollection?.pubMagicMetadata?.data.asc ?? false}
- onAscClick={changeSortOrderAsc}
- onDescClick={changeSortOrderDesc}
+ sortBy={collectionSortBy(
+ activeCollection?.pubMagicMetadata?.data,
+ )}
+ onSort={changeSortOrder}
/>
</Box>
);
@@ -1025,28 +1028,24 @@ interface CollectionSortOrderMenuProps {
onClose: () => void;
overflowMenuIconRef: React.RefObject<SVGSVGElement | null>;
sortAsc: boolean;
- onAscClick: () => void;
- onDescClick: () => void;
+ sortBy: CollectionSortBy;
+ onSort: (sortBy: CollectionSortBy, asc: boolean) => void;
}
-const CollectionSortOrderMenu: React.FC<CollectionSortOrderMenuProps> = ({
+function CollectionSortOrderMenu({
open,
onClose,
overflowMenuIconRef,
sortAsc,
- onAscClick,
- onDescClick,
-}) => {
- const handleAscClick = () => {
- onAscClick();
- onClose();
- };
-
- const handleDescClick = () => {
- onDescClick();
- onClose();
- };
-
+ sortBy,
+ onSort,
+}: CollectionSortOrderMenuProps) {
+ const options: { by: CollectionSortBy; asc: boolean; label: string }[] = [
+ { by: "date", asc: false, label: t("newest_first") },
+ { by: "date", asc: true, label: t("oldest_first") },
+ { by: "name", asc: true, label: t("album_sort_name_asc") },
+ { by: "name", asc: false, label: t("album_sort_name_desc") },
+ ];
return (
<Menu
id="collection-files-sort"
@@ -1054,26 +1053,27 @@ const CollectionSortOrderMenu: React.FC<CollectionSortOrderMenuProps> = ({
open={open}
onClose={onClose}
slotProps={{
- list: {
- disablePadding: true,
- "aria-labelledby": "collection-files-sort",
- },
+ list: { disablePadding: true, "aria-label": t("sort_by") },
}}
anchorOrigin={{ vertical: "bottom", horizontal: "right" }}
transformOrigin={{ vertical: "top", horizontal: "right" }}
>
- <OverflowMenuOption
- onClick={handleDescClick}
- endIcon={!sortAsc ? <CheckIcon /> : undefined}
- >
- {t("newest_first")}
- </OverflowMenuOption>
- <OverflowMenuOption
- onClick={handleAscClick}
- endIcon={sortAsc ? <CheckIcon /> : undefined}
- >
- {t("oldest_first")}
- </OverflowMenuOption>
+ {options.map(({ by, asc, label }) => (
+ <OverflowMenuOption
+ key={`${by}-${asc}`}
+ onClick={() => {
+ onSort(by, asc);
+ onClose();
+ }}
+ endIcon={
+ sortBy === by && sortAsc === asc ? (
+ <CheckIcon />
+ ) : undefined
+ }
+ >
+ {label}
+ </OverflowMenuOption>
+ ))}
</Menu>
);
-};
+}
diff --git a/web/apps/photos/src/components/gallery/reducer.ts b/web/apps/photos/src/components/gallery/reducer.ts
index 0c41c2096e..a2a74f60ba 100644
--- a/web/apps/photos/src/components/gallery/reducer.ts
+++ b/web/apps/photos/src/components/gallery/reducer.ts
@@ -11,6 +11,10 @@ import {
findUserUncategorizedCollection,
type Collection,
} from "ente-media/collection";
+import {
+ collectionSortBy,
+ sortCollectionFiles,
+} from "ente-media/collection-sort";
import type { EnteFile } from "ente-media/file";
import {
isArchivedFile,
@@ -1760,8 +1764,11 @@ const sortAndUniqueFilteredFiles = (
const uniqueFiles = uniqueFilesByID(
suppressSharedFilesSavedByUser(files, currentUserID, activeCollection),
);
- const sortAsc = activeCollection?.pubMagicMetadata?.data.asc ?? false;
- return sortAsc ? sortFiles(uniqueFiles, true) : uniqueFiles;
+ const metadata = activeCollection?.pubMagicMetadata?.data;
+ // The synced library is already in newest-first order.
+ return metadata?.asc || collectionSortBy(metadata) !== "date"
+ ? sortCollectionFiles(uniqueFiles, metadata)
+ : uniqueFiles;
};
const suppressSharedFilesSavedByUser = (
diff --git a/web/apps/photos/src/pages/gallery.tsx b/web/apps/photos/src/pages/gallery.tsx
index 4ac9b60d00..93b2a186c5 100644
--- a/web/apps/photos/src/pages/gallery.tsx
+++ b/web/apps/photos/src/pages/gallery.tsx
@@ -97,6 +97,7 @@ import type { UploadTypeSelectorIntent } from "ente-gallery/components/Upload";
import { useSaveGroups } from "ente-gallery/components/utils/save-groups";
import type { FileViewerInitialSidebar } from "ente-gallery/components/viewer/FileViewer";
import type { Collection } from "ente-media/collection";
+import { collectionSortBy } from "ente-media/collection-sort";
import type { EnteFile } from "ente-media/file";
import { ItemVisibility, metadataHash } from "ente-media/file-metadata";
import { AssignPersonDialog } from "ente-new/photos/components/AssignPersonDialog";
@@ -2067,7 +2068,13 @@ const Page: React.FC = () => {
files={filteredFiles}
onShowMap={handleShowCollectionMap}
enableDownload={true}
- disableGrouping={state.searchSuggestion?.type == "clip"}
+ disableGrouping={
+ state.searchSuggestion?.type == "clip" ||
+ (!isInSearchMode &&
+ collectionSortBy(
+ activeCollection?.pubMagicMetadata?.data,
+ ) === "name")
+ }
enableSelect={true}
selected={selected}
setSelected={setSelected}
diff --git a/web/apps/photos/tests/collection-sort-save.test.ts b/web/apps/photos/tests/collection-sort-save.test.ts
new file mode 100644
index 0000000000..8266a42e9f
--- /dev/null
+++ b/web/apps/photos/tests/collection-sort-save.test.ts
@@ -0,0 +1,92 @@
+import { generateKey } from "ente-base/crypto";
+import type { Collection } from "ente-media/collection";
+import {
+ decryptMagicMetadata,
+ type RemoteMagicMetadata,
+} from "ente-media/magic-metadata";
+import { updateCollectionSortOrder } from "ente-new/photos/services/collection";
+import { afterEach, beforeEach, expect, test, vi } from "vitest";
+
+// Run the same crypto implementation directly in Node instead of a web worker.
+vi.mock("ente-base/crypto", () => import("ente-base/crypto/libsodium"));
+
+vi.mock("ente-base/http", async (importOriginal) => ({
+ ...(await importOriginal<typeof import("ente-base/http")>()),
+ authenticatedRequestHeaders: () => Promise.resolve({}),
+}));
+vi.mock("ente-base/origins", () => ({
+ apiURL: (path: string) => Promise.resolve(`https://example.invalid${path}`),
+}));
+
+const fetchMock = vi.fn();
+beforeEach(() => {
+ vi.stubGlobal("fetch", fetchMock);
+ fetchMock.mockResolvedValue(new Response(null, { status: 200 }));
+});
+afterEach(() => {
+ vi.unstubAllGlobals();
+ vi.clearAllMocks();
+});
+
+const album = async () =>
+ ({
+ id: 10,
+ key: await generateKey(),
+ pubMagicMetadata: {
+ version: 7,
+ count: 5,
+ data: {
+ caption: "Our trip",
+ coverID: 2,
+ layout: "grouped",
+ sortBy: "name",
+ futureField: "retain",
+ },
+ },
+ }) as unknown as Collection;
+
+async function savedMetadata(collection: Collection) {
+ const [url, request] = fetchMock.mock.calls[0]! as [string, RequestInit];
+ expect(url).toBe(
+ "https://example.invalid/collections/public-magic-metadata",
+ );
+ expect(request.method).toBe("PUT");
+ const payload = JSON.parse(request.body as string) as {
+ id: number;
+ magicMetadata: RemoteMagicMetadata;
+ };
+ expect(payload.id).toBe(collection.id);
+ expect(payload.magicMetadata.version).toBe(7);
+ return (await decryptMagicMetadata(payload.magicMetadata, collection.key))
+ .data;
+}
+
+test("filename sorting is encrypted with the album key and preserves unrelated metadata", async () => {
+ const collection = await album();
+ await updateCollectionSortOrder(collection, true, "name");
+ expect(await savedMetadata(collection)).toEqual({
+ ...collection.pubMagicMetadata!.data,
+ sortBy: "name",
+ asc: true,
+ });
+});
+
+test("legacy newest/oldest calls reset the mode to date", async () => {
+ const collection = await album();
+ await updateCollectionSortOrder(collection, false);
+ expect(await savedMetadata(collection)).toEqual({
+ ...collection.pubMagicMetadata!.data,
+ sortBy: "date",
+ asc: false,
+ });
+});
+
+test("a rejected save propagates the error and leaves the local album unchanged", async () => {
+ const collection = await album();
+ const before = structuredClone(collection);
+ fetchMock.mockResolvedValueOnce(new Response(null, { status: 409 }));
+ await expect(
+ updateCollectionSortOrder(collection, false, "name"),
+ ).rejects.toThrow();
+ expect(collection).toEqual(before);
+});
diff --git a/web/apps/photos/tests/collection-sort.test.ts b/web/apps/photos/tests/collection-sort.test.ts
new file mode 100644
index 0000000000..544e2b64c2
--- /dev/null
+++ b/web/apps/photos/tests/collection-sort.test.ts
@@ -0,0 +1,97 @@
+import { sortFiles } from "ente-gallery/utils/file";
+import { CollectionPublicMagicMetadataData } from "ente-media/collection";
+import {
+ collectionSortBy,
+ sortCollectionFiles,
+} from "ente-media/collection-sort";
+import type { EnteFile } from "ente-media/file";
+import { describe, expect, test } from "vitest";
+
+const photo = (id: number, title = `photo${id}.jpg`): EnteFile =>
+ ({
+ id,
+ collectionID: 10,
+ metadata: {
+ title,
+ creationTime: id * 1_000_000,
+ modificationTime: id * 1_000_000,
+ },
+ }) as EnteFile;
+const ids = (files: EnteFile[]) => files.map(({ id }) => id);
+
+describe("album sorting", () => {
+ test("preserves legacy date ordering without mutating the library", () => {
+ const files = [photo(2), photo(1), photo(3)];
+ expect(sortCollectionFiles(files)).toEqual(sortFiles([...files]));
+ expect(sortCollectionFiles(files, { asc: true })).toEqual(
+ sortFiles([...files], true),
+ );
+ expect(ids(files)).toEqual([2, 1, 3]);
+ expect(sortCollectionFiles([])).toEqual([]);
+ });
+ test("uses edited dates and modification time like the existing sorter", () => {
+ const files = [photo(1), photo(2), photo(3)];
+ files[0]!.pubMagicMetadata = {
+ data: { editedTime: 3_000_000 },
+ version: 1,
+ count: 1,
+ };
+ expect(sortCollectionFiles(files)).toEqual(sortFiles([...files]));
+ expect(sortCollectionFiles(files, { asc: true })).toEqual(
+ sortFiles([...files], true),
+ );
+ });
+ test("sorts filenames naturally, ignoring case and honoring renamed files", () => {
+ const files = [
+ photo(1, "IMG10.jpg"),
+ photo(2, "img2.jpg"),
+ photo(3, "z.jpg"),
+ ];
+ files[2]!.pubMagicMetadata = {
+ version: 1,
+ count: 1,
+ data: { editedName: "img1.jpg" },
+ };
+ expect(
+ ids(sortCollectionFiles(files, { sortBy: "name", asc: true })),
+ ).toEqual([3, 2, 1]);
+ expect(
+ ids(sortCollectionFiles(files, { sortBy: "name", asc: false })),
+ ).toEqual([1, 2, 3]);
+ });
+ test("equal filenames have a deterministic order across syncs", () => {
+ const files = [photo(2, "a.jpg"), photo(1, "A.jpg")];
+ expect(
+ ids(sortCollectionFiles(files, { sortBy: "name", asc: true })),
+ ).toEqual([1, 2]);
+ expect(
+ sortCollectionFiles([...files].reverse(), { sortBy: "name" }),
+ ).toEqual(sortCollectionFiles(files, { sortBy: "name" }));
+ });
+ test("future sort modes fall back to legacy date ordering", () => {
+ const metadata = { sortBy: "future-mode", asc: true };
+ expect(collectionSortBy(metadata)).toBe("date");
+ expect(
+ ids(sortCollectionFiles([photo(3), photo(1), photo(2)], metadata)),
+ ).toEqual([1, 2, 3]);
+ });
+ test("metadata round trips retain ordering and unrelated fields", () => {
+ const metadata = {
+ asc: true,
+ sortBy: "name",
+ caption: "Trip",
+ coverID: 1,
+ futureField: "preserve",
+ };
+ expect(
+ JSON.parse(
+ JSON.stringify(
+ CollectionPublicMagicMetadataData.parse(metadata),
+ ),
+ ),
+ ).toEqual(metadata);
+ expect(
+ CollectionPublicMagicMetadataData.parse({ sortBy: null }),
+ ).toMatchObject({ sortBy: undefined });
+ });
+});
diff --git a/web/packages/base/locales/en-US/translation.json b/web/packages/base/locales/en-US/translation.json
index f7428baadb..de763a8d7c 100644
--- a/web/packages/base/locales/en-US/translation.json
+++ b/web/packages/base/locales/en-US/translation.json
@@ -955,6 +955,8 @@
"hide": "Hide",
"unhide": "Unhide",
"sort_by": "Sort by",
+ "album_sort_name_asc": "Filename (A–Z)",
+ "album_sort_name_desc": "Filename (Z–A)",
"newest_first": "Newest first",
"oldest_first": "Oldest first",
"most_relevant": "Most relevant",
diff --git a/web/packages/media/collection-sort.ts b/web/packages/media/collection-sort.ts
new file mode 100644
index 0000000000..68f4a76521
--- /dev/null
+++ b/web/packages/media/collection-sort.ts
@@ -0,0 +1,49 @@
+import type { CollectionPublicMagicMetadataData } from "./collection";
+import type { EnteFile } from "./file";
+import { fileCreationPhotoSortTime, fileFileName } from "./file-metadata";
+
+export type CollectionSortBy = "date" | "name";
+
+type SortMetadata = Pick<CollectionPublicMagicMetadataData, "sortBy" | "asc">;
+
+export const collectionSortBy = (
+ metadata: SortMetadata | undefined,
+): CollectionSortBy => (metadata?.sortBy === "name" ? "name" : "date");
+
+const filenameCollator = new Intl.Collator(undefined, {
+ numeric: true,
+ sensitivity: "base",
+});
+
+/** Return a sorted copy, preserving the existing date order for legacy albums. */
+export const sortCollectionFiles = (
+ files: EnteFile[],
+ metadata?: SortMetadata,
+): EnteFile[] => {
+ const direction = metadata?.asc ? 1 : -1;
+ if (collectionSortBy(metadata) === "name") {
+ return [...files].sort(
+ (a, b) =>
+ direction *
+ filenameCollator.compare(
+ fileFileName(a),
+ fileFileName(b),
+ ) || a.id - b.id,
+ );
+ }
+ const dates = new Map<EnteFile, number>();
+ const dateForFile = (file: EnteFile) => {
+ let date = dates.get(file);
+ if (date === undefined) {
+ date = fileCreationPhotoSortTime(file);
+ dates.set(file, date);
+ }
+ return date;
+ };
+ return [...files].sort(
+ (a, b) =>
+ direction *
+ (dateForFile(a) - dateForFile(b) ||
+ a.metadata.modificationTime - b.metadata.modificationTime),
+ );
+};
diff --git a/web/packages/media/collection.ts b/web/packages/media/collection.ts
index ad1365b928..e158546f38 100644
--- a/web/packages/media/collection.ts
+++ b/web/packages/media/collection.ts
@@ -241,6 +241,8 @@ export const CollectionPrivateMagicMetadataData = z.looseObject({
export interface CollectionPublicMagicMetadataData {
asc?: boolean;
+ // Unknown sort modes fall back to date order in older clients.
+ sortBy?: string;
coverID?: number;
layout?: string;
caption?: string;
@@ -250,6 +252,7 @@ export const maxAlbumDescriptionLength = 200;
export const CollectionPublicMagicMetadataData = z.looseObject({
asc: z.boolean().nullish().transform(nullToUndefined),
+ sortBy: z.string().nullish().transform(nullToUndefined),
coverID: z.number().nullish().transform(nullToUndefined),
layout: z.string().nullish().transform(nullToUndefined),
caption: z.string().nullish().transform(nullToUndefined),
diff --git a/web/packages/new/photos/services/collection.ts b/web/packages/new/photos/services/collection.ts
index 03f9ca34e4..1730defd61 100644
--- a/web/packages/new/photos/services/collection.ts
+++ b/web/packages/new/photos/services/collection.ts
@@ -21,6 +21,7 @@ import {
type CollectionType,
type PublicURL,
} from "ente-media/collection";
+import type { CollectionSortBy } from "ente-media/collection-sort";
import {
decryptRemoteFile,
FileDiffResponse,
@@ -977,7 +978,8 @@ export const updateShareeCollectionOrder = async (
export const updateCollectionSortOrder = async (
collection: Collection,
asc: boolean,
-) => updateCollectionPublicMagicMetadata(collection, { asc });
+ sortBy: CollectionSortBy = "date",
+) => updateCollectionPublicMagicMetadata(collection, { asc, sortBy });
const albumDescriptionSegmenter =
typeof Intl !== "undefined" && "Segmenter" in Intl