From 917f694db7b009a681423071afa89e7d03083e6e Mon Sep 17 00:00:00 2001 From: Varun Raj Date: Mon, 21 Jul 2025 09:40:27 +0530 Subject: [PATCH] refactor: enhance AlbumImages and AssetOffsetDialog components for improved asset management - Integrated PhotoSelectionContext into AlbumImages for better state management of selected assets. - Replaced local asset state with context-driven updates, allowing for seamless asset fetching and selection. - Added image gallery functionality using react-grid-gallery and yet-another-react-lightbox for enhanced user experience. - Updated AssetOffsetDialog to include timezone options for date adjustments, improving flexibility in asset date management. - Refactored UI elements for better layout and usability across both components. --- src/components/albums/info/AlbumImages.tsx | 142 ++++++++++--- .../assets-options/AssetOffsetDialog.tsx | 192 +++++++++++++++--- src/pages/albums/[albumId].tsx | 121 ++++++++++- 3 files changed, 384 insertions(+), 71 deletions(-) diff --git a/src/components/albums/info/AlbumImages.tsx b/src/components/albums/info/AlbumImages.tsx index 9240e0d..e789a83 100644 --- a/src/components/albums/info/AlbumImages.tsx +++ b/src/components/albums/info/AlbumImages.tsx @@ -3,14 +3,15 @@ import { listAlbumAssets } from "@/handlers/api/album.handler"; import { useConfig } from "@/contexts/ConfigContext"; import { IAlbum } from "@/types/album"; import { IAsset } from "@/types/asset"; -import React, { useEffect, useMemo, useRef, useState } from "react"; +import React, { useEffect, useMemo, useRef, useState, MouseEvent } from "react"; import { Hourglass } from "lucide-react"; import { useRouter } from "next/router"; import { Button } from "@/components/ui/button"; -import AssetGrid from "@/components/shared/AssetGrid"; -import PhotoSelectionContext, { - IPhotoSelectionContext, -} from "@/contexts/PhotoSelectionContext"; +import { Gallery } from "react-grid-gallery"; +import Lightbox from "yet-another-react-lightbox"; +import Captions from "yet-another-react-lightbox/plugins/captions"; +import LazyGridImage from "@/components/ui/lazy-grid-image"; +import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext"; interface AlbumImagesProps { album: IAlbum; @@ -20,11 +21,15 @@ interface IAssetFilter { faceId?: string; page: number; } + export default function AlbumImages({ album }: AlbumImagesProps) { const { exImmichUrl } = useConfig(); const router = useRouter(); const { faceId } = router.query as { faceId: string }; - const [assets, setAssets] = useState([]); + + // Use context from parent instead of managing own + const { selectedIds, updateContext, assets } = usePhotoSelectionContext(); + const [loading, setLoading] = useState(false); const [errorMessage, setErrorMessage] = useState(null); const [filters, setFilters] = useState({ @@ -32,32 +37,17 @@ export default function AlbumImages({ album }: AlbumImagesProps) { page: 1, }); const [hasMore, setHasMore] = useState(true); - - // Initialize context state - const [contextState, setContextState] = useState({ - selectedIds: [], - assets: [], - config: {}, - updateContext: (newConfig: Partial) => { - setContextState((prevState) => ({ - ...prevState, - ...newConfig, - // No deep merge needed for config here as it's simple - config: newConfig.config - ? { ...prevState.config, ...newConfig.config } - : prevState.config, - })); - }, - }); + const [index, setIndex] = useState(-1); + const [lastSelectedIndex, setLastSelectedIndex] = useState(-1); const fetchAssets = async () => { setLoading(true); return listAlbumAssets(album.id, filters) .then((newAssets) => { if (filters.page === 1) { - setAssets(newAssets); + updateContext({ assets: newAssets }); } else { - setAssets((prevAssets) => [...prevAssets, ...newAssets]); + updateContext({ assets: [...assets, ...newAssets] }); } setHasMore(newAssets.length === 100); }) @@ -65,6 +55,76 @@ export default function AlbumImages({ album }: AlbumImagesProps) { .finally(() => setLoading(false)); }; + const images = useMemo(() => { + return assets.map((p) => ({ + ...p, + src: p.url as string, + original: p.previewUrl as string, + width: p.exifImageWidth as number, + height: p.exifImageHeight as number, + isSelected: selectedIds.includes(p.id), + orientation: 1, + tags: [ + { + title: "Immich Link", + value: ( + + Open in Immich + + ), + }, + ], + })); + }, [assets, selectedIds, exImmichUrl]); + + const slides = useMemo( + () => + images.map(({ original, width, height }) => ({ + src: original, + width, + height, + })), + [images] + ); + + const handleClick = (idx: number, asset: IAsset, event: MouseEvent) => { + if (selectedIds.length > 0) { + handleSelect(idx, asset, event); + } else { + setIndex(idx); + } + }; + + const handleSelect = (_idx: number, asset: IAsset, event: MouseEvent) => { + event.stopPropagation(); + const isPresent = selectedIds.includes(asset.id); + if (isPresent) { + updateContext({ + selectedIds: selectedIds.filter((id) => id !== asset.id), + }); + } else { + const clickedIndex = images.findIndex((image) => { + return image.id === asset.id; + }); + if (event.shiftKey && lastSelectedIndex !== -1) { + const startIndex = Math.min(clickedIndex, lastSelectedIndex); + const endIndex = Math.max(clickedIndex, lastSelectedIndex); + if (startIndex >= 0 && endIndex < images.length) { + const newSelectedIds = images.slice(startIndex, endIndex + 1).map((image) => image.id); + const allSelectedIds = [...selectedIds, ...newSelectedIds]; + const uniqueSelectedIds = [...new Set(allSelectedIds)]; + updateContext({ selectedIds: uniqueSelectedIds }); + } else { + console.warn("Shift-select index out of bounds"); + updateContext({ selectedIds: [...selectedIds, asset.id] }); + } + } else { + updateContext({ selectedIds: [...selectedIds, asset.id] }); + } + setLastSelectedIndex(clickedIndex); + } + }; + useEffect(() => { if (album.id) { fetchAssets(); @@ -76,7 +136,7 @@ export default function AlbumImages({ album }: AlbumImagesProps) { faceId, page: 1, }); - setAssets([]); + updateContext({ assets: [], selectedIds: [] }); setHasMore(true); }, [faceId]); @@ -97,11 +157,29 @@ export default function AlbumImages({ album }: AlbumImagesProps) { } return ( - -
- + <> + = 0} + index={index} + close={() => setIndex(-1)} + /> +
+ {hasMore && (
- + ); } diff --git a/src/components/assets/assets-options/AssetOffsetDialog.tsx b/src/components/assets/assets-options/AssetOffsetDialog.tsx index bc21585..60bcea6 100644 --- a/src/components/assets/assets-options/AssetOffsetDialog.tsx +++ b/src/components/assets/assets-options/AssetOffsetDialog.tsx @@ -4,6 +4,7 @@ import { Dialog, DialogTitle, DialogHeader, DialogContent, DialogTrigger } from import { Label } from '@/components/ui/label'; import { Input } from '@/components/ui/input'; import { Button } from '@/components/ui/button'; +import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@/components/ui/select'; import { formatDate, offsetDate } from '@/helpers/date.helper'; import Image from 'next/image'; import { updateAssets } from '@/handlers/api/asset.handler'; @@ -14,21 +15,132 @@ interface IProps { onComplete: () => void; } +// Comprehensive timezone options +const TIMEZONE_OPTIONS = [ + { value: 'none', label: 'No timezone change' }, + + // GMT -12 to -9 + { value: 'Pacific/Kwajalein', label: '(GMT -12:00) Eniwetok, Kwajalein' }, + { value: 'Pacific/Midway', label: '(GMT -11:00) Midway Island, Samoa' }, + { value: 'Pacific/Honolulu', label: '(GMT -10:00) Hawaii' }, + { value: 'Pacific/Marquesas', label: '(GMT -9:30) Taiohae' }, + { value: 'America/Anchorage', label: '(GMT -9:00) Alaska' }, + + // GMT -8 to -4 + { value: 'America/Los_Angeles', label: '(GMT -8:00) Pacific Time (US & Canada)' }, + { value: 'America/Denver', label: '(GMT -7:00) Mountain Time (US & Canada)' }, + { value: 'America/Chicago', label: '(GMT -6:00) Central Time (US & Canada), Mexico City' }, + { value: 'America/New_York', label: '(GMT -5:00) Eastern Time (US & Canada), Bogota, Lima' }, + { value: 'America/Caracas', label: '(GMT -4:30) Caracas' }, + { value: 'America/Halifax', label: '(GMT -4:00) Atlantic Time (Canada), La Paz' }, + + // GMT -3 to 0 + { value: 'America/St_Johns', label: '(GMT -3:30) Newfoundland' }, + { value: 'America/Sao_Paulo', label: '(GMT -3:00) Brazil, Buenos Aires, Georgetown' }, + { value: 'Atlantic/South_Georgia', label: '(GMT -2:00) Mid-Atlantic' }, + { value: 'Atlantic/Azores', label: '(GMT -1:00) Azores, Cape Verde Islands' }, + { value: 'UTC', label: '(GMT) UTC' }, + { value: 'Europe/London', label: '(GMT) Western Europe Time, London, Lisbon, Casablanca' }, + + // GMT +1 to +4 + { value: 'Europe/Paris', label: '(GMT +1:00) Brussels, Copenhagen, Madrid, Paris' }, + { value: 'Europe/Berlin', label: '(GMT +1:00) Berlin, Rome, Amsterdam' }, + { value: 'Africa/Cairo', label: '(GMT +2:00) Cairo, South Africa' }, + { value: 'Europe/Moscow', label: '(GMT +3:00) Baghdad, Riyadh, Moscow, St. Petersburg' }, + { value: 'Asia/Tehran', label: '(GMT +3:30) Tehran' }, + { value: 'Asia/Dubai', label: '(GMT +4:00) Abu Dhabi, Muscat, Baku, Tbilisi' }, + { value: 'Asia/Kabul', label: '(GMT +4:30) Kabul' }, + + // GMT +5 to +8 + { value: 'Asia/Karachi', label: '(GMT +5:00) Ekaterinburg, Islamabad, Karachi, Tashkent' }, + { value: 'Asia/Kolkata', label: '(GMT +5:30) Bombay, Calcutta, Madras, New Delhi' }, + { value: 'Asia/Kathmandu', label: '(GMT +5:45) Kathmandu, Pokhara' }, + { value: 'Asia/Dhaka', label: '(GMT +6:00) Almaty, Dhaka, Colombo' }, + { value: 'Asia/Yangon', label: '(GMT +6:30) Yangon, Mandalay' }, + { value: 'Asia/Bangkok', label: '(GMT +7:00) Bangkok, Hanoi, Jakarta' }, + { value: 'Asia/Shanghai', label: '(GMT +8:00) Beijing, Perth, Singapore, Hong Kong' }, + { value: 'Australia/Eucla', label: '(GMT +8:45) Eucla' }, + + // GMT +9 to +12 + { value: 'Asia/Tokyo', label: '(GMT +9:00) Tokyo, Seoul, Osaka, Sapporo, Yakutsk' }, + { value: 'Australia/Adelaide', label: '(GMT +9:30) Adelaide, Darwin' }, + { value: 'Australia/Sydney', label: '(GMT +10:00) Eastern Australia, Guam, Vladivostok' }, + { value: 'Australia/Lord_Howe', label: '(GMT +10:30) Lord Howe Island' }, + { value: 'Pacific/Noumea', label: '(GMT +11:00) Magadan, Solomon Islands, New Caledonia' }, + { value: 'Pacific/Norfolk', label: '(GMT +11:30) Norfolk Island' }, + { value: 'Pacific/Auckland', label: '(GMT +12:00) Auckland, Wellington, Fiji, Kamchatka' }, + { value: 'Pacific/Chatham', label: '(GMT +12:45) Chatham Islands' }, + + // GMT +13 to +14 + { value: 'Pacific/Apia', label: '(GMT +13:00) Apia, Nukualofa' }, + { value: 'Pacific/Kiritimati', label: '(GMT +14:00) Line Islands, Tokelau' }, +]; + +const offsetDateWithTimezone = ( + date: string, + offset: { + years: number, + days: number, + hours: number, + minutes: number, + seconds: number + }, + timezone?: string +): string => { + // First apply the standard offset + const offsettedDate = offsetDate(date, offset); + + // If no timezone specified or "none" selected, return the offset date + if (!timezone || timezone === 'none') { + return offsettedDate; + } + + // Convert timezone + try { + const parsedDate = new Date(offsettedDate); + + // Get the current timezone offset + const currentOffset = parsedDate.getTimezoneOffset(); + + // Get the target timezone offset + const targetDate = new Date(parsedDate.toLocaleString('en-US', { timeZone: timezone })); + const utcDate = new Date(parsedDate.toLocaleString('en-US', { timeZone: 'UTC' })); + const targetOffset = (utcDate.getTime() - targetDate.getTime()) / 60000; + + // Calculate the difference and apply it + const offsetDifference = targetOffset - currentOffset; + const finalDate = new Date(parsedDate.getTime() + (offsetDifference * 60000)); + + return finalDate.toISOString(); + } catch (error) { + console.warn('Timezone conversion failed, using offset date:', error); + return offsettedDate; + } +}; + export default function AssetOffsetDialog({ assets: _assets, onComplete }: IProps) { const { toast } = useToast(); const [open, setOpen] = useState(false); const [assets, setAssets] = useState(_assets); - const [offsetData, setOffsetData] = useState<{ days: number, hours: number, minutes: number, seconds: number, years: number }>({ + const [offsetData, setOffsetData] = useState<{ + days: number, + hours: number, + minutes: number, + seconds: number, + years: number, + timezone: string + }>({ days: 0, hours: 0, minutes: 0, seconds: 0, - years: 0 + years: 0, + timezone: 'none' }); const [loading, setLoading] = useState(false); const [assetStatus, setAssetStatus] = useState>({}); - const handleChange = (key: keyof typeof offsetData, value: number) => { + const handleChange = (key: keyof typeof offsetData, value: number | string) => { setOffsetData({ ...offsetData, [key]: value }); } @@ -39,7 +151,7 @@ export default function AssetOffsetDialog({ assets: _assets, onComplete }: IProp setAssetStatus({ [asset.id]: 'pending' }); await updateAssets({ ids: [asset.id], - dateTimeOriginal: offsetDate(asset.dateTimeOriginal, offsetData) + dateTimeOriginal: offsetDateWithTimezone(asset.dateTimeOriginal, offsetData, offsetData.timezone) }) .then(() => { setLoading(false); @@ -60,7 +172,6 @@ export default function AssetOffsetDialog({ assets: _assets, onComplete }: IProp }) } - useEffect(() => { setAssets(_assets); }, [_assets]); @@ -72,32 +183,53 @@ export default function AssetOffsetDialog({ assets: _assets, onComplete }: IProp Offset Dates - + Offset Asset Dates -
-
- - handleChange("years", parseInt(e.target.value))} /> + +
+
+ + handleChange("years", parseInt(e.target.value) || 0)} /> +
+
+ + handleChange("days", parseInt(e.target.value) || 0)} /> +
+
+ + handleChange("hours", parseInt(e.target.value) || 0)} /> +
+
+ + handleChange("minutes", parseInt(e.target.value) || 0)} /> +
-
- - handleChange("days", parseInt(e.target.value))} /> +
+
+ + handleChange("seconds", parseInt(e.target.value) || 0)} /> +
+
+ + +
+
+ +
-
- - handleChange("hours", parseInt(e.target.value))} /> -
-
- - handleChange("minutes", parseInt(e.target.value))} /> -
-
- - handleChange("seconds", parseInt(e.target.value))} /> -
-
{assets.map((asset) => ( @@ -106,7 +238,9 @@ export default function AssetOffsetDialog({ assets: _assets, onComplete }: IProp {assetStatus[asset.id] === 'pending' ?

Offsetting...

: ( -
{formatDate(offsetDate(asset.dateTimeOriginal, offsetData), 'PPpp')}
+
+ {formatDate(offsetDateWithTimezone(asset.dateTimeOriginal, offsetData, offsetData.timezone), 'PPpp')} +
)} -
{formatDate(asset.dateTimeOriginal, 'PPpp')}
+
+ {formatDate(asset.dateTimeOriginal, 'PPpp')} +
))} diff --git a/src/pages/albums/[albumId].tsx b/src/pages/albums/[albumId].tsx index 13574e8..c4a3738 100644 --- a/src/pages/albums/[albumId].tsx +++ b/src/pages/albums/[albumId].tsx @@ -3,14 +3,20 @@ import Header from '@/components/shared/Header' import Loader from '@/components/ui/loader' import { useConfig } from '@/contexts/ConfigContext' import { getAlbumInfo } from '@/handlers/api/album.handler' +import { deleteAssets, updateAssets } from '@/handlers/api/asset.handler' import { IAlbum } from '@/types/album' import Link from 'next/link' -import React, { useEffect, useState } from 'react' +import React, { useEffect, useState, useMemo } from 'react' import { useRouter } from 'next/router' import AlbumPeople from '@/components/albums/info/AlbumPeople' import AlbumImages from '@/components/albums/info/AlbumImages' import { Camera, ExternalLink, Users } from 'lucide-react' import { humanizeNumber } from '@/helpers/string.helper' +import PhotoSelectionContext, { IPhotoSelectionContext } from '@/contexts/PhotoSelectionContext' +import FloatingBar from '@/components/shared/FloatingBar' +import { Button } from '@/components/ui/button' +import { AlertDialog } from '@/components/ui/alert-dialog' +import AssetOffsetDialog from '@/components/assets/assets-options/AssetOffsetDialog' export default function AlbumListPage() { const { exImmichUrl } = useConfig() @@ -20,7 +26,29 @@ export default function AlbumListPage() { const [albumInfo, setAlbumInfo] = useState() const [loading, setLoading] = useState(false) const [errorMessage, setErrorMessage] = useState('') - const [selectedAlbums, setSelectedAlbums] = useState([]) + + // PhotoSelection context state + const [contextState, setContextState] = useState({ + selectedIds: [], + assets: [], + config: { + albumId: albumId, + sort: "fileOriginalDate", + sortOrder: "asc" + }, + updateContext: (newConfig: Partial) => { + setContextState(prevState => ({ + ...prevState, + ...newConfig, + config: newConfig.config ? { ...prevState.config, ...newConfig.config } : prevState.config + })); + } + }); + + const selectedAssets = useMemo(() => + contextState.assets.filter((a) => contextState.selectedIds.includes(a.id)), + [contextState.assets, contextState.selectedIds] + ); const fetchAlbumInfo = async () => { setLoading(true) @@ -38,13 +66,12 @@ export default function AlbumListPage() { fetchAlbumInfo() }, []) - const handleSelect = (checked: boolean, albumId: string) => { - if (checked) { - setSelectedAlbums([...selectedAlbums, albumId]) - } else { - setSelectedAlbums(selectedAlbums.filter((id) => id !== albumId)) - } - } + // Update context albumId when router albumId changes + useEffect(() => { + contextState.updateContext({ + config: { ...contextState.config, albumId: albumId } + }); + }, [albumId]); const handleSelectPerson = (personId: string) => { if (faceId === personId) { @@ -65,6 +92,22 @@ export default function AlbumListPage() { } } + const handleDelete = () => { + return deleteAssets(contextState.selectedIds).then(() => { + const newAssets = contextState.assets.filter((a) => !contextState.selectedIds.includes(a.id)); + contextState.updateContext({ + selectedIds: [], + assets: newAssets, + }); + }) + } + + const handleOffsetComplete = () => { + contextState.updateContext({ + selectedIds: [], + }); + } + const renderContent = () => { if (loading) { return @@ -83,8 +126,9 @@ export default function AlbumListPage() {
) } + return ( - +
- {renderContent()} + + {renderContent()} + {selectedAssets.length > 0 && + +
+

+ {contextState.selectedIds.length} Selected +

+
+ {contextState.selectedIds.length === contextState.assets.length ? ( + + ) : ( + + )} + +
+ + + +
+
+
+ } +
) }