refactor: migrate from PotentialAlbumContext to PhotoSelectionContext
- Replaced instances of PotentialAlbumContext with PhotoSelectionContext across multiple components to unify state management for photo selection. - Updated context usage in AlbumSelectorDialog, PotentialAlbumsAssets, PotentialAlbumsDates, and MissingLocation components. - Enhanced loading and error handling in asset fetching functions. - Improved user feedback by updating UI elements to reflect the number of selected assets. - Removed unused PotentialAlbumContext and related files to streamline the codebase.
This commit is contained in:
1 parent
59c8fd1139
commit
0f77c32f2f
14 files changed
+380
-268
No files matched your search
@@ -11,7 +11,7 @@ import { Button } from "../ui/button";
|
||||
import { listAlbums } from "@/handlers/api/album.handler";
|
||||
import { IAlbum, IAlbumCreate } from "@/types/album";
|
||||
import { Input } from "../ui/input";
|
||||
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
|
||||
import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
|
||||
import { Tabs, TabsContent, TabsList, TabsTrigger } from "../ui/tabs";
|
||||
import toast from "react-hot-toast";
|
||||
import { Label } from "../ui/label";
|
||||
@@ -27,12 +27,13 @@ export default function AlbumSelectorDialog({ onSelected, onCreated, onSubmit }:
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
const [search, setSearch] = useState("");
|
||||
const { selectedIds, assets } = usePotentialAlbumContext();
|
||||
const { selectedIds, assets } = usePhotoSelectionContext();
|
||||
const [formData, setFormData] = useState({
|
||||
albumName: "",
|
||||
});
|
||||
|
||||
const fetchData = () => {
|
||||
setLoading(true);
|
||||
return listAlbums()
|
||||
.then(setAlbums)
|
||||
.catch(setErrorMessage)
|
||||
@@ -45,12 +46,12 @@ export default function AlbumSelectorDialog({ onSelected, onCreated, onSubmit }:
|
||||
);
|
||||
}, [albums, search]);
|
||||
|
||||
const handleSelect = (album: IAlbum) => () => {
|
||||
const handleSelect = useCallback((album: IAlbum) => () => {
|
||||
onSelected(album).then(() => {
|
||||
setOpen(false);
|
||||
setSearch("");
|
||||
});
|
||||
}
|
||||
}, [onSelected]);
|
||||
|
||||
|
||||
const handleSubmit = useCallback((e: React.FormEvent<HTMLFormElement>) => {
|
||||
@@ -62,6 +63,7 @@ export default function AlbumSelectorDialog({ onSelected, onCreated, onSubmit }:
|
||||
toast.success("Album created successfully");
|
||||
setFormData({ albumName: "" });
|
||||
setOpen(false);
|
||||
fetchData();
|
||||
})
|
||||
.catch((e) => {
|
||||
toast.error("Failed to create album");
|
||||
@@ -73,21 +75,22 @@ export default function AlbumSelectorDialog({ onSelected, onCreated, onSubmit }:
|
||||
|
||||
|
||||
useEffect(() => {
|
||||
if (open && !albums.length) fetchData();
|
||||
if (open) fetchData();
|
||||
}, [open]);
|
||||
|
||||
const renderContent = useCallback(() => {
|
||||
if (loading) return <p>Loading...</p>;
|
||||
if (loading && !albums.length) return <p>Loading...</p>;
|
||||
if (errorMessage) return <p>{errorMessage}</p>;
|
||||
return (
|
||||
<div>
|
||||
<Input
|
||||
placeholder="Search Albums"
|
||||
value={search}
|
||||
onChange={(e) => {
|
||||
setSearch(e.target.value);
|
||||
}}
|
||||
/>
|
||||
<div className="max-h-[500px] min-h-[500px] overflow-y-auto flex flex-col gap-2 py-2">
|
||||
<div className="max-h-[450px] min-h-[450px] overflow-y-auto flex flex-col gap-2 py-2">
|
||||
{filteredAlbums.map((album) => (
|
||||
<div
|
||||
key={album.id}
|
||||
@@ -100,51 +103,59 @@ export default function AlbumSelectorDialog({ onSelected, onCreated, onSubmit }:
|
||||
<p className="font-mono text-sm">{album.albumName}</p>
|
||||
</div>
|
||||
))}
|
||||
{filteredAlbums.length === 0 && !loading && (
|
||||
<p className="text-center text-sm text-zinc-500 dark:text-zinc-400 py-4">
|
||||
No albums found matching "{search}".
|
||||
</p>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}, [albums, filteredAlbums, handleSelect, loading, errorMessage]);
|
||||
}, [filteredAlbums, handleSelect, loading, errorMessage, search]);
|
||||
|
||||
const renderCreateContent = useCallback(() => {
|
||||
const renderCreateContent = useCallback(() => {
|
||||
return (
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4 max-h-[500px] min-h-[500px]">
|
||||
<form onSubmit={handleSubmit} className="flex flex-col gap-4 max-h-[450px] min-h-[450px]">
|
||||
<p className="text-sm text-zinc-500 dark:text-zinc-400">
|
||||
Create a new album and add the selected assets to it
|
||||
Create a new album and add the selected {selectedIds.length} asset(s) to it.
|
||||
</p>
|
||||
<div className="flex flex-col gap-2">
|
||||
<Label>Album Name</Label>
|
||||
<Label htmlFor="albumName">Album Name</Label>
|
||||
<Input
|
||||
id="albumName"
|
||||
placeholder="Album Name"
|
||||
required
|
||||
value={formData.albumName}
|
||||
onChange={(e) => {
|
||||
setFormData({ ...formData, albumName: e.target.value });
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
<div className="self-end">
|
||||
<Button disabled={loading} type="submit">
|
||||
{loading ? "Creating Album" : "Create Album"}
|
||||
<div className="self-end mt-auto pt-4">
|
||||
<Button disabled={loading || !formData.albumName} type="submit">
|
||||
{loading ? "Creating Album..." : "Create Album"}
|
||||
</Button>
|
||||
</div>
|
||||
</form>
|
||||
)
|
||||
}, [loading, formData, handleSubmit]);
|
||||
}, [loading, formData, handleSubmit, selectedIds.length]);
|
||||
|
||||
return (
|
||||
<Dialog open={open} onOpenChange={setOpen}>
|
||||
<DialogTrigger asChild>
|
||||
<Button size={"sm"} disabled={!selectedIds.length}>Add to Album</Button>
|
||||
<Button size={"sm"} disabled={selectedIds.length === 0}>Add to Album</Button>
|
||||
</DialogTrigger>
|
||||
<DialogContent>
|
||||
<DialogContent className="sm:max-w-[425px]">
|
||||
<DialogHeader>
|
||||
<DialogTitle>Select Albums</DialogTitle>
|
||||
<DialogTitle>Select Album</DialogTitle>
|
||||
<DialogDescription>
|
||||
Select the albums you want to add the selected assets to
|
||||
Add the selected {selectedIds.length} asset(s) to an existing album or create a new one.
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Tabs defaultValue="albums" className="w-full">
|
||||
<TabsList className="w-full">
|
||||
<TabsTrigger className="w-full" value="albums">Albums</TabsTrigger>
|
||||
<TabsTrigger className="w-full" value="create">Create</TabsTrigger>
|
||||
<Tabs defaultValue="albums" className="w-full">
|
||||
<TabsList className="w-full grid grid-cols-2">
|
||||
<TabsTrigger value="albums">Existing Album</TabsTrigger>
|
||||
<TabsTrigger value="create">Create New</TabsTrigger>
|
||||
</TabsList>
|
||||
<TabsContent value="albums">
|
||||
{renderContent()}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import "yet-another-react-lightbox/styles.css";
|
||||
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
|
||||
import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
|
||||
import { listPotentialAlbumsAssets } from "@/handlers/api/album.handler";
|
||||
import type { IAsset } from "@/types/asset";
|
||||
import React, { type MouseEvent, useEffect, useMemo, useState } from "react";
|
||||
@@ -13,8 +13,13 @@ import LazyGridImage from "@/components/ui/lazy-grid-image";
|
||||
|
||||
export default function PotentialAlbumsAssets() {
|
||||
const { exImmichUrl } = useConfig();
|
||||
const { startDate, selectedIds, assets, updateContext } =
|
||||
usePotentialAlbumContext();
|
||||
const {
|
||||
selectedIds,
|
||||
assets,
|
||||
updateContext,
|
||||
config
|
||||
} = usePhotoSelectionContext();
|
||||
const { startDate } = config;
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
@@ -23,18 +28,28 @@ export default function PotentialAlbumsAssets() {
|
||||
const [lastSelectedIndex, setLastSelectedIndex] = useState(-1);
|
||||
|
||||
const fetchAssets = async () => {
|
||||
if (!startDate) return;
|
||||
setLoading(true);
|
||||
updateContext({
|
||||
assets: [],
|
||||
selectedIds: [],
|
||||
});
|
||||
return listPotentialAlbumsAssets({ startDate })
|
||||
.then((assets) => updateContext({ assets }))
|
||||
.then((fetchedAssets) => updateContext({ assets: fetchedAssets }))
|
||||
.catch(setErrorMessage)
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
const images = useMemo(() => {
|
||||
return assets.map((p) => ({
|
||||
const sortedAssets = [...assets].sort((a, b) => {
|
||||
try {
|
||||
return new Date(a.dateTimeOriginal ?? 0).getTime() - new Date(b.dateTimeOriginal ?? 0).getTime();
|
||||
} catch {
|
||||
return 0;
|
||||
}
|
||||
});
|
||||
|
||||
return sortedAssets.map((p) => ({
|
||||
...p,
|
||||
src: p.url as string,
|
||||
original: p.previewUrl as string,
|
||||
@@ -76,31 +91,48 @@ export default function PotentialAlbumsAssets() {
|
||||
[images]
|
||||
);
|
||||
|
||||
const handleClick = (idx: number, asset: IAsset, event: MouseEvent<HTMLElement>) => {
|
||||
if (selectedIds.length > 0 && (event.ctrlKey || event.metaKey || event.shiftKey)) {
|
||||
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),
|
||||
});
|
||||
if (event.ctrlKey || event.metaKey || selectedIds.length === 1) {
|
||||
updateContext({
|
||||
selectedIds: selectedIds.filter((id) => id !== asset.id),
|
||||
});
|
||||
} else if (!event.shiftKey) {
|
||||
updateContext({ selectedIds: [asset.id] });
|
||||
}
|
||||
} else {
|
||||
const clickedIndex = images.findIndex((image) => {
|
||||
return image.id === asset.id
|
||||
});
|
||||
if (event.shiftKey) {
|
||||
const clickedIndex = images.findIndex((image) => image.id === asset.id);
|
||||
|
||||
if (event.shiftKey && lastSelectedIndex !== -1) {
|
||||
const startIndex = Math.min(clickedIndex, lastSelectedIndex);
|
||||
const endIndex = Math.max(clickedIndex, lastSelectedIndex);
|
||||
const newSelectedIds = images.slice(startIndex, endIndex + 1).map((image) => image.id);
|
||||
const allSelectedIds = [...selectedIds, ...newSelectedIds];
|
||||
const uniqueSelectedIds = [...new Set(allSelectedIds)];
|
||||
updateContext({ selectedIds: uniqueSelectedIds });
|
||||
} else {
|
||||
if (startIndex >= 0 && endIndex < images.length) {
|
||||
const newSelectedIds = images.slice(startIndex, endIndex + 1).map((image) => image.id);
|
||||
const combined = event.ctrlKey || event.metaKey ? [...selectedIds, ...newSelectedIds] : newSelectedIds;
|
||||
const uniqueSelectedIds = [...new Set(combined)];
|
||||
updateContext({ selectedIds: uniqueSelectedIds });
|
||||
} else {
|
||||
updateContext({ selectedIds: [...selectedIds, asset.id] });
|
||||
}
|
||||
} else if (event.ctrlKey || event.metaKey) {
|
||||
updateContext({ selectedIds: [...selectedIds, asset.id] });
|
||||
} else {
|
||||
updateContext({ selectedIds: [asset.id] });
|
||||
}
|
||||
setLastSelectedIndex(clickedIndex);
|
||||
}
|
||||
|
||||
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
@@ -120,8 +152,8 @@ export default function PotentialAlbumsAssets() {
|
||||
<div className="flex flex-col gap-2 min-h-full justify-center items-center w-full">
|
||||
<CalendarArrowUp />
|
||||
<p className="text-lg">Please select a date</p>
|
||||
<p className="text-sm text-zinc-700">
|
||||
When you select a date from the left, you will see all the orphan
|
||||
<p className="text-sm text-zinc-700 dark:text-zinc-400">
|
||||
When you select a date from the left, you will see all the potential album
|
||||
assets captured on that date
|
||||
</p>
|
||||
</div>
|
||||
@@ -138,16 +170,18 @@ export default function PotentialAlbumsAssets() {
|
||||
<div className="w-full overflow-y-auto max-h-[calc(100vh-60px)]">
|
||||
<Gallery
|
||||
images={images}
|
||||
onClick={setIndex}
|
||||
onClick={handleClick}
|
||||
enableImageSelection={true}
|
||||
onSelect={handleSelect}
|
||||
thumbnailImageComponent={LazyGridImage}
|
||||
rowHeight={220}
|
||||
margin={3}
|
||||
tagStyle={{
|
||||
color: "white",
|
||||
fontSize: "12px",
|
||||
backgroundColor: "rgba(0, 0, 0)",
|
||||
padding: "2px",
|
||||
borderRadius: "5px",
|
||||
backgroundColor: "rgba(0, 0, 0, 0.7)",
|
||||
padding: "2px 4px",
|
||||
borderRadius: "3px",
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
|
||||
@@ -4,7 +4,7 @@ import {
|
||||
} from "@/handlers/api/album.handler";
|
||||
import React, { useEffect, useState } from "react";
|
||||
import PotentialDateItem from "./PotentialDateItem";
|
||||
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
|
||||
import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
|
||||
import { useRouter } from "next/router";
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -12,7 +12,9 @@ import { SortAsc, SortDesc } from "lucide-react";
|
||||
|
||||
export default function PotentialAlbumsDates() {
|
||||
const router = useRouter();
|
||||
const { updateContext, minAssets } = usePotentialAlbumContext();
|
||||
const { config, updateContext } = usePhotoSelectionContext();
|
||||
const { minAssets } = config;
|
||||
|
||||
const [dateRecords, setDateRecords] = React.useState<
|
||||
IPotentialAlbumsDatesResponse[]
|
||||
>([]);
|
||||
@@ -23,6 +25,7 @@ export default function PotentialAlbumsDates() {
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const fetchData = async () => {
|
||||
setLoading(true);
|
||||
return listPotentialAlbumsDates({
|
||||
sortBy: filters.sortBy,
|
||||
sortOrder: filters.sortOrder,
|
||||
@@ -34,7 +37,7 @@ export default function PotentialAlbumsDates() {
|
||||
};
|
||||
|
||||
const handleSelect = (date: string) => {
|
||||
updateContext({ startDate: date });
|
||||
updateContext({ config: { ...config, startDate: date } });
|
||||
router.push({
|
||||
pathname: router.pathname,
|
||||
query: { startDate: date },
|
||||
@@ -44,20 +47,21 @@ export default function PotentialAlbumsDates() {
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [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="flex justify-between items-center gap-2">
|
||||
<Select
|
||||
defaultValue={filters.sortBy}
|
||||
value={filters.sortBy}
|
||||
onValueChange={(value) => setFilters({ ...filters, sortBy: value })}
|
||||
>
|
||||
<SelectTrigger className="!p-2">
|
||||
<SelectValue placeholder="Sort by" />
|
||||
</SelectTrigger>
|
||||
<SelectContent defaultValue={filters.sortBy}>
|
||||
<SelectGroup title="Sort by">
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectLabel>Sort by</SelectLabel>
|
||||
<SelectItem value="date">Date</SelectItem>
|
||||
<SelectItem value="asset_count">Asset Count</SelectItem>
|
||||
|
||||
@@ -1,24 +1,43 @@
|
||||
import { usePotentialAlbumContext } from "@/contexts/PotentialAlbumContext";
|
||||
import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
|
||||
import { IPotentialAlbumsDatesResponse } from "@/handlers/api/album.handler";
|
||||
import { formatDate } from "@/helpers/date.helper";
|
||||
import { parseDate } from "@/helpers/date.helper";
|
||||
import { cn } from "@/lib/utils";
|
||||
import React, { useMemo } from "react";
|
||||
import React, { useEffect, useMemo, useRef } from "react";
|
||||
|
||||
interface IProps {
|
||||
record: IPotentialAlbumsDatesResponse;
|
||||
onSelect: (date: string) => void;
|
||||
}
|
||||
export default function PotentialDateItem({ record, onSelect }: IProps) {
|
||||
const { startDate } = usePotentialAlbumContext()
|
||||
const { config } = usePhotoSelectionContext();
|
||||
const { startDate } = config;
|
||||
|
||||
const itemsRef = useRef<HTMLDivElement | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (startDate === record.date) {
|
||||
itemsRef.current?.scrollIntoView({
|
||||
behavior: "auto",
|
||||
block: "nearest",
|
||||
});
|
||||
}
|
||||
}, [startDate, record.date]);
|
||||
|
||||
const dateLabel = useMemo(() => {
|
||||
return formatDate(parseDate(record.date, "yyyy-MM-dd").toISOString(), "do MMM yyyy")
|
||||
try {
|
||||
return formatDate(parseDate(record.date, "yyyy-MM-dd").toISOString(), "do MMM yyyy")
|
||||
} catch (e) {
|
||||
console.error("Error formatting date label:", e);
|
||||
return record.date;
|
||||
}
|
||||
}, [record.date])
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
onClick={() => onSelect(record.date)}
|
||||
key={record.date}
|
||||
ref={itemsRef}
|
||||
className={
|
||||
cn("flex gap-1 flex-col p-2 py-1 rounded-lg hover:dark:bg-zinc-800 border border-transparent hover:bg-zinc-100",
|
||||
startDate === record.date ? "bg-zinc-100 dark:bg-zinc-800 border-gray-300 dark:border-zinc-700" : "")
|
||||
|
||||
@@ -8,7 +8,7 @@ import {
|
||||
CalendarArrowUp,
|
||||
Hourglass,
|
||||
} from "lucide-react";
|
||||
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
|
||||
import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
|
||||
import { listMissingLocationAssets } from "@/handlers/api/asset.handler";
|
||||
import { useConfig } from "@/contexts/ConfigContext";
|
||||
import LazyGridImage from "@/components/ui/lazy-grid-image";
|
||||
@@ -19,8 +19,13 @@ interface IProps {
|
||||
export default function MissingLocationAssets({ groupBy }: IProps) {
|
||||
const { exImmichUrl } = useConfig();
|
||||
|
||||
const { startDate, albumId, selectedIds, sortOrder, sort, assets, updateContext } =
|
||||
useMissingLocationContext();
|
||||
const {
|
||||
selectedIds,
|
||||
assets,
|
||||
updateContext,
|
||||
config
|
||||
} = usePhotoSelectionContext();
|
||||
const { startDate, albumId, sortOrder, sort } = config;
|
||||
|
||||
const [loading, setLoading] = useState(false);
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
@@ -36,18 +41,22 @@ export default function MissingLocationAssets({ groupBy }: IProps) {
|
||||
});
|
||||
const filters = groupBy === "date" ? { startDate } : { albumId }
|
||||
return listMissingLocationAssets(filters)
|
||||
.then((assets) => updateContext({ assets }))
|
||||
.then((fetchedAssets) => updateContext({ assets: fetchedAssets }))
|
||||
.catch(setErrorMessage)
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
const images = useMemo(() => {
|
||||
let sortedAssets: IAsset[];
|
||||
|
||||
if (sortOrder === "desc")
|
||||
sortedAssets = assets.sort((a, b) => new Date(b.dateTimeOriginal).getTime() - new Date(a.dateTimeOriginal).getTime())
|
||||
else
|
||||
sortedAssets = assets.sort((a, b) => new Date(a.dateTimeOriginal).getTime() - new Date(b.dateTimeOriginal).getTime());
|
||||
try {
|
||||
if (sortOrder === "desc")
|
||||
sortedAssets = [...assets].sort((a, b) => new Date(b.dateTimeOriginal!).getTime() - new Date(a.dateTimeOriginal!).getTime())
|
||||
else
|
||||
sortedAssets = [...assets].sort((a, b) => new Date(a.dateTimeOriginal!).getTime() - new Date(b.dateTimeOriginal!).getTime());
|
||||
} catch (error) {
|
||||
console.error("Error sorting assets by date:", error);
|
||||
sortedAssets = [...assets];
|
||||
}
|
||||
|
||||
return sortedAssets.
|
||||
map((p) => ({
|
||||
@@ -62,14 +71,14 @@ export default function MissingLocationAssets({ groupBy }: IProps) {
|
||||
{
|
||||
title: "Immich Link",
|
||||
value: (
|
||||
<a href={exImmichUrl + "/photos/" + p.id} target="_blank">
|
||||
<a href={exImmichUrl + "/photos/" + p.id} target="_blank" rel="noopener noreferrer">
|
||||
Open in Immich
|
||||
</a>
|
||||
),
|
||||
},
|
||||
],
|
||||
}));
|
||||
}, [assets, selectedIds, sortOrder]);
|
||||
}, [assets, selectedIds, sortOrder, exImmichUrl]);
|
||||
|
||||
const slides = useMemo(
|
||||
() =>
|
||||
@@ -102,13 +111,18 @@ export default function MissingLocationAssets({ groupBy }: IProps) {
|
||||
const clickedIndex = images.findIndex((image) => {
|
||||
return image.id === asset.id;
|
||||
});
|
||||
if (event.shiftKey) {
|
||||
if (event.shiftKey && lastSelectedIndex !== -1) {
|
||||
const startIndex = Math.min(clickedIndex, lastSelectedIndex);
|
||||
const endIndex = Math.max(clickedIndex, lastSelectedIndex);
|
||||
const newSelectedIds = images.slice(startIndex, endIndex + 1).map((image) => image.id);
|
||||
const allSelectedIds = [...selectedIds, ...newSelectedIds];
|
||||
const uniqueSelectedIds = [...new Set(allSelectedIds)];
|
||||
updateContext({ selectedIds: uniqueSelectedIds });
|
||||
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] });
|
||||
}
|
||||
@@ -132,10 +146,10 @@ export default function MissingLocationAssets({ groupBy }: IProps) {
|
||||
return (
|
||||
<div className="flex flex-col gap-2 h-full justify-center items-center w-full">
|
||||
<CalendarArrowUp />
|
||||
<p className="text-lg">Please select a date</p>
|
||||
<p className="text-lg">Please select a date or album</p>
|
||||
<p className="text-sm">
|
||||
When you select a date from the left, you will see all the orphan
|
||||
assets captured on that date
|
||||
When you select an item from the left, you will see all the orphan
|
||||
assets associated with it.
|
||||
</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
|
||||
import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
|
||||
|
||||
import { IMissingLocationDatesResponse } from "@/handlers/api/asset.handler";
|
||||
import { parseDate, formatDate } from "@/helpers/date.helper";
|
||||
@@ -12,43 +12,50 @@ interface IProps {
|
||||
}
|
||||
|
||||
export default function MissingLocationDateItem({ record, onSelect, groupBy }: IProps) {
|
||||
// Effect to handle scrolling after rendering
|
||||
useEffect(() => {
|
||||
if (startDate === record.label) {
|
||||
itemsRef.current?.scrollIntoView({
|
||||
behavior: "smooth", // Smooth scrolling
|
||||
block: "center", // Center the item in the view
|
||||
});
|
||||
}
|
||||
}, []);
|
||||
const { config } = usePhotoSelectionContext();
|
||||
const { startDate, albumId } = config;
|
||||
|
||||
const itemsRef = useRef<HTMLDivElement | null>(null);
|
||||
const { startDate } = useMissingLocationContext()
|
||||
|
||||
const dateLabel = useMemo(() => {
|
||||
if (groupBy === "album") {
|
||||
return record.label
|
||||
useEffect(() => {
|
||||
const currentIdentifier = groupBy === "album" ? albumId : startDate;
|
||||
if (currentIdentifier === record.value) {
|
||||
itemsRef.current?.scrollIntoView({
|
||||
behavior: "auto",
|
||||
block: "center",
|
||||
});
|
||||
}
|
||||
if (!record.label) return "Unknown"
|
||||
}, [startDate, albumId, groupBy, record.value]);
|
||||
|
||||
const displayLabel = useMemo(() => {
|
||||
if (groupBy === "album") {
|
||||
return record.label;
|
||||
}
|
||||
if (!record.label) return "Unknown Date";
|
||||
try {
|
||||
return formatDate(parseDate(record.label, "yyyy-MM-dd").toISOString(), "do MMM yyyy")
|
||||
return formatDate(parseDate(record.label, "yyyy-MM-dd").toISOString(), "do MMM yyyy");
|
||||
} catch (e) {
|
||||
return record.label
|
||||
console.error("Error formatting date label:", e);
|
||||
return record.label;
|
||||
}
|
||||
}, [record.label, groupBy])
|
||||
}, [record.label, groupBy]);
|
||||
|
||||
const isSelected = useMemo(() => {
|
||||
return groupBy === "album" ? albumId === record.value : startDate === record.value;
|
||||
}, [groupBy, albumId, startDate, record.value]);
|
||||
|
||||
return (
|
||||
<div
|
||||
role="button"
|
||||
onClick={() => onSelect(record.value)}
|
||||
key={record.label}
|
||||
key={record.value}
|
||||
className={
|
||||
cn("flex gap-1 flex-col p-1 rounded-lg hover:dark:bg-zinc-800 border border-transparent hover:bg-zinc-100",
|
||||
startDate === record.label ? "bg-zinc-100 dark:bg-zinc-800 border-gray-300 dark:border-zinc-700" : "")
|
||||
isSelected ? "bg-zinc-100 dark:bg-zinc-800 border-gray-300 dark:border-zinc-700" : "")
|
||||
}
|
||||
ref={itemsRef}
|
||||
>
|
||||
<p className="text-sm truncate">{dateLabel}</p>
|
||||
<p className="text-sm truncate">{displayLabel}</p>
|
||||
<p className="text-xs text-foreground/50">{record.asset_count} Assets</p>
|
||||
</div>
|
||||
);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import React, { useEffect, useState } from "react";
|
||||
import { listMissingLocationAlbums, listMissingLocationDates } from "@/handlers/api/asset.handler";
|
||||
import MissingLocationDateItem from "./MissingLocationDateItem";
|
||||
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
|
||||
import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
|
||||
import { useRouter } from "next/router";
|
||||
import { Select, SelectContent, SelectGroup, SelectItem, SelectLabel, SelectTrigger, SelectValue } from "@/components/ui/select";
|
||||
import { Button } from "@/components/ui/button";
|
||||
@@ -12,44 +12,50 @@ interface IMissingLocationDatesProps {
|
||||
|
||||
}
|
||||
export default function MissingLocationDates({ groupBy }: IMissingLocationDatesProps) {
|
||||
const { dates, updateContext } = useMissingLocationContext();
|
||||
const { config, updateContext } = usePhotoSelectionContext();
|
||||
const { dates } = config;
|
||||
|
||||
const router = useRouter();
|
||||
const [filters, setFilters] = useState<{ sortBy: string, sortOrder: string }>({ sortBy: "date", sortOrder: "desc" });
|
||||
const [filters, setFilters] = useState<{ sortBy: string, sortOrder: string }>({
|
||||
sortBy: groupBy === "album" ? "name" : "date",
|
||||
sortOrder: "desc"
|
||||
});
|
||||
const [loading, setLoading] = useState(false);
|
||||
|
||||
const [errorMessage, setErrorMessage] = useState<string | null>(null);
|
||||
|
||||
const fetchData = async () => {
|
||||
const func = groupBy === "album" ? listMissingLocationAlbums : listMissingLocationDates
|
||||
updateContext({ dates: [] })
|
||||
updateContext({ config: { ...config, dates: [] } })
|
||||
setLoading(true);
|
||||
return func({
|
||||
sortBy: filters.sortBy,
|
||||
sortOrder: filters.sortOrder,
|
||||
})
|
||||
.then((r) => updateContext({ dates: r }))
|
||||
.then((r) => updateContext({ config: { ...config, dates: r } }))
|
||||
.catch(setErrorMessage)
|
||||
.finally(() => setLoading(false));
|
||||
};
|
||||
|
||||
const handleSelect = (date: string) => {
|
||||
const handleSelect = (value: string) => {
|
||||
if (groupBy === "album") {
|
||||
updateContext({ albumId: date });
|
||||
updateContext({ config: { ...config, albumId: value, startDate: undefined } });
|
||||
router.push({
|
||||
pathname: router.pathname,
|
||||
query: {
|
||||
...router.query,
|
||||
albumId: date,
|
||||
albumId: value,
|
||||
groupBy: "album",
|
||||
startDate: undefined
|
||||
},
|
||||
});
|
||||
} else {
|
||||
updateContext({ startDate: date });
|
||||
updateContext({ config: { ...config, startDate: value, albumId: undefined } });
|
||||
router.push({
|
||||
pathname: router.pathname,
|
||||
query: {
|
||||
...router.query,
|
||||
startDate: date,
|
||||
startDate: value,
|
||||
groupBy: "date",
|
||||
albumId: undefined
|
||||
},
|
||||
@@ -57,9 +63,16 @@ export default function MissingLocationDates({ groupBy }: IMissingLocationDatesP
|
||||
}
|
||||
};
|
||||
|
||||
useEffect(() => {
|
||||
setFilters({
|
||||
sortBy: groupBy === "album" ? "name" : "date",
|
||||
sortOrder: "desc"
|
||||
});
|
||||
}, [groupBy]);
|
||||
|
||||
useEffect(() => {
|
||||
fetchData();
|
||||
}, [filters, groupBy]);
|
||||
}, [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">
|
||||
@@ -67,14 +80,14 @@ export default function MissingLocationDates({ groupBy }: IMissingLocationDatesP
|
||||
{groupBy === "album" ? (
|
||||
<p className="text-sm text-gray-500 dark:text-zinc-400">Asset Count</p>
|
||||
) : (<Select
|
||||
defaultValue={filters.sortBy}
|
||||
value={filters.sortBy}
|
||||
onValueChange={(value) => setFilters({ ...filters, sortBy: value })}
|
||||
>
|
||||
<SelectTrigger className="!p-2">
|
||||
<SelectValue placeholder="Sort by" />
|
||||
</SelectTrigger>
|
||||
<SelectContent defaultValue={filters.sortBy}>
|
||||
<SelectGroup title="Sort by">
|
||||
<SelectContent>
|
||||
<SelectGroup>
|
||||
<SelectLabel>Sort by</SelectLabel>
|
||||
<SelectItem value="date">Date</SelectItem>
|
||||
<SelectItem value="asset_count">Asset Count</SelectItem>
|
||||
@@ -92,7 +105,7 @@ export default function MissingLocationDates({ groupBy }: IMissingLocationDatesP
|
||||
</div>
|
||||
</div>
|
||||
<div className="overflow-y-auto flex flex-col gap-2">
|
||||
{dates.map((record) => (
|
||||
{dates?.map((record) => (
|
||||
<MissingLocationDateItem
|
||||
key={record.value}
|
||||
record={record}
|
||||
|
||||
+3
-3
@@ -14,7 +14,7 @@ import TagMissingLocationSearchAndAdd from "./TagMissingLocationSearchAndAdd";
|
||||
import TagMissingLocationSearchLatLong from "./TagMissingLocationSearchLatLong";
|
||||
import TagMissingLocationOSMSearchAndAdd from "./TagMissingLocationOSMSearchAndAdd";
|
||||
import dynamic from "next/dynamic";
|
||||
import { useMissingLocationContext } from "@/contexts/MissingLocationContext";
|
||||
import { usePhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
|
||||
|
||||
const LazyMap = dynamic(() => import("./Map"), {
|
||||
ssr: false
|
||||
@@ -26,7 +26,7 @@ interface ITagMissingLocationDialogProps {
|
||||
export default function TagMissingLocationDialog({
|
||||
onSubmit,
|
||||
}: ITagMissingLocationDialogProps) {
|
||||
const { selectedIds } = useMissingLocationContext();
|
||||
const { selectedIds } = usePhotoSelectionContext();
|
||||
const [open, setOpen] = useState(false);
|
||||
const [mapPosition, setMapPosition] = useState<IPlace>({
|
||||
latitude: 48.210033,
|
||||
@@ -43,7 +43,7 @@ export default function TagMissingLocationDialog({
|
||||
<DialogHeader>
|
||||
<DialogTitle>Tag Missing Location</DialogTitle>
|
||||
<DialogDescription>
|
||||
Tagging a location will add the location to the selected assets.
|
||||
Tagging a location will add the location to the selected {selectedIds.length} asset(s).
|
||||
</DialogDescription>
|
||||
</DialogHeader>
|
||||
<Tabs defaultValue="searchOsm" className="border rounded-lg">
|
||||
|
||||
@@ -1,35 +0,0 @@
|
||||
import { IMissingLocationDatesResponse } from "@/handlers/api/asset.handler";
|
||||
import { IAsset } from "@/types/asset";
|
||||
import { createContext, useContext } from "react";
|
||||
|
||||
export interface IMissingLocationConfig {
|
||||
startDate?: string;
|
||||
albumId?: string;
|
||||
selectedIds: string[];
|
||||
assets: IAsset[];
|
||||
sort: "fileOriginalDate";
|
||||
sortOrder: "asc"|"desc";
|
||||
dates: IMissingLocationDatesResponse[];
|
||||
}
|
||||
|
||||
export interface MissingLocationContext extends IMissingLocationConfig {
|
||||
updateContext: (newConfig: Partial<MissingLocationContext>) => void;
|
||||
}
|
||||
const MissingLocationContext = createContext<MissingLocationContext>({
|
||||
startDate: undefined,
|
||||
albumId: undefined,
|
||||
dates: [],
|
||||
selectedIds: [],
|
||||
assets: [],
|
||||
updateContext: () => { },
|
||||
sort:"fileOriginalDate",
|
||||
sortOrder: "asc"
|
||||
});
|
||||
|
||||
export default MissingLocationContext;
|
||||
|
||||
const useMissingLocationContext = () => {
|
||||
return useContext(MissingLocationContext) as MissingLocationContext;
|
||||
}
|
||||
export { useMissingLocationContext };
|
||||
|
||||
@@ -0,0 +1,59 @@
|
||||
import { IMissingLocationDatesResponse } from "@/handlers/api/asset.handler";
|
||||
import { IAsset } from "@/types/asset";
|
||||
import { createContext, useContext } from "react";
|
||||
|
||||
// Interface for specific configuration options
|
||||
export interface IPhotoSelectionConfig {
|
||||
// Common config potentially used by multiple features
|
||||
startDate?: string;
|
||||
|
||||
// MissingLocation specific config
|
||||
albumId?: string;
|
||||
sort?: string; // More generic sort field
|
||||
sortOrder?: "asc" | "desc";
|
||||
dates?: IMissingLocationDatesResponse[]; // Specific to Missing Location
|
||||
|
||||
// PotentialAlbum specific config
|
||||
minAssets?: number;
|
||||
}
|
||||
|
||||
// Interface for the main context
|
||||
export interface IPhotoSelectionContext {
|
||||
selectedIds: string[];
|
||||
assets: IAsset[];
|
||||
config: IPhotoSelectionConfig;
|
||||
updateContext: (newConfig: Partial<IPhotoSelectionContext>) => void;
|
||||
}
|
||||
|
||||
// Default values for the context
|
||||
const defaultPhotoSelectionContext: IPhotoSelectionContext = {
|
||||
selectedIds: [],
|
||||
assets: [],
|
||||
config: {
|
||||
// Sensible defaults for config fields
|
||||
startDate: undefined,
|
||||
albumId: undefined,
|
||||
sort: "fileOriginalDate", // Default sort for MissingLocation, can be overridden
|
||||
sortOrder: "asc",
|
||||
dates: [],
|
||||
minAssets: 1, // Default for PotentialAlbum
|
||||
},
|
||||
updateContext: () => {},
|
||||
};
|
||||
|
||||
// Create the context
|
||||
const PhotoSelectionContext = createContext<IPhotoSelectionContext>(defaultPhotoSelectionContext);
|
||||
|
||||
export default PhotoSelectionContext;
|
||||
|
||||
// Hook to use the context
|
||||
const usePhotoSelectionContext = () => {
|
||||
const context = useContext(PhotoSelectionContext);
|
||||
if (context === undefined) {
|
||||
throw new Error("usePhotoSelectionContext must be used within a PhotoSelectionProvider");
|
||||
// Consider implementing a Provider component if you haven't already
|
||||
}
|
||||
return context;
|
||||
};
|
||||
|
||||
export { usePhotoSelectionContext };
|
||||
@@ -1,28 +0,0 @@
|
||||
import { IAsset } from "@/types/asset";
|
||||
import { createContext, useContext } from "react";
|
||||
|
||||
export interface IPotentialAlbumConfig {
|
||||
startDate?: string;
|
||||
selectedIds: string[];
|
||||
assets: IAsset[];
|
||||
minAssets?: number;
|
||||
}
|
||||
|
||||
export interface IPotentialAlbumContext extends IPotentialAlbumConfig {
|
||||
updateContext: (newConfig: Partial<IPotentialAlbumContext>) => void;
|
||||
}
|
||||
const PotentialAlbumContext = createContext<IPotentialAlbumContext>({
|
||||
startDate: undefined,
|
||||
selectedIds: [],
|
||||
assets: [],
|
||||
minAssets: 1,
|
||||
updateContext: () => { },
|
||||
});
|
||||
|
||||
export default PotentialAlbumContext;
|
||||
|
||||
const usePotentialAlbumContext = () => {
|
||||
return useContext(PotentialAlbumContext) as IPotentialAlbumContext;
|
||||
}
|
||||
export { usePotentialAlbumContext };
|
||||
|
||||
@@ -11,9 +11,7 @@ import { Button } from "@/components/ui/button";
|
||||
import { Input } from "@/components/ui/input";
|
||||
import { useToast } from "@/components/ui/use-toast";
|
||||
import { useCurrentUser } from "@/contexts/CurrentUserContext";
|
||||
import PotentialAlbumContext, {
|
||||
IPotentialAlbumConfig,
|
||||
} from "@/contexts/PotentialAlbumContext";
|
||||
import PhotoSelectionContext, { IPhotoSelectionContext } from "@/contexts/PhotoSelectionContext";
|
||||
import { addAssetToAlbum, createAlbum } from "@/handlers/api/album.handler";
|
||||
import { deleteAssets } from "@/handlers/api/asset.handler";
|
||||
import { IAlbum, IAlbumCreate } from "@/types/album";
|
||||
@@ -26,31 +24,39 @@ export default function PotentialAlbums() {
|
||||
|
||||
const { query } = useRouter();
|
||||
const { startDate } = query as { startDate: string };
|
||||
const [config, setConfig] = React.useState<IPotentialAlbumConfig>({
|
||||
startDate: startDate || undefined,
|
||||
|
||||
const [contextState, setContextState] = React.useState<IPhotoSelectionContext>({
|
||||
selectedIds: [],
|
||||
assets: [],
|
||||
minAssets: 1,
|
||||
config: {
|
||||
startDate: startDate || undefined,
|
||||
minAssets: 1,
|
||||
},
|
||||
updateContext: (newConfig: Partial<IPhotoSelectionContext>) => {
|
||||
setContextState(prevState => ({
|
||||
...prevState,
|
||||
...newConfig,
|
||||
config: newConfig.config ? { ...prevState.config, ...newConfig.config } : prevState.config
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
||||
const selectedAssets = useMemo(() => config.assets.filter((a) => config.selectedIds.includes(a.id)), [config.assets, config.selectedIds]);
|
||||
const selectedAssets = useMemo(() => contextState.assets.filter((a) => contextState.selectedIds.includes(a.id)), [contextState.assets, contextState.selectedIds]);
|
||||
|
||||
const updateContext = contextState.updateContext;
|
||||
|
||||
const handleSelect = (album: IAlbum) => {
|
||||
return addAssetToAlbum(album.id, config.selectedIds)
|
||||
return addAssetToAlbum(album.id, contextState.selectedIds)
|
||||
.then(() => {
|
||||
setConfig({ ...config, selectedIds: [] });
|
||||
setConfig({
|
||||
...config,
|
||||
assets: config.assets.filter(
|
||||
(asset) => !config.selectedIds.includes(asset.id)
|
||||
),
|
||||
selectedIds: [],
|
||||
});
|
||||
const newAssets = contextState.assets.filter(
|
||||
(asset) => !contextState.selectedIds.includes(asset.id)
|
||||
);
|
||||
updateContext({ selectedIds: [], assets: newAssets });
|
||||
})
|
||||
.then(() => {
|
||||
toast({
|
||||
title: `Assets added to ${album.albumName}`,
|
||||
description: `${config.selectedIds.length} assets added to album`,
|
||||
description: `${contextState.selectedIds.length} assets added to album`,
|
||||
});
|
||||
})
|
||||
.catch(() => {
|
||||
@@ -65,20 +71,22 @@ export default function PotentialAlbums() {
|
||||
const handleCreate = (formData: IAlbumCreate) => {
|
||||
return createAlbum({
|
||||
...formData,
|
||||
assetIds: config.selectedIds,
|
||||
assetIds: contextState.selectedIds,
|
||||
}).then(() => {
|
||||
toast({
|
||||
title: "Album created",
|
||||
description: "Album created successfully",
|
||||
});
|
||||
setConfig({ ...config, selectedIds: [], assets: config.assets.filter(a => !config.selectedIds.includes(a.id)) });
|
||||
const newAssets = contextState.assets.filter(a => !contextState.selectedIds.includes(a.id));
|
||||
updateContext({ selectedIds: [], assets: newAssets });
|
||||
})
|
||||
}
|
||||
|
||||
const handleDelete = () => {
|
||||
return deleteAssets(config.selectedIds)
|
||||
return deleteAssets(contextState.selectedIds)
|
||||
.then(() => {
|
||||
setConfig({ ...config, selectedIds: [], assets: config.assets.filter(a => !config.selectedIds.includes(a.id)) });
|
||||
const newAssets = contextState.assets.filter(a => !contextState.selectedIds.includes(a.id));
|
||||
updateContext({ selectedIds: [], assets: newAssets });
|
||||
})
|
||||
.then(() => {
|
||||
toast({
|
||||
@@ -96,8 +104,7 @@ export default function PotentialAlbums() {
|
||||
}
|
||||
|
||||
const handleOffsetComplete = () => {
|
||||
setConfig({
|
||||
...config,
|
||||
updateContext({
|
||||
selectedIds: [],
|
||||
});
|
||||
}
|
||||
@@ -110,40 +117,42 @@ export default function PotentialAlbums() {
|
||||
<div className="flex items-center gap-2">
|
||||
<Input
|
||||
placeholder="Minimum Assets Count"
|
||||
defaultValue={config.minAssets}
|
||||
type="number"
|
||||
defaultValue={contextState.config.minAssets}
|
||||
onChange={(e) => {
|
||||
if (e.target.value) {
|
||||
setConfig({ ...config, minAssets: parseInt(e.target.value) });
|
||||
const newMinAssets = parseInt(e.target.value);
|
||||
if (!isNaN(newMinAssets)) {
|
||||
updateContext({ config: { ...contextState.config, minAssets: newMinAssets } });
|
||||
}
|
||||
}
|
||||
}}
|
||||
/>
|
||||
</div>
|
||||
)}
|
||||
/>
|
||||
<PotentialAlbumContext.Provider
|
||||
<PhotoSelectionContext.Provider
|
||||
value={{
|
||||
...config,
|
||||
updateContext: (newConfig: Partial<IPotentialAlbumConfig>) =>
|
||||
setConfig({ ...config, ...newConfig }),
|
||||
...contextState,
|
||||
updateContext: updateContext,
|
||||
}}
|
||||
>
|
||||
<div className="flex divide-y">
|
||||
<PotentialAlbumsDates />
|
||||
<PotentialAlbumsAssets />
|
||||
</div>
|
||||
{selectedAssets.length &&
|
||||
{selectedAssets.length > 0 &&
|
||||
<FloatingBar>
|
||||
<div className="flex items-center gap-2 justify-between w-full">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{config.selectedIds.length} Selected
|
||||
{contextState.selectedIds.length} Selected
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
<Button
|
||||
variant={"outline"}
|
||||
size={"sm"}
|
||||
onClick={() =>
|
||||
setConfig({
|
||||
...config,
|
||||
updateContext({
|
||||
selectedIds: [],
|
||||
})
|
||||
}
|
||||
@@ -155,9 +164,8 @@ export default function PotentialAlbums() {
|
||||
variant={"outline"}
|
||||
size={"sm"}
|
||||
onClick={() =>
|
||||
setConfig({
|
||||
...config,
|
||||
selectedIds: config.assets.map((a) => a.id),
|
||||
updateContext({
|
||||
selectedIds: contextState.assets.map((a) => a.id),
|
||||
})
|
||||
}
|
||||
|
||||
@@ -172,9 +180,9 @@ export default function PotentialAlbums() {
|
||||
title="Delete the selected assets?"
|
||||
description="This action will delete the selected assets and cannot be undone."
|
||||
onConfirm={handleDelete}
|
||||
disabled={config.selectedIds.length === 0}
|
||||
disabled={contextState.selectedIds.length === 0}
|
||||
>
|
||||
<Button variant={"destructive"} size={"sm"} disabled={config.selectedIds.length === 0}>
|
||||
<Button variant={"destructive"} size={"sm"} disabled={contextState.selectedIds.length === 0}>
|
||||
Delete
|
||||
</Button>
|
||||
</AlertDialog>
|
||||
@@ -182,7 +190,7 @@ export default function PotentialAlbums() {
|
||||
</div>
|
||||
</FloatingBar>
|
||||
}
|
||||
</PotentialAlbumContext.Provider>
|
||||
</PhotoSelectionContext.Provider>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
@@ -4,9 +4,7 @@ import TagMissingLocationDialog from "@/components/assets/missing-location/TagMi
|
||||
import PageLayout from "@/components/layouts/PageLayout";
|
||||
import Header from "@/components/shared/Header";
|
||||
import { Button } from "@/components/ui/button";
|
||||
import MissingLocationContext, {
|
||||
IMissingLocationConfig,
|
||||
} from "@/contexts/MissingLocationContext";
|
||||
import PhotoSelectionContext, { IPhotoSelectionContext, IPhotoSelectionConfig } from "@/contexts/PhotoSelectionContext";
|
||||
import { deleteAssets, updateAssets } from "@/handlers/api/asset.handler";
|
||||
|
||||
import { IPlace } from "@/types/common";
|
||||
@@ -21,68 +19,78 @@ import AssetOffsetDialog from "@/components/assets/assets-options/AssetOffsetDia
|
||||
|
||||
export default function MissingLocations() {
|
||||
const { query, push } = useRouter();
|
||||
const { startDate, groupBy = "date" } = query as { startDate: string, groupBy: string };
|
||||
const [config, setConfig] = React.useState<IMissingLocationConfig>({
|
||||
startDate: startDate || undefined,
|
||||
const { startDate, groupBy = "date", albumId } = query as { startDate: string, groupBy: string, albumId: string };
|
||||
|
||||
const [contextState, setContextState] = React.useState<IPhotoSelectionContext>({
|
||||
selectedIds: [],
|
||||
assets: [],
|
||||
sort: "fileOriginalDate",
|
||||
sortOrder: "asc",
|
||||
dates: []
|
||||
config: {
|
||||
startDate: startDate || undefined,
|
||||
albumId: albumId || undefined,
|
||||
sort: "fileOriginalDate",
|
||||
sortOrder: "asc",
|
||||
dates: []
|
||||
},
|
||||
updateContext: (newConfig: Partial<IPhotoSelectionContext>) => {
|
||||
setContextState(prevState => ({
|
||||
...prevState,
|
||||
...newConfig,
|
||||
config: newConfig.config ? { ...prevState.config, ...newConfig.config } : prevState.config
|
||||
}));
|
||||
}
|
||||
});
|
||||
|
||||
const selectedAssets = useMemo(() => config.assets.filter((a) => config.selectedIds.includes(a.id)), [config.assets, config.selectedIds]);
|
||||
const selectedAssets = useMemo(() => contextState.assets.filter((a) => contextState.selectedIds.includes(a.id)), [contextState.assets, contextState.selectedIds]);
|
||||
|
||||
const handleSubmit = async (place: IPlace) => {
|
||||
await updateAssets({
|
||||
ids: config.selectedIds,
|
||||
ids: contextState.selectedIds,
|
||||
latitude: Number(place.latitude),
|
||||
longitude: Number(place.longitude),
|
||||
});
|
||||
|
||||
const newAssets = config.assets.filter(asset => !config.selectedIds.includes(asset.id));
|
||||
const newAssets = contextState.assets.filter(asset => !contextState.selectedIds.includes(asset.id));
|
||||
let newDates = [...contextState.config.dates || []];
|
||||
|
||||
if (config.startDate) {
|
||||
const dayRecord = config.dates.filter(f => isSameDay(new Date(f.value), new Date(config.startDate!)));
|
||||
if (contextState.config.startDate) {
|
||||
const dayRecordIndex = newDates.findIndex(f => isSameDay(new Date(f.value), new Date(contextState.config.startDate!)));
|
||||
|
||||
if (dayRecord.length === 1) {
|
||||
if (newAssets.length > 0)
|
||||
dayRecord[0].asset_count = newAssets.length;
|
||||
if (dayRecordIndex !== -1) {
|
||||
if (newAssets.length > 0) {
|
||||
newDates[dayRecordIndex] = { ...newDates[dayRecordIndex], asset_count: newAssets.length };
|
||||
}
|
||||
else {
|
||||
const indexToRemove = config.dates.findIndex(v=>isSameDay(v.value, dayRecord[0].value));
|
||||
|
||||
if (indexToRemove !== -1) {
|
||||
config.dates.splice(indexToRemove, 1);
|
||||
}
|
||||
newDates.splice(dayRecordIndex, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
setConfig({
|
||||
...config,
|
||||
contextState.updateContext({
|
||||
selectedIds: [],
|
||||
assets: newAssets
|
||||
assets: newAssets,
|
||||
config: { ...contextState.config, dates: newDates }
|
||||
});
|
||||
};
|
||||
|
||||
const handleDelete = () => {
|
||||
return deleteAssets(config.selectedIds).then(() => {
|
||||
setConfig({
|
||||
...config,
|
||||
return deleteAssets(contextState.selectedIds).then(() => {
|
||||
const newAssets = contextState.assets.filter((a) => !contextState.selectedIds.includes(a.id));
|
||||
let newDates = [...contextState.config.dates || []];
|
||||
|
||||
contextState.updateContext({
|
||||
selectedIds: [],
|
||||
assets: config.assets.filter((a) => !config.selectedIds.includes(a.id)),
|
||||
assets: newAssets,
|
||||
});
|
||||
})
|
||||
}
|
||||
|
||||
const handleOffsetComplete = () => {
|
||||
setConfig({
|
||||
...config,
|
||||
contextState.updateContext({
|
||||
selectedIds: [],
|
||||
});
|
||||
}
|
||||
const handleChange = (e: { sortOrder: "asc" | "desc" }) => {
|
||||
setConfig({ ...config, sortOrder: e.sortOrder });
|
||||
contextState.updateContext({ config: { ...contextState.config, sortOrder: e.sortOrder } });
|
||||
}
|
||||
|
||||
return (
|
||||
@@ -92,6 +100,7 @@ export default function MissingLocations() {
|
||||
rightComponent={
|
||||
<div className="flex items-center gap-2">
|
||||
<Select value={groupBy} onValueChange={(value) => {
|
||||
contextState.updateContext({ config: { startDate: undefined, albumId: undefined } });
|
||||
push({
|
||||
pathname: "/assets/missing-locations",
|
||||
query: {
|
||||
@@ -111,38 +120,36 @@ export default function MissingLocations() {
|
||||
</SelectContent>
|
||||
</Select>
|
||||
<div>
|
||||
<Button variant="default" size="sm" onClick={() => handleChange({ sortOrder: config.sortOrder === "asc" ? "desc" : "asc" })}>
|
||||
{config.sortOrder === "asc" ? <SortAsc size={16} /> : <SortDesc size={16} />}
|
||||
<Button variant="default" size="sm" onClick={() => handleChange({ sortOrder: contextState.config.sortOrder === "asc" ? "desc" : "asc" })}>
|
||||
{contextState.config.sortOrder === "asc" ? <SortAsc size={16} /> : <SortDesc size={16} />}
|
||||
</Button>
|
||||
</div>
|
||||
</div>
|
||||
}
|
||||
/>
|
||||
<MissingLocationContext.Provider
|
||||
<PhotoSelectionContext.Provider
|
||||
value={{
|
||||
...config,
|
||||
updateContext: (newConfig: Partial<IMissingLocationConfig>) =>
|
||||
setConfig({ ...config, ...newConfig }),
|
||||
...contextState,
|
||||
updateContext: contextState.updateContext,
|
||||
}}
|
||||
>
|
||||
<div className="flex divide-y">
|
||||
<MissingLocationDates groupBy={groupBy as "date" | "album"} />
|
||||
<MissingLocationAssets groupBy={groupBy as "date" | "album"} />
|
||||
</div>
|
||||
{selectedAssets.length &&
|
||||
{selectedAssets.length > 0 &&
|
||||
<FloatingBar>
|
||||
<div className="flex items-center gap-2 justify-between w-full">
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{config.selectedIds.length} Selected
|
||||
{contextState.selectedIds.length} Selected
|
||||
</p>
|
||||
<div className="flex items-center gap-2">
|
||||
{config.selectedIds.length === config.assets.length ? (
|
||||
{contextState.selectedIds.length === contextState.assets.length ? (
|
||||
<Button
|
||||
variant={"outline"}
|
||||
size={"sm"}
|
||||
onClick={() =>
|
||||
setConfig({
|
||||
...config,
|
||||
contextState.updateContext({
|
||||
selectedIds: [],
|
||||
})
|
||||
}
|
||||
@@ -154,16 +161,14 @@ export default function MissingLocations() {
|
||||
variant={"outline"}
|
||||
size={"sm"}
|
||||
onClick={() =>
|
||||
setConfig({
|
||||
...config,
|
||||
selectedIds: config.assets.map((a) => a.id),
|
||||
contextState.updateContext({
|
||||
selectedIds: contextState.assets.map((a) => a.id),
|
||||
})
|
||||
}
|
||||
>
|
||||
Select all
|
||||
</Button>
|
||||
)}
|
||||
{/* Seperator */}
|
||||
<TagMissingLocationDialog onSubmit={handleSubmit} />
|
||||
<AssetOffsetDialog assets={selectedAssets} onComplete={handleOffsetComplete} />
|
||||
<div className="h-[10px] w-[1px] bg-zinc-500 dark:bg-zinc-600"></div>
|
||||
@@ -171,9 +176,9 @@ export default function MissingLocations() {
|
||||
title="Delete the selected assets?"
|
||||
description="This action will delete the selected assets and cannot be undone."
|
||||
onConfirm={handleDelete}
|
||||
disabled={config.selectedIds.length === 0}
|
||||
disabled={contextState.selectedIds.length === 0}
|
||||
>
|
||||
<Button variant={"destructive"} size={"sm"} disabled={config.selectedIds.length === 0}>
|
||||
<Button variant={"destructive"} size={"sm"} disabled={contextState.selectedIds.length === 0}>
|
||||
Delete
|
||||
</Button>
|
||||
</AlertDialog>
|
||||
@@ -181,7 +186,7 @@ export default function MissingLocations() {
|
||||
</div>
|
||||
</FloatingBar>
|
||||
}
|
||||
</MissingLocationContext.Provider>
|
||||
</PhotoSelectionContext.Provider>
|
||||
</PageLayout>
|
||||
);
|
||||
}
|
||||
@@ -156,6 +156,7 @@ export default function FindPage() {
|
||||
<p className="text-sm text-muted-foreground">
|
||||
{selectedIds.length} Selected
|
||||
</p>
|
||||
|
||||
<AssetsBulkDeleteButton
|
||||
selectedIds={selectedIds}
|
||||
onDelete={handleDelete}
|
||||
|
||||
Reference in new issue
Block a user