Merge branch 'dev' into add-more-openapi

This commit is contained in:
Meier Lukas committed 2025-12-10 15:58:04 +01:00
commit df5704019b
309 files changed
+23031 -8513

No files matched your search

+27 -27
View File
@@ -48,44 +48,44 @@
"@homarr/translation": "workspace:^0.1.0",
"@homarr/ui": "workspace:^0.1.0",
"@homarr/validation": "workspace:^0.1.0",
"@mantine/charts": "^8.3.1",
"@mantine/core": "^8.3.1",
"@mantine/hooks": "^8.3.1",
"@tabler/icons-react": "^3.34.1",
"@tiptap/extension-color": "2.26.1",
"@tiptap/extension-highlight": "2.26.1",
"@tiptap/extension-image": "2.26.1",
"@tiptap/extension-link": "^2.26.1",
"@tiptap/extension-placeholder": "^2.26.1",
"@tiptap/extension-table": "2.26.1",
"@tiptap/extension-table-cell": "2.26.1",
"@tiptap/extension-table-header": "2.26.1",
"@tiptap/extension-table-row": "2.26.1",
"@tiptap/extension-task-item": "2.26.1",
"@tiptap/extension-task-list": "2.26.1",
"@tiptap/extension-text-align": "2.26.1",
"@tiptap/extension-text-style": "2.26.1",
"@tiptap/extension-underline": "2.26.1",
"@tiptap/react": "^2.26.1",
"@tiptap/starter-kit": "^2.26.1",
"@mantine/charts": "^8.3.9",
"@mantine/core": "^8.3.9",
"@mantine/hooks": "^8.3.9",
"@tabler/icons-react": "^3.35.0",
"@tiptap/extension-color": "2.27.1",
"@tiptap/extension-highlight": "2.27.1",
"@tiptap/extension-image": "2.27.1",
"@tiptap/extension-link": "^2.27.1",
"@tiptap/extension-placeholder": "^2.27.1",
"@tiptap/extension-table": "2.27.1",
"@tiptap/extension-table-cell": "2.27.1",
"@tiptap/extension-table-header": "2.27.1",
"@tiptap/extension-table-row": "2.27.1",
"@tiptap/extension-task-item": "2.27.1",
"@tiptap/extension-task-list": "2.27.1",
"@tiptap/extension-text-align": "2.27.1",
"@tiptap/extension-text-style": "2.27.1",
"@tiptap/extension-underline": "2.27.1",
"@tiptap/react": "^2.27.1",
"@tiptap/starter-kit": "^2.27.1",
"clsx": "^2.1.1",
"dayjs": "^1.11.18",
"dayjs": "^1.11.19",
"mantine-form-zod-resolver": "^1.3.0",
"mantine-react-table": "2.0.0-beta.9",
"next": "15.5.2",
"react": "19.1.1",
"react-dom": "19.1.1",
"next": "16.0.7",
"react": "19.2.1",
"react-dom": "19.2.1",
"react-markdown": "^10.1.0",
"recharts": "^2.15.4",
"video.js": "^8.23.4",
"zod": "^4.1.5"
"zod": "^4.1.13"
},
"devDependencies": {
"@homarr/eslint-config": "workspace:^0.2.0",
"@homarr/prettier-config": "workspace:^0.1.0",
"@homarr/tsconfig": "workspace:^0.1.0",
"@types/video.js": "^7.3.58",
"eslint": "^9.35.0",
"typescript": "^5.9.2"
"eslint": "^9.39.1",
"typescript": "^5.9.3"
}
}
@@ -1,16 +1,17 @@
"use client";
import { memo, useMemo } from "react";
import Link from "next/link";
import type { SelectProps } from "@mantine/core";
import { Anchor, Button, Group, Loader, Select, SimpleGrid, Text } from "@mantine/core";
import { IconCheck, IconRocket } from "@tabler/icons-react";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useSession } from "@homarr/auth/client";
import { useModalAction } from "@homarr/modals";
import { QuickAddAppModal } from "@homarr/modals-collection";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import type { CommonWidgetInputProps } from "./common";
import { useWidgetInputTranslation } from "./common";
@@ -21,6 +22,8 @@ export const WidgetAppInput = ({ property, kind }: CommonWidgetInputProps<"app">
const tInput = useWidgetInputTranslation(kind, property);
const form = useFormContext();
const { data: apps, isPending, refetch } = clientApi.app.selectable.useQuery();
const { data: session } = useSession();
const canCreateApps = session?.user.permissions.includes("app-create") ?? false;
const { openModal } = useModalAction(QuickAddAppModal);
@@ -30,7 +33,7 @@ export const WidgetAppInput = ({ property, kind }: CommonWidgetInputProps<"app">
);
return (
<SimpleGrid cols={{ base: 1, md: 2 }} spacing={{ base: "md" }} style={{ alignItems: "center" }}>
<SimpleGrid cols={{ base: 1, md: canCreateApps ? 2 : 1 }} spacing={{ base: "md" }} style={{ alignItems: "center" }}>
<Select
label={tInput("label")}
searchable
@@ -59,22 +62,24 @@ export const WidgetAppInput = ({ property, kind }: CommonWidgetInputProps<"app">
styles={{ root: { flex: "1" } }}
{...form.getInputProps(`options.${property}`)}
/>
<Button
mt={3}
rightSection={<IconRocket size="1.5rem" />}
variant="default"
onClick={() =>
openModal({
// eslint-disable-next-line no-restricted-syntax
async onClose(createdAppId) {
await refetch();
form.setFieldValue(`options.${property}`, createdAppId);
},
})
}
>
{t("widget.common.app.quickCreate")}
</Button>
{canCreateApps && (
<Button
mt={3}
rightSection={<IconRocket size="1.5rem" />}
variant="default"
onClick={() =>
openModal({
onClose(createdAppId) {
void refetch().then(() => {
form.setFieldValue(`options.${property}`, createdAppId);
});
},
})
}
>
{t("widget.common.app.quickCreate")}
</Button>
)}
</SimpleGrid>
);
};
@@ -11,9 +11,10 @@ import {
Text,
useMantineColorScheme,
} from "@mantine/core";
import { IconClock } from "@tabler/icons-react";
import { IconClock, IconPin } from "@tabler/icons-react";
import dayjs from "dayjs";
import { isNullOrWhitespace } from "@homarr/common";
import type { CalendarEvent } from "@homarr/integrations/types";
import { useI18n } from "@homarr/translation/client";
@@ -40,85 +41,116 @@ export const CalendarEventList = ({ events }: CalendarEventListProps) => {
<Stack>
{events.map((event, eventIndex) => (
<Group key={`event-${eventIndex}`} align={"stretch"} wrap="nowrap">
<Box pos={"relative"} w={70} h={120}>
<Image
src={event.thumbnail}
w={70}
h={120}
radius={"sm"}
fallbackSrc={"https://placehold.co/400x600?text=No%20image"}
/>
{event.mediaInformation?.type === "tv" && (
<Badge
pos={"absolute"}
bottom={-6}
left={"50%"}
w={"inherit"}
className={classes.badge}
>{`S${event.mediaInformation.seasonNumber} / E${event.mediaInformation.episodeNumber}`}</Badge>
)}
</Box>
{event.image !== null && (
<Box pos="relative">
<Image
src={event.image.src}
w={70}
mah={150}
style={{
aspectRatio: event.image.aspectRatio
? `${event.image.aspectRatio.width} / ${event.image.aspectRatio.height}`
: "1/1",
}}
radius="sm"
fallbackSrc="https://placehold.co/400x400?text=No%20image"
/>
{event.image.badge !== undefined && (
<Badge pos="absolute" bottom={-6} left="50%" w="90%" className={classes.badge}>
{event.image.badge.content}
</Badge>
)}
</Box>
)}
<Stack style={{ flexGrow: 1 }} gap={0}>
<Group justify={"space-between"} align={"start"} mb={"xs"} wrap="nowrap">
<Group justify="space-between" align="start" mb="xs" wrap="nowrap">
<Stack gap={0}>
{event.subName && (
{event.subTitle !== null && (
<Text lineClamp={1} size="sm">
{event.subName}
{event.subTitle}
</Text>
)}
<Text fw={"bold"} lineClamp={1} size="sm">
{event.name}
{event.title}
</Text>
</Stack>
{event.dates ? (
{event.metadata?.type === "radarr" && (
<Group wrap="nowrap">
<Text c="dimmed" size="sm">
{t(
`widget.calendar.option.releaseType.options.${event.dates.find(({ date }) => event.date === date)?.type ?? "inCinemas"}`,
)}
</Text>
</Group>
) : (
<Group gap={3} wrap="nowrap" align={"center"}>
<IconClock opacity={0.7} size={"1rem"} />
<Text c={"dimmed"} size={"sm"}>
{dayjs(event.date).format("HH:mm")}
{t(`widget.calendar.option.releaseType.options.${event.metadata.releaseType}`)}
</Text>
</Group>
)}
<Group gap={3} wrap="nowrap" align={"center"}>
<IconClock opacity={0.7} size={"1rem"} />
{isAllDay(event) ? (
<Text c={"dimmed"} size={"sm"}>
{t("widget.calendar.duration.allDay")}
</Text>
) : (
<>
<Text c={"dimmed"} size={"sm"}>
{dayjs(event.startDate).format("HH:mm")}
</Text>
{event.endDate !== null && (
<>
-{" "}
<Text c={"dimmed"} size={"sm"}>
{dayjs(event.endDate).format("HH:mm")}
</Text>
</>
)}
</>
)}
</Group>
</Group>
{event.description && (
{event.location !== null && (
<Group gap={4} mb={isNullOrWhitespace(event.description) ? 0 : "sm"}>
<IconPin opacity={0.7} size={"1rem"} />
<Text size={"xs"} c={"dimmed"} lineClamp={1}>
{event.location}
</Text>
</Group>
)}
{!isNullOrWhitespace(event.description) && (
<Text size={"xs"} c={"dimmed"} lineClamp={2}>
{event.description}
</Text>
)}
{event.links.length > 0 && (
<Group pt={5} gap={5} mt={"auto"} wrap="nowrap">
{event.links.map((link) => (
<Button
key={link.href}
component={"a"}
href={link.href.toString()}
target={"_blank"}
size={"xs"}
radius={"xl"}
variant={link.color ? undefined : "default"}
styles={{
root: {
backgroundColor: link.color,
color: link.isDark && colorScheme === "dark" ? "white" : "black",
"&:hover": link.color
? {
backgroundColor: link.isDark ? lighten(link.color, 0.1) : darken(link.color, 0.1),
}
: undefined,
},
}}
leftSection={link.logo ? <Image src={link.logo} w={20} h={20} /> : undefined}
>
<Text>{link.name}</Text>
</Button>
))}
{event.links
.filter((link) => link.href)
.map((link) => (
<Button
key={link.href}
component={"a"}
href={link.href.toString()}
target={"_blank"}
size={"xs"}
radius={"xl"}
variant={link.color ? undefined : "default"}
styles={{
root: {
backgroundColor: link.color,
color: link.isDark && colorScheme === "dark" ? "white" : "black",
"&:hover": link.color
? {
backgroundColor: link.isDark ? lighten(link.color, 0.1) : darken(link.color, 0.1),
}
: undefined,
},
}}
leftSection={link.logo ? <Image src={link.logo} fit="contain" w={20} h={20} /> : undefined}
>
<Text>{link.name}</Text>
</Button>
))}
</Group>
)}
</Stack>
@@ -128,3 +160,12 @@ export const CalendarEventList = ({ events }: CalendarEventListProps) => {
</ScrollArea>
);
};
const isAllDay = (event: Pick<CalendarEvent, "startDate" | "endDate">) => {
if (!event.endDate) return false;
const start = dayjs(event.startDate);
const end = dayjs(event.endDate);
return start.startOf("day").isSame(start) && end.endOf("day").isSame(end);
};
@@ -0,0 +1,66 @@
import { describe, expect, test } from "vitest";
import type { CalendarEvent } from "@homarr/integrations/types";
import { splitEvents } from "./component";
describe("splitEvents should split multi-day events into multiple single-day events", () => {
test("2 day all-day event should be split up into two all-day events", () => {
const event = createEvent(new Date(2025, 0, 1), new Date(2025, 0, 3));
const result = splitEvents([event]);
expect(result).toHaveLength(2);
expect(result[0]?.startDate).toEqual(event.startDate);
expect(result[0]?.endDate).toEqual(new Date(new Date(2025, 0, 2).getTime() - 1));
expect(result[1]?.startDate).toEqual(new Date(2025, 0, 2));
// Because we want to end the event on the previous day, we have not the same endDate.
// Otherwise there would be three single-day events, with the last being from 0:00 - 0:00
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
expect(result[1]?.endDate).toEqual(new Date(event.endDate!.getTime() - 1));
});
test("2 day partial event should be split up into two events", () => {
const event = createEvent(new Date(2025, 0, 1, 15), new Date(2025, 0, 2, 9));
const result = splitEvents([event]);
expect(result).toHaveLength(2);
expect(result[0]?.startDate).toEqual(event.startDate);
expect(result[0]?.endDate).toEqual(new Date(new Date(2025, 0, 2).getTime() - 1));
expect(result[1]?.startDate).toEqual(new Date(2025, 0, 2));
expect(result[1]?.endDate).toEqual(event.endDate);
});
test("one day partial event should only have one event after split", () => {
const event = createEvent(new Date(2025, 0, 1), new Date(2025, 0, 2));
const result = splitEvents([event]);
expect(result).toHaveLength(1);
});
test("without endDate should not be split", () => {
const event = createEvent(new Date(2025, 0, 1));
const result = splitEvents([event]);
expect(result).toHaveLength(1);
});
test("startDate after endDate should not cause infinite loop", () => {
const event = createEvent(new Date(2025, 0, 2), new Date(2025, 0, 1));
const result = splitEvents([event]);
expect(result).toHaveLength(0);
});
});
const createEvent = (startDate: Date, endDate: Date | null = null): CalendarEvent => ({
title: "Test",
subTitle: null,
description: null,
startDate,
endDate,
image: null,
indicatorColor: "red",
links: [],
location: null,
});
@@ -79,7 +79,7 @@ interface NotificationIndicatorProps {
}
const NotificationIndicator = ({ events, isSmall }: NotificationIndicatorProps) => {
const notificationEvents = [...new Set(events.map((event) => event.links[0]?.notificationColor))].filter(String);
const notificationEvents = [...new Set(events.map((event) => event.indicatorColor))].filter(String);
/* position bottom is lower when small to not be on top of number*/
return (
<Flex w="75%" pos={"absolute"} bottom={isSmall ? 4 : 10} left={"12.5%"} p={0} direction={"row"} justify={"center"}>
+78 -25
View File
@@ -1,13 +1,12 @@
"use client";
import { useState } from "react";
import { useMemo, useState } from "react";
import { useParams } from "next/navigation";
import { useMantineTheme } from "@mantine/core";
import { Calendar } from "@mantine/dates";
import { useElementSize } from "@mantine/hooks";
import dayjs from "dayjs";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useRequiredBoard } from "@homarr/boards/context";
import type { CalendarEvent } from "@homarr/integrations/types";
@@ -33,28 +32,43 @@ interface FetchCalendarProps extends WidgetComponentProps<"calendar"> {
}
const FetchCalendar = ({ month, setMonth, isEditMode, integrationIds, options }: FetchCalendarProps) => {
const [events] = clientApi.widget.calendar.findAllEvents.useSuspenseQuery(
{
integrationIds,
month: month.getMonth(),
year: month.getFullYear(),
releaseType: options.releaseType,
showUnmonitored: options.showUnmonitored,
const input = {
integrationIds,
month: month.getMonth(),
year: month.getFullYear(),
releaseType: options.releaseType,
showUnmonitored: options.showUnmonitored,
};
const [data] = clientApi.widget.calendar.findAllEvents.useSuspenseQuery(input, {
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: false,
});
const utils = clientApi.useUtils();
clientApi.widget.calendar.subscribeToEvents.useSubscription(input, {
onData(data) {
utils.widget.calendar.findAllEvents.setData(input, (old) => {
return old?.map((item) => {
if (item.integration.id !== data.integration.id) return item;
return {
...item,
events: data.events,
};
});
});
},
{
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
retry: false,
},
);
});
const events = useMemo(() => data.flatMap((item) => item.events), [data]);
return <CalendarBase isEditMode={isEditMode} events={events} month={month} setMonth={setMonth} options={options} />;
};
interface CalendarBaseProps {
isEditMode: boolean;
events: RouterOutputs["widget"]["calendar"]["findAllEvents"];
events: CalendarEvent[];
month: Date;
setMonth: (date: Date) => void;
options: WidgetComponentProps<"calendar">["options"];
@@ -70,6 +84,8 @@ const CalendarBase = ({ isEditMode, events, month, setMonth, options }: Calendar
const { ref, width, height } = useElementSize();
const isSmall = width < 256;
const normalizedEvents = useMemo(() => splitEvents(events), [events]);
return (
<Calendar
defaultDate={new Date()}
@@ -123,14 +139,12 @@ const CalendarBase = ({ isEditMode, events, month, setMonth, options }: Calendar
},
}}
renderDay={(tileDate) => {
const eventsForDate = events
.map((event) => ({
...event,
date: (event.dates?.filter(({ type }) => options.releaseType.includes(type)) ?? [event]).find(({ date }) =>
dayjs(date).isSame(tileDate, "day"),
)?.date,
}))
.filter((event): event is CalendarEvent => Boolean(event.date));
const eventsForDate = normalizedEvents
.filter((event) => dayjs(event.startDate).isSame(tileDate, "day"))
.filter(
(event) => event.metadata?.type !== "radarr" || options.releaseType.includes(event.metadata.releaseType),
)
.sort((eventA, eventB) => eventA.startDate.getTime() - eventB.startDate.getTime());
return (
<CalendarDay
@@ -148,3 +162,42 @@ const CalendarBase = ({ isEditMode, events, month, setMonth, options }: Calendar
/>
);
};
/**
* Splits multi-day events into multiple single-day events.
* @param events The events to split.
* @returns The split events.
*/
export const splitEvents = (events: CalendarEvent[]): CalendarEvent[] => {
const splitEvents: CalendarEvent[] = [];
for (const event of events) {
if (!event.endDate) {
splitEvents.push(event);
continue;
}
if (dayjs(event.startDate).isSame(event.endDate, "day")) {
splitEvents.push(event);
continue;
}
if (dayjs(event.startDate).isAfter(event.endDate)) {
// Invalid event, skip it
continue;
}
// Event spans multiple days, split it
let currentStart = dayjs(event.startDate);
while (currentStart.isBefore(event.endDate)) {
splitEvents.push({
...event,
startDate: currentStart.toDate(),
endDate: currentStart.endOf("day").isAfter(event.endDate) ? event.endDate : currentStart.endOf("day").toDate(),
});
currentStart = currentStart.add(1, "day").startOf("day");
}
}
return splitEvents;
};
+7 -6
View File
@@ -111,9 +111,13 @@ const createColumns = (
header: t("action.title"),
Cell({ row }) {
const utils = clientApi.useUtils();
const { mutateAsync: startContainer } = clientApi.docker.startAll.useMutation();
const { mutateAsync: stopContainer } = clientApi.docker.stopAll.useMutation();
const { mutateAsync: restartContainer } = clientApi.docker.restartAll.useMutation();
// eslint-disable-next-line no-restricted-syntax
const onSettled = async () => {
await utils.docker.getContainers.invalidate();
};
const { mutateAsync: startContainer } = clientApi.docker.startAll.useMutation({ onSettled });
const { mutateAsync: stopContainer } = clientApi.docker.stopAll.useMutation({ onSettled });
const { mutateAsync: restartContainer } = clientApi.docker.restartAll.useMutation({ onSettled });
const handleActionAsync = async (action: "start" | "stop" | "restart") => {
const mutation = action === "start" ? startContainer : action === "stop" ? stopContainer : restartContainer;
@@ -121,9 +125,6 @@ const createColumns = (
await mutation(
{ ids: [row.original.id] },
{
async onSettled() {
await utils.docker.getContainers.invalidate();
},
onSuccess() {
showSuccessNotification({
title: t(`action.${action}.notification.success.title`),
@@ -1,9 +1,9 @@
import Link from "next/link";
import { Anchor, Button, Stack, Text } from "@mantine/core";
import type { stringOrTranslation } from "@homarr/translation";
import { translateIfNecessary } from "@homarr/translation";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import type { TablerIcon } from "@homarr/ui";
export interface BaseWidgetErrorProps {
+26 -2
View File
@@ -11,8 +11,9 @@ import classes from "./component.module.css";
export default function IFrameWidget({ options, isEditMode }: WidgetComponentProps<"iframe">) {
const t = useI18n();
const { embedUrl, ...permissions } = options;
const { embedUrl, allowScrolling, ...permissions } = options;
const allowedPermissions = getAllowedPermissions(permissions);
const sandboxFlags = getSandboxFlags(permissions);
if (embedUrl.trim() === "") return <NoUrl />;
if (!isSupportedProtocol(embedUrl)) {
@@ -27,7 +28,8 @@ export default function IFrameWidget({ options, isEditMode }: WidgetComponentPro
src={embedUrl}
title="widget iframe"
allow={allowedPermissions.join(" ")}
scrolling={options.allowScrolling ? "yes" : "no"}
scrolling={allowScrolling ? "yes" : "no"}
sandbox={sandboxFlags.join(" ")}
>
<Text>{t("widget.iframe.error.noBrowerSupport")}</Text>
</iframe>
@@ -80,6 +82,28 @@ const getAllowedPermissions = (
.map(([key]) => permissionMapping[key]);
};
const getSandboxFlags = (
permissions: Omit<WidgetComponentProps<"iframe">["options"], "embedUrl" | "allowScrolling">,
) => {
const baseSandbox = [
"allow-scripts",
"allow-same-origin",
"allow-forms",
"allow-popups",
"allow-top-navigation-by-user-activation",
];
if (permissions.allowFullScreen) {
baseSandbox.push("allow-presentation");
}
if (permissions.allowPayment) {
baseSandbox.push("allow-popups-to-escape-sandbox");
}
return baseSandbox;
};
const permissionMapping = {
allowAutoPlay: "autoplay",
allowCamera: "camera",
@@ -3,10 +3,11 @@
import { ActionIcon, Anchor, Avatar, Badge, Card, Group, Image, ScrollArea, Stack, Text, Tooltip } from "@mantine/core";
import { IconThumbDown, IconThumbUp } from "@tabler/icons-react";
import type { RouterInputs, RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { useRequiredBoard } from "@homarr/boards/context";
import { MediaAvailability, MediaRequestStatus } from "@homarr/integrations/types";
import type { ScopedTranslationFunction } from "@homarr/translation";
import type { MediaRequestStatus } from "@homarr/integrations/types";
import { mediaAvailabilityConfiguration, mediaRequestStatusConfiguration } from "@homarr/integrations/types";
import { useScopedI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../../definition";
@@ -18,7 +19,6 @@ export default function MediaServerWidget({
options,
width,
}: WidgetComponentProps<"mediaRequests-requestList">) {
const t = useScopedI18n("widget.mediaRequests-requestList");
const [mediaRequests] = clientApi.widget.mediaRequests.getLatestRequests.useSuspenseQuery(
{
integrationIds,
@@ -48,20 +48,18 @@ export default function MediaServerWidget({
return dataB.createdAt.getTime() - dataA.createdAt.getTime();
}
return dataA.status - dataB.status;
return (
mediaRequestStatusConfiguration[dataA.status].position -
mediaRequestStatusConfiguration[dataB.status].position
);
});
});
},
},
);
const { mutate: mutateRequestAnswer } = clientApi.widget.mediaRequests.answerRequest.useMutation();
const board = useRequiredBoard();
if (mediaRequests.length === 0) throw new NoIntegrationDataError();
const isTiny = width < 256;
return (
<ScrollArea
className="mediaRequests-list-scrollArea"
@@ -70,193 +68,188 @@ export default function MediaServerWidget({
>
<Stack className="mediaRequests-list-list" gap="xs" p="sm">
{mediaRequests.map((mediaRequest) => (
<Card
className={`mediaRequests-list-item-wrapper mediaRequests-list-item-${mediaRequest.type} mediaRequests-list-item-${mediaRequest.status}`}
<MediaRequestCard
key={`${mediaRequest.integrationId}-${mediaRequest.id}`}
radius={board.itemRadius}
p="xs"
withBorder
>
<Image
className="mediaRequests-list-item-background"
src={mediaRequest.backdropImageUrl}
pos="absolute"
w="100%"
h="100%"
opacity={0.2}
top={0}
left={0}
alt=""
/>
<Group
className="mediaRequests-list-item-contents"
h="100%"
style={{ zIndex: 1 }}
justify="space-between"
wrap="nowrap"
gap={0}
>
<Group className="mediaRequests-list-item-left-side" h="100%" gap="md" wrap="nowrap" flex={1}>
{!isTiny && (
<Image
className="mediaRequests-list-item-poster"
src={mediaRequest.posterImagePath}
h={40}
w="auto"
radius={"md"}
/>
)}
<Stack gap={0} w="100%">
<Group justify="space-between" gap="xs" className="mediaRequests-list-item-top-group">
<Group gap="xs">
<Text className="mediaRequests-list-item-media-year" size="xs">
{mediaRequest.airDate?.getFullYear() ?? t("toBeDetermined")}
</Text>
{!isTiny && (
<Badge
className="mediaRequests-list-item-media-status"
color={getAvailabilityProperties(mediaRequest.availability, t).color}
variant="light"
size="xs"
>
{getAvailabilityProperties(mediaRequest.availability, t).label}
</Badge>
)}
</Group>
<Group className="mediaRequests-list-item-request-user" gap={4} wrap="nowrap">
<Avatar
className="mediaRequests-list-item-request-user-avatar"
src={mediaRequest.requestedBy?.avatar}
size="xs"
/>
<Anchor
className="mediaRequests-list-item-request-user-name"
href={mediaRequest.requestedBy?.link}
c="var(--mantine-color-text)"
target={options.linksTargetNewTab ? "_blank" : "_self"}
fz="xs"
lineClamp={1}
style={{ wordBreak: "break-all" }}
>
{(mediaRequest.requestedBy?.displayName ?? "") || "unknown"}
</Anchor>
</Group>
</Group>
<Group gap="xs" justify="space-between" className="mediaRequests-list-item-bottom-group">
<Anchor
className="mediaRequests-list-item-info-second-line mediaRequests-list-item-media-title"
href={mediaRequest.href}
c="var(--mantine-color-text)"
target={options.linksTargetNewTab ? "_blank" : "_self"}
fz={isTiny ? "xs" : "sm"}
fw={"bold"}
title={mediaRequest.name}
lineClamp={1}
>
{mediaRequest.name || "unknown"}
</Anchor>
{mediaRequest.status === MediaRequestStatus.PendingApproval ? (
<Group className="mediaRequests-list-item-pending-buttons" gap="sm">
<Tooltip label={t("pending.approve")}>
<ActionIcon
className="mediaRequests-list-item-pending-button-approve"
variant="light"
color="green"
size="xs"
radius="md"
onClick={() => {
mutateRequestAnswer({
integrationId: mediaRequest.integrationId,
requestId: mediaRequest.id,
answer: "approve",
});
}}
>
<IconThumbUp size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label={t("pending.decline")}>
<ActionIcon
className="mediaRequests-list-item-pending-button-decline"
variant="light"
color="red"
size="xs"
radius="md"
onClick={() => {
mutateRequestAnswer({
integrationId: mediaRequest.integrationId,
requestId: mediaRequest.id,
answer: "decline",
});
}}
>
<IconThumbDown size={16} />
</ActionIcon>
</Tooltip>
</Group>
) : (
<StatusBadge status={mediaRequest.status} />
)}
</Group>
</Stack>
</Group>
</Group>
</Card>
request={mediaRequest}
isTiny={width <= 256}
options={options}
/>
))}
</Stack>
</ScrollArea>
);
}
const statusMapping = {
[MediaRequestStatus.PendingApproval]: { color: "blue", label: (t) => t("pending") },
[MediaRequestStatus.Approved]: { color: "green", label: (t) => t("approved") },
[MediaRequestStatus.Declined]: { color: "red", label: (t) => t("declined") },
[MediaRequestStatus.Failed]: { color: "red", label: (t) => t("failed") },
[MediaRequestStatus.Completed]: { color: "green", label: (t) => t("completed") },
} satisfies Record<
MediaRequestStatus,
{
color: string;
label: (t: ScopedTranslationFunction<"widget.mediaRequests-requestList.status">) => string;
}
>;
interface MediaRequestCardProps {
request: RouterOutputs["widget"]["mediaRequests"]["getLatestRequests"][number];
isTiny: boolean;
options: WidgetComponentProps<"mediaRequests-requestList">["options"];
}
const MediaRequestCard = ({ request, isTiny, options }: MediaRequestCardProps) => {
const board = useRequiredBoard();
const t = useScopedI18n("widget.mediaRequests-requestList");
return (
<Card
className={`mediaRequests-list-item-wrapper mediaRequests-list-item-${request.type} mediaRequests-list-item-${request.status}`}
radius={board.itemRadius}
p="xs"
withBorder
>
<Image
className="mediaRequests-list-item-background"
src={request.backdropImageUrl}
pos="absolute"
w="100%"
h="100%"
opacity={0.2}
top={0}
left={0}
alt=""
/>
<Group
className="mediaRequests-list-item-contents"
h="100%"
style={{ zIndex: 1 }}
justify="space-between"
wrap="nowrap"
gap={0}
>
<Group className="mediaRequests-list-item-left-side" h="100%" gap="md" wrap="nowrap" flex={1}>
{!isTiny && (
<Image
className="mediaRequests-list-item-poster"
src={request.posterImagePath}
h={40}
w="auto"
radius={"md"}
/>
)}
<Stack gap={0} w="100%">
<Group justify="space-between" gap="xs" className="mediaRequests-list-item-top-group">
<Group gap="xs">
<Text className="mediaRequests-list-item-media-year" size="xs">
{request.airDate?.getFullYear() ?? t("toBeDetermined")}
</Text>
{!isTiny && (
<Badge
className="mediaRequests-list-item-media-status"
color={mediaAvailabilityConfiguration[request.availability].color}
variant="light"
size="xs"
>
{t(`availability.${request.availability}`)}
</Badge>
)}
</Group>
<Group className="mediaRequests-list-item-request-user" gap={4} wrap="nowrap">
<Avatar
className="mediaRequests-list-item-request-user-avatar"
src={request.requestedBy?.avatar}
size="xs"
/>
<Anchor
className="mediaRequests-list-item-request-user-name"
href={request.requestedBy?.link}
c="var(--mantine-color-text)"
target={options.linksTargetNewTab ? "_blank" : "_self"}
fz="xs"
lineClamp={1}
style={{ wordBreak: "break-all" }}
>
{(request.requestedBy?.displayName ?? "") || "unknown"}
</Anchor>
</Group>
</Group>
<Group gap="xs" justify="space-between" className="mediaRequests-list-item-bottom-group">
<Anchor
className="mediaRequests-list-item-info-second-line mediaRequests-list-item-media-title"
href={request.href}
c="var(--mantine-color-text)"
target={options.linksTargetNewTab ? "_blank" : "_self"}
fz={isTiny ? "xs" : "sm"}
fw={"bold"}
title={request.name}
lineClamp={1}
>
{request.name || "unknown"}
</Anchor>
{request.status === "pending" ? (
<DecisionButtons requestId={request.id} integrationId={request.integrationId} />
) : (
<StatusBadge status={request.status} />
)}
</Group>
</Stack>
</Group>
</Group>
</Card>
);
};
interface DecisionButtonsProps {
requestId: number;
integrationId: string;
}
const DecisionButtons = ({ requestId, integrationId }: DecisionButtonsProps) => {
const { mutate: mutateRequestAnswer } = clientApi.widget.mediaRequests.answerRequest.useMutation();
const t = useScopedI18n("widget.mediaRequests-requestList");
const handleDecision = (answer: RouterInputs["widget"]["mediaRequests"]["answerRequest"]["answer"]) => {
mutateRequestAnswer({
integrationId,
requestId,
answer,
});
};
return (
<Group className="mediaRequests-list-item-pending-buttons" gap="sm">
<Tooltip label={t("pending.approve")}>
<ActionIcon
className="mediaRequests-list-item-pending-button-approve"
variant="light"
color="green"
size="xs"
radius="md"
onClick={() => {
handleDecision("approve");
}}
>
<IconThumbUp size={16} />
</ActionIcon>
</Tooltip>
<Tooltip label={t("pending.decline")}>
<ActionIcon
className="mediaRequests-list-item-pending-button-decline"
variant="light"
color="red"
size="xs"
radius="md"
onClick={() => {
handleDecision("decline");
}}
>
<IconThumbDown size={16} />
</ActionIcon>
</Tooltip>
</Group>
);
};
interface StatusBadgeProps {
status: MediaRequestStatus;
}
const StatusBadge = ({ status }: StatusBadgeProps) => {
const { color, label } = statusMapping[status];
const tStatus = useScopedI18n("widget.mediaRequests-requestList.status");
return (
<Badge size="xs" color={color} variant="light">
{label(tStatus)}
<Badge size="xs" color={mediaRequestStatusConfiguration[status].color} variant="light">
{tStatus(status)}
</Badge>
);
};
function getAvailabilityProperties(
mediaRequestAvailability: MediaAvailability,
t: ScopedTranslationFunction<"widget.mediaRequests-requestList">,
) {
switch (mediaRequestAvailability) {
case MediaAvailability.Available:
return { color: "green", label: t("availability.available") };
case MediaAvailability.PartiallyAvailable:
return { color: "yellow", label: t("availability.partiallyAvailable") };
case MediaAvailability.Processing:
return { color: "blue", label: t("availability.processing") };
case MediaAvailability.Pending:
return { color: "violet", label: t("availability.pending") };
case MediaAvailability.Blacklisted:
return { color: "gray", label: t("availability.blacklisted") };
case MediaAvailability.Deleted:
return { color: "red", label: t("availability.deleted") };
default:
return { color: "orange", label: t("availability.unknown") };
}
}
@@ -1,13 +1,14 @@
"use client";
import type { ReactNode } from "react";
import { useMemo } from "react";
import { Avatar, Flex, Group, Stack, Text, Title } from "@mantine/core";
import { Fragment, useMemo } from "react";
import { Avatar, Divider, Flex, Group, Stack, Text, Title } from "@mantine/core";
import { IconDeviceTv, IconHeadphones, IconMovie, IconVideo } from "@tabler/icons-react";
import type { MRT_ColumnDef } from "mantine-react-table";
import { MantineReactTable } from "mantine-react-table";
import { clientApi } from "@homarr/api/client";
import { objectEntries } from "@homarr/common";
import { getIconUrl, integrationDefs } from "@homarr/definitions";
import type { StreamSession } from "@homarr/integrations";
import { createModal, useModalAction } from "@homarr/modals";
@@ -123,7 +124,7 @@ export default function MediaServerWidget({
[currentStreams],
);
const { openModal } = useModalAction(itemInfoModal);
const { openModal } = useModalAction(ItemInfoModal);
const table = useTranslatedMantineReactTable({
columns,
data: flatSessions,
@@ -219,10 +220,16 @@ export default function MediaServerWidget({
);
}
const itemInfoModal = createModal<{ item: StreamSession }>(({ innerProps }) => {
const ItemInfoModal = createModal<{ item: StreamSession }>(({ innerProps }) => {
const t = useScopedI18n("widget.mediaServer.items");
const Icon = innerProps.item.currentlyPlaying ? mediaTypeIconMap[innerProps.item.currentlyPlaying.type] : null;
const metadata = useMemo(() => {
return innerProps.item.currentlyPlaying?.metadata
? constructMetadata(innerProps.item.currentlyPlaying.metadata)
: null;
}, [innerProps.item.currentlyPlaying?.metadata]);
return (
<Stack align="center">
<Flex direction="column" gap="xs" align="center">
@@ -255,6 +262,32 @@ const itemInfoModal = createModal<{ item: StreamSession }>(({ innerProps }) => {
/>
<NormalizedLine itemKey={t("name")} value={<Text>{innerProps.item.sessionName}</Text>} />
<NormalizedLine itemKey={t("id")} value={<Text>{innerProps.item.sessionId}</Text>} />
{metadata ? (
<Stack w="100%" gap={0}>
<Divider label={t("metadata.title")} labelPosition="center" mt="lg" mb="sm" />
<Group align="flex-start">
{objectEntries(metadata).map(([key, value], index) => (
<Fragment key={key}>
{index !== 0 && <Divider key={index} orientation="vertical" />}
<Stack gap={4}>
<Text fw="bold">{t(`metadata.${key}.title`)}</Text>
{Object.entries(value)
.filter(([_, value]) => Boolean(value))
.map(([innerKey, value]) => (
<Group justify="space-between" w="100%" key={innerKey} wrap="nowrap">
<Text>{t(`metadata.${key}.${innerKey}` as never)}</Text>
<Text>{value}</Text>
</Group>
))}
</Stack>
</Fragment>
))}
</Group>
</Stack>
) : null}
</Stack>
);
}).withOptions({
@@ -280,3 +313,23 @@ const mediaTypeIconMap = {
video: IconVideo,
audio: IconHeadphones,
} satisfies Record<Exclude<StreamSession["currentlyPlaying"], null>["type"], TablerIcon>;
const constructMetadata = (metadata: Exclude<Exclude<StreamSession["currentlyPlaying"], null>["metadata"], null>) => ({
video: {
resolution: metadata.video.resolution
? `${metadata.video.resolution.width}x${metadata.video.resolution.height}`
: null,
frameRate: metadata.video.frameRate,
},
audio: {
channelCount: metadata.audio.channelCount,
codec: metadata.audio.codec,
},
transcoding: {
container: metadata.transcoding.container,
resolution: metadata.transcoding.resolution
? `${metadata.transcoding.resolution.width}x${metadata.transcoding.resolution.height}`
: null,
target: `${metadata.transcoding.target.videoCodec} ${metadata.transcoding.target.audioCodec}`.trim(),
},
});
@@ -30,18 +30,23 @@ export default function MediaTranscodingWidget({
}: WidgetComponentProps<"mediaTranscoding">) {
const [queuePage, setQueuePage] = useState(1);
const queuePageSize = 10;
const [transcodingData] = clientApi.widget.mediaTranscoding.getDataAsync.useSuspenseQuery(
{
integrationId: integrationIds[0] ?? "",
pageSize: queuePageSize,
page: queuePage,
const input = {
integrationId: integrationIds[0] ?? "",
pageSize: queuePageSize,
page: queuePage,
};
const [transcodingData] = clientApi.widget.mediaTranscoding.getDataAsync.useSuspenseQuery(input, {
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
const utils = clientApi.useUtils();
clientApi.widget.mediaTranscoding.subscribeData.useSubscription(input, {
onData(data) {
utils.widget.mediaTranscoding.getDataAsync.setData(input, data);
},
{
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
},
);
});
const [view, setView] = useState<View>(options.defaultView);
const totalQueuePages = Math.ceil((transcodingData.data.queue.totalCount || 1) / queuePageSize);
@@ -1,7 +1,7 @@
"use client";
import { Box, Flex, Group, Text, Tooltip } from "@mantine/core";
import { IconUsersGroup } from "@tabler/icons-react";
import { IconCube, IconUsersGroup } from "@tabler/icons-react";
import { clientApi } from "@homarr/api/client";
import { formatNumber } from "@homarr/common";
@@ -44,13 +44,25 @@ export default function MinecraftServerStatusWidget({ options }: WidgetComponent
</Group>
{data.online && (
<>
{!options.isBedrockServer && (
<img
style={{ flex: 1, transform: "scale(0.8)", objectFit: "contain" }}
alt={`minecraft icon ${options.domain}`}
src={data.icon}
/>
)}
{!options.isBedrockServer &&
(data.icon ? (
<img
style={{ flex: 1, transform: "scale(0.8)", objectFit: "contain" }}
alt={`minecraft icon ${options.domain}`}
src={data.icon}
/>
) : (
<Box
style={{
flex: 1,
display: "flex",
alignItems: "center",
justifyContent: "center",
}}
>
<IconCube size="3rem" color="var(--mantine-color-gray-5)" />
</Box>
))}
<Group gap={5} c="gray.6" align="center">
<IconUsersGroup size="1rem" />
<Text size="md">
+2 -1
View File
@@ -72,6 +72,7 @@ import "./notebook.css";
import { useSession } from "@homarr/auth/client";
import { constructBoardPermissions } from "@homarr/auth/shared";
import { useRequiredBoard } from "@homarr/boards/context";
import { hotkeys } from "@homarr/definitions";
import { useConfirmModal } from "@homarr/modals";
const iconProps = {
@@ -266,7 +267,7 @@ export function Notebook({ options, setOptions, isEditMode, boardId, itemId }: W
p={0}
mt={0}
h="100%"
onKeyDown={isEditing ? getHotkeyHandler([["mod+s", handleEditToggle]]) : undefined}
onKeyDown={isEditing ? getHotkeyHandler([[hotkeys.saveNotebook, handleEditToggle]]) : undefined}
editor={editor}
styles={(theme) => ({
root: {
+10 -6
View File
@@ -19,14 +19,17 @@ interface TextInput extends CommonInput<string> {
validate?: z.ZodType<string>;
}
interface MultiSelectInput<TOptions extends SelectOption[]>
extends CommonInput<inferSelectOptionValue<TOptions[number]>[]> {
interface MultiSelectInput<TOptions extends SelectOption[]> extends CommonInput<
inferSelectOptionValue<TOptions[number]>[]
> {
options: TOptions;
searchable?: boolean;
}
export interface SortableItemListInput<TItem, TOptionValue extends UniqueIdentifier>
extends Omit<CommonInput<TOptionValue[]>, "withDescription"> {
export interface SortableItemListInput<TItem, TOptionValue extends UniqueIdentifier> extends Omit<
CommonInput<TOptionValue[]>,
"withDescription"
> {
AddButton: (props: { addItem: (item: TItem) => void; values: TOptionValue[] }) => React.ReactNode;
ItemComponent: (props: {
item: TItem;
@@ -39,8 +42,9 @@ export interface SortableItemListInput<TItem, TOptionValue extends UniqueIdentif
validate: z.ZodArray<z.ZodType>;
}
interface SelectInput<TOptions extends readonly SelectOption[]>
extends CommonInput<inferSelectOptionValue<TOptions[number]>> {
interface SelectInput<TOptions extends readonly SelectOption[]> extends CommonInput<
inferSelectOptionValue<TOptions[number]>
> {
options: TOptions;
searchable?: boolean;
}
+17 -38
View File
@@ -21,6 +21,7 @@ import ReactMarkdown from "react-markdown";
import { clientApi } from "@homarr/api/client";
import { useRequiredBoard } from "@homarr/boards/context";
import { isDateWithin, isNullOrWhitespace, splitToChunksWithNItems } from "@homarr/common";
import { getIconUrl } from "@homarr/definitions";
import { useScopedI18n } from "@homarr/translation/client";
import { MaskedOrNormalImage } from "@homarr/ui";
@@ -96,55 +97,33 @@ export default function ReleasesWidget({ options }: WidgetComponentProps<"releas
const repositories = useMemo(() => {
const formattedResults = options.repositories
.map((repository) => {
if (repository.providerIntegrationId === undefined) {
return {
...repository,
isNewRelease: false,
isStaleRelease: false,
latestReleaseAt: undefined,
error: {
code: "noProviderSeleceted",
},
};
}
if (!repository.providerIntegrationId) return { ...repository, error: { code: "noProviderSeleceted" } };
const response = results.flat().find(({ data }) => data.id === repository.id)?.data;
const repositoryResult = results.flat().find(({ id }) => id === repository.id);
if (!repositoryResult) return { ...repository, error: { code: "noProviderResponse" } };
if (!repositoryResult.success) return { ...repository, error: repositoryResult.error };
if (response === undefined)
return {
...repository,
isNewRelease: false,
isStaleRelease: false,
latestReleaseAt: undefined,
error: {
code: "noProviderResponse",
},
};
const { data: release, integration } = repositoryResult;
const isReleaseWithin = (relativeDate: string) =>
Boolean(relativeDate) && isDateWithin(release.latestReleaseAt, relativeDate);
return {
...repository,
...response,
isNewRelease:
relativeDateOptions.newReleaseWithin !== "" && response.latestReleaseAt
? isDateWithin(response.latestReleaseAt, relativeDateOptions.newReleaseWithin)
: false,
isStaleRelease:
relativeDateOptions.staleReleaseWithin !== "" && response.latestReleaseAt
? !isDateWithin(response.latestReleaseAt, relativeDateOptions.staleReleaseWithin)
: false,
viewed: releasesViewedList[repository.id] === response.latestRelease,
...release,
integration: { name: integration.name, iconUrl: getIconUrl(integration.kind) },
isNewRelease: isReleaseWithin(relativeDateOptions.newReleaseWithin),
isStaleRelease: !isReleaseWithin(relativeDateOptions.staleReleaseWithin),
viewed: releasesViewedList[repository.id] === release.latestRelease,
};
})
.filter(
(repository) =>
repository.error !== undefined ||
!options.showOnlyHighlighted ||
repository.isNewRelease ||
repository.isStaleRelease,
"error" in repository || !options.showOnlyHighlighted || repository.isNewRelease || repository.isStaleRelease,
)
.sort((repoA, repoB) => {
if (repoA.latestReleaseAt === undefined) return -1;
if (repoB.latestReleaseAt === undefined) return 1;
if ("error" in repoA) return -1;
if ("error" in repoB) return 1;
return repoA.latestReleaseAt > repoB.latestReleaseAt ? -1 : 1;
}) as ReleasesRepositoryResponse[];
+9 -11
View File
@@ -26,15 +26,13 @@ export default function StockPriceWidget({ options, width, height }: WidgetCompo
const theme = useMantineTheme();
const [{ data }] = clientApi.widget.stockPrice.getPriceHistory.useSuspenseQuery(options);
const stockValues = data.indicators.quote[0]?.close ?? [];
const stockValuesChange = round(calculateChange(stockValues[stockValues.length - 1] ?? 0, stockValues[0] ?? 0));
const stockValuesChange = round(calculateChange(data.priceHistory.at(-1) ?? 0, data.priceHistory[0] ?? 0));
const stockValuesChangePercentage = round(
calculateChangePercentage(stockValues[stockValues.length - 1] ?? 0, stockValues[0] ?? 0),
calculateChangePercentage(data.priceHistory.at(-1) ?? 0, data.priceHistory[0] ?? 0),
);
const stockValuesMin = Math.min(...stockValues);
const stockGraphValues = stockValues.map((value) => value - stockValuesMin + 50);
const stockValuesMin = Math.min(...data.priceHistory);
const stockGraphValues = data.priceHistory.map((value) => value - stockValuesMin + 50);
return (
<Flex h="100%" w="100%">
@@ -57,17 +55,17 @@ export default function StockPriceWidget({ options, width, height }: WidgetCompo
) : (
<IconTrendingDown size="1.5rem" color={theme.colors.red[7]} />
)}
{data.meta.symbol}
{data.symbol}
</Text>
{width > 280 && height > 280 && (
<Text size="md" lh="1">
{data.meta.shortName}
{data.shortName}
</Text>
)}
</Stack>
<Title pos="absolute" bottom={10} right={10} order={width > 280 ? 1 : 2} fw={700}>
{new Intl.NumberFormat().format(round(stockValues[stockValues.length - 1] ?? 0))}
{new Intl.NumberFormat().format(round(data.priceHistory.at(-1) ?? 0))}
</Title>
{width > 280 && (
@@ -90,11 +88,11 @@ export default function StockPriceWidget({ options, width, height }: WidgetCompo
) : (
<IconTrendingDown size="1.5rem" color={theme.colors.red[7]} />
)}
{data.meta.symbol}
{data.symbol}
</Text>
{width > 280 && height > 280 && (
<Text size="md" lh="1">
{data.meta.shortName}
{data.shortName}
</Text>
)}
</Stack>
@@ -1,17 +1,23 @@
import { Box, Group, Paper, Stack, Text } from "@mantine/core";
import { IconNetwork } from "@tabler/icons-react";
import { humanFileSize } from "@homarr/common";
import { useScopedI18n } from "@homarr/translation/client";
import type { LabelDisplayModeOption } from "..";
import { CommonChart } from "./common-chart";
export const CombinedNetworkTrafficChart = ({
usageOverTime,
hasShadow,
labelDisplayMode,
}: {
usageOverTime: {
up: number;
down: number;
}[];
hasShadow: boolean;
labelDisplayMode: LabelDisplayModeOption;
}) => {
const chartData = usageOverTime.map((usage, index) => ({ index, up: usage.up, down: usage.down }));
const t = useScopedI18n("widget.systemResources.card");
@@ -25,7 +31,10 @@ export const CombinedNetworkTrafficChart = ({
{ name: "down", color: "yellow.5" },
]}
title={t("network")}
icon={IconNetwork}
yAxisProps={{ domain: [0, "dataMax"] }}
chartType={hasShadow ? "area" : "line"}
labelDisplayMode={labelDisplayMode}
tooltipProps={{
content: ({ payload }) => {
if (!payload) {
@@ -1,28 +1,38 @@
/* eslint-disable @typescript-eslint/no-explicit-any */
import type { LineChartSeries } from "@mantine/charts";
import { LineChart } from "@mantine/charts";
import type { ReactNode } from "react";
import type { AreaChartSeries } from "@mantine/charts";
import { AreaChart, LineChart } from "@mantine/charts";
import { Card, Center, Group, Loader, Stack, Text, useMantineColorScheme, useMantineTheme } from "@mantine/core";
import { useElementSize, useHover, useMergedRef } from "@mantine/hooks";
import type { TooltipProps, YAxisProps } from "recharts";
import { useRequiredBoard } from "@homarr/boards/context";
import type { TablerIcon } from "@homarr/ui";
import type { LabelDisplayModeOption } from "..";
export const CommonChart = ({
data,
dataKey,
series,
title,
icon: Icon,
labelDisplayMode,
tooltipProps,
yAxisProps,
lastValue,
chartType = "line",
}: {
data: Record<string, any>[];
dataKey: string;
series: LineChartSeries[];
title: string;
series: AreaChartSeries[];
title: ReactNode;
icon: TablerIcon;
labelDisplayMode: LabelDisplayModeOption;
tooltipProps?: TooltipProps<number, any>;
yAxisProps?: Omit<YAxisProps, "ref">;
lastValue?: string;
chartType?: "line" | "area";
}) => {
const { ref: elementSizeRef, height } = useElementSize();
const theme = useMantineTheme();
@@ -35,6 +45,10 @@ export const CommonChart = ({
const backgroundColor =
scheme.colorScheme === "dark" ? `rgba(57, 57, 57, ${opacity})` : `rgba(246, 247, 248, ${opacity})`;
const ChartComponent = chartType === "line" ? LineChart : AreaChart;
const showIcon = labelDisplayMode === "icon" || labelDisplayMode === "textWithIcon";
const showText = labelDisplayMode === "text" || labelDisplayMode === "textWithIcon";
return (
<Card
ref={ref}
@@ -55,10 +69,14 @@ export const CommonChart = ({
gap={5}
wrap={"nowrap"}
style={{ zIndex: 2, pointerEvents: "none" }}
align="center"
>
<Text c={"dimmed"} size={height > 100 ? "md" : "xs"} fw={"bold"}>
{title}
</Text>
{showIcon && <Icon color={"var(--mantine-color-dimmed)"} size={height > 100 ? 20 : 14} stroke={1.5} />}
{showText && (
<Text c={"dimmed"} size={height > 100 ? "md" : "xs"} fw={"bold"}>
{title}
</Text>
)}
{lastValue && (
<Text c={"dimmed"} size={height > 100 ? "md" : "xs"} lineClamp={1}>
{lastValue}
@@ -73,7 +91,7 @@ export const CommonChart = ({
</Stack>
</Center>
) : (
<LineChart
<ChartComponent
data={data}
dataKey={dataKey}
h={"100%"}
@@ -90,6 +108,7 @@ export const CommonChart = ({
tooltipProps={tooltipProps}
withTooltip={height >= 64}
yAxisProps={yAxisProps}
fillOpacity={chartType === "area" ? 0.3 : undefined}
/>
)}
</Card>
@@ -1,10 +1,20 @@
import { Paper, Text } from "@mantine/core";
import { IconCpu } from "@tabler/icons-react";
import { useScopedI18n } from "@homarr/translation/client";
import type { LabelDisplayModeOption } from "..";
import { CommonChart } from "./common-chart";
export const SystemResourceCPUChart = ({ cpuUsageOverTime }: { cpuUsageOverTime: number[] }) => {
export const SystemResourceCPUChart = ({
cpuUsageOverTime,
hasShadow,
labelDisplayMode,
}: {
cpuUsageOverTime: number[];
hasShadow: boolean;
labelDisplayMode: LabelDisplayModeOption;
}) => {
const chartData = cpuUsageOverTime.map((usage, index) => ({ index, usage }));
const t = useScopedI18n("widget.systemResources.card");
@@ -14,11 +24,14 @@ export const SystemResourceCPUChart = ({ cpuUsageOverTime }: { cpuUsageOverTime:
dataKey={"index"}
series={[{ name: "usage", color: "blue.5" }]}
title={t("cpu")}
icon={IconCpu}
lastValue={
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
cpuUsageOverTime.length > 0 ? `${Math.round(cpuUsageOverTime[cpuUsageOverTime.length - 1]!)}%` : undefined
}
chartType={hasShadow ? "area" : "line"}
yAxisProps={{ domain: [0, 100] }}
labelDisplayMode={labelDisplayMode}
tooltipProps={{
content: ({ payload }) => {
if (!payload) {
@@ -1,16 +1,22 @@
import { Paper, Text } from "@mantine/core";
import { IconBrain } from "@tabler/icons-react";
import { humanFileSize } from "@homarr/common";
import { useScopedI18n } from "@homarr/translation/client";
import type { LabelDisplayModeOption } from "..";
import { CommonChart } from "./common-chart";
export const SystemResourceMemoryChart = ({
memoryUsageOverTime,
totalCapacityInBytes,
hasShadow,
labelDisplayMode,
}: {
memoryUsageOverTime: number[];
totalCapacityInBytes: number;
hasShadow: boolean;
labelDisplayMode: LabelDisplayModeOption;
}) => {
const chartData = memoryUsageOverTime.map((usage, index) => ({ index, usage }));
const t = useScopedI18n("widget.systemResources.card");
@@ -27,8 +33,11 @@ export const SystemResourceMemoryChart = ({
dataKey={"index"}
series={[{ name: "usage", color: "red.6" }]}
title={t("memory")}
icon={IconBrain}
labelDisplayMode={labelDisplayMode}
yAxisProps={{ domain: [0, totalCapacityInBytes] }}
lastValue={percentageUsed !== undefined ? `${Math.round(percentageUsed * 100)}%` : undefined}
chartType={hasShadow ? "area" : "line"}
tooltipProps={{
content: ({ payload }) => {
if (!payload) {
@@ -1,11 +1,23 @@
import { Paper, Text } from "@mantine/core";
import { IconArrowDown, IconArrowUp } from "@tabler/icons-react";
import { humanFileSize } from "@homarr/common";
import { useScopedI18n } from "@homarr/translation/client";
import type { LabelDisplayModeOption } from "..";
import { CommonChart } from "./common-chart";
export const NetworkTrafficChart = ({ usageOverTime, isUp }: { usageOverTime: number[]; isUp: boolean }) => {
export const NetworkTrafficChart = ({
usageOverTime,
isUp,
hasShadow,
labelDisplayMode,
}: {
usageOverTime: number[];
isUp: boolean;
hasShadow: boolean;
labelDisplayMode: LabelDisplayModeOption;
}) => {
const chartData = usageOverTime.map((usage, index) => ({ index, usage }));
const t = useScopedI18n("widget.systemResources.card");
@@ -18,8 +30,11 @@ export const NetworkTrafficChart = ({ usageOverTime, isUp }: { usageOverTime: nu
dataKey={"index"}
series={[{ name: "usage", color: "yellow.5" }]}
title={isUp ? t("up") : t("down")}
icon={isUp ? IconArrowUp : IconArrowDown}
yAxisProps={{ domain: [0, upperBound] }}
lastValue={`${humanFileSize(Math.round(max))}/s`}
chartType={hasShadow ? "area" : "line"}
labelDisplayMode={labelDisplayMode}
tooltipProps={{
content: ({ payload }) => {
if (!payload) {
@@ -57,7 +57,11 @@ export default function SystemResources({ integrationIds, options }: WidgetCompo
<Stack gap="xs" p="xs" ref={ref} h="100%">
{options.visibleCharts.includes("cpu") && (
<Box h={rowHeight}>
<SystemResourceCPUChart cpuUsageOverTime={items.map((item) => item.cpu)} />
<SystemResourceCPUChart
cpuUsageOverTime={items.map((item) => item.cpu)}
hasShadow={options.hasShadow}
labelDisplayMode={options.labelDisplayMode}
/>
</Box>
)}
{options.visibleCharts.includes("memory") && (
@@ -65,22 +69,38 @@ export default function SystemResources({ integrationIds, options }: WidgetCompo
<SystemResourceMemoryChart
memoryUsageOverTime={items.map((item) => item.memory)}
totalCapacityInBytes={memoryCapacityInBytes}
hasShadow={options.hasShadow}
labelDisplayMode={options.labelDisplayMode}
/>
</Box>
)}
{showNetwork &&
(width > 256 ? (
<Group h={rowHeight} gap="xs" grow>
{/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */}
<NetworkTrafficChart usageOverTime={items.map((item) => item.network!.down)} isUp={false} />
<NetworkTrafficChart
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
usageOverTime={items.map((item) => item.network!.down)}
isUp={false}
hasShadow={options.hasShadow}
labelDisplayMode={options.labelDisplayMode}
/>
{/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */}
<NetworkTrafficChart usageOverTime={items.map((item) => item.network!.up)} isUp />
<NetworkTrafficChart
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
usageOverTime={items.map((item) => item.network!.up)}
isUp
hasShadow={options.hasShadow}
labelDisplayMode={options.labelDisplayMode}
/>
</Group>
) : (
<Box h={rowHeight}>
{/* eslint-disable-next-line @typescript-eslint/no-non-null-assertion */}
<CombinedNetworkTrafficChart usageOverTime={items.map((item) => item.network!)} />
<CombinedNetworkTrafficChart
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
usageOverTime={items.map((item) => item.network!)}
hasShadow={options.hasShadow}
labelDisplayMode={options.labelDisplayMode}
/>
</Box>
))}
</Stack>
+23 -1
View File
@@ -1,13 +1,23 @@
import { IconGraphFilled } from "@tabler/icons-react";
import { IconAlignLeft, IconEyeOff, IconGraphFilled, IconListDetails, IconPhoto } from "@tabler/icons-react";
import { objectEntries } from "@homarr/common";
import { createWidgetDefinition } from "../definition";
import { optionsBuilder } from "../options";
const labelDisplayModeOptions = {
textWithIcon: IconListDetails,
text: IconAlignLeft,
icon: IconPhoto,
hidden: IconEyeOff,
} as const;
export const { definition, componentLoader } = createWidgetDefinition("systemResources", {
icon: IconGraphFilled,
supportedIntegrations: ["dashDot", "openmediavault", "truenas"],
createOptions() {
return optionsBuilder.from((factory) => ({
hasShadow: factory.switch({ defaultValue: true }),
visibleCharts: factory.multiSelect({
options: (["cpu", "memory", "network"] as const).map((key) => ({
value: key,
@@ -16,6 +26,18 @@ export const { definition, componentLoader } = createWidgetDefinition("systemRes
defaultValue: ["cpu", "memory", "network"],
withDescription: true,
}),
labelDisplayMode: factory.select({
options: objectEntries(labelDisplayModeOptions).map(([key, icon]) => ({
value: key,
label: (t) => t(`widget.systemResources.option.labelDisplayMode.option.${key}`),
icon,
})),
defaultValue: "textWithIcon",
}),
}));
},
}).withDynamicImport(() => import("./component"));
export type LabelDisplayModeOption = ReturnType<
(typeof definition)["createOptions"]
>["labelDisplayMode"]["options"][number]["value"];
+28 -12
View File
@@ -7,23 +7,27 @@ import dayjs from "dayjs";
import type { RouterOutputs } from "@homarr/api";
import { clientApi } from "@homarr/api/client";
import { metricToImperial } from "@homarr/common";
import { useScopedI18n } from "@homarr/translation/client";
import type { WidgetComponentProps } from "../definition";
import { WeatherDescription, WeatherIcon } from "./icon";
export default function WeatherWidget({ isEditMode, options }: WidgetComponentProps<"weather">) {
const [weather] = clientApi.widget.weather.atLocation.useSuspenseQuery(
{
latitude: options.location.latitude,
longitude: options.location.longitude,
},
{
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
},
);
const input = {
latitude: options.location.latitude,
longitude: options.location.longitude,
};
const [weather] = clientApi.widget.weather.atLocation.useSuspenseQuery(input, {
refetchOnMount: false,
refetchOnWindowFocus: false,
refetchOnReconnect: false,
});
const utils = clientApi.useUtils();
clientApi.widget.weather.subscribeAtLocation.useSubscription(input, {
onData: (data) => utils.widget.weather.atLocation.setData(input, data),
});
return (
<Stack
@@ -49,6 +53,7 @@ interface WeatherProps extends Pick<WidgetComponentProps<"weather">, "options">
const DailyWeather = ({ options, weather }: WeatherProps) => {
const t = useScopedI18n("widget.weather");
const tCommon = useScopedI18n("common");
return (
<>
@@ -75,7 +80,17 @@ const DailyWeather = ({ options, weather }: WeatherProps) => {
{options.showCurrentWindSpeed && (
<Group className="weather-current-wind-speed-group" wrap="nowrap" gap="xs">
<IconWind size={16} />
<Text fz={16}>{t("currentWindSpeed", { currentWindSpeed: String(weather.current.windspeed) })}</Text>
<Text fz={16}>
{t("currentWindSpeed", {
currentWindSpeed: (options.useImperialSpeed
? metricToImperial(weather.current.windspeed)
: weather.current.windspeed
).toFixed(1),
unit: options.useImperialSpeed
? tCommon("unit.speed.milesPerHour")
: tCommon("unit.speed.kilometersPerHour"),
})}
</Text>
</Group>
)}
<Group className="weather-max-min-temp-group" wrap="nowrap" gap="sm">
@@ -177,6 +192,7 @@ function Forecast({ weather, options }: WeatherProps) {
</HoverCard.Target>
<HoverCard.Dropdown>
<WeatherDescription
useImperialSpeed={options.useImperialSpeed}
dateFormat={dateFormat}
time={dayWeather.time}
weatherCode={dayWeather.weatherCode}
+11 -2
View File
@@ -15,6 +15,7 @@ import {
} from "@tabler/icons-react";
import dayjs from "dayjs";
import { metricToImperial } from "@homarr/common";
import type { TranslationObject } from "@homarr/translation";
import { useScopedI18n } from "@homarr/translation/client";
import type { TablerIcon } from "@homarr/ui";
@@ -40,6 +41,7 @@ export const WeatherIcon = ({ code, size = 50 }: WeatherIconProps) => {
interface WeatherDescriptionProps {
weatherOnly?: boolean;
useImperialSpeed?: boolean;
dateFormat?: WidgetProps<"weather">["options"]["dateFormat"];
time?: string;
weatherCode: number;
@@ -66,6 +68,7 @@ interface WeatherDescriptionProps {
*/
export const WeatherDescription = ({
weatherOnly,
useImperialSpeed,
dateFormat,
time,
weatherCode,
@@ -96,12 +99,18 @@ export const WeatherDescription = ({
<List.Item icon={<IconMoon size={15} />}>{`${t("dailyForecast.sunset")}: ${sunset}`}</List.Item>
{maxWindSpeed !== undefined && (
<List.Item icon={<IconWind size={15} />}>
{t("dailyForecast.maxWindSpeed", { maxWindSpeed: String(maxWindSpeed) })}
{t("dailyForecast.maxWindSpeed", {
maxWindSpeed: (useImperialSpeed ? metricToImperial(maxWindSpeed) : maxWindSpeed).toFixed(1),
unit: useImperialSpeed ? tCommon("unit.speed.milesPerHour") : tCommon("unit.speed.kilometersPerHour"),
})}
</List.Item>
)}
{maxWindGusts !== undefined && (
<List.Item icon={<IconWind size={15} />}>
{t("dailyForecast.maxWindGusts", { maxWindGusts: String(maxWindGusts) })}
{t("dailyForecast.maxWindGusts", {
maxWindGusts: (useImperialSpeed ? metricToImperial(maxWindGusts) : maxWindGusts).toFixed(1),
unit: useImperialSpeed ? tCommon("unit.speed.milesPerHour") : tCommon("unit.speed.kilometersPerHour"),
})}
</List.Item>
)}
</List>
+1
View File
@@ -13,6 +13,7 @@ export const { definition, componentLoader } = createWidgetDefinition("weather",
isFormatFahrenheit: factory.switch(),
disableTemperatureDecimals: factory.switch(),
showCurrentWindSpeed: factory.switch({ withDescription: true }),
useImperialSpeed: factory.switch(),
location: factory.location({
defaultValue: {
name: "Paris",
@@ -1,7 +1,6 @@
"use client";
import type { FocusEventHandler } from "react";
import Link from "next/link";
import {
Anchor,
Avatar,
@@ -20,6 +19,7 @@ import {
import type { IntegrationKind } from "@homarr/definitions";
import { getIconUrl } from "@homarr/definitions";
import { useI18n } from "@homarr/translation/client";
import { Link } from "@homarr/ui";
import classes from "./widget-integration-select.module.css";