Merge pull request #162 from varun-raj/july-release

July release
This commit is contained in:
Varun Raj Manoharan authored and GitHub committed 2025-07-27 18:05:45 +05:30
commit 3e022ac784
26 files changed
+979 -200

No files matched your search

+116 -34
View File
@@ -1,30 +1,38 @@
import "yet-another-react-lightbox/styles.css";
import { listAlbumAssets } from "@/handlers/api/album.handler";
import { useConfig } from "@/contexts/ConfigContext";
import { IAlbum } from "@/types/album";
import { IAlbum, IAlbumPerson } 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";
import { PERSON_THUBNAIL_PATH } from "@/config/routes";
import Image from "next/image";
interface AlbumImagesProps {
album: IAlbum;
selectedPerson: IAlbumPerson | null;
}
interface IAssetFilter {
faceId?: string;
page: number;
}
export default function AlbumImages({ album }: AlbumImagesProps) {
export default function AlbumImages({ album, selectedPerson }: 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 +40,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 +58,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 +139,7 @@ export default function AlbumImages({ album }: AlbumImagesProps) {
faceId,
page: 1,
});
setAssets([]);
updateContext({ assets: [], selectedIds: [] });
setHasMore(true);
}, [faceId]);
@@ -97,11 +160,30 @@ 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 +200,6 @@ export default function AlbumImages({ album }: AlbumImagesProps) {
</Button>
)}
</div>
</PhotoSelectionContext.Provider>
</>
);
}
+156 -79
View File
@@ -1,5 +1,5 @@
import React, { useEffect, useMemo, useState } from 'react'
import { IAlbum } from '@/types/album'
import React, { useEffect, useImperativeHandle, useMemo, useState } from 'react'
import { IAlbum, IAlbumPerson } from '@/types/album'
import { getAlbumPeople } from '@/handlers/api/album.handler'
import Loader from '@/components/ui/loader'
import LazyImage from '@/components/ui/lazy-image'
@@ -14,20 +14,23 @@ import { Button } from '@/components/ui/button'
import { updatePerson } from '@/handlers/api/people.handler'
import { Checkbox } from '@/components/ui/checkbox'
import { Input } from '@/components/ui/input'
import { Accordion, AccordionContent, AccordionItem, AccordionTrigger } from '@/components/ui/accordion'
import { CheckIcon } from '@radix-ui/react-icons'
import { HoverCard, HoverCardContent, HoverCardTrigger } from '@/components/ui/hover-card'
interface AlbumPeopleProps {
album: IAlbum
onSelect: (personId: string) => void
onSelect: (person: IAlbumPerson) => void
readOnly?: boolean
}
interface IAlbumPerson {
id: string
name: string
numberOfPhotos: number
export interface IAlbumPeopleRef {
updatePerson: (person: IAlbumPerson) => void
mergePerson: (oldPerson: IAlbumPerson, newPerson: IAlbumPerson) => void
}
export default function AlbumPeople({ album, onSelect, readOnly }: AlbumPeopleProps) {
const AlbumPeople = React.forwardRef<IAlbumPeopleRef, AlbumPeopleProps>(({ album, onSelect, readOnly }, ref) => {
const { exImmichUrl } = useConfig()
const router = useRouter()
const { query, pathname } = router
@@ -47,6 +50,13 @@ export default function AlbumPeople({ album, onSelect, readOnly }: AlbumPeoplePr
return people.filter((person) => person.name.toLowerCase().includes(searchQuery.toLowerCase()))
}, [people, searchQuery])
const { knownPeople, unknownPeople } = useMemo(() => {
return {
knownPeople: filteredPeople.filter((person) => person.name),
unknownPeople: filteredPeople.filter((person) => !person.name)
}
}, [filteredPeople])
const fetchPeople = async () => {
return getAlbumPeople(album.id).then((people) => {
setPeople(people)
@@ -91,10 +101,31 @@ export default function AlbumPeople({ album, onSelect, readOnly }: AlbumPeoplePr
}
}
const handleUnknownPeopleCheck = (checked: boolean) => {
setSelectedPeople(checked ? unknownPeople.map((person) => person.id) : [])
router.push({
pathname,
query: {
...query,
faceId: null
}
})
}
useEffect(() => {
fetchPeople()
}, [])
useImperativeHandle(ref, () => ({
updatePerson: (person: IAlbumPerson) => {
setPeople((oldPeople) => oldPeople.map((p) => p.id === person.id ? person : p))
},
mergePerson: (oldPerson: IAlbumPerson, newPerson: IAlbumPerson) => {
setPeople((oldPeople) => oldPeople.map((p) => p.id === oldPerson.id ? newPerson : p))
}
}))
if (loading) {
return <Loader />
}
@@ -102,16 +133,73 @@ export default function AlbumPeople({ album, onSelect, readOnly }: AlbumPeoplePr
return <div>{errorMessage}</div>
}
const renderPerson = (person: IAlbumPerson) => (
<div
className={cn(
'flex items-center gap-2 cursor-pointer hover:bg-gray-300 dark:hover:bg-gray-700 rounded-md p-1',
selectedPerson?.id === person.id ? "bg-gray-300 dark:bg-gray-700" : ""
)}
key={person.id}
onClick={() => {
if (selectionMode) {
handleBulkSelect(person.id)
} else {
onSelect(person)
}
}}
>
{selectionMode && (
<Checkbox
id={person.id + "_checkbox"}
checked={selectedPeople.includes(person.id)}
onCheckedChange={() => handleBulkSelect(person.id)}
/>
)}
<LazyImage
role="button"
className={
cn("cursor-pointer h-10 w-10 min-w-10 rounded-full",
)
}
src={PERSON_THUBNAIL_PATH(person.id)} alt={person.name} />
<div className='flex flex-col'>
<p className='text-sm'>{person.name || "No Name"}</p>
<p className={
cn("text-xs text-gray-500 dark:text-gray-400")
}>{person.numberOfPhotos} photos</p>
</div>
</div>
)
return (
<div className="overflow-y-auto min-w-[200px] sticky top-0 py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] border-r border-gray-200 dark:border-zinc-800 flex flex-col gap-2 px-2">
<Input
placeholder="Search"
className="w-full"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
<div className="overflow-y-auto min-w-[200px] sticky top-0 py-2 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] border-r border-gray-200 dark:border-zinc-800 flex flex-col gap-2 px-2">
<div className="flex items-center gap-2">
<Input
placeholder="Search"
className="flex-1"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
/>
{!readOnly && !selectedPerson && (
<Button
variant={selectionMode ? "default" : "outline"}
size="sm"
className="h-8 w-8 p-0"
onClick={() => {
setSelectionMode(!selectionMode)
if (selectionMode) {
setSelectedPeople([])
}
}}
>
<CheckIcon className="h-4 w-4" />
</Button>
)}
</div>
{selectedPerson && (
<div className='flex flex-col gap-2 bg-white dark:bg-zinc-900 p-2 rounded-md'>
<div className='flex flex-col gap-2 bg-white dark:bg-zinc-900 py-2 rounded-md'>
<div className='flex items-center gap-2'>
<Image
src={PERSON_THUBNAIL_PATH(selectedPerson.id)}
@@ -121,6 +209,7 @@ export default function AlbumPeople({ album, onSelect, readOnly }: AlbumPeoplePr
className="rounded-full"
/>
<Link target="_blank" href={`${exImmichUrl}/people/${selectedPerson.id}`}
className="text-sm font-medium">
{selectedPerson.name || "No Name"}
@@ -147,7 +236,7 @@ export default function AlbumPeople({ album, onSelect, readOnly }: AlbumPeoplePr
}
})
}} />
<Button disabled={hidingPerson} className="!py-0.5 !px-2 text-xs h-7 flex-1" variant="outline" onClick={() => handleHidePerson(selectedPerson.id)}>
<Button disabled={hidingPerson} variant={"outline"} className="!py-0.5 !px-2 text-xs h-7 flex-1" onClick={() => handleHidePerson(selectedPerson.id)}>
Hide
</Button>
</div>
@@ -155,69 +244,57 @@ export default function AlbumPeople({ album, onSelect, readOnly }: AlbumPeoplePr
</div>
)}
<div className="flex items-center gap-2 justify-between">
<p className="text-sm font-medium">People</p>
{!readOnly && (
<>
{!selectedPerson && (
<Button variant="outline" className="!py-0.5 !px-2 text-xs h-7" onClick={() => {
setSelectionMode(!selectionMode)
setSelectedPeople([])
}}>
{selectionMode ? "Cancel" : "Select"}
</Button>
)}
{selectedPeople.length > 0 && (
<div className='absolute mx-auto bottom-0 w-full py-2 bg-white darl:bg-black -mx-2 px-2'>
<Button variant="outline" className="!py-0.5 !px-2 text-xs h-7" onClick={handleHideSelectedPeople}>
Hide {selectedPeople.length} people
</Button>
<div className='flex flex-col gap-1 flex-1 overflow-y-auto'>
<Accordion type="multiple" className="w-full">
<AccordionItem value="known-people" className="border-none">
<AccordionTrigger className="py-2 hover:no-underline">
<div className="flex items-center gap-2 justify-between w-full">
<p className="text-xs font-medium">Known ({knownPeople.length})</p>
</div>
)}
</>
)}
</div>
<div className="flex flex-col overflow-x-hidden gap-2">
{filteredPeople.map((person) => (
<div
className={cn(
'flex items-center gap-2 cursor-pointer hover:bg-gray-300 dark:hover:bg-gray-700 rounded-md p-1',
selectedPerson?.id === person.id ? "bg-gray-300 dark:bg-gray-700" : ""
)}
key={person.id}
onClick={() => {
if (selectionMode) {
handleBulkSelect(person.id)
} else {
onSelect(person.id)
}
}}
>
{selectionMode && (
<Checkbox
id={person.id + "_checkbox"}
checked={selectedPeople.includes(person.id)}
onCheckedChange={() => handleBulkSelect(person.id)}
/>
)}
<LazyImage
role="button"
className={
cn("cursor-pointer h-10 w-10 min-w-10 rounded-full border-2",
!!person.name ? "border-green-500" : "border-gray-500",
)
}
src={PERSON_THUBNAIL_PATH(person.id)} alt={person.name} />
<div className='flex flex-col'>
<p>{person.name || "No Name"}</p>
<p className={
cn("text-xs text-gray-500 dark:text-gray-400")
}>{person.numberOfPhotos} photos</p>
</div>
</AccordionTrigger>
<AccordionContent>
<div className="flex flex-col gap-1">
{knownPeople.map(renderPerson)}
</div>
</AccordionContent>
</AccordionItem>
{unknownPeople.length > 0 && (
<AccordionItem value="unknown-people" className="border-none">
<AccordionTrigger className="py-2 hover:no-underline">
<div className="flex items-center gap-2 justify-between w-full">
<p className="text-xs font-medium">Unknown ({unknownPeople.length})</p>
<Checkbox
id='unknown-people-checkbox'
checked={selectedPeople.length === unknownPeople.length}
onCheckedChange={(checked: boolean) => {
handleUnknownPeopleCheck(checked)
}}
onClick={(e) => e.stopPropagation()}
/>
</div>
</AccordionTrigger>
<AccordionContent>
<div className="flex flex-col gap-1">
{unknownPeople.map(renderPerson)}
</div>
</AccordionContent>
</AccordionItem>
)}
</Accordion>
{selectedPeople.length > 0 && (
<div className='sticky bottom-0 w-full py-2 bg-white dark:bg-zinc-900 border-t border-gray-200 dark:border-zinc-800'>
<Button variant="default" className="!py-0.5 !px-2 text-xs h-7 w-full" onClick={handleHideSelectedPeople}>
Hide {selectedPeople.length} people
</Button>
</div>
))}
)}
</div>
</div>
)
}
})
AlbumPeople.displayName = "AlbumPeople"
export default AlbumPeople
@@ -0,0 +1,113 @@
import FloatingBar from '@/components/shared/FloatingBar'
import { AlertDialog, IAlertDialogActions } from '@/components/ui/alert-dialog'
import { Autocomplete, AutocompleteOption } from '@/components/ui/autocomplete'
import { useToast } from '@/components/ui/use-toast'
import { PERSON_THUBNAIL_PATH } from '@/config/routes'
import { mergePerson, searchPeople, updatePerson } from '@/handlers/api/people.handler'
import { IAlbumPerson } from '@/types/album'
import Image from 'next/image'
import { useRef, useState } from 'react'
interface AlbumPersonNameBarProps {
selectedPerson: IAlbumPerson | null
faceId: string
onUpdate: (person: IAlbumPerson | null) => void
onMerge: (oldPerson: IAlbumPerson, newPerson: IAlbumPerson) => void
}
export default function AlbumPersonNameBar({ selectedPerson, faceId, onUpdate, onMerge }: AlbumPersonNameBarProps) {
const [newName, setNewName] = useState(selectedPerson?.name)
const [loading, setLoading] = useState(false)
const mergeDialogRef = useRef<IAlertDialogActions>(null);
const selectedPersonRef = useRef<AutocompleteOption | null>(null);
const { toast } = useToast()
const handleFormSubmit = () => {
if (!faceId) return
setLoading(true)
updatePerson(faceId, {
name: newName
})
.then((person) => {
onUpdate(person)
})
.catch((error) => {
toast({
title: "Error updating person",
description: error.message,
variant: "destructive"
})
})
.finally(() => {
setLoading(false)
})
}
const handleMerge = async (option: AutocompleteOption) => {
if (!selectedPerson) return
return mergePerson(option.value, [selectedPerson.id]).then(() => {
onMerge(selectedPerson, {
...selectedPerson,
id: option.value,
name: option.label,
})
})
.catch((error) => {
toast({
title: "Error merging person",
description: error.message,
variant: "destructive"
})
})
.finally(() => {
setLoading(false)
})
};
return (
<>
<FloatingBar>
<div className="flex items-center gap-2 justify-between w-full">
<Autocomplete
position="bottom"
loadOptions={(query: string) => searchPeople(query).then((people) => people.map((person: any) => ({
label: person.name, value: person.id,
imageUrl: person.thumbnailPath
})))}
type="text"
defaultValue={newName}
placeholder="Enter name"
autoFocus
onChange={(e) => {
setNewName(e.target.value);
}}
value={newName || ""}
onOptionSelect={(value) => {
mergeDialogRef.current?.open();
selectedPersonRef.current = value;
}}
createNewLabel="Create"
disabled={loading}
onCreateNew={() => {
console.log("create new")
handleFormSubmit();
}}
/>
</div>
</FloatingBar>
<AlertDialog
ref={mergeDialogRef}
title="Merge Person"
description="Are you sure you want to merge this person with the selected person?"
onConfirm={() => {
if (selectedPersonRef.current) {
handleMerge(selectedPersonRef.current);
}
}}
/>
</>
)
}
@@ -51,7 +51,7 @@ export default function PotentialAlbumsDates() {
}, [filters, minAssets]);
return (
<div className="min-w-[200px] py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] border-r border-gray-200 dark:border-zinc-800 flex flex-col gap-2 px-1">
<div className="min-w-[200px] py-2 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] border-r border-gray-200 dark:border-zinc-800 flex flex-col gap-2 px-1">
<div className="flex justify-between items-center gap-2">
<Select
value={filters.sortBy}
@@ -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>
))}
@@ -75,7 +75,7 @@ export default function MissingLocationDates({ groupBy }: IMissingLocationDatesP
}, [filters]);
return (
<div className="min-w-[200px] max-w-[200px] sticky top-0 py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] border-r border-gray-200 dark:border-zinc-800 flex flex-col gap-2 px-2">
<div className="min-w-[200px] max-w-[200px] sticky top-0 py-2 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] border-r border-gray-200 dark:border-zinc-800 flex flex-col gap-2 px-2">
<div className="flex justify-between items-center gap-2">
{groupBy === "album" ? (
<p className="text-sm text-gray-500 dark:text-zinc-400">Asset Count</p>
@@ -11,6 +11,8 @@ import { MapContainer, TileLayer, useMapEvents } from "react-leaflet";
import { useState } from "react";
import { IPlace } from "@/types/common";
import CustomMarker from "./CustomMarker";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
interface MapComponentProps {
location: IPlace;
@@ -33,6 +35,7 @@ const MapMouseHandler = ({ onMouseDown }: MapMouseHandlerProps) => {
export default function Map({ location, onLocationChange }: MapComponentProps) {
const [position, setPosition] = useState<LatLngExpression>([location.latitude, location.longitude]);
const [locationName, setLocationName] = useState(location.name || "");
const handleClick = (coords: LatLngExpression) => {
const normalized = L.latLng(coords);
@@ -41,23 +44,41 @@ export default function Map({ location, onLocationChange }: MapComponentProps) {
onLocationChange({
latitude: normalized.lat,
longitude: normalized.lng,
name: ""
name: locationName
});
};
const handleNameChange = (name: string) => {
setLocationName(name);
onLocationChange({
latitude: location.latitude,
longitude: location.longitude,
name: name
});
};
return (
<MapContainer
center={position}
zoom={14}
scrollWheelZoom={true}
style={{ width: '500px', height: '400px' }}
>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MapMouseHandler onMouseDown={handleClick} />
<CustomMarker position={position} />
</MapContainer>
<div className="flex flex-col gap-4">
<div className="flex flex-col gap-2">
<Label>Location Name</Label>
<Input
placeholder="Enter location name"
value={locationName}
onChange={(e) => handleNameChange(e.target.value)}
/>
</div>
<MapContainer
center={position}
zoom={14}
scrollWheelZoom={true}
style={{ width: '500px', height: '400px' }}
>
<TileLayer
url="https://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png"
/>
<MapMouseHandler onMouseDown={handleClick} />
<CustomMarker position={position} />
</MapContainer>
</div>
);
}
@@ -0,0 +1,79 @@
import { Button } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { getRecentSearchesByType, RecentSearch } from "@/lib/utils";
import { IPlace } from "@/types/common";
import { Clock, MapPin } from "lucide-react";
import React from "react";
interface RecentSearchesProps {
searchType: RecentSearch['searchType'];
onSelect: (place: IPlace) => void;
selectedPlace?: IPlace | null;
}
export default function RecentSearches({ searchType, onSelect, selectedPlace }: RecentSearchesProps) {
const recentSearches = getRecentSearchesByType(searchType);
if (recentSearches.length === 0) {
return null;
}
const formatTimeAgo = (timestamp: number) => {
const now = Date.now();
const diff = now - timestamp;
const minutes = Math.floor(diff / (1000 * 60));
const hours = Math.floor(diff / (1000 * 60 * 60));
const days = Math.floor(diff / (1000 * 60 * 60 * 24));
if (days > 0) return `${days}d ago`;
if (hours > 0) return `${hours}h ago`;
if (minutes > 0) return `${minutes}m ago`;
return 'Just now';
};
return (
<div className="mb-4">
<div className="flex items-center gap-2 mb-3">
<Clock className="h-4 w-4 text-muted-foreground" />
<h3 className="text-sm font-medium text-muted-foreground">Recent Searches</h3>
</div>
<div className="flex flex-col gap-2 max-h-[200px] overflow-y-auto">
{recentSearches.map((search, index) => (
<div
key={`${search.name}-${search.latitude}-${search.longitude}-${index}`}
onClick={() => onSelect({
name: search.name,
latitude: search.latitude,
longitude: search.longitude
})}
className={cn(
"hover:bg-zinc-200 dark:hover:bg-zinc-800 flex justify-between items-center px-3 py-2 rounded-lg cursor-pointer border",
{
"bg-zinc-200 dark:bg-zinc-800 border-primary":
selectedPlace &&
selectedPlace.name === search.name &&
selectedPlace.latitude === search.latitude &&
selectedPlace.longitude === search.longitude,
}
)}
>
<div className="flex-1 min-w-0">
<div className="flex items-center gap-2">
<MapPin className="h-3 w-3 text-muted-foreground flex-shrink-0" />
<p className="text-sm truncate">{search.name}</p>
</div>
<div className="flex items-center justify-between mt-1">
<span className="text-xs text-muted-foreground">
{search.latitude.toFixed(4)}, {search.longitude.toFixed(4)}
</span>
<span className="text-xs text-muted-foreground">
{formatTimeAgo(search.timestamp)}
</span>
</div>
</div>
</div>
))}
</div>
</div>
);
}
@@ -15,6 +15,8 @@ import TagMissingLocationSearchLatLong from "./TagMissingLocationSearchLatLong";
import TagMissingLocationOSMSearchAndAdd from "./TagMissingLocationOSMSearchAndAdd";
import dynamic from "next/dynamic";
import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
import { addRecentSearch } from "@/lib/utils";
import RecentSearches from "./RecentSearches";
const LazyMap = dynamic(() => import("./Map"), {
ssr: false
@@ -31,9 +33,15 @@ export default function TagMissingLocationDialog({
const [mapPosition, setMapPosition] = useState<IPlace>({
latitude: 48.210033,
longitude: 16.363449,
name: "Vienna, Austria"
name: ""
});
const handleMapSubmit = async (place: IPlace) => {
// Save to recent searches
addRecentSearch(place, 'map');
return onSubmit(place);
};
return (
<Dialog open={open} onOpenChange={setOpen}>
<DialogTrigger asChild >
@@ -64,11 +72,39 @@ export default function TagMissingLocationDialog({
</TabsContent>
<TabsContent value="maps">
<div className="flex flex-col gap-6 items-center ">
{/* Recent Searches */}
<RecentSearches
searchType="map"
onSelect={(place) => {
setMapPosition(place);
}}
selectedPlace={mapPosition.name ? mapPosition : null}
/>
<LazyMap location={{
latitude: isNaN(mapPosition.latitude) ? 0 : mapPosition.latitude,
longitude: isNaN(mapPosition.longitude) ? 0 : mapPosition.longitude,
name: mapPosition.name,
}} onLocationChange={setMapPosition} />
<div className="flex gap-2">
<Button
variant="outline"
onClick={() => setMapPosition({
latitude: 48.210033,
longitude: 16.363449,
name: ""
})}
>
Reset
</Button>
<Button
variant="default"
onClick={() => handleMapSubmit(mapPosition)}
disabled={!mapPosition.name}
>
Tag Location
</Button>
</div>
</div>
</TabsContent>
</Tabs>
@@ -4,11 +4,12 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import Loader from "@/components/ui/loader";
import { useToast } from "@/components/ui/use-toast";
import { cn } from "@/lib/utils";
import { cn, addRecentSearch } from "@/lib/utils";
import { IPlace } from "@/types/common";
import axios from "axios";
import { Check } from "lucide-react";
import React, { useRef, useState } from "react";
import RecentSearches from "./RecentSearches";
interface ITagMissingLocationSearchAndAddProps {
onSubmit: (place: IPlace) => Promise<any>;
@@ -107,6 +108,8 @@ export default function TagMissingLocationOSMSearchAndAdd(
setSubmitting(true);
onSubmit(selectedPlace)
.then(() => {
// Save to recent searches
addRecentSearch(selectedPlace, 'osm');
toast({
title: "Location updated",
description: "Location updated successfully",
@@ -136,6 +139,19 @@ export default function TagMissingLocationOSMSearchAndAdd(
handleSearch(e.target.value);
}}
/>
{/* Recent Searches */}
{!loading && !searchedPlaces && (
<RecentSearches
searchType="osm"
onSelect={(place) => {
setSelectedPlace(place);
onLocationChange(place);
}}
selectedPlace={selectedPlace}
/>
)}
<div>
{loading && <Loader />}
{!loading && searchedPlaces && searchedPlaces.length === 0 && (
@@ -5,10 +5,11 @@ import { Input } from "@/components/ui/input";
import Loader from "@/components/ui/loader";
import { useToast } from "@/components/ui/use-toast";
import { searchPlaces } from "@/handlers/api/common.handler";
import { cn } from "@/lib/utils";
import { cn, addRecentSearch } from "@/lib/utils";
import { IPlace } from "@/types/common";
import { Check } from "lucide-react";
import React, { useRef, useState } from "react";
import RecentSearches from "./RecentSearches";
interface ITagMissingLocationSearchAndAddProps {
onSubmit: (place: IPlace) => Promise<any>;
@@ -70,6 +71,8 @@ export default function TagMissingLocationSearchAndAdd(
setSubmitting(true);
onSubmit(selectedPlace)
.then(() => {
// Save to recent searches
addRecentSearch(selectedPlace, 'immich');
toast({
title: "Location updated",
description: "Location updated successfully",
@@ -101,6 +104,18 @@ export default function TagMissingLocationSearchAndAdd(
}}
/>
</div>
{/* Recent Searches */}
{!loading && !searchedPlaces && (
<RecentSearches
searchType="immich"
onSelect={(place) => {
setSelectedPlace(place);
}}
selectedPlace={selectedPlace}
/>
)}
<div>
{loading && <Loader />}
{!loading && searchedPlaces && searchedPlaces.length === 0 && (
@@ -113,9 +128,9 @@ export default function TagMissingLocationSearchAndAdd(
key={place.name}
onClick={() => handleSelect(place)}
className={cn(
"hover:bg-zinc-200 dark:hover:bg-zinc-800 flex justify-between items-center px-2 py-1 rounded-lg cursor-pointer",
"hover:bg-gray-300 dark:hover:bg-gray-700 flex justify-between items-center px-2 py-1 rounded-lg cursor-pointer",
{
"bg-zinc-900 dark:bg-zinc-200":
"bg-gray-300 dark:bg-gray-700":
selectedPlace && selectedPlace.name === place.name,
}
)}
@@ -4,8 +4,10 @@ import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { useToast } from "@/components/ui/use-toast";
import { addRecentSearch } from "@/lib/utils";
import { IPlace } from "@/types/common";
import React, { useEffect, useMemo, useState } from "react";
import RecentSearches from "./RecentSearches";
interface TagMissingLocationSearchLatLongProps {
onSubmit: (place: IPlace) => Promise<any>;
@@ -52,6 +54,8 @@ export default function TagMissingLocationSearchLatLong(
setSubmitting(true);
onSubmit(formData)
.then(() => {
// Save to recent searches
addRecentSearch(formData, 'latlong');
toast({
title: "Location updated",
description: "Location updated successfully",
@@ -119,6 +123,17 @@ export default function TagMissingLocationSearchLatLong(
</div>
</div>
{/* Recent Searches */}
<RecentSearches
searchType="latlong"
onSelect={(place) => {
setFormData(place);
onLocationChange(place);
setLatLong(`${place.latitude}, ${place.longitude}`);
}}
selectedPlace={formData.name ? formData : null}
/>
<div className="self-end">
<Button
variant="outline"
+1 -3
View File
@@ -6,10 +6,8 @@ interface FloatingBarProps {
export default function FloatingBar({ children }: FloatingBarProps) {
return (
<div className='absolute bottom-10 left-0 right-0'>
<div className='max-w-2xl mx-auto py-2 px-2 rounded-lg flex justify-between items-center bg-white dark:bg-zinc-900 border-t border-zinc-200 dark:border-zinc-800 border'>
<div className='absolute bottom-10 left-0 right-0 max-w-2xl mx-auto py-2 px-2 rounded-lg flex justify-between items-center bg-white dark:bg-zinc-900 border-t border-zinc-200 dark:border-zinc-800 border shadow-lg'>
{children}
</div>
</div>
)
}
+1 -1
View File
@@ -48,7 +48,7 @@ export default function Header({ leftComponent, rightComponent, title }: IProps)
</Head>
)}
<header key="header" className={
clsx("sticky z-10 top-0 w-full flex h-14 items-center gap-4 border-b bg-white dark:bg-black px-4 lg:h-[60px] lg:px-6")
clsx("sticky z-10 top-0 w-full flex h-12 items-center gap-4 border-b bg-white dark:bg-black px-4 lg:px-6")
}>
<Sheet>
<SheetTrigger asChild>
+4 -4
View File
@@ -18,14 +18,14 @@ export default function Sidebar() {
return (
<div className="hidden border-r bg-muted/40 md:block max-h-screen min-h-screen">
<div className="flex h-full max-h-screen flex-col gap-2">
<div className="flex h-14 items-center justify-between border-b px-2 lg:h-[60px] lg:px-2">
<div className="flex h-12 items-center justify-between border-b px-2 lg:px-2">
<Link href="/" className="flex items-center gap-1 font-semibold">
<img
src="/favicon.png"
width={32}
height={32}
width={26}
height={26}
alt="Immich Power Tools"
className="w-8 h-8"
className="w-6 h-6"
/>
<span className="">Immich Power Tools</span>
</Link>
+3 -1
View File
@@ -20,6 +20,7 @@ export interface AutocompleteProps extends React.InputHTMLAttributes<HTMLInputEl
isLoading?: boolean
onCreateNew?: (inputValue: string) => void
createNewLabel?: string
position?: "top" | "bottom"
}
const Autocomplete = React.forwardRef<HTMLInputElement, AutocompleteProps>(
@@ -34,6 +35,7 @@ const Autocomplete = React.forwardRef<HTMLInputElement, AutocompleteProps>(
isLoading: externalLoading,
onCreateNew,
createNewLabel = "Create new",
position = "top",
...props
}, forwardedRef) => {
const [open, setOpen] = React.useState(false)
@@ -193,7 +195,7 @@ const Autocomplete = React.forwardRef<HTMLInputElement, AutocompleteProps>(
}}
/>
{open && (filteredOptions.length > 0 || isLoading || showCreateNew) && (
<div className="absolute left-0 right-0 top-full z-50 mt-1 max-h-[300px] overflow-auto rounded-md border bg-popover shadow-md">
<div className={cn("absolute left-0 right-0 z-50 mt-1 max-h-[300px] overflow-auto rounded-md border bg-popover shadow-md", position === "top" ? "top-full" : "bottom-full")}>
{isLoading ? (
<div className="px-3 py-2 text-sm text-muted-foreground">
Loading...
+5 -5
View File
@@ -1,11 +1,11 @@
import { GalleryHorizontal, GalleryVerticalEnd, Image as ImageIcon, MapPin, MapPinX, Rewind, Search, User } from "lucide-react";
export const sidebarNavs = [
{
title: "Rewind 2024",
link: "/rewind",
icon: <Rewind className="h-4 w-4" />,
},
// {
// title: "Rewind 2024",
// link: "/rewind",
// icon: <Rewind className="h-4 w-4" />,
// },
{
title: "Find Assets",
link: "/find",
View File
Whitespace-only changes.
-1
View File
@@ -19,7 +19,6 @@ export class APIError extends Error {
}
const handleErrors = (error: AxiosError | any) => {
let errorObject = {}
if (error.response && error.response.data) {
return Promise.reject({
+58
View File
@@ -4,3 +4,61 @@ import { twMerge } from "tailwind-merge"
export function cn(...inputs: ClassValue[]) {
return twMerge(clsx(inputs))
}
// Recent searches localStorage utilities
export const RECENT_SEARCHES_KEY = 'immich-recent-location-searches';
export const MAX_RECENT_SEARCHES = 10;
export interface RecentSearch {
name: string;
latitude: number;
longitude: number;
timestamp: number;
searchType: 'osm' | 'immich' | 'latlong' | 'map';
}
export const getRecentSearches = (): RecentSearch[] => {
if (typeof window === 'undefined') return [];
try {
const stored = localStorage.getItem(RECENT_SEARCHES_KEY);
return stored ? JSON.parse(stored) : [];
} catch (error) {
console.error('Error reading recent searches from localStorage:', error);
return [];
}
};
export const addRecentSearch = (place: { name: string; latitude: number; longitude: number }, searchType: RecentSearch['searchType']): void => {
if (typeof window === 'undefined') return;
try {
const recentSearches = getRecentSearches();
const newSearch: RecentSearch = {
name: place.name,
latitude: place.latitude,
longitude: place.longitude,
timestamp: Date.now(),
searchType
};
// Remove duplicate if exists
const filteredSearches = recentSearches.filter(
search => !(search.name === place.name &&
search.latitude === place.latitude &&
search.longitude === place.longitude)
);
// Add new search at the beginning
const updatedSearches = [newSearch, ...filteredSearches].slice(0, MAX_RECENT_SEARCHES);
localStorage.setItem(RECENT_SEARCHES_KEY, JSON.stringify(updatedSearches));
} catch (error) {
console.error('Error saving recent search to localStorage:', error);
}
};
export const getRecentSearchesByType = (searchType: RecentSearch['searchType']): RecentSearch[] => {
const allSearches = getRecentSearches();
return allSearches.filter(search => search.searchType === searchType);
};
+139 -19
View File
@@ -3,14 +3,22 @@ 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 { IAlbum } from '@/types/album'
import { deleteAssets, updateAssets } from '@/handlers/api/asset.handler'
import { IAlbum, IAlbumPerson } from '@/types/album'
import Link from 'next/link'
import React, { useEffect, useState } from 'react'
import React, { useEffect, useState, useMemo, useRef } from 'react'
import { useRouter } from 'next/router'
import AlbumPeople from '@/components/albums/info/AlbumPeople'
import AlbumPeople, { IAlbumPeopleRef } 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'
import { Input } from '@/components/ui/input'
import AlbumPersonNameBar from '@/components/albums/info/AlbumPersonNameBar'
export default function AlbumListPage() {
const { exImmichUrl } = useConfig()
@@ -20,7 +28,31 @@ export default function AlbumListPage() {
const [albumInfo, setAlbumInfo] = useState<IAlbum>()
const [loading, setLoading] = useState(false)
const [errorMessage, setErrorMessage] = useState('')
const [selectedAlbums, setSelectedAlbums] = useState<string[]>([])
const [selectedPerson, setSelectedPerson] = useState<IAlbumPerson | null>(null)
const albumPeopleRef = useRef<IAlbumPeopleRef>(null)
// 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)
@@ -36,18 +68,18 @@ export default function AlbumListPage() {
useEffect(() => {
fetchAlbumInfo()
}, [])
// Update context albumId when router albumId changes
useEffect(() => {
contextState.updateContext({
config: { ...contextState.config, albumId: albumId }
});
}, [albumId]);
const handleSelect = (checked: boolean, albumId: string) => {
if (checked) {
setSelectedAlbums([...selectedAlbums, albumId])
} else {
setSelectedAlbums(selectedAlbums.filter((id) => id !== albumId))
}
}
const handleSelectPerson = (personId: string) => {
if (faceId === personId) {
const handleSelectPerson = (person: IAlbumPerson) => {
setSelectedPerson(person)
if (faceId === person.id) {
router.push({
pathname,
query: {
@@ -59,12 +91,40 @@ export default function AlbumListPage() {
pathname,
query: {
albumId,
faceId: personId
faceId: person.id
}
})
}
}
const handleUpdatePerson = (person: IAlbumPerson | null) => {
setSelectedPerson(person)
if (person) {
albumPeopleRef.current?.updatePerson(person)
}
}
const handleMergePerson = (oldPerson: IAlbumPerson, newPerson: IAlbumPerson) => {
setSelectedPerson(newPerson)
albumPeopleRef.current?.mergePerson(oldPerson, newPerson)
}
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 />
@@ -76,15 +136,16 @@ export default function AlbumListPage() {
<div className="flex divide-y">
{albumInfo && (
<>
<AlbumPeople album={albumInfo} key={albumInfo.id} onSelect={handleSelectPerson} />
<AlbumImages album={albumInfo} key={albumInfo.id} />
<AlbumPeople ref={albumPeopleRef} album={albumInfo} key={albumInfo.id} onSelect={handleSelectPerson} />
<AlbumImages album={albumInfo} key={albumInfo.id} selectedPerson={selectedPerson} />
</>
)}
</div>
)
}
return (
<PageLayout className="!p-0 !mb-0">
<PageLayout className="!p-0 !mb-0 relative">
<Header
leftComponent={albumInfo?.albumName || "Loading..."}
rightComponent={
@@ -111,7 +172,66 @@ 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>
}
{!selectedAssets.length && faceId && !selectedPerson?.name && (
<AlbumPersonNameBar selectedPerson={selectedPerson} faceId={faceId} onUpdate={handleUpdatePerson} onMerge={handleMergePerson} />
)}
</PhotoSelectionContext.Provider>
</PageLayout>
)
}
+2
View File
@@ -79,6 +79,8 @@ export default function PotentialAlbums() {
});
const newAssets = contextState.assets.filter(a => !contextState.selectedIds.includes(a.id));
updateContext({ selectedIds: [], assets: newAssets });
}).catch((error) => {
console.log("Error", error);
})
}
+4 -1
View File
@@ -3,7 +3,7 @@ import { NextApiRequest } from "next";
import { db } from "@/config/db";
import { getCurrentUser } from "@/handlers/serverUtils/user.utils";
import { NextApiResponse } from "next";
import { and, eq, isNotNull } from "drizzle-orm";
import { and, desc, eq, isNotNull } from "drizzle-orm";
import { assets } from "@/schema/assets.schema";
import { albumsAssetsAssets } from "@/schema/albumAssetsAssets.schema";
import { assetFaces, exif, person } from "@/schema";
@@ -56,6 +56,7 @@ export default async function handler(
eq(assets.status, "active"),
faceId ? eq(assetFaces.personId, faceId) : undefined,
))
.orderBy(desc(assets.id), desc(assets.localDateTime))
.limit(100)
.offset(100 * (page - 1));
@@ -71,6 +72,8 @@ export default async function handler(
orientation: asset?.orientation,
downloadUrl: asset?.id ? ASSET_VIDEO_PATH(asset.id) : null,
};
}).sort((b, a) => {
return new Date(b.localDateTime || 0).getTime() - new Date(a.localDateTime || 0).getTime();
});
res.status(200).json(cleanedAssets);
}
+3 -3
View File
@@ -28,9 +28,9 @@ export default async function handler(req: NextApiRequest, res: NextApiResponse)
res.setHeader(key, value)
})
// Stream the response body
const reader = response.body?.getReader()
if (reader) {
// Only stream the response body if it exists and has content
if (response.body) {
const reader = response.body.getReader()
while (true) {
const { done, value } = await reader.read()
if (done) break
+1 -1
View File
@@ -95,7 +95,7 @@ export default function PersonPage() {
}
/>
<div className="flex divide-y">
<div className="overflow-y-auto sticky top-0 min-w-[200px] py-4 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] dark:bg-zinc-900 bg-gray-200 flex flex-col gap-2 px-2">
<div className="overflow-y-auto sticky top-0 min-w-[200px] py-2 max-h-[calc(100vh-60px)] min-h-[calc(100vh-60px)] dark:bg-zinc-900 bg-gray-200 flex flex-col gap-2 px-2">
<ul className="flex flex-col gap-1">
<li>
<Link href={{
+7
View File
@@ -38,4 +38,11 @@ export interface IAlbumCreate {
role: string;
userId: string;
}[];
}
export interface IAlbumPerson {
id: string
name: string
numberOfPhotos: number
}