feat!: release v2 (#6545)
Co-authored-by: Artur <145776561+arturict@users.noreply.github.com> Co-authored-by: arturict <arturict@users.noreply.github.com> Co-authored-by: Thomas <thomas@ajnart.fr> Co-authored-by: Afonso Jorge Ramos <afonsojorgeramos@gmail.com> Co-authored-by: Danura30082 <danura30082+github@gmail.com> Co-authored-by: Kushie <122986913+kushiemoon-dev@users.noreply.github.com> Co-authored-by: ajnart <thomas@ajnart.fr> Co-authored-by: ajnart <thomas@ajnart.dev> Co-authored-by: chenjun <chenjun@foxmail.com> Co-authored-by: Wikibear <wikibear@users.noreply.github.com> Co-authored-by: Bergasha <bergasha@gmail.com> Co-authored-by: leafyelin <43306196+leafyelin@users.noreply.github.com> Co-authored-by: Lucas Araujo <lucas.lra@gmail.com> Co-authored-by: GreenMonito <86085570+GreenMonito@users.noreply.github.com> Co-authored-by: Nerdy-Technician <roffo@nerdy-technician.social> Co-authored-by: Jun <34545896+jcstrong@users.noreply.github.com> Co-authored-by: Edmond Abraham <54119952+gitedmond@users.noreply.github.com> Co-authored-by: thrawnx <tight.bulb9384@fastmail.com> Co-authored-by: Chris <58918656+nordada@users.noreply.github.com> Co-authored-by: yi111 <153097222+Yi-111-a@users.noreply.github.com> Co-authored-by: Yanis <naamaneyanis@gmail.com> Co-authored-by: Wikibear <me@sej.de> Co-authored-by: alessiottavo <93441886+alessiottavo@users.noreply.github.com>
This commit is contained in:
3286 files changed
+284386
-139176
No files matched your search
@@ -14,6 +14,11 @@
|
||||
background-color: var(--mantine-color-gray-8);
|
||||
}
|
||||
|
||||
.carouselImage[data-fit="contain"] {
|
||||
object-fit: contain;
|
||||
background-color: var(--mantine-color-black);
|
||||
}
|
||||
|
||||
.photoInfo {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
@@ -24,29 +29,42 @@
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.dots {
|
||||
.carouselControls {
|
||||
position: absolute;
|
||||
bottom: 12px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 10;
|
||||
inset-block-start: 8px;
|
||||
inset-inline-end: 8px;
|
||||
z-index: 1;
|
||||
opacity: 0;
|
||||
pointer-events: none;
|
||||
transform: translateY(-2px);
|
||||
transition:
|
||||
opacity 120ms ease,
|
||||
transform 120ms ease;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background-color: rgba(255, 255, 255, 0.5);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
.carouselContainer:hover .carouselControls,
|
||||
.carouselContainer:focus-within .carouselControls,
|
||||
.carouselControls[data-visible="true"] {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
&[data-active="true"] {
|
||||
background-color: rgba(255, 255, 255, 1);
|
||||
width: 24px;
|
||||
border-radius: 4px;
|
||||
@media (any-pointer: coarse) {
|
||||
.carouselControls {
|
||||
opacity: 1;
|
||||
pointer-events: auto;
|
||||
transform: none;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(255, 255, 255, 0.8);
|
||||
.carouselControls button {
|
||||
width: 44px;
|
||||
height: 44px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-reduced-motion: reduce) {
|
||||
.carouselControls {
|
||||
transition: none;
|
||||
}
|
||||
}
|
||||
@@ -1,59 +1,109 @@
|
||||
"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 { useCallback, useEffect, useMemo, useState } from "react";
|
||||
import { ActionIcon, Box, Center, Group, Image, ScrollArea, Stack, Text, UnstyledButton } from "@mantine/core";
|
||||
import { useReducedMotion } from "@mantine/hooks";
|
||||
import {
|
||||
IconAlertCircle,
|
||||
IconCalendar,
|
||||
IconChevronLeft,
|
||||
IconChevronRight,
|
||||
IconPlayerPause,
|
||||
IconPlayerPlay,
|
||||
} from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
|
||||
import { iconSizes } from "@homarr/ui";
|
||||
|
||||
import { WidgetEmptyState } from "../../common/empty-state";
|
||||
import type { WidgetComponentProps } from "../../definition";
|
||||
import { useWidgetRuntimeActions } from "../../runtime-hooks";
|
||||
import { getUsableWidgetQueryData } from "../../common/query-state";
|
||||
import classes from "./component.module.css";
|
||||
import { ALL_PHOTOS_ALBUM_ID } from "./constants";
|
||||
|
||||
export default function ImmichAlbumCarouselWidget({
|
||||
integrationIds,
|
||||
options,
|
||||
displayMode = "compact",
|
||||
widgetRuntimeRef,
|
||||
}: WidgetComponentProps<"immich-albumCarousel">) {
|
||||
const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);
|
||||
const [paused, setPaused] = useState(false);
|
||||
const [firstPreviewPhoto, setFirstPreviewPhoto] = useState<{ albumId: string; assetId: string } | null>(null);
|
||||
let albumId: string | undefined;
|
||||
if (options.albumId && options.albumId !== ALL_PHOTOS_ALBUM_ID) albumId = options.albumId;
|
||||
const integrationId = integrationIds[0] ?? "";
|
||||
|
||||
const { data: album } = clientApi.widget.immich.getAlbum.useQuery(
|
||||
{
|
||||
integrationId: integrationIds[0] ?? "",
|
||||
albumId: options.albumId && options.albumId !== ALL_PHOTOS_ALBUM_ID ? options.albumId : undefined,
|
||||
},
|
||||
const albumQuery = clientApi.widget.immich.getAlbum.useQuery(
|
||||
{ integrationId, albumId },
|
||||
{ enabled: integrationIds.length > 0 },
|
||||
);
|
||||
const previewQuery = clientApi.widget.immich.getAlbumPreview.useQuery(
|
||||
{ integrationId, albumId: albumId ?? "", randomizePhotos: options.randomizePhotos },
|
||||
{ enabled: integrationIds.length > 0 && albumId !== undefined },
|
||||
);
|
||||
const fullAlbum = getUsableWidgetQueryData(albumQuery);
|
||||
const preview = previewQuery.data;
|
||||
const album = fullAlbum ?? preview;
|
||||
|
||||
useEffect(() => {
|
||||
const asset = preview?.assets[0];
|
||||
if (!albumId || !asset || fullAlbum || firstPreviewPhoto?.albumId === albumId) return;
|
||||
setFirstPreviewPhoto({ albumId, assetId: asset.id });
|
||||
}, [albumId, firstPreviewPhoto?.albumId, fullAlbum, preview?.assets]);
|
||||
|
||||
const photoAssets = useMemo(() => {
|
||||
const assets = album?.assets.filter((asset) => asset.type === "IMAGE") ?? [];
|
||||
return options.randomizePhotos ? shuffle(assets) : assets;
|
||||
}, [album?.assets, options.randomizePhotos]);
|
||||
if (!options.randomizePhotos) return assets;
|
||||
const randomized = shuffle(assets);
|
||||
if (!fullAlbum || !firstPreviewPhoto || firstPreviewPhoto.albumId !== albumId) return randomized;
|
||||
const first = randomized.find((asset) => asset.id === firstPreviewPhoto.assetId);
|
||||
if (!first) return randomized;
|
||||
return [first, ...randomized.filter((asset) => asset.id !== first.id)];
|
||||
}, [album?.assets, albumId, firstPreviewPhoto, fullAlbum, options.randomizePhotos]);
|
||||
|
||||
useEffect(() => {
|
||||
setCurrentPhotoIndex(0);
|
||||
}, [photoAssets]);
|
||||
if (photoAssets.length === 0) return;
|
||||
setCurrentPhotoIndex((current) => Math.min(current, photoAssets.length - 1));
|
||||
}, [photoAssets.length]);
|
||||
|
||||
if (!album) return <WidgetEmptyState />;
|
||||
const previousPhoto = useCallback(
|
||||
() => setCurrentPhotoIndex((current) => (current - 1 + photoAssets.length) % photoAssets.length),
|
||||
[photoAssets.length],
|
||||
);
|
||||
const nextPhoto = useCallback(
|
||||
() => setCurrentPhotoIndex((current) => (current + 1) % photoAssets.length),
|
||||
[photoAssets.length],
|
||||
);
|
||||
const toggleSlideshow = useCallback(() => setPaused((value) => !value), []);
|
||||
useWidgetRuntimeActions(
|
||||
widgetRuntimeRef,
|
||||
photoAssets.length > 1 ? { previousPhoto, nextPhoto, toggleSlideshow } : {},
|
||||
);
|
||||
|
||||
if (album.assets.length === 0) {
|
||||
return <NoPhotosInAlbum />;
|
||||
}
|
||||
|
||||
if (photoAssets.length === 0) {
|
||||
return <NoPhotosInAlbum />;
|
||||
}
|
||||
if (!album || (!fullAlbum && album.assets.length === 0)) return <WidgetEmptyState />;
|
||||
|
||||
return (
|
||||
<Carousel
|
||||
assets={photoAssets}
|
||||
currentIndex={currentPhotoIndex}
|
||||
setCurrentIndex={setCurrentPhotoIndex}
|
||||
rotationInterval={options.rotationIntervalSeconds}
|
||||
showPhotoInfo={options.showPhotoInfo}
|
||||
/>
|
||||
<Box h="100%" pos="relative">
|
||||
{album.assets.length === 0 || photoAssets.length === 0 ? (
|
||||
<NoPhotosInAlbum />
|
||||
) : (
|
||||
<Carousel
|
||||
assets={photoAssets}
|
||||
currentIndex={currentPhotoIndex}
|
||||
setCurrentIndex={setCurrentPhotoIndex}
|
||||
rotationInterval={options.rotationIntervalSeconds}
|
||||
showPhotoInfo={options.showPhotoInfo}
|
||||
albumName={album.albumName}
|
||||
advanced={displayMode === "advanced"}
|
||||
paused={paused}
|
||||
setPaused={setPaused}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
@@ -73,7 +123,6 @@ function shuffle<T>(items: T[]) {
|
||||
interface CarouselProps {
|
||||
assets: {
|
||||
id: string;
|
||||
originalPath: string;
|
||||
fileModifiedAt: string;
|
||||
publicLink: string;
|
||||
}[];
|
||||
@@ -81,47 +130,155 @@ interface CarouselProps {
|
||||
setCurrentIndex: Dispatch<SetStateAction<number>>;
|
||||
rotationInterval: number;
|
||||
showPhotoInfo: boolean;
|
||||
albumName: string;
|
||||
advanced: boolean;
|
||||
paused: boolean;
|
||||
setPaused: Dispatch<SetStateAction<boolean>>;
|
||||
}
|
||||
|
||||
function Carousel({ assets, currentIndex, setCurrentIndex, rotationInterval, showPhotoInfo }: CarouselProps) {
|
||||
function Carousel({
|
||||
assets,
|
||||
currentIndex,
|
||||
setCurrentIndex,
|
||||
rotationInterval,
|
||||
showPhotoInfo,
|
||||
albumName,
|
||||
advanced,
|
||||
paused,
|
||||
setPaused,
|
||||
}: CarouselProps) {
|
||||
const t = useI18n("widget.immich-albumCarousel");
|
||||
const locale = useCurrentIntlLocale();
|
||||
const reduceMotion = useReducedMotion();
|
||||
|
||||
useEffect(() => {
|
||||
if (paused || reduceMotion || assets.length <= 1) return;
|
||||
const interval = setInterval(() => {
|
||||
setCurrentIndex((prev) => (prev + 1) % assets.length);
|
||||
}, rotationInterval * 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [assets.length, rotationInterval, setCurrentIndex]);
|
||||
}, [assets.length, paused, reduceMotion, rotationInterval, setCurrentIndex]);
|
||||
|
||||
const safeCurrentIndex = Math.min(currentIndex, assets.length - 1);
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const currentAsset = assets[currentIndex]!;
|
||||
const currentAsset = assets[safeCurrentIndex]!;
|
||||
|
||||
const move = (offset: number) => setCurrentIndex((current) => (current + offset + assets.length) % assets.length);
|
||||
|
||||
return (
|
||||
<Box w="100%" h="100%" className={classes.carouselContainer}>
|
||||
<Image src={currentAsset.publicLink} alt="Album photo" className={classes.carouselImage} />
|
||||
<Stack w="100%" h="100%" gap={0}>
|
||||
<Box w="100%" style={{ flex: 1, minHeight: 0 }} className={classes.carouselContainer}>
|
||||
<Image
|
||||
src={currentAsset.publicLink}
|
||||
alt={t("albumPhoto")}
|
||||
className={classes.carouselImage}
|
||||
data-fit={advanced ? "contain" : "cover"}
|
||||
/>
|
||||
|
||||
{showPhotoInfo && (
|
||||
<Stack gap="xs" className={classes.photoInfo} p="md">
|
||||
<Group gap="xs">
|
||||
<IconCalendar size={16} />
|
||||
<Text size="xs">{new Date(currentAsset.fileModifiedAt).toLocaleDateString()}</Text>
|
||||
{assets.length > 1 && (
|
||||
<Group
|
||||
className={classes.carouselControls}
|
||||
data-visible={advanced || paused || undefined}
|
||||
gap={4}
|
||||
wrap="nowrap"
|
||||
>
|
||||
{advanced && (
|
||||
<ActionIcon
|
||||
aria-label={t("actions.previousPhoto")}
|
||||
variant="filled"
|
||||
color="dark"
|
||||
radius="xl"
|
||||
size={40}
|
||||
onClick={() => move(-1)}
|
||||
>
|
||||
<IconChevronLeft size="var(--mantine-font-size-lg)" />
|
||||
</ActionIcon>
|
||||
)}
|
||||
<ActionIcon
|
||||
aria-label={paused ? t("actions.resumeSlideshow") : t("actions.pauseSlideshow")}
|
||||
variant="filled"
|
||||
color="dark"
|
||||
radius="xl"
|
||||
size={advanced ? 40 : 32}
|
||||
onClick={() => setPaused((value) => !value)}
|
||||
>
|
||||
{paused ? (
|
||||
<IconPlayerPlay size="var(--mantine-font-size-lg)" />
|
||||
) : (
|
||||
<IconPlayerPause size="var(--mantine-font-size-lg)" />
|
||||
)}
|
||||
</ActionIcon>
|
||||
{advanced && (
|
||||
<ActionIcon
|
||||
aria-label={t("actions.nextPhoto")}
|
||||
variant="filled"
|
||||
color="dark"
|
||||
radius="xl"
|
||||
size={40}
|
||||
onClick={() => move(1)}
|
||||
>
|
||||
<IconChevronRight size="var(--mantine-font-size-lg)" />
|
||||
</ActionIcon>
|
||||
)}
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
{currentIndex + 1} / {assets.length}
|
||||
</Text>
|
||||
</Stack>
|
||||
)}
|
||||
|
||||
{(showPhotoInfo || advanced) && (
|
||||
<Stack gap="xs" className={classes.photoInfo} p="md">
|
||||
{albumName && (
|
||||
<Text size="xs" fw={600}>
|
||||
{albumName}
|
||||
</Text>
|
||||
)}
|
||||
<Group gap="xs">
|
||||
<IconCalendar size="var(--mantine-font-size-md)" />
|
||||
<Text size="xs">{new Date(currentAsset.fileModifiedAt).toLocaleDateString(locale)}</Text>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
{safeCurrentIndex + 1} / {assets.length}
|
||||
</Text>
|
||||
</Stack>
|
||||
)}
|
||||
</Box>
|
||||
{advanced && (
|
||||
<ScrollArea px="xs" py={6}>
|
||||
<Group gap={6} wrap="nowrap">
|
||||
{assets.map((asset, index) => (
|
||||
<UnstyledButton
|
||||
key={asset.id}
|
||||
onClick={() => setCurrentIndex(index)}
|
||||
aria-label={t("actions.photo", { number: index + 1 })}
|
||||
aria-pressed={index === safeCurrentIndex}
|
||||
aria-current={index === safeCurrentIndex ? "true" : undefined}
|
||||
>
|
||||
<Image
|
||||
src={asset.publicLink}
|
||||
alt=""
|
||||
loading="lazy"
|
||||
w={64}
|
||||
h={44}
|
||||
radius="sm"
|
||||
fit="cover"
|
||||
style={{ opacity: index === currentIndex ? 1 : 0.55 }}
|
||||
/>
|
||||
</UnstyledButton>
|
||||
))}
|
||||
</Group>
|
||||
</ScrollArea>
|
||||
)}
|
||||
</Box>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function NoPhotosInAlbum() {
|
||||
const t = useI18n();
|
||||
const t = useI18n("widget.immich-albumCarousel");
|
||||
return (
|
||||
<Center h="100%">
|
||||
<Stack align="center" gap="xs">
|
||||
<IconAlertCircle size={32} />
|
||||
<IconAlertCircle style={iconSizes.xl} />
|
||||
<Text size="sm" fw={500}>
|
||||
{t("widget.immich-albumCarousel.noPhotos")}
|
||||
{t("noPhotos")}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Center>
|
||||
|
||||
@@ -1,58 +1,97 @@
|
||||
import { IconPhoto } from "@tabler/icons-react";
|
||||
import { IconChevronLeft, IconChevronRight, IconPhoto, IconPlayerPause } from "@tabler/icons-react";
|
||||
import z from "zod";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
import { getWidgetIntegrationConfig } from "@homarr/definitions";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import { createWidgetDefinition } from "../../definition";
|
||||
import { createWidgetDefinition, widgetQueryInputMatches } from "../../definition";
|
||||
import { optionsBuilder } from "../../options";
|
||||
import { ALL_PHOTOS_ALBUM_ID } from "./constants";
|
||||
|
||||
const createOptions = () =>
|
||||
optionsBuilder.from((factory) => ({
|
||||
albumId: factory.integrationSelect({
|
||||
defaultValue: ALL_PHOTOS_ALBUM_ID,
|
||||
withDescription: true,
|
||||
clearable: true,
|
||||
useOptions: (integrationIds: string[]) => {
|
||||
const t = useI18n("widget.immich-albumCarousel");
|
||||
const {
|
||||
data = [],
|
||||
isPending,
|
||||
isError,
|
||||
} = clientApi.widget.immich.getAlbums.useQuery(
|
||||
{ integrationId: integrationIds[0] ?? "" },
|
||||
{ enabled: integrationIds.length > 0, staleTime: 15 * 60 * 1000 },
|
||||
);
|
||||
return {
|
||||
data: [
|
||||
{ value: ALL_PHOTOS_ALBUM_ID, label: t("allPhotos") },
|
||||
...data.map((album) => ({ value: album.id, label: album.albumName })),
|
||||
],
|
||||
isPending,
|
||||
isError,
|
||||
};
|
||||
},
|
||||
}),
|
||||
rotationIntervalSeconds: factory.number({
|
||||
defaultValue: 5,
|
||||
validate: z.number().min(1).max(3600),
|
||||
withDescription: true,
|
||||
}),
|
||||
showPhotoInfo: factory.switch({
|
||||
defaultValue: false,
|
||||
withDescription: true,
|
||||
}),
|
||||
randomizePhotos: factory.switch({
|
||||
defaultValue: false,
|
||||
withDescription: true,
|
||||
}),
|
||||
}));
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("immich-albumCarousel", {
|
||||
icon: IconPhoto,
|
||||
queryKey: [["widget", "immich"]],
|
||||
refetchInterval: null,
|
||||
supportedIntegrations: ["immich"],
|
||||
integrationsRequired: true,
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
albumId: factory.integrationSelect({
|
||||
defaultValue: ALL_PHOTOS_ALBUM_ID,
|
||||
withDescription: true,
|
||||
clearable: true,
|
||||
useOptions: (integrationIds: string[]) => {
|
||||
const t = useScopedI18n("widget.immich-albumCarousel");
|
||||
const {
|
||||
data = [],
|
||||
isPending,
|
||||
isError,
|
||||
} = clientApi.widget.immich.getAlbums.useQuery(
|
||||
{ integrationId: integrationIds[0] ?? "" },
|
||||
{ enabled: integrationIds.length > 0, staleTime: 15 * 60 * 1000 },
|
||||
);
|
||||
return {
|
||||
data: [
|
||||
{ value: ALL_PHOTOS_ALBUM_ID, label: t("allPhotos") },
|
||||
...data.map((album) => ({ value: album.id, label: album.albumName })),
|
||||
],
|
||||
isPending,
|
||||
isError,
|
||||
};
|
||||
},
|
||||
}),
|
||||
rotationIntervalSeconds: factory.number({
|
||||
defaultValue: 5,
|
||||
validate: z.number().min(1).max(3600),
|
||||
withDescription: true,
|
||||
}),
|
||||
showPhotoInfo: factory.switch({
|
||||
defaultValue: false,
|
||||
withDescription: true,
|
||||
}),
|
||||
randomizePhotos: factory.switch({
|
||||
defaultValue: false,
|
||||
withDescription: true,
|
||||
}),
|
||||
}));
|
||||
supportsAdvancedFocus: true,
|
||||
queryKeys: [[["widget", "immich", "getAlbum"]], [["widget", "immich", "getAlbumPreview"]]],
|
||||
queryMatcher: ({ path, input }, scope) => {
|
||||
let albumId: string | undefined;
|
||||
if (typeof scope.options.albumId === "string" && scope.options.albumId !== ALL_PHOTOS_ALBUM_ID)
|
||||
albumId = scope.options.albumId;
|
||||
const expected = { integrationId: scope.integrationIds[0] ?? "", albumId };
|
||||
if (path.at(-1) === "getAlbumPreview") {
|
||||
if (!albumId) return false;
|
||||
return widgetQueryInputMatches(input, { ...expected, randomizePhotos: scope.options.randomizePhotos === true });
|
||||
}
|
||||
return widgetQueryInputMatches(input, expected);
|
||||
},
|
||||
refetchInterval: null,
|
||||
...getWidgetIntegrationConfig("immich-albumCarousel"),
|
||||
contextActions: ({ widgetRuntimeRef }) => {
|
||||
const actions = widgetRuntimeRef.current.actions;
|
||||
return [
|
||||
{
|
||||
key: "previousPhoto",
|
||||
label: "widget.immich-albumCarousel.actions.previousPhoto",
|
||||
icon: IconChevronLeft,
|
||||
disabled: typeof actions.previousPhoto !== "function",
|
||||
onClick: () => actions.previousPhoto?.(),
|
||||
},
|
||||
{
|
||||
key: "nextPhoto",
|
||||
label: "widget.immich-albumCarousel.actions.nextPhoto",
|
||||
icon: IconChevronRight,
|
||||
disabled: typeof actions.nextPhoto !== "function",
|
||||
onClick: () => actions.nextPhoto?.(),
|
||||
},
|
||||
{
|
||||
key: "toggleSlideshow",
|
||||
label: "widget.immich-albumCarousel.actions.toggleSlideshow",
|
||||
icon: IconPlayerPause,
|
||||
disabled: typeof actions.toggleSlideshow !== "function",
|
||||
onClick: () => actions.toggleSlideshow?.(),
|
||||
},
|
||||
];
|
||||
},
|
||||
createOptions,
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -0,0 +1,107 @@
|
||||
// @vitest-environment jsdom
|
||||
|
||||
import { act, createElement } from "react";
|
||||
import { createRoot } from "react-dom/client";
|
||||
import { MantineProvider } from "@mantine/core";
|
||||
import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import ImmichServerStatsWidget from "./server-stats/component";
|
||||
import { definition as albumCarouselDefinition } from "./album-carousel";
|
||||
|
||||
const mocks = vi.hoisted(() => ({
|
||||
getAlbums: vi.fn(() => ({ data: [], isPending: false, isError: false })),
|
||||
}));
|
||||
|
||||
vi.mock("@trpc/react-query", () => ({
|
||||
getQueryKey: (procedure: { path: string[] }, input: unknown) => [procedure.path, { input, type: "query" }],
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/api/client", () => ({
|
||||
clientApi: {
|
||||
widget: {
|
||||
immich: {
|
||||
getAlbums: { path: ["widget", "immich", "getAlbums"], useQuery: mocks.getAlbums },
|
||||
getServerStats: {
|
||||
path: ["widget", "immich", "getServerStats"],
|
||||
useQuery: () => ({ data: undefined }),
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/translation/client", () => ({
|
||||
useCurrentIntlLocale: () => "en",
|
||||
useI18n: () => (key: string) => key,
|
||||
}));
|
||||
|
||||
vi.mock("@homarr/settings", () => ({
|
||||
useByteFormatter: () => ({ formatBytes: (bytes: number) => `${bytes} B` }),
|
||||
}));
|
||||
|
||||
describe("Immich album queries", () => {
|
||||
let host: HTMLDivElement | undefined;
|
||||
let root: ReturnType<typeof createRoot> | undefined;
|
||||
|
||||
beforeEach(() => vi.clearAllMocks());
|
||||
|
||||
afterEach(async () => {
|
||||
if (root) await act(async () => root?.unmount());
|
||||
host?.remove();
|
||||
vi.unstubAllGlobals();
|
||||
});
|
||||
|
||||
test("server stats requests a bounded album response", async () => {
|
||||
vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
|
||||
vi.stubGlobal("matchMedia", (query: string) => ({
|
||||
matches: false,
|
||||
media: query,
|
||||
onchange: null,
|
||||
addListener: () => undefined,
|
||||
removeListener: () => undefined,
|
||||
addEventListener: () => undefined,
|
||||
removeEventListener: () => undefined,
|
||||
dispatchEvent: () => false,
|
||||
}));
|
||||
host = document.createElement("div");
|
||||
document.body.append(host);
|
||||
root = createRoot(host);
|
||||
|
||||
await act(async () =>
|
||||
root?.render(
|
||||
createElement(
|
||||
MantineProvider,
|
||||
null,
|
||||
createElement(ImmichServerStatsWidget, {
|
||||
integrationIds: ["immich-id"],
|
||||
options: { showUsers: true, showPhotos: true, showVideos: true, showStorage: true },
|
||||
displayMode: "advanced",
|
||||
width: 800,
|
||||
height: 600,
|
||||
isEditMode: false,
|
||||
boardId: "board-id",
|
||||
itemId: "item-id",
|
||||
setOptions: vi.fn(),
|
||||
} satisfies WidgetComponentProps<"immich-serverStats">),
|
||||
),
|
||||
),
|
||||
);
|
||||
|
||||
expect(mocks.getAlbums).toHaveBeenCalledWith(
|
||||
{ integrationId: "immich-id", limit: 50 },
|
||||
expect.objectContaining({ enabled: true }),
|
||||
);
|
||||
});
|
||||
|
||||
test("album carousel keeps requesting every album for its selector", () => {
|
||||
const options = albumCarouselDefinition.createOptions();
|
||||
|
||||
options.albumId.useOptions(["immich-id"]);
|
||||
|
||||
expect(mocks.getAlbums).toHaveBeenCalledWith(
|
||||
{ integrationId: "immich-id" },
|
||||
expect.objectContaining({ enabled: true }),
|
||||
);
|
||||
});
|
||||
});
|
||||
@@ -1,10 +1,38 @@
|
||||
.statItem {
|
||||
padding: 8px 10px;
|
||||
border: 0.0625rem solid rgb(from var(--mantine-color-secondaryColor-filled) r g b / calc(var(--opacity, 1) * 0.38));
|
||||
border-radius: var(--mantine-radius-sm);
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.statItemDense {
|
||||
min-width: 0;
|
||||
min-height: 40px;
|
||||
padding: 3px 6px;
|
||||
border: 0.0625rem solid rgb(from var(--mantine-color-secondaryColor-filled) r g b / calc(var(--opacity, 1) * 0.32));
|
||||
border-radius: var(--mantine-radius-sm);
|
||||
background-color: transparent;
|
||||
}
|
||||
|
||||
.statItemCompact {
|
||||
padding: 12px;
|
||||
border-radius: var(--mantine-radius-md);
|
||||
background-color: light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6));
|
||||
transition: all 0.2s ease;
|
||||
background-color: rgb(
|
||||
from light-dark(var(--mantine-color-gray-0), var(--mantine-color-dark-6)) r g b / var(--opacity, 1)
|
||||
);
|
||||
transition: background-color 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-5));
|
||||
background-color: rgb(
|
||||
from light-dark(var(--mantine-color-gray-1), var(--mantine-color-dark-5)) r g b / var(--opacity, 1)
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@media (forced-colors: active) {
|
||||
.statItem,
|
||||
.statItemDense,
|
||||
.statItemCompact {
|
||||
border: 0.0625rem solid CanvasText;
|
||||
}
|
||||
}
|
||||
@@ -1,54 +1,150 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { Group, Stack, Text } from "@mantine/core";
|
||||
import { Group, Progress, ScrollArea, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import { IconDatabase, IconPhoto, IconUsers, IconVideo } from "@tabler/icons-react";
|
||||
import { getQueryKey } from "@trpc/react-query";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { formatBytes } from "@homarr/common";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
import { useCurrentIntlLocale, useI18n } from "@homarr/translation/client";
|
||||
import { useByteFormatter } from "@homarr/settings";
|
||||
import { zoomCompensatedSize } from "@homarr/ui";
|
||||
|
||||
import { WidgetEmptyState } from "../../common/empty-state";
|
||||
import type { WidgetComponentProps } from "../../definition";
|
||||
import { getUsableWidgetQueryData, isInitialWidgetQueryPending } from "../../common/query-state";
|
||||
import { WidgetQueryLoadingState } from "../../common/query-state-indicator";
|
||||
import { useWidgetRuntimeQueries } from "../../runtime-hooks";
|
||||
import classes from "./component.module.css";
|
||||
|
||||
const MAX_ADVANCED_ALBUMS = 50;
|
||||
|
||||
export default function ImmichServerStatsWidget({
|
||||
integrationIds,
|
||||
options,
|
||||
displayMode = "compact",
|
||||
width,
|
||||
height,
|
||||
widgetRuntimeRef,
|
||||
}: WidgetComponentProps<"immich-serverStats">) {
|
||||
const t = useI18n();
|
||||
const { data: stats } = clientApi.widget.immich.getServerStats.useQuery({
|
||||
integrationId: integrationIds[0] ?? "",
|
||||
const t = useI18n("widget.immich-serverStats");
|
||||
const { formatBytes } = useByteFormatter();
|
||||
const locale = useCurrentIntlLocale();
|
||||
const input = { integrationId: integrationIds[0] ?? "" };
|
||||
const albumsInput = { ...input, limit: MAX_ADVANCED_ALBUMS };
|
||||
const isAdvanced = displayMode === "advanced";
|
||||
const albumsEnabled = isAdvanced && integrationIds.length > 0;
|
||||
const statsQuery = clientApi.widget.immich.getServerStats.useQuery(input);
|
||||
const stats = getUsableWidgetQueryData(statsQuery);
|
||||
const albumsQuery = clientApi.widget.immich.getAlbums.useQuery(albumsInput, {
|
||||
enabled: albumsEnabled,
|
||||
staleTime: 15 * 60 * 1000,
|
||||
});
|
||||
const albums = albumsQuery.data ?? [];
|
||||
useWidgetRuntimeQueries(widgetRuntimeRef, [
|
||||
getQueryKey(clientApi.widget.immich.getServerStats, input, "query"),
|
||||
...(albumsEnabled ? [getQueryKey(clientApi.widget.immich.getAlbums, albumsInput, "query")] : []),
|
||||
]);
|
||||
|
||||
if (isInitialWidgetQueryPending(statsQuery)) return <WidgetQueryLoadingState />;
|
||||
if (!stats) return <WidgetEmptyState />;
|
||||
|
||||
const statVisibility = getImmichStatVisibility(options, isAdvanced);
|
||||
const statCount =
|
||||
Number(statVisibility.showUsers) +
|
||||
Number(statVisibility.showPhotos) +
|
||||
Number(statVisibility.showVideos) +
|
||||
Number(statVisibility.showStorage);
|
||||
const statsLayout = getImmichStatsLayout(width, height, statCount, isAdvanced);
|
||||
|
||||
const statItems = [
|
||||
{
|
||||
key: "users",
|
||||
enabled: statVisibility.showUsers,
|
||||
icon: <IconUsers style={zoomCompensatedSize(isAdvanced ? 18 : 20)} />,
|
||||
label: t("users"),
|
||||
value: stats.userCount.toLocaleString(locale),
|
||||
},
|
||||
{
|
||||
key: "photos",
|
||||
enabled: statVisibility.showPhotos,
|
||||
icon: <IconPhoto style={zoomCompensatedSize(isAdvanced ? 18 : 20)} />,
|
||||
label: t("photos"),
|
||||
value: stats.photoCount.toLocaleString(locale),
|
||||
},
|
||||
{
|
||||
key: "videos",
|
||||
enabled: statVisibility.showVideos,
|
||||
icon: <IconVideo style={zoomCompensatedSize(isAdvanced ? 18 : 20)} />,
|
||||
label: t("videos"),
|
||||
value: stats.videoCount.toLocaleString(locale),
|
||||
},
|
||||
{
|
||||
key: "storage",
|
||||
enabled: statVisibility.showStorage,
|
||||
icon: <IconDatabase style={zoomCompensatedSize(isAdvanced ? 18 : 20)} />,
|
||||
label: t("storage"),
|
||||
value: formatBytes(stats.totalLibraryUsageInBytes),
|
||||
},
|
||||
]
|
||||
.filter((item) => item.enabled)
|
||||
.map(({ key, icon, label, value }) => (
|
||||
<StatItem
|
||||
key={key}
|
||||
icon={icon}
|
||||
label={label}
|
||||
value={value}
|
||||
dense={isAdvanced && statsLayout.dense}
|
||||
compact={!isAdvanced}
|
||||
/>
|
||||
));
|
||||
|
||||
if (!isAdvanced) {
|
||||
return (
|
||||
<Stack gap="md" h="100%" p="md">
|
||||
{statItems}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
const statsContent = (
|
||||
<SimpleGrid cols={statsLayout.columns} spacing={statsLayout.dense ? 4 : "sm"}>
|
||||
{statItems}
|
||||
</SimpleGrid>
|
||||
);
|
||||
const sortedAlbums = albums;
|
||||
const maxAssets = sortedAlbums[0]?.assetCount ?? 1;
|
||||
return (
|
||||
<Stack gap="md" h="100%" p="md">
|
||||
{options.showUsers && (
|
||||
<StatItem icon={<IconUsers size={20} />} label={t("widget.immich-serverStats.users")} value={stats.userCount} />
|
||||
)}
|
||||
{options.showPhotos && (
|
||||
<StatItem
|
||||
icon={<IconPhoto size={20} />}
|
||||
label={t("widget.immich-serverStats.photos")}
|
||||
value={stats.photoCount}
|
||||
/>
|
||||
)}
|
||||
{options.showVideos && (
|
||||
<StatItem
|
||||
icon={<IconVideo size={20} />}
|
||||
label={t("widget.immich-serverStats.videos")}
|
||||
value={stats.videoCount}
|
||||
/>
|
||||
)}
|
||||
{options.showStorage && (
|
||||
<StatItem
|
||||
icon={<IconDatabase size={20} />}
|
||||
label={t("widget.immich-serverStats.storage")}
|
||||
value={formatBytes(stats.totalLibraryUsageInBytes)}
|
||||
/>
|
||||
)}
|
||||
<Stack gap="lg" h="100%" p="lg">
|
||||
{statsContent}
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("albumLimit", { count: MAX_ADVANCED_ALBUMS })}
|
||||
</Text>
|
||||
</Group>
|
||||
<ScrollArea style={{ flex: 1, minHeight: 0 }}>
|
||||
{isInitialWidgetQueryPending(albumsQuery) ? (
|
||||
<WidgetQueryLoadingState />
|
||||
) : albums.length === 0 ? (
|
||||
<WidgetEmptyState />
|
||||
) : (
|
||||
<SimpleGrid cols={width >= 900 ? 2 : 1} spacing="xs">
|
||||
{sortedAlbums.map((album) => (
|
||||
<Stack key={album.id} gap={4} p="xs">
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Text size="sm" fw={600} truncate>
|
||||
{album.albumName}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{album.assetCount.toLocaleString(locale)}
|
||||
</Text>
|
||||
</Group>
|
||||
<Progress value={(album.assetCount / Math.max(maxAssets, 1)) * 100} size="sm" />
|
||||
</Stack>
|
||||
))}
|
||||
</SimpleGrid>
|
||||
)}
|
||||
</ScrollArea>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -57,20 +153,54 @@ interface StatItemProps {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
value: string | number;
|
||||
dense: boolean;
|
||||
compact: boolean;
|
||||
}
|
||||
|
||||
function StatItem({ icon, label, value }: StatItemProps) {
|
||||
function StatItem({ icon, label, value, dense, compact }: StatItemProps) {
|
||||
if (dense) {
|
||||
return (
|
||||
<Stack gap={1} align="center" justify="center" className={classes.statItemDense} title={`${label}: ${value}`}>
|
||||
<Text size="sm" fw={700} truncate="end" w="100%" ta="center">
|
||||
{value}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" truncate="end" w="100%" ta="center">
|
||||
{label}
|
||||
</Text>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Group justify="space-between" align="center" className={classes.statItem}>
|
||||
<Group gap="sm" align="center">
|
||||
<Group justify="space-between" align="center" className={compact ? classes.statItemCompact : classes.statItem}>
|
||||
<Group gap="sm" align="center" wrap="nowrap" miw={0}>
|
||||
{icon}
|
||||
<Text size="sm" fw={500}>
|
||||
<Text size="sm" fw={500} truncate="end">
|
||||
{label}
|
||||
</Text>
|
||||
</Group>
|
||||
<Text size="sm" fw={700} c="var(--mantine-primary-color)">
|
||||
<Text size="sm" fw={700} c="var(--mantine-primary-color)" truncate="end" title={String(value)}>
|
||||
{value}
|
||||
</Text>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
|
||||
export const getImmichStatsLayout = (width: number, _height: number, itemCount: number, isAdvanced = false) => {
|
||||
const count = Math.max(1, itemCount);
|
||||
if (isAdvanced) {
|
||||
return { columns: width >= 720 ? Math.min(count, 4) : width >= 360 ? Math.min(count, 2) : 1, dense: false };
|
||||
}
|
||||
|
||||
return { columns: 1, dense: false };
|
||||
};
|
||||
|
||||
export const getImmichStatVisibility = (
|
||||
options: WidgetComponentProps<"immich-serverStats">["options"],
|
||||
isAdvanced: boolean,
|
||||
) => ({
|
||||
showUsers: isAdvanced || options.showUsers,
|
||||
showPhotos: isAdvanced || options.showPhotos,
|
||||
showVideos: isAdvanced || options.showVideos,
|
||||
showStorage: isAdvanced || options.showStorage,
|
||||
});
|
||||
@@ -1,14 +1,17 @@
|
||||
import { IconGraphFilled } from "@tabler/icons-react";
|
||||
|
||||
import { createWidgetDefinition } from "../../definition";
|
||||
import { getWidgetIntegrationConfig } from "@homarr/definitions";
|
||||
|
||||
import { createWidgetDefinition, matchesWidgetRuntimeQuery } from "../../definition";
|
||||
import { optionsBuilder } from "../../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("immich-serverStats", {
|
||||
icon: IconGraphFilled,
|
||||
queryKey: [["widget", "immich"]],
|
||||
supportsAdvancedFocus: true,
|
||||
queryKeys: [[["widget", "immich", "getServerStats"]], [["widget", "immich", "getAlbums"]]],
|
||||
queryMatcher: matchesWidgetRuntimeQuery,
|
||||
refetchInterval: null,
|
||||
supportedIntegrations: ["immich"],
|
||||
integrationsRequired: true,
|
||||
...getWidgetIntegrationConfig("immich-serverStats"),
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
showUsers: factory.switch({
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
import { describe, expect, test } from "vitest";
|
||||
|
||||
import { getImmichStatsLayout, getImmichStatVisibility } from "./component";
|
||||
|
||||
describe("Immich server statistics compact layout", () => {
|
||||
test("keeps the v1 one-column non-dense layout at every compact size", () => {
|
||||
expect(getImmichStatsLayout(280, 120, 4)).toEqual({ columns: 1, dense: false });
|
||||
expect(getImmichStatsLayout(480, 120, 4)).toEqual({ columns: 1, dense: false });
|
||||
expect(getImmichStatsLayout(360, 240, 4)).toEqual({ columns: 1, dense: false });
|
||||
expect(getImmichStatsLayout(200, 180, 4)).toEqual({ columns: 1, dense: false });
|
||||
});
|
||||
|
||||
test("advanced mode shows all four headline stats", () => {
|
||||
const options = { showUsers: false, showPhotos: false, showVideos: false, showStorage: false };
|
||||
|
||||
expect(getImmichStatVisibility(options, true)).toEqual({
|
||||
showUsers: true,
|
||||
showPhotos: true,
|
||||
showVideos: true,
|
||||
showStorage: true,
|
||||
});
|
||||
expect(getImmichStatVisibility(options, false)).toEqual(options);
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user