From 2dba053b866a3885eb98d49a6034f6263a227493 Mon Sep 17 00:00:00 2001
From: Varun Raj
Date: Wed, 29 Oct 2025 22:09:07 +0530
Subject: [PATCH] refactor: update album selection logic and add merge
functionality
- Changed the `onSelect` prop in `AlbumThumbnail` to accept the entire album object instead of just the album ID.
- Introduced new API routes for merging albums and added the corresponding handler.
- Removed the `useAlbumSelection` hook and integrated selection logic directly in the `AlbumList` component.
- Added a `MergeAlbumDialog` component for merging albums.
- Updated the album list page to handle album merging and selection state more effectively.
---
src/components/albums/MergeAlbumDialog.tsx | 97 +++++++++++++++++
src/components/albums/list/AlbumThumbnail.tsx | 4 +-
src/config/routes.ts | 4 +
src/contexts/AlbumSelectionContext.tsx | 80 ++++++++++++++
src/handlers/api/album.handler.ts | 6 +-
src/hooks/index.ts | 1 -
src/hooks/useAlbumSelection.ts | 68 ------------
src/pages/albums/index.tsx | 57 +++++++---
src/pages/api/albums/merge.ts | 103 ++++++++++++++++++
9 files changed, 332 insertions(+), 88 deletions(-)
create mode 100644 src/components/albums/MergeAlbumDialog.tsx
create mode 100644 src/contexts/AlbumSelectionContext.tsx
delete mode 100644 src/hooks/useAlbumSelection.ts
create mode 100644 src/pages/api/albums/merge.ts
diff --git a/src/components/albums/MergeAlbumDialog.tsx b/src/components/albums/MergeAlbumDialog.tsx
new file mode 100644
index 0000000..9359c3a
--- /dev/null
+++ b/src/components/albums/MergeAlbumDialog.tsx
@@ -0,0 +1,97 @@
+import React, { useState } from 'react'
+import { Dialog, DialogHeader, DialogContent, DialogTitle, DialogTrigger, DialogFooter } from '@/components/ui/dialog'
+import { Button } from '../ui/button'
+import { IAlbum } from '@/types/album';
+import { useAlbumSelection } from '@/contexts/AlbumSelectionContext';
+import AlbumThumbnail from './list/AlbumThumbnail';
+import { mergeAlbums } from '@/handlers/api/album.handler';
+import toast from 'react-hot-toast';
+
+interface IProps {
+ onMerge: (primaryAlbumId: string, secondaryAlbumIds: string[]) => void;
+}
+
+export default function MergeAlbumDialog({ onMerge }: IProps) {
+ const [open, setOpen] = useState(false);
+ const [primaryAlbum, setPrimaryAlbum] = useState(null);
+ const [mergeLoading, setMergeLoading] = useState(false);
+
+ const { selectedAlbums, clearSelection } = useAlbumSelection();
+
+ const handleMergeAlbums = () => {
+ const primaryAlbumId = selectedAlbums.find(album => album.id === primaryAlbum?.id)?.id;
+ const secondaryAlbumIds = selectedAlbums.filter(album => album.id !== primaryAlbum?.id).map(album => album.id);
+
+ if (!primaryAlbumId || !secondaryAlbumIds) {
+ toast.error('Failed to merge albums')
+ return
+ }
+ setMergeLoading(true);
+
+ return mergeAlbums(primaryAlbumId, secondaryAlbumIds).then(() => {
+ onMerge(primaryAlbumId, secondaryAlbumIds)
+ clearSelection()
+ setOpen(false)
+ toast.success('Albums merged successfully')
+ }).catch((error) => {
+ toast.error(error.message)
+ }).finally(() => {
+ setOpen(false)
+ setMergeLoading(false)
+ })
+ }
+
+ if (selectedAlbums.length < 2) {
+ return null;
+ }
+
+ return (
+
+ )
+}
diff --git a/src/components/albums/list/AlbumThumbnail.tsx b/src/components/albums/list/AlbumThumbnail.tsx
index b2973fe..af70d22 100644
--- a/src/components/albums/list/AlbumThumbnail.tsx
+++ b/src/components/albums/list/AlbumThumbnail.tsx
@@ -12,7 +12,7 @@ import { Calendar, Camera } from 'lucide-react';
interface IAlbumThumbnailProps {
album: IAlbum;
- onSelect: (albumId: string, isShiftClick?: boolean) => void;
+ onSelect: (album: IAlbum, isShiftClick?: boolean) => void;
selected: boolean;
}
@@ -23,7 +23,7 @@ export default function AlbumThumbnail({ album, onSelect, selected }: IAlbumThum
const handleCheckboxChange = (event: React.MouseEvent) => {
const isShiftClick = event.shiftKey;
- onSelect(album.id, isShiftClick);
+ onSelect(album, isShiftClick);
};
return (
diff --git a/src/config/routes.ts b/src/config/routes.ts
index bffdcb0..b58dfef 100644
--- a/src/config/routes.ts
+++ b/src/config/routes.ts
@@ -29,6 +29,10 @@ export const CREATE_ALBUM_PATH = BASE_PROXY_ENDPOINT + "/albums";
export const ADD_ASSETS_ALBUMS_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/albums/" + id + "/assets";
export const SHARE_ALBUMS_PATH = BASE_API_ENDPOINT + "/albums/share";
export const DELETE_ALBUMS_PATH = BASE_API_ENDPOINT + "/albums/delete";
+
+
+export const ADD_ASSETS_TO_ALBUM_PATH = (id: string) => BASE_PROXY_ENDPOINT + "/albums/" + id + "/assets";
+export const MERGE_ALBUMS_PATH = BASE_API_ENDPOINT + "/albums/merge";
// Assets
export const LIST_MISSING_LOCATION_DATES_PATH = BASE_API_ENDPOINT + "/assets/missing-location-dates";
export const LIST_MISSING_LOCATION_ALBUMS_PATH = BASE_API_ENDPOINT + "/assets/missing-location-albums";
diff --git a/src/contexts/AlbumSelectionContext.tsx b/src/contexts/AlbumSelectionContext.tsx
new file mode 100644
index 0000000..54b9dda
--- /dev/null
+++ b/src/contexts/AlbumSelectionContext.tsx
@@ -0,0 +1,80 @@
+import { createContext, useContext, useState } from "react";
+import { IAlbum } from "@/types/album";
+
+interface AlbumSelectionContextType {
+ selectedAlbums: IAlbum[];
+ lastSelectedId: string | null;
+ selectAlbum: (album: IAlbum, albums: IAlbum[], isShiftClick?: boolean) => void;
+ selectAll: (albums: IAlbum[]) => void;
+ clearSelection: () => void;
+}
+
+export const AlbumSelectionContext = createContext({
+ selectedAlbums: [],
+ lastSelectedId: null,
+ selectAlbum: () => { },
+ selectAll: () => { },
+ clearSelection: () => { },
+});
+
+export const useAlbumSelection = () => {
+ return useContext(AlbumSelectionContext);
+};
+
+export const AlbumSelectionProvider = ({ children }: { children: React.ReactNode }) => {
+ const [selectedAlbums, setSelectedAlbums] = useState([]);
+ const [lastSelectedId, setLastSelectedId] = useState(null);
+
+ const selectAlbum = (album: IAlbum, albums: IAlbum[], isShiftClick?: boolean) => {
+ setSelectedAlbums(prevSelectedAlbums => {
+ let newSelectedAlbums: IAlbum[] = [];
+ if (isShiftClick && lastSelectedId && lastSelectedId !== album.id) {
+ const currentIndex = albums.findIndex(a => a.id === album.id);
+ const lastIndex = albums.findIndex(a => a.id === lastSelectedId);
+ if (currentIndex !== -1 && lastIndex !== -1) {
+ const startIndex = Math.min(currentIndex, lastIndex);
+ const endIndex = Math.max(currentIndex, lastIndex);
+ const rangeAlbums = albums.slice(startIndex, endIndex + 1);
+ // Avoid duplicate albums by id
+ const uniqueIds = new Set(prevSelectedAlbums.map(a => a.id));
+ newSelectedAlbums = [...prevSelectedAlbums];
+ for (const alb of rangeAlbums) {
+ if (!uniqueIds.has(alb.id)) {
+ newSelectedAlbums.push(alb);
+ uniqueIds.add(alb.id);
+ }
+ }
+ } else {
+ newSelectedAlbums = [...prevSelectedAlbums];
+ }
+ } else {
+ // Toggle single selection
+ const isAlreadySelected = prevSelectedAlbums.some(a => a.id === album.id);
+ if (isAlreadySelected) {
+ newSelectedAlbums = prevSelectedAlbums.filter(a => a.id !== album.id);
+ } else {
+ newSelectedAlbums = [...prevSelectedAlbums, album];
+ }
+ }
+ return newSelectedAlbums;
+ });
+ setLastSelectedId(album.id);
+ }
+
+ const selectAll = (albums: IAlbum[]) => {
+ setSelectedAlbums(albums as IAlbum[]);
+ };
+
+ const clearSelection = () => {
+ setSelectedAlbums([]);
+ };
+
+ return (
+ {children}
+ );
+};
\ No newline at end of file
diff --git a/src/handlers/api/album.handler.ts b/src/handlers/api/album.handler.ts
index 32541f7..f510df8 100644
--- a/src/handlers/api/album.handler.ts
+++ b/src/handlers/api/album.handler.ts
@@ -1,4 +1,4 @@
-import { ADD_ASSETS_ALBUMS_PATH, ALBUM_ASSETS_PATH, ALBUM_INFO_PATH, ALBUM_PEOPLE_PATH, CREATE_ALBUM_PATH, DELETE_ALBUMS_PATH, LIST_ALBUMS_PATH, LIST_POTENTIAL_ALBUMS_ASSETS_PATH, LIST_POTENTIAL_ALBUMS_DATES_PATH, SHARE_ALBUMS_PATH } from "@/config/routes";
+import { ADD_ASSETS_ALBUMS_PATH, ALBUM_ASSETS_PATH, ALBUM_INFO_PATH, ALBUM_PEOPLE_PATH, CREATE_ALBUM_PATH, DELETE_ALBUMS_PATH, LIST_ALBUMS_PATH, LIST_POTENTIAL_ALBUMS_ASSETS_PATH, LIST_POTENTIAL_ALBUMS_DATES_PATH, MERGE_ALBUMS_PATH, SHARE_ALBUMS_PATH } from "@/config/routes";
import { cleanUpAsset } from "@/helpers/asset.helper";
import API from "@/lib/api";
import { IAlbumCreate } from "@/types/album";
@@ -53,4 +53,8 @@ export const shareAlbums = async (albums: { albumId: string, allowDownload: bool
export const deleteAlbums = async (albumIds: string[]) => {
return API.delete(DELETE_ALBUMS_PATH, { albumIds });
+}
+
+export const mergeAlbums = async (primaryAlbumId: string, secondaryAlbumIds: string[]) => {
+ return API.post(MERGE_ALBUMS_PATH, { primaryAlbumId, secondaryAlbumIds });
}
\ No newline at end of file
diff --git a/src/hooks/index.ts b/src/hooks/index.ts
index 2a4749c..9b9e34b 100644
--- a/src/hooks/index.ts
+++ b/src/hooks/index.ts
@@ -1,2 +1 @@
-export { useAlbumSelection } from './useAlbumSelection'
export { useGridDimensions } from './useGridDimensions'
\ No newline at end of file
diff --git a/src/hooks/useAlbumSelection.ts b/src/hooks/useAlbumSelection.ts
deleted file mode 100644
index 3e6189c..0000000
--- a/src/hooks/useAlbumSelection.ts
+++ /dev/null
@@ -1,68 +0,0 @@
-import { useState, useCallback } from 'react'
-import { IAlbum } from '@/types/album'
-
-/**
- * Custom hook for album selection with shift-click support
- * @param albums - Array of albums to manage selection for
- * @returns Selection state and methods
- */
-export const useAlbumSelection = (albums: IAlbum[]) => {
- const [selectedIds, setSelectedIds] = useState>(new Set())
- const [lastSelectedId, setLastSelectedId] = useState(null)
-
- const selectAlbum = useCallback((albumId: string, isShiftClick: boolean = false) => {
- if (isShiftClick && lastSelectedId && lastSelectedId !== albumId) {
- // Handle shift-click range selection
- const currentIndex = albums.findIndex(album => album.id === albumId)
- const lastIndex = albums.findIndex(album => album.id === lastSelectedId)
-
- if (currentIndex !== -1 && lastIndex !== -1) {
- const startIndex = Math.min(currentIndex, lastIndex)
- const endIndex = Math.max(currentIndex, lastIndex)
-
- const newSelectedIds = new Set(selectedIds)
- for (let i = startIndex; i <= endIndex; i++) {
- newSelectedIds.add(albums[i].id)
- }
- setSelectedIds(newSelectedIds)
- }
- } else {
- // Toggle single selection
- const newSelectedIds = new Set(selectedIds)
- if (newSelectedIds.has(albumId)) {
- newSelectedIds.delete(albumId)
- } else {
- newSelectedIds.add(albumId)
- }
- setSelectedIds(newSelectedIds)
- }
-
- setLastSelectedId(albumId)
- }, [albums, selectedIds, lastSelectedId])
-
- const selectAll = useCallback(() => {
- setSelectedIds(new Set(albums.map(album => album.id)))
- }, [albums])
-
- const clearSelection = useCallback(() => {
- setSelectedIds(new Set())
- setLastSelectedId(null)
- }, [])
-
- const isSelected = useCallback((albumId: string) => selectedIds.has(albumId), [selectedIds])
-
- const selectedCount = selectedIds.size
- const isAllSelected = albums.length > 0 && selectedCount === albums.length
- const isPartiallySelected = selectedCount > 0 && selectedCount < albums.length
-
- return {
- selectedIds: Array.from(selectedIds),
- selectedCount,
- isSelected,
- selectAlbum,
- selectAll,
- clearSelection,
- isAllSelected,
- isPartiallySelected
- }
-}
\ No newline at end of file
diff --git a/src/pages/albums/index.tsx b/src/pages/albums/index.tsx
index f018ce4..4221306 100644
--- a/src/pages/albums/index.tsx
+++ b/src/pages/albums/index.tsx
@@ -14,10 +14,11 @@ import { Input } from '@/components/ui/input'
import AlbumShareDialog, { IAlbumShareDialogRef } from '@/components/albums/share/AlbumShareDialog'
import { AlertDialog } from '@/components/ui/alert-dialog'
import toast from 'react-hot-toast'
-import { useAlbumSelection } from '@/hooks'
import FloatingBar from '@/components/shared/FloatingBar'
import DataTable, { DataTableRef } from '@/components/ui/data-table'
import { albumColumns } from '@/components/albums/AlbumTableColumns'
+import MergeAlbumDialog from '@/components/albums/MergeAlbumDialog'
+import { AlbumSelectionProvider, useAlbumSelection } from '@/contexts/AlbumSelectionContext'
const SORT_BY_OPTIONS = [
{ value: 'lastPhotoDate', label: 'Last Photo Date' },
@@ -30,7 +31,7 @@ const SORT_BY_OPTIONS = [
{ value: 'faceCount', label: 'Number of People' },
]
-export default function AlbumListPage() {
+const AlbumList = () => {
const router = useRouter()
const [search, setSearch] = useState('')
const [viewMode, setViewMode] = useState<'grid' | 'table'>('grid')
@@ -52,22 +53,15 @@ export default function AlbumListPage() {
const searchedAlbums = useMemo(() => albums.filter((album) => album.albumName.toLowerCase().includes(search.toLowerCase())), [albums, search])
const {
- selectedIds,
- selectedCount,
- isSelected,
+ selectedAlbums,
selectAlbum,
selectAll,
clearSelection,
- isAllSelected,
- isPartiallySelected
- } = useAlbumSelection(searchedAlbums)
-
- const selectedAlbums = useMemo(() => albums.filter((album) => selectedIds.includes(album.id)), [albums, selectedIds])
+ } = useAlbumSelection()
// Use appropriate selection state based on view mode
- const currentSelectedIds = viewMode === 'table' ? tableSelectedIds : selectedIds
+ const currentSelectedIds = viewMode === 'table' ? tableSelectedIds : selectedAlbums.map(album => album.id)
const currentSelectedCount = currentSelectedIds.length
- const currentSelectedAlbums = useMemo(() => albums.filter((album) => currentSelectedIds.includes(album.id)), [albums, currentSelectedIds])
const fetchAlbums = async () => {
setLoading(true)
@@ -105,6 +99,11 @@ export default function AlbumListPage() {
})
}
+ const handleMergeAlbums = async (primaryAlbumId: string, secondaryAlbumIds: string[] ) => {
+ setAlbums(albums.filter((album) => !secondaryAlbumIds.includes(album.id) && album.id !== primaryAlbumId))
+ toast.success(`Merged ${secondaryAlbumIds.length} albums`)
+ }
+
const handleTableSelectionChange = useCallback((selectedRowIds: string[]) => {
setTableSelectedIds(selectedRowIds)
}, [])
@@ -113,7 +112,7 @@ export default function AlbumListPage() {
if (viewMode === 'table') {
setTableSelectedIds(searchedAlbums.map(album => album.id))
} else {
- selectAll()
+ selectAll(searchedAlbums)
}
}
@@ -125,6 +124,19 @@ export default function AlbumListPage() {
}
}
+ const handleEscape = (e: KeyboardEvent) => {
+ if (e.key === 'Escape') {
+ handleClearSelection()
+ }
+ }
+
+ useEffect(() => {
+ // Escape to clear selection
+
+ window.addEventListener('keydown', handleEscape)
+ return () => window.removeEventListener('keydown', handleEscape)
+ }, [])
+
const isAllSelectedCurrent = searchedAlbums.length > 0 && currentSelectedCount === searchedAlbums.length
const isPartiallySelectedCurrent = currentSelectedCount > 0 && currentSelectedCount < searchedAlbums.length
@@ -158,8 +170,8 @@ export default function AlbumListPage() {
selectedAlbum.id === album.id)}
+ onSelect={(album, isShiftClick) => selectAlbum(album, searchedAlbums, isShiftClick ?? false)}
/>
))}
@@ -202,6 +214,7 @@ export default function AlbumListPage() {
+
+
+
{isAllSelectedCurrent ? (
@@ -294,3 +311,11 @@ export default function AlbumListPage() {
)
}
+
+export default function AlbumListPage() {
+ return (
+
+
+
+ )
+}
diff --git a/src/pages/api/albums/merge.ts b/src/pages/api/albums/merge.ts
new file mode 100644
index 0000000..b10e873
--- /dev/null
+++ b/src/pages/api/albums/merge.ts
@@ -0,0 +1,103 @@
+import { db } from "@/config/db";
+import { ENV } from "@/config/environment";
+import { ADD_ASSETS_TO_ALBUM_PATH, DELETE_ALBUMS_PATH } from "@/config/routes";
+import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
+import API from "@/lib/api";
+import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
+import { albums } from "@/schema/albums.schema";
+import { and, eq, inArray } from "drizzle-orm";
+import { NextApiRequest, NextApiResponse } from "next";
+
+export default async function handler(
+ req: NextApiRequest,
+ res: NextApiResponse
+) {
+ const currentUser = await getCurrentUser(req);
+ if (!currentUser) {
+ return res.status(401).json({ error: "Unauthorized" });
+ }
+ const { primaryAlbumId, secondaryAlbumIds } = req.body as {
+ primaryAlbumId: string;
+ secondaryAlbumIds: string[];
+ };
+
+ if (!primaryAlbumId || !secondaryAlbumIds) {
+ return res
+ .status(400)
+ .json({ error: "primaryAlbumId and secondaryAlbumIds are required" });
+ }
+
+ if (secondaryAlbumIds.length === 0) {
+ return res
+ .status(400)
+ .json({
+ error: "secondaryAlbumIds must be an array of at least one album id",
+ });
+ }
+
+ const primaryAlbum = await db
+ .select()
+ .from(albums)
+ .where(
+ and(eq(albums.id, primaryAlbumId), eq(albums.ownerId, currentUser.id))
+ )
+ .limit(1);
+
+ if (!primaryAlbum) {
+ return res.status(404).json({ error: "Primary album not found" });
+ }
+
+
+ const secondaryAlbums = await db
+ .select()
+ .from(albums)
+ .where(and(inArray(albums.id, secondaryAlbumIds), eq(albums.ownerId, currentUser.id)));
+
+
+ if (secondaryAlbums.length === 0) {
+ return res.status(404).json({ error: "Secondary albums not found" });
+ }
+
+ const secondaryAlbumAssets = await db
+ .select()
+ .from(albumsAssetsAssets)
+ .where(inArray(albumsAssetsAssets.albumsId, secondaryAlbumIds));
+
+ if (secondaryAlbumAssets.length === 0) {
+ return res.status(404).json({ error: "Secondary album assets not found" });
+ }
+
+ const secondaryAlbumAssetsIds = secondaryAlbumAssets.map((albumAsset) => albumAsset.assetsId);
+
+ const addAssetsToPrimaryAlbumURL = `${ENV.IMMICH_URL}/api/albums/${primaryAlbumId}/assets`;
+ const addAssetsToPrimaryAlbum = await fetch(addAssetsToPrimaryAlbumURL, {
+ method: 'PUT',
+ body: JSON.stringify({ ids: secondaryAlbumAssetsIds }),
+ headers: {
+ 'Content-Type': 'application/json',
+ 'Authorization': `Bearer ${currentUser.accessToken}`
+ }
+ });
+
+ if (!addAssetsToPrimaryAlbum.ok) {
+ return res.status(500).json({ error: "Failed to add assets to primary album" });
+ }
+
+ // Delete secondary albums
+ const deleteSecondaryAlbums = secondaryAlbums.map(async (album) => {
+ const deleteAlbumURL = `${ENV.IMMICH_URL}/api/albums/${album.id}`;
+ return fetch(deleteAlbumURL, {
+ method: 'DELETE',
+ headers: {
+ 'Authorization': `Bearer ${currentUser.accessToken}`
+ }
+ });
+ });
+
+ await Promise.all(deleteSecondaryAlbums);
+
+ return res.status(200).json({
+ success: true,
+ message: "Albums merged successfully",
+ });
+}