"use client";
import type { Dispatch, SetStateAction } from "react";
import { useEffect, useMemo, useState } from "react";
import { Box, Center, Group, Image, Stack, Text } from "@mantine/core";
import { IconAlertCircle, IconCalendar } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { useI18n } from "@homarr/translation/client";
import { WidgetEmptyState } from "../../common/empty-state";
import type { WidgetComponentProps } from "../../definition";
import classes from "./component.module.css";
export default function ImmichAlbumCarouselWidget({
integrationIds,
options,
}: WidgetComponentProps<"immich-albumCarousel">) {
const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);
const { data: album } = clientApi.widget.immich.getAlbum.useQuery(
{
integrationId: integrationIds[0] ?? "",
albumId: options.albumId ?? "",
},
{ enabled: Boolean(options.albumId) },
);
const photoAssets = useMemo(() => {
const assets = album?.assets.filter((asset) => asset.type === "IMAGE") ?? [];
return options.randomizePhotos ? shuffle(assets) : assets;
}, [album?.assets, options.randomizePhotos]);
useEffect(() => {
setCurrentPhotoIndex(0);
}, [photoAssets]);
if (!options.albumId) {
return ;
}
if (!album) return ;
if (album.assets.length === 0) {
return ;
}
if (photoAssets.length === 0) {
return ;
}
return (
);
}
function shuffle(items: T[]) {
const shuffled = [...items];
for (let index = shuffled.length - 1; index > 0; index--) {
const randomIndex = Math.floor(Math.random() * (index + 1));
const current = shuffled[index];
const random = shuffled[randomIndex];
if (current === undefined || random === undefined) continue;
shuffled[index] = random;
shuffled[randomIndex] = current;
}
return shuffled;
}
interface CarouselProps {
assets: {
id: string;
originalPath: string;
fileModifiedAt: string;
publicLink: string;
}[];
currentIndex: number;
setCurrentIndex: Dispatch>;
rotationInterval: number;
showPhotoInfo: boolean;
}
function Carousel({ assets, currentIndex, setCurrentIndex, rotationInterval, showPhotoInfo }: CarouselProps) {
useEffect(() => {
const interval = setInterval(() => {
setCurrentIndex((prev) => (prev + 1) % assets.length);
}, rotationInterval * 1000);
return () => clearInterval(interval);
}, [assets.length, rotationInterval, setCurrentIndex]);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const currentAsset = assets[currentIndex]!;
return (
{showPhotoInfo && (
{new Date(currentAsset.fileModifiedAt).toLocaleDateString()}
{currentIndex + 1} / {assets.length}
)}
);
}
function NoAlbumSelected() {
const t = useI18n();
return (
{t("widget.immich-albumCarousel.noAlbumSelected")}
);
}
function NoPhotosInAlbum() {
const t = useI18n();
return (
{t("widget.immich-albumCarousel.noPhotos")}
);
}