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.
This commit is contained in:
Varun Raj committed 2025-07-21 09:40:27 +05:30
1 parent c8f773a10f
commit 917f694db7
3 files changed
+384 -71

No files matched your search

+110 -32
View File
@@ -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<IAsset[]>([]);
// Use context from parent instead of managing own
const { selectedIds, updateContext, assets } = usePhotoSelectionContext();
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState<string | null>(null);
const [filters, setFilters] = useState<IAssetFilter>({
@@ -32,32 +37,17 @@ export default function AlbumImages({ album }: AlbumImagesProps) {
page: 1,
});
const [hasMore, setHasMore] = useState(true);
// Initialize context state
const [contextState, setContextState] = useState<IPhotoSelectionContext>({
selectedIds: [],
assets: [],
config: {},
updateContext: (newConfig: Partial<IPhotoSelectionContext>) => {
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: (
<a href={exImmichUrl + "/photos/" + p.id} target="_blank" rel="noopener noreferrer">
Open in Immich
</a>
),
},
],
}));
}, [assets, selectedIds, exImmichUrl]);
const slides = useMemo(
() =>
images.map(({ original, width, height }) => ({
src: original,
width,
height,
})),
[images]
);
const handleClick = (idx: number, asset: IAsset, event: MouseEvent<HTMLElement>) => {
if (selectedIds.length > 0) {
handleSelect(idx, asset, event);
} else {
setIndex(idx);
}
};
const handleSelect = (_idx: number, asset: IAsset, event: MouseEvent<HTMLElement>) => {
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 (
<PhotoSelectionContext.Provider
value={{ ...contextState, updateContext: contextState.updateContext }}
>
<div className="w-full p-2">
<AssetGrid assets={assets} />
<>
<Lightbox
slides={slides}
plugins={[Captions]}
open={index >= 0}
index={index}
close={() => setIndex(-1)}
/>
<div className="w-full p-2 overflow-y-auto max-h-[calc(100vh-60px)]">
<Gallery
images={images}
onClick={handleClick}
enableImageSelection={true}
onSelect={handleSelect}
thumbnailImageComponent={LazyGridImage}
tagStyle={{
color: "white",
fontSize: "12px",
backgroundColor: "rgba(0, 0, 0)",
padding: "2px",
borderRadius: "5px",
}}
/>
{hasMore && (
<Button
variant="outline"
@@ -118,6 +196,6 @@ export default function AlbumImages({ album }: AlbumImagesProps) {
</Button>
)}
</div>
</PhotoSelectionContext.Provider>
</>
);
}
@@ -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<IAsset[]>(_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<Record<string, string>>({});
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
</Button>
</DialogTrigger>
<DialogContent className='max-w-[800px]'>
<DialogContent className='max-w-[900px]'>
<DialogHeader>
<DialogTitle>Offset Asset Dates</DialogTitle>
</DialogHeader>
<form onSubmit={handleSubmit} className='flex items-end gap-2'>
<div>
<Label>Years</Label>
<Input type="number" value={offsetData.years} onChange={(e) => handleChange("years", parseInt(e.target.value))} />
<form onSubmit={handleSubmit} className='space-y-4'>
<div className='grid grid-cols-4 gap-4 items-end'>
<div>
<Label>Years</Label>
<Input type="number" value={offsetData.years} onChange={(e) => handleChange("years", parseInt(e.target.value) || 0)} />
</div>
<div>
<Label>Days</Label>
<Input type="number" value={offsetData.days} onChange={(e) => handleChange("days", parseInt(e.target.value) || 0)} />
</div>
<div>
<Label>Hours</Label>
<Input type="number" value={offsetData.hours} onChange={(e) => handleChange("hours", parseInt(e.target.value) || 0)} />
</div>
<div>
<Label>Minutes</Label>
<Input type="number" value={offsetData.minutes} onChange={(e) => handleChange("minutes", parseInt(e.target.value) || 0)} />
</div>
</div>
<div>
<Label>Days</Label>
<Input type="number" value={offsetData.days} onChange={(e) => handleChange("days", parseInt(e.target.value))} />
<div className='grid grid-cols-3 gap-4 items-end'>
<div>
<Label>Seconds</Label>
<Input type="number" value={offsetData.seconds} onChange={(e) => handleChange("seconds", parseInt(e.target.value) || 0)} />
</div>
<div>
<Label>Convert to Timezone</Label>
<Select value={offsetData.timezone} onValueChange={(value) => handleChange("timezone", value)}>
<SelectTrigger>
<SelectValue placeholder="Select timezone (optional)" />
</SelectTrigger>
<SelectContent>
{TIMEZONE_OPTIONS.map((tz) => (
<SelectItem key={tz.value} value={tz.value}>
{tz.label}
</SelectItem>
))}
</SelectContent>
</Select>
</div>
<div>
<Button disabled={loading} type="submit" className="w-full">Offset Dates</Button>
</div>
</div>
<div>
<Label>Hours</Label>
<Input type="number" value={offsetData.hours} onChange={(e) => handleChange("hours", parseInt(e.target.value))} />
</div>
<div>
<Label>Minutes</Label>
<Input type="number" value={offsetData.minutes} onChange={(e) => handleChange("minutes", parseInt(e.target.value))} />
</div>
<div>
<Label>Seconds</Label>
<Input type="number" value={offsetData.seconds} onChange={(e) => handleChange("seconds", parseInt(e.target.value))} />
</div>
<Button disabled={loading} type="submit">Offset Dates</Button>
</form>
<div className='grid grid-cols-3 gap-4 py-2 overflow-y-auto max-h-[500px]'>
{assets.map((asset) => (
@@ -106,7 +238,9 @@ export default function AssetOffsetDialog({ assets: _assets, onComplete }: IProp
{assetStatus[asset.id] === 'pending' ? <div className='absolute text-xs text-center bottom-0 left-0 right-0 bg-blue-500/50 text-white p-2'>
<p className='text-white'>Offsetting...</p>
</div> : (
<div className='absolute text-xs text-center bottom-0 left-0 right-0 bg-green-500/50 text-white p-2'>{formatDate(offsetDate(asset.dateTimeOriginal, offsetData), 'PPpp')} </div>
<div className='absolute text-xs text-center bottom-0 left-0 right-0 bg-green-500/50 text-white p-2'>
{formatDate(offsetDateWithTimezone(asset.dateTimeOriginal, offsetData, offsetData.timezone), 'PPpp')}
</div>
)}
<Image
src={asset.previewUrl}
@@ -121,7 +255,9 @@ export default function AssetOffsetDialog({ assets: _assets, onComplete }: IProp
width: '100%'
}}
/>
<div className='absolute text-xs text-center top-0 left-0 right-0 bg-red-500/50 text-white p-2'>{formatDate(asset.dateTimeOriginal, 'PPpp')}</div>
<div className='absolute text-xs text-center top-0 left-0 right-0 bg-red-500/50 text-white p-2'>
{formatDate(asset.dateTimeOriginal, 'PPpp')}
</div>
</div>
</div>
))}
+110 -11
View File
@@ -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<IAlbum>()
const [loading, setLoading] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const [selectedAlbums, setSelectedAlbums] = useState<string[]>([])
// PhotoSelection context state
const [contextState, setContextState] = useState<IPhotoSelectionContext>({
selectedIds: [],
assets: [],
config: {
albumId: albumId,
sort: "fileOriginalDate",
sortOrder: "asc"
},
updateContext: (newConfig: Partial<IPhotoSelectionContext>) => {
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 <Loader />
@@ -83,8 +126,9 @@ export default function AlbumListPage() {
</div>
)
}
return (
<PageLayout className="!p-0 !mb-0">
<PageLayout className="!p-0 !mb-0 relative">
<Header
leftComponent={albumInfo?.albumName || "Loading..."}
rightComponent={
@@ -111,7 +155,62 @@ export default function AlbumListPage() {
)
}
/>
{renderContent()}
<PhotoSelectionContext.Provider
value={{
...contextState,
updateContext: contextState.updateContext,
}}
>
{renderContent()}
{selectedAssets.length > 0 &&
<FloatingBar>
<div className="flex items-center gap-2 justify-between w-full">
<p className="text-sm text-muted-foreground">
{contextState.selectedIds.length} Selected
</p>
<div className="flex items-center gap-2">
{contextState.selectedIds.length === contextState.assets.length ? (
<Button
variant={"outline"}
size={"sm"}
onClick={() =>
contextState.updateContext({
selectedIds: [],
})
}
>
Unselect all
</Button>
) : (
<Button
variant={"outline"}
size={"sm"}
onClick={() =>
contextState.updateContext({
selectedIds: contextState.assets.map((a) => a.id),
})
}
>
Select all
</Button>
)}
<AssetOffsetDialog assets={selectedAssets} onComplete={handleOffsetComplete} />
<div className="h-[10px] w-[1px] bg-zinc-500 dark:bg-zinc-600"></div>
<AlertDialog
title="Delete the selected assets?"
description="This action will delete the selected assets and cannot be undone."
onConfirm={handleDelete}
disabled={contextState.selectedIds.length === 0}
>
<Button variant={"destructive"} size={"sm"} disabled={contextState.selectedIds.length === 0}>
Delete
</Button>
</AlertDialog>
</div>
</div>
</FloatingBar>
}
</PhotoSelectionContext.Provider>
</PageLayout>
)
}