Merge branch 'dev' into feat/docker-logs
Resolve docker.ts conflict by keeping dev improvements (host field, bestMatch icons, Promise.allSettled with logging, Podman-safe stats) alongside container log streaming and decode utilities.
This commit is contained in:
406 files changed
+54691
-14600
No files matched your search
@@ -1,5 +1,7 @@
|
||||
import type { WidgetOptionType } from "../options";
|
||||
import { WidgetAnchorNoteInput } from "./widget-anchor-note-input";
|
||||
import { WidgetAppInput } from "./widget-app-input";
|
||||
import { WidgetDynamicSelectInput } from "./widget-dynamic-select-input";
|
||||
import { WidgetLocationInput } from "./widget-location-input";
|
||||
import { WidgetMultiTextInput } from "./widget-multi-text-input";
|
||||
import { WidgetMultiReleasesRepositoriesInput } from "./widget-multiReleasesRepositories-input";
|
||||
@@ -10,8 +12,12 @@ import { WidgetSliderInput } from "./widget-slider-input";
|
||||
import { WidgetSortedItemListInput } from "./widget-sortable-item-list-input";
|
||||
import { WidgetSwitchInput } from "./widget-switch-input";
|
||||
import { WidgetTextInput } from "./widget-text-input";
|
||||
import { WidgetUmamiEventInput } from "./widget-umami-event-input";
|
||||
import { WidgetUmamiEventNamesInput } from "./widget-umami-event-names-input";
|
||||
import { WidgetUmamiWebsiteInput } from "./widget-umami-website-input";
|
||||
|
||||
const mapping = {
|
||||
anchorNote: WidgetAnchorNoteInput,
|
||||
text: WidgetTextInput,
|
||||
location: WidgetLocationInput,
|
||||
multiSelect: WidgetMultiSelectInput,
|
||||
@@ -23,6 +29,10 @@ const mapping = {
|
||||
app: WidgetAppInput,
|
||||
sortableItemList: WidgetSortedItemListInput,
|
||||
multiReleasesRepositories: WidgetMultiReleasesRepositoriesInput,
|
||||
dynamicSelect: WidgetDynamicSelectInput,
|
||||
umamiEventName: WidgetUmamiEventInput,
|
||||
umamiEventNames: WidgetUmamiEventNamesInput,
|
||||
umamiWebsite: WidgetUmamiWebsiteInput,
|
||||
} satisfies Record<WidgetOptionType, unknown>;
|
||||
|
||||
export const getInputForType = <TType extends WidgetOptionType>(type: TType) => {
|
||||
|
||||
@@ -0,0 +1,63 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo, useState } from "react";
|
||||
import { Loader, Select } from "@mantine/core";
|
||||
import { useDebouncedValue } from "@mantine/hooks";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n, useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
export const WidgetAnchorNoteInput = ({ property, kind, options }: CommonWidgetInputProps<"anchorNote">) => {
|
||||
const t = useI18n();
|
||||
const tWidget = useWidgetInputTranslation(kind, property);
|
||||
const tAnchor = useScopedI18n("widget.anchorNote");
|
||||
const form = useFormContext();
|
||||
|
||||
const integrationId = form.values.integrationIds[0];
|
||||
const [search, setSearch] = useState("");
|
||||
const [debouncedSearch] = useDebouncedValue(search, 250);
|
||||
|
||||
const { data: notes, isPending } = clientApi.widget.anchorNotes.listNotes.useQuery(
|
||||
{
|
||||
integrationId: integrationId ?? "",
|
||||
search: debouncedSearch.trim() ? debouncedSearch : undefined,
|
||||
limit: 200,
|
||||
},
|
||||
{
|
||||
enabled: Boolean(integrationId),
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
retry: false,
|
||||
},
|
||||
);
|
||||
|
||||
const noteOptions = useMemo(
|
||||
() =>
|
||||
notes?.map((note) => ({
|
||||
value: note.id,
|
||||
label: note.title || tAnchor("untitled"),
|
||||
})) ?? [],
|
||||
[notes, tAnchor],
|
||||
);
|
||||
|
||||
return (
|
||||
<Select
|
||||
label={tWidget("label")}
|
||||
description={options.withDescription ? tWidget("description") : undefined}
|
||||
placeholder={integrationId ? t("common.select.placeholder") : tAnchor("integrationRequired")}
|
||||
nothingFoundMessage={integrationId ? tAnchor("noNotes") : tAnchor("integrationRequired")}
|
||||
searchable
|
||||
searchValue={search}
|
||||
onSearchChange={setSearch}
|
||||
data={noteOptions}
|
||||
leftSection={isPending && integrationId ? <Loader size={16} /> : undefined}
|
||||
disabled={!integrationId}
|
||||
{...form.getInputProps(`options.${property}`)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -69,9 +69,9 @@ export const WidgetAppInput = ({ property, kind }: CommonWidgetInputProps<"app">
|
||||
variant="default"
|
||||
onClick={() =>
|
||||
openModal({
|
||||
onClose(createdAppId) {
|
||||
onClose({ id }) {
|
||||
void refetch().then(() => {
|
||||
form.setFieldValue(`options.${property}`, createdAppId);
|
||||
form.setFieldValue(`options.${property}`, id);
|
||||
});
|
||||
},
|
||||
})
|
||||
|
||||
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import { useState } from "react";
|
||||
import { Group, Loader, Select } from "@mantine/core";
|
||||
import { useDebouncedValue } from "@mantine/hooks";
|
||||
import { IconCheck } from "@tabler/icons-react";
|
||||
|
||||
import { translateIfNecessary } from "@homarr/translation";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
export interface DynamicSelectOption {
|
||||
value: string;
|
||||
label: string;
|
||||
}
|
||||
|
||||
export const WidgetDynamicSelectInput = ({ property, kind, options }: CommonWidgetInputProps<"dynamicSelect">) => {
|
||||
const t = useI18n();
|
||||
const tWidget = useWidgetInputTranslation(kind, property);
|
||||
const form = useFormContext();
|
||||
const inputProps = form.getInputProps(`options.${property}`);
|
||||
const [search, setSearch] = useState("");
|
||||
const [debouncedSearch] = useDebouncedValue(search, 300);
|
||||
const { isPending, options: selectOptions } = options.useOptions(debouncedSearch, form.values.integrationIds);
|
||||
const value = inputProps.value as DynamicSelectOption | null;
|
||||
const onChange = inputProps.onChange as (value: DynamicSelectOption | null) => void;
|
||||
|
||||
return (
|
||||
<Select
|
||||
label={tWidget("label")}
|
||||
data={selectOptions
|
||||
.map((option) =>
|
||||
typeof option === "string"
|
||||
? option
|
||||
: {
|
||||
value: option.value,
|
||||
label: translateIfNecessary(t, option.label) ?? option.value,
|
||||
},
|
||||
)
|
||||
.concat(
|
||||
typeof value === "object" &&
|
||||
value !== null &&
|
||||
!selectOptions.some((option) =>
|
||||
typeof option === "string" ? option === value.value : option.value === value.value,
|
||||
)
|
||||
? {
|
||||
value: value.value,
|
||||
label: value.label,
|
||||
}
|
||||
: [],
|
||||
)}
|
||||
searchValue={search}
|
||||
onSearchChange={setSearch}
|
||||
leftSection={isPending && <Loader size="xs" />}
|
||||
renderOption={({ option, checked }) => {
|
||||
return (
|
||||
<Group flex="1" gap="xs">
|
||||
{option.label}
|
||||
{checked && (
|
||||
<IconCheck
|
||||
style={{ marginInlineStart: "auto" }}
|
||||
color="currentColor"
|
||||
opacity={0.6}
|
||||
size={18}
|
||||
stroke={1.5}
|
||||
/>
|
||||
)}
|
||||
</Group>
|
||||
);
|
||||
}}
|
||||
description={options.withDescription ? tWidget("description") : undefined}
|
||||
searchable
|
||||
{...inputProps}
|
||||
value={value?.value ?? null}
|
||||
onChange={(value) =>
|
||||
onChange(
|
||||
value
|
||||
? {
|
||||
value,
|
||||
label:
|
||||
selectOptions.filter((option) => typeof option === "object").find((option) => option.value === value)
|
||||
?.label ?? value,
|
||||
}
|
||||
: null,
|
||||
)
|
||||
}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { Select, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
export const WidgetUmamiEventInput = ({ property, kind }: CommonWidgetInputProps<"umamiEventName">) => {
|
||||
const t = useScopedI18n("widget.umami.option.eventName");
|
||||
const tInput = useWidgetInputTranslation(kind, property);
|
||||
const form = useFormContext();
|
||||
|
||||
const integrationIds = form.values.integrationIds;
|
||||
const websiteId = form.values.options.websiteId as string | undefined;
|
||||
|
||||
const { data: eventNames, isPending } = clientApi.widget.umami.getEventNames.useQuery(
|
||||
{ integrationId: integrationIds[0] ?? "", websiteId: websiteId ?? "" },
|
||||
{ enabled: Boolean(integrationIds[0]) && Boolean(websiteId) },
|
||||
);
|
||||
|
||||
if (!websiteId || integrationIds.length === 0) {
|
||||
return (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("configureWebsiteFirst")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
const data = [{ value: "", label: t("none") }, ...(eventNames ?? [])];
|
||||
|
||||
return (
|
||||
<Select
|
||||
label={tInput("label")}
|
||||
description={tInput("description")}
|
||||
placeholder={isPending ? t("loading") : undefined}
|
||||
searchable
|
||||
nothingFoundMessage={t("noEvents")}
|
||||
data={data}
|
||||
{...form.getInputProps(`options.${property}`)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { MultiSelect, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
export const WidgetUmamiEventNamesInput = ({ property, kind }: CommonWidgetInputProps<"umamiEventNames">) => {
|
||||
const t = useScopedI18n("widget.umami.option.eventNames");
|
||||
const tInput = useWidgetInputTranslation(kind, property);
|
||||
const form = useFormContext();
|
||||
|
||||
const integrationIds = form.values.integrationIds;
|
||||
const websiteId = form.values.options.websiteId as string | undefined;
|
||||
|
||||
const { data: eventNames, isPending } = clientApi.widget.umami.getEventNames.useQuery(
|
||||
{ integrationId: integrationIds[0] ?? "", websiteId: websiteId ?? "" },
|
||||
{ enabled: Boolean(integrationIds[0]) && Boolean(websiteId) },
|
||||
);
|
||||
|
||||
if (!websiteId || integrationIds.length === 0) {
|
||||
return (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("configureWebsiteFirst")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<MultiSelect
|
||||
label={tInput("label")}
|
||||
description={tInput("description")}
|
||||
placeholder={isPending ? t("loading") : t("placeholder")}
|
||||
searchable
|
||||
nothingFoundMessage={t("noEvents")}
|
||||
data={eventNames ?? []}
|
||||
{...form.getInputProps(`options.${property}`)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,44 @@
|
||||
"use client";
|
||||
|
||||
import { Select, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { CommonWidgetInputProps } from "./common";
|
||||
import { useWidgetInputTranslation } from "./common";
|
||||
import { useFormContext } from "./form";
|
||||
|
||||
export const WidgetUmamiWebsiteInput = ({ property, kind }: CommonWidgetInputProps<"umamiWebsite">) => {
|
||||
const t = useScopedI18n("widget.umami.option.websiteId");
|
||||
const tInput = useWidgetInputTranslation(kind, property);
|
||||
const form = useFormContext();
|
||||
|
||||
const integrationIds = form.values.integrationIds;
|
||||
|
||||
const { data: websites, isPending } = clientApi.widget.umami.getWebsites.useQuery(
|
||||
{ integrationId: integrationIds[0] ?? "" },
|
||||
{ enabled: Boolean(integrationIds[0]) },
|
||||
);
|
||||
|
||||
if (integrationIds.length === 0) {
|
||||
return (
|
||||
<Text size="sm" c="dimmed">
|
||||
{t("configureIntegrationFirst")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Select
|
||||
label={tInput("label")}
|
||||
description={tInput("description")}
|
||||
placeholder={isPending ? t("loading") : t("placeholder")}
|
||||
clearable
|
||||
searchable
|
||||
nothingFoundMessage={t("noWebsites")}
|
||||
data={(websites ?? []).map((site) => ({ value: site.id, label: site.domain }))}
|
||||
{...form.getInputProps(`options.${property}`)}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,115 @@
|
||||
.homarr-anchor-quill {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
height: 100%;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-toolbar.ql-snow,
|
||||
.homarr-anchor-quill .ql-container.ql-snow {
|
||||
border: 0;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-toolbar.ql-snow {
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-container.ql-snow {
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
flex: 1;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor {
|
||||
min-height: 160px;
|
||||
flex: 1;
|
||||
padding: 0;
|
||||
color: var(--mantine-color-text);
|
||||
font-size: var(--mantine-font-size-sm, 0.95rem);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor.ql-blank::before {
|
||||
color: var(--mantine-color-dimmed);
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor ol,
|
||||
.homarr-anchor-quill .ql-editor ul {
|
||||
padding-left: 1.5rem;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor li {
|
||||
margin: 0.25rem 0;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor li[data-list="unchecked"],
|
||||
.homarr-anchor-quill .ql-editor li[data-list="checked"] {
|
||||
padding-left: 28px !important;
|
||||
list-style: none;
|
||||
position: relative;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor li[data-list="checked"] > .ql-ui,
|
||||
.homarr-anchor-quill .ql-editor li[data-list="unchecked"] > .ql-ui {
|
||||
position: absolute;
|
||||
left: 0;
|
||||
top: 0.35em;
|
||||
width: 18px !important;
|
||||
height: 18px !important;
|
||||
border-radius: 5px;
|
||||
box-sizing: border-box;
|
||||
transition: all 150ms ease;
|
||||
background: transparent;
|
||||
padding: 0 !important;
|
||||
margin: 0 !important;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor li[data-list="checked"] > .ql-ui::before,
|
||||
.homarr-anchor-quill .ql-editor li[data-list="unchecked"] > .ql-ui::before {
|
||||
content: "" !important;
|
||||
display: none !important;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor li[data-list="unchecked"] > .ql-ui {
|
||||
border: 2px solid var(--mantine-color-dimmed);
|
||||
opacity: 0.7;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor li[data-list="unchecked"]:hover > .ql-ui {
|
||||
border-color: var(--mantine-primary-color-filled);
|
||||
opacity: 1;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor li[data-list="checked"] > .ql-ui {
|
||||
border: 2px solid var(--mantine-primary-color-filled);
|
||||
background: var(--mantine-primary-color-filled);
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor li[data-list="checked"] > .ql-ui::after {
|
||||
content: "";
|
||||
display: block;
|
||||
position: absolute;
|
||||
left: 50%;
|
||||
top: 45%;
|
||||
width: 5px;
|
||||
height: 9px;
|
||||
border: solid var(--mantine-color-white, #fff);
|
||||
border-width: 0 2px 2px 0;
|
||||
transform: translate(-50%, -50%) rotate(45deg);
|
||||
}
|
||||
|
||||
.homarr-anchor-quill .ql-editor li[data-list="checked"] {
|
||||
color: var(--mantine-color-dimmed);
|
||||
text-decoration: line-through;
|
||||
text-decoration-color: var(--mantine-color-dimmed);
|
||||
}
|
||||
|
||||
.homarr-anchor-quill--readonly .ql-toolbar.ql-snow {
|
||||
display: none;
|
||||
}
|
||||
|
||||
.homarr-anchor-quill--readonly .ql-container.ql-snow {
|
||||
border-radius: 0;
|
||||
}
|
||||
@@ -0,0 +1,320 @@
|
||||
"use client";
|
||||
|
||||
import { startTransition, useCallback, useEffect, useMemo, useState } from "react";
|
||||
import type { ComponentProps } from "react";
|
||||
import dynamic from "next/dynamic";
|
||||
import { Button, Center, Group, Stack, Text, TextInput } from "@mantine/core";
|
||||
import { Quill } from "react-quill-new";
|
||||
import type { DeltaStatic } from "react-quill-new";
|
||||
import type ReactQuillComponent from "react-quill-new";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useTimeAgo } from "@homarr/common";
|
||||
import type { AnchorNotePermission } from "@homarr/integrations";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
|
||||
import "react-quill-new/dist/quill.snow.css";
|
||||
import "./anchor-note.css";
|
||||
|
||||
type ReactQuillProps = ComponentProps<typeof ReactQuillComponent>;
|
||||
type ReactQuillOnChange = NonNullable<ReactQuillProps["onChange"]>;
|
||||
|
||||
const ReactQuill = dynamic(() => import("react-quill-new"), { ssr: false });
|
||||
|
||||
const quillDeltaOperationSchema = z.object({
|
||||
insert: z.unknown().optional(),
|
||||
attributes: z.record(z.string(), z.unknown()).optional(),
|
||||
});
|
||||
|
||||
const quillDeltaSchema = z.object({
|
||||
ops: z.array(quillDeltaOperationSchema),
|
||||
});
|
||||
|
||||
type QuillDelta = z.infer<typeof quillDeltaSchema>;
|
||||
|
||||
const DeltaConstructor = Quill.import("delta") as new (
|
||||
ops?: QuillDelta["ops"] | { ops: QuillDelta["ops"] },
|
||||
) => DeltaStatic;
|
||||
|
||||
const quillModules = {
|
||||
toolbar: [
|
||||
["bold", "italic", "underline", "strike"],
|
||||
[{ header: [1, 2, 3, 4, false] }],
|
||||
[{ align: [] }],
|
||||
[{ list: "ordered" }, { list: "bullet" }, { list: "check" }],
|
||||
[{ indent: "-1" }, { indent: "+1" }],
|
||||
["blockquote", "code-block"],
|
||||
["link"],
|
||||
["clean"],
|
||||
],
|
||||
history: {
|
||||
delay: 1000,
|
||||
maxStack: 200,
|
||||
userOnly: true,
|
||||
},
|
||||
};
|
||||
|
||||
const readOnlyModules = {
|
||||
toolbar: false,
|
||||
};
|
||||
|
||||
const quillFormats = [
|
||||
"bold",
|
||||
"italic",
|
||||
"underline",
|
||||
"strike",
|
||||
"header",
|
||||
"align",
|
||||
"list",
|
||||
"indent",
|
||||
"blockquote",
|
||||
"code-block",
|
||||
"link",
|
||||
];
|
||||
|
||||
const emptyDelta = (): DeltaStatic => new DeltaConstructor([{ insert: "\n" }]);
|
||||
|
||||
const toPlainTextDelta = (value: string): DeltaStatic => {
|
||||
const normalized = value.endsWith("\n") ? value : `${value}\n`;
|
||||
return new DeltaConstructor([{ insert: normalized }]);
|
||||
};
|
||||
|
||||
const parseStoredContent = (content?: string | null): DeltaStatic => {
|
||||
if (!content) return emptyDelta();
|
||||
|
||||
try {
|
||||
const parsedDelta = quillDeltaSchema.safeParse(JSON.parse(content));
|
||||
if (parsedDelta.success) {
|
||||
return new DeltaConstructor(parsedDelta.data.ops);
|
||||
}
|
||||
} catch {
|
||||
return toPlainTextDelta(content);
|
||||
}
|
||||
|
||||
return toPlainTextDelta(content);
|
||||
};
|
||||
|
||||
const stringifyDelta = (delta: unknown): string => {
|
||||
const parsedDelta = quillDeltaSchema.safeParse(delta);
|
||||
if (parsedDelta.success) {
|
||||
return JSON.stringify(parsedDelta.data);
|
||||
}
|
||||
return JSON.stringify(emptyDelta());
|
||||
};
|
||||
|
||||
const canEditPermission = (permission: AnchorNotePermission) => {
|
||||
return permission === "owner" || permission === "editor";
|
||||
};
|
||||
|
||||
const isForbiddenError = (error: unknown): boolean => {
|
||||
if (typeof error !== "object" || error === null) return false;
|
||||
|
||||
const data = (error as { data?: unknown }).data;
|
||||
if (typeof data !== "object" || data === null) return false;
|
||||
|
||||
return (data as { code?: unknown }).code === "FORBIDDEN";
|
||||
};
|
||||
|
||||
export default function AnchorNoteWidget({ options, integrationIds }: WidgetComponentProps<"anchorNote">) {
|
||||
const t = useScopedI18n("widget.anchorNote");
|
||||
const noteId = options.noteId.trim();
|
||||
if (!noteId) {
|
||||
return (
|
||||
<Center h="100%">
|
||||
<Text c="dimmed">{t("empty")}</Text>
|
||||
</Center>
|
||||
);
|
||||
}
|
||||
|
||||
// It will always have at least one integration as otherwise the NoIntegrationSelectedError would be thrown in item-content.tsx
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const integrationId = integrationIds[0]!;
|
||||
|
||||
return <AnchorNoteWidgetContent options={options} integrationId={integrationId} noteId={noteId} />;
|
||||
}
|
||||
|
||||
interface AnchorNoteWidgetContentProps {
|
||||
options: WidgetComponentProps<"anchorNote">["options"];
|
||||
integrationId: string;
|
||||
noteId: string;
|
||||
}
|
||||
|
||||
const AnchorNoteWidgetContent = ({ options, integrationId, noteId }: AnchorNoteWidgetContentProps) => {
|
||||
const t = useScopedI18n("widget.anchorNote");
|
||||
const [note, { refetch }] = clientApi.widget.anchorNotes.getNote.useSuspenseQuery(
|
||||
{
|
||||
integrationId,
|
||||
noteId,
|
||||
},
|
||||
{
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
retry: false,
|
||||
},
|
||||
);
|
||||
const { mutateAsync: updateNoteAsync, isPending: isUpdating } = clientApi.widget.anchorNotes.updateNote.useMutation();
|
||||
|
||||
const [isEditing, setIsEditing] = useState(false);
|
||||
const [draftTitle, setDraftTitle] = useState(note.title);
|
||||
const [draftContent, setDraftContent] = useState(note.content ?? "");
|
||||
const [saveError, setSaveError] = useState<string | null>(null);
|
||||
|
||||
useEffect(() => {
|
||||
if (isEditing) return;
|
||||
|
||||
startTransition(() => {
|
||||
setDraftTitle(note.title);
|
||||
setDraftContent(note.content ?? "");
|
||||
});
|
||||
}, [isEditing, note.content, note.title]);
|
||||
|
||||
const canEdit = canEditPermission(note.permission);
|
||||
const isViewer = note.permission === "viewer";
|
||||
const updatedAt = useMemo(() => new Date(note.updatedAt), [note.updatedAt]);
|
||||
const updatedAtRelative = useTimeAgo(updatedAt, 30000);
|
||||
|
||||
const hasChanges = useMemo(() => {
|
||||
const normalizedTitle = draftTitle.trim() || note.title;
|
||||
return normalizedTitle !== note.title || draftContent !== (note.content ?? "");
|
||||
}, [draftContent, draftTitle, note.content, note.title]);
|
||||
|
||||
const editorValue = useMemo(() => parseStoredContent(draftContent), [draftContent]);
|
||||
const readOnlyValue = useMemo(() => parseStoredContent(note.content), [note.content]);
|
||||
const handleEditorChange = useCallback<ReactQuillOnChange>(
|
||||
(_html, _delta, source, editor) => {
|
||||
if (!isEditing || source !== "user") return;
|
||||
const next = stringifyDelta(editor.getContents());
|
||||
setDraftContent(next);
|
||||
},
|
||||
[isEditing],
|
||||
);
|
||||
|
||||
const handleEdit = useCallback(() => {
|
||||
if (!canEdit) return;
|
||||
startTransition(() => {
|
||||
setDraftTitle(note.title);
|
||||
setDraftContent(note.content ?? "");
|
||||
setSaveError(null);
|
||||
setIsEditing(true);
|
||||
});
|
||||
}, [canEdit, note.content, note.title]);
|
||||
|
||||
const handleCancel = useCallback(() => {
|
||||
startTransition(() => {
|
||||
setDraftTitle(note.title);
|
||||
setDraftContent(note.content ?? "");
|
||||
setSaveError(null);
|
||||
setIsEditing(false);
|
||||
});
|
||||
}, [note.content, note.title]);
|
||||
|
||||
const handleSave = useCallback(async () => {
|
||||
if (!canEdit) return;
|
||||
|
||||
const normalizedTitle = draftTitle.trim() || note.title || t("untitled");
|
||||
|
||||
if (!hasChanges) {
|
||||
startTransition(() => {
|
||||
setSaveError(null);
|
||||
setIsEditing(false);
|
||||
});
|
||||
return;
|
||||
}
|
||||
|
||||
await updateNoteAsync(
|
||||
{
|
||||
integrationId,
|
||||
noteId,
|
||||
title: normalizedTitle,
|
||||
content: draftContent,
|
||||
},
|
||||
{
|
||||
onSuccess() {
|
||||
void (async () => {
|
||||
await refetch();
|
||||
startTransition(() => {
|
||||
setSaveError(null);
|
||||
setIsEditing(false);
|
||||
});
|
||||
})();
|
||||
},
|
||||
onError(error) {
|
||||
if (isForbiddenError(error)) {
|
||||
void (async () => {
|
||||
await refetch();
|
||||
startTransition(() => {
|
||||
setSaveError(t("saveForbidden"));
|
||||
setIsEditing(false);
|
||||
});
|
||||
})();
|
||||
return;
|
||||
}
|
||||
|
||||
startTransition(() => {
|
||||
setSaveError(t("saveFailed"));
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
}, [canEdit, draftContent, draftTitle, hasChanges, integrationId, note.title, noteId, refetch, t, updateNoteAsync]);
|
||||
|
||||
return (
|
||||
<Stack h="100%" gap="xs" p="sm">
|
||||
<Group justify="space-between" align="flex-start">
|
||||
<Stack gap={2} style={{ flex: 1 }}>
|
||||
{isEditing ? (
|
||||
<TextInput value={draftTitle} onChange={(event) => setDraftTitle(event.currentTarget.value)} size="sm" />
|
||||
) : (
|
||||
options.showTitle && <Text fw={600}>{note.title || t("untitled")}</Text>
|
||||
)}
|
||||
{!isEditing && options.showUpdatedAt && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("updatedAt", { date: updatedAtRelative })}
|
||||
</Text>
|
||||
)}
|
||||
{!isEditing && isViewer && (
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("readOnlyViewer")}
|
||||
</Text>
|
||||
)}
|
||||
{saveError && (
|
||||
<Text size="xs" c="red">
|
||||
{saveError}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
<Group gap="xs">
|
||||
{isEditing ? (
|
||||
<>
|
||||
<Button size="xs" onClick={handleSave} loading={isUpdating} disabled={!hasChanges || !canEdit}>
|
||||
{t("save")}
|
||||
</Button>
|
||||
<Button size="xs" variant="subtle" onClick={handleCancel} disabled={isUpdating}>
|
||||
{t("cancel")}
|
||||
</Button>
|
||||
</>
|
||||
) : (
|
||||
<Button size="xs" variant="light" onClick={handleEdit} disabled={!canEdit || isUpdating}>
|
||||
{t("edit")}
|
||||
</Button>
|
||||
)}
|
||||
</Group>
|
||||
</Group>
|
||||
<div className={`homarr-anchor-quill${isEditing ? "" : " homarr-anchor-quill--readonly"}`} style={{ flex: 1 }}>
|
||||
<ReactQuill
|
||||
theme="snow"
|
||||
readOnly={!isEditing}
|
||||
value={isEditing ? editorValue : readOnlyValue}
|
||||
onChange={handleEditorChange}
|
||||
modules={isEditing ? quillModules : readOnlyModules}
|
||||
formats={quillFormats}
|
||||
placeholder={t("emptyContent")}
|
||||
/>
|
||||
</div>
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,20 @@
|
||||
import { IconNotes } from "@tabler/icons-react";
|
||||
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("anchorNote", {
|
||||
icon: IconNotes,
|
||||
supportedIntegrations: ["anchor"],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
noteId: factory.anchorNote(),
|
||||
showTitle: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
showUpdatedAt: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
}));
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -131,7 +131,7 @@ export default function AppWidget({ options, isEditMode, height, width }: Widget
|
||||
</Tooltip.Floating>
|
||||
{options.pingEnabled && !settings.forceDisableStatus && !board.disableStatus && app.href ? (
|
||||
<Suspense fallback={<PingDot icon={IconLoader} color="blue" tooltip={`${t("common.action.loading")}…`} />}>
|
||||
<PingIndicator href={app.pingUrl ?? app.href} />
|
||||
<PingIndicator appId={app.id} />
|
||||
</Suspense>
|
||||
) : null}
|
||||
</AppLink>
|
||||
|
||||
@@ -7,13 +7,13 @@ import { clientApi } from "@homarr/api/client";
|
||||
import { PingDot } from "./ping-dot";
|
||||
|
||||
interface PingIndicatorProps {
|
||||
href: string;
|
||||
appId: string;
|
||||
}
|
||||
|
||||
export const PingIndicator = ({ href }: PingIndicatorProps) => {
|
||||
export const PingIndicator = ({ appId }: PingIndicatorProps) => {
|
||||
const [ping] = clientApi.widget.app.ping.useSuspenseQuery(
|
||||
{
|
||||
url: href,
|
||||
id: appId,
|
||||
},
|
||||
{
|
||||
refetchOnMount: false,
|
||||
@@ -24,7 +24,7 @@ export const PingIndicator = ({ href }: PingIndicatorProps) => {
|
||||
const [pingResult, setPingResult] = useState<RouterOutputs["widget"]["app"]["ping"]>(ping);
|
||||
|
||||
clientApi.widget.app.updatedPing.useSubscription(
|
||||
{ url: href },
|
||||
{ id: appId },
|
||||
{
|
||||
onData(data) {
|
||||
setPingResult(data);
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import { Accordion, Badge, Group, Stack, Text } from "@mantine/core";
|
||||
import { IconCloud } from "@tabler/icons-react";
|
||||
|
||||
import type { CoolifyApplicationWithContext } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { getBadgeColor, parseStatus } from "./coolify-utils";
|
||||
import { ResourceRow } from "./resource-row";
|
||||
|
||||
interface ApplicationsSectionProps {
|
||||
applications: CoolifyApplicationWithContext[];
|
||||
baseUrl: string;
|
||||
isTiny: boolean;
|
||||
}
|
||||
|
||||
export function ApplicationsSection({ applications, baseUrl, isTiny }: ApplicationsSectionProps) {
|
||||
const t = useScopedI18n("widget.coolify");
|
||||
const tCommon = useScopedI18n("common");
|
||||
const runningApps = applications.filter((app) => parseStatus(app.status ?? "") === "running").length;
|
||||
|
||||
return (
|
||||
<Accordion.Item value="applications">
|
||||
<Accordion.Control icon={isTiny ? null : <IconCloud size={16} />}>
|
||||
<Group gap="xs">
|
||||
<Text size="xs">{tCommon("applications")}</Text>
|
||||
<Badge variant="dot" color={getBadgeColor(runningApps, applications.length)} size="xs">
|
||||
{runningApps} / {applications.length}
|
||||
</Badge>
|
||||
</Group>
|
||||
</Accordion.Control>
|
||||
<Accordion.Panel p={4}>
|
||||
{applications.length > 0 ? (
|
||||
<Stack gap={4}>
|
||||
{applications.map((app) => (
|
||||
<ResourceRow key={app.uuid} item={app} baseUrl={baseUrl} isTiny={isTiny} resourceType="application" />
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed" ta="center" py="xs">
|
||||
{t("empty.applications")}
|
||||
</Text>
|
||||
)}
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,76 @@
|
||||
"use client";
|
||||
|
||||
import { ScrollArea, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { createWidgetKey } from "./coolify-utils";
|
||||
import { InstanceCard } from "./instance-card";
|
||||
import { SingleInstanceLayout } from "./single-instance-layout";
|
||||
|
||||
export default function CoolifyWidget({ options, integrationIds, width }: WidgetComponentProps<"coolify">) {
|
||||
const t = useScopedI18n("widget.coolify");
|
||||
|
||||
if (integrationIds.length === 0) {
|
||||
return (
|
||||
<Stack align="center" justify="center" h="100%">
|
||||
<Text c="dimmed">{t("error.noIntegration")}</Text>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
return <CoolifyContent integrationIds={integrationIds} options={options} width={width} />;
|
||||
}
|
||||
|
||||
interface CoolifyContentProps {
|
||||
integrationIds: string[];
|
||||
options: WidgetComponentProps<"coolify">["options"];
|
||||
width: number;
|
||||
}
|
||||
|
||||
function CoolifyContent({ integrationIds, options, width }: CoolifyContentProps) {
|
||||
const [instancesData] = clientApi.widget.coolify.getInstancesInfo.useSuspenseQuery({ integrationIds });
|
||||
|
||||
const utils = clientApi.useUtils();
|
||||
clientApi.widget.coolify.subscribeInstancesInfo.useSubscription(
|
||||
{ integrationIds },
|
||||
{
|
||||
onData(newData) {
|
||||
utils.widget.coolify.getInstancesInfo.setData({ integrationIds }, (prevData) => {
|
||||
if (!prevData) return prevData;
|
||||
return prevData.map((instance) =>
|
||||
instance.integrationId === newData.integrationId
|
||||
? { ...instance, instanceInfo: newData.instanceInfo, updatedAt: newData.timestamp }
|
||||
: instance,
|
||||
);
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const isTiny = width < 256;
|
||||
const [firstInstance] = instancesData;
|
||||
const widgetKey = createWidgetKey(integrationIds);
|
||||
|
||||
if (instancesData.length === 1 && firstInstance) {
|
||||
return <SingleInstanceLayout instance={firstInstance} options={options} isTiny={isTiny} widgetKey={widgetKey} />;
|
||||
}
|
||||
|
||||
return (
|
||||
<ScrollArea h="100%">
|
||||
<Stack gap="xs" p="xs">
|
||||
{instancesData.map((instance) => (
|
||||
<InstanceCard
|
||||
key={instance.integrationId}
|
||||
instance={instance}
|
||||
options={options}
|
||||
isTiny={isTiny}
|
||||
widgetKey={widgetKey}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,125 @@
|
||||
import type {
|
||||
CoolifyApplicationWithContext,
|
||||
CoolifyServer,
|
||||
CoolifyServiceWithContext,
|
||||
} from "@homarr/integrations/types";
|
||||
|
||||
export function parseStatus(status: string): string {
|
||||
const firstPart = status.split(":")[0]?.toLowerCase();
|
||||
if (!firstPart) return "unknown";
|
||||
return firstPart;
|
||||
}
|
||||
|
||||
export function cleanFqdn(fqdn: string | undefined | null): string | undefined {
|
||||
if (!fqdn) return undefined;
|
||||
const firstUrl = fqdn.split(",")[0]?.trim();
|
||||
if (!firstUrl) return undefined;
|
||||
try {
|
||||
const url = new URL(firstUrl);
|
||||
return `${url.protocol}//${url.host}${url.pathname}`.replace(/\/$/, "");
|
||||
} catch {
|
||||
return firstUrl;
|
||||
}
|
||||
}
|
||||
|
||||
export function getStatusColor(status: string): string {
|
||||
const colors: Record<string, string> = {
|
||||
running: "green",
|
||||
stopped: "red",
|
||||
exited: "red",
|
||||
starting: "yellow",
|
||||
restarting: "yellow",
|
||||
};
|
||||
return colors[status] ?? "gray";
|
||||
}
|
||||
|
||||
export function getBadgeColor(running: number, total: number): string {
|
||||
if (total === 0) return "gray";
|
||||
if (running === total) return "green";
|
||||
if (running > 0) return "yellow";
|
||||
return "red";
|
||||
}
|
||||
|
||||
export function formatRelativeTime(dateString: string | null | undefined): string | undefined {
|
||||
if (!dateString) return undefined;
|
||||
const date = new Date(dateString);
|
||||
if (isNaN(date.getTime())) return undefined;
|
||||
|
||||
const now = new Date();
|
||||
const diffMs = now.getTime() - date.getTime();
|
||||
const diffSec = Math.floor(diffMs / 1000);
|
||||
const diffMin = Math.floor(diffSec / 60);
|
||||
const diffHour = Math.floor(diffMin / 60);
|
||||
const diffDay = Math.floor(diffHour / 24);
|
||||
|
||||
if (diffDay > 0) {
|
||||
const remainingHours = diffHour % 24;
|
||||
return remainingHours > 0 ? `${diffDay}d ${remainingHours}h ago` : `${diffDay}d ago`;
|
||||
}
|
||||
if (diffHour > 0) {
|
||||
const remainingMin = diffMin % 60;
|
||||
return remainingMin > 0 ? `${diffHour}h ${remainingMin}m ago` : `${diffHour}h ago`;
|
||||
}
|
||||
if (diffMin > 0) return `${diffMin}m ago`;
|
||||
return "just now";
|
||||
}
|
||||
|
||||
export function getResourceTimestamp(
|
||||
item: { updated_at?: string | null; last_online_at?: string | null; status?: string | null },
|
||||
resourceType: "application" | "service",
|
||||
): string | undefined {
|
||||
const status = parseStatus(item.status ?? "");
|
||||
const isRunning = status === "running";
|
||||
|
||||
if (isRunning) return undefined;
|
||||
|
||||
const timestamp = resourceType === "application" ? (item.last_online_at ?? item.updated_at) : item.updated_at;
|
||||
return formatRelativeTime(timestamp);
|
||||
}
|
||||
|
||||
export function buildServerResourceCounts(
|
||||
servers: CoolifyServer[],
|
||||
applications: CoolifyApplicationWithContext[],
|
||||
services: CoolifyServiceWithContext[],
|
||||
): Map<number, { apps: number; services: number }> {
|
||||
const serverResourceCounts = new Map<number, { apps: number; services: number }>();
|
||||
|
||||
for (const server of servers) {
|
||||
const serverId = server.settings?.server_id ?? server.id ?? 0;
|
||||
serverResourceCounts.set(serverId, { apps: 0, services: 0 });
|
||||
}
|
||||
|
||||
const destinationToServer = new Map<number, number>();
|
||||
for (const service of services) {
|
||||
if (service.destination_id != null && service.server_id != null) {
|
||||
destinationToServer.set(service.destination_id, service.server_id);
|
||||
}
|
||||
}
|
||||
|
||||
for (const app of applications) {
|
||||
const serverId = app.server_id ?? destinationToServer.get(app.destination_id ?? 0) ?? app.destination_id ?? 0;
|
||||
const counts = serverResourceCounts.get(serverId);
|
||||
if (counts) {
|
||||
counts.apps++;
|
||||
}
|
||||
}
|
||||
|
||||
for (const service of services) {
|
||||
const serverId = service.server_id ?? service.destination_id ?? 0;
|
||||
const counts = serverResourceCounts.get(serverId);
|
||||
if (counts) {
|
||||
counts.services++;
|
||||
}
|
||||
}
|
||||
|
||||
return serverResourceCounts;
|
||||
}
|
||||
|
||||
export function createWidgetKey(integrationIds: string[]): string {
|
||||
return integrationIds.slice().sort().join("-");
|
||||
}
|
||||
|
||||
export function createStorageKey(widgetKey: string, integrationId: string, type: "sections" | "show-ip"): string {
|
||||
const cardKey = widgetKey.includes("-") ? `${widgetKey}-${integrationId}` : widgetKey;
|
||||
return `coolify-${type}-${cardKey}`;
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { IconCloud, IconServerOff } from "@tabler/icons-react";
|
||||
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("coolify", {
|
||||
icon: IconCloud,
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
showServers: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
showApplications: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
showServices: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
}));
|
||||
},
|
||||
supportedIntegrations: ["coolify"],
|
||||
errors: {
|
||||
INTERNAL_SERVER_ERROR: {
|
||||
icon: IconServerOff,
|
||||
message: (t) => t("widget.coolify.error.internalServerError"),
|
||||
},
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -0,0 +1,122 @@
|
||||
"use client";
|
||||
|
||||
import { Accordion, Anchor, Badge, Card, Group, Image, Text } from "@mantine/core";
|
||||
import { useLocalStorage } from "@mantine/hooks";
|
||||
|
||||
import { useTimeAgo } from "@homarr/common";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { ApplicationsSection } from "./applications-section";
|
||||
import { buildServerResourceCounts, getBadgeColor, parseStatus } from "./coolify-utils";
|
||||
import { ServersSection } from "./servers-section";
|
||||
import { ServicesSection } from "./services-section";
|
||||
import type { CoolifyOptions, InstanceData } from "./types";
|
||||
import { COOLIFY_ICON_URL } from "./types";
|
||||
|
||||
interface InstanceCardProps {
|
||||
instance: InstanceData;
|
||||
options: CoolifyOptions;
|
||||
isTiny: boolean;
|
||||
widgetKey: string;
|
||||
}
|
||||
|
||||
export function InstanceCard({ instance, options, isTiny, widgetKey }: InstanceCardProps) {
|
||||
const t = useScopedI18n("widget.coolify");
|
||||
const cardKey = `${widgetKey}-${instance.integrationId}`;
|
||||
const [showIp, setShowIp] = useLocalStorage({
|
||||
key: `coolify-show-ip-${cardKey}`,
|
||||
defaultValue: false,
|
||||
});
|
||||
const [openSections, setOpenSections] = useLocalStorage<string[]>({
|
||||
key: `coolify-sections-${cardKey}`,
|
||||
defaultValue: ["applications"],
|
||||
});
|
||||
|
||||
const serverResourceCounts = buildServerResourceCounts(
|
||||
instance.instanceInfo.servers,
|
||||
instance.instanceInfo.applications,
|
||||
instance.instanceInfo.services,
|
||||
);
|
||||
|
||||
const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
|
||||
const relativeTime = useTimeAgo(instance.updatedAt);
|
||||
|
||||
const onlineServers = instance.instanceInfo.servers.filter((s) => s.is_reachable !== false).length;
|
||||
const runningApps = instance.instanceInfo.applications.filter(
|
||||
(a) => parseStatus(a.status ?? "") === "running",
|
||||
).length;
|
||||
const runningServices = instance.instanceInfo.services.filter(
|
||||
(s) => parseStatus(s.status ?? "") === "running",
|
||||
).length;
|
||||
|
||||
return (
|
||||
<Card p={0} radius="sm" withBorder>
|
||||
<Group
|
||||
p="xs"
|
||||
justify="space-between"
|
||||
wrap="nowrap"
|
||||
style={{ borderBottom: "1px solid var(--mantine-color-dark-4)" }}
|
||||
>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
<Image src={COOLIFY_ICON_URL} alt="Coolify" w={16} h={16} />
|
||||
<Anchor href={baseUrl} target="_blank" fz={isTiny ? "10px" : "xs"} fw={600} c="inherit" lineClamp={1}>
|
||||
{instance.integrationName}
|
||||
</Anchor>
|
||||
</Group>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
{options.showServers && (
|
||||
<Badge variant="dot" color={getBadgeColor(onlineServers, instance.instanceInfo.servers.length)} size="xs">
|
||||
{onlineServers}/{instance.instanceInfo.servers.length}
|
||||
</Badge>
|
||||
)}
|
||||
{options.showApplications && (
|
||||
<Badge
|
||||
variant="dot"
|
||||
color={getBadgeColor(runningApps, instance.instanceInfo.applications.length)}
|
||||
size="xs"
|
||||
>
|
||||
{runningApps}/{instance.instanceInfo.applications.length}
|
||||
</Badge>
|
||||
)}
|
||||
{options.showServices && (
|
||||
<Badge
|
||||
variant="dot"
|
||||
color={getBadgeColor(runningServices, instance.instanceInfo.services.length)}
|
||||
size="xs"
|
||||
>
|
||||
{runningServices}/{instance.instanceInfo.services.length}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<Accordion variant="filled" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
|
||||
{options.showServers && (
|
||||
<ServersSection
|
||||
servers={instance.instanceInfo.servers}
|
||||
serverResourceCounts={serverResourceCounts}
|
||||
baseUrl={baseUrl}
|
||||
isTiny={isTiny}
|
||||
showIp={showIp}
|
||||
onToggleIp={() => setShowIp((prev) => !prev)}
|
||||
/>
|
||||
)}
|
||||
{options.showApplications && (
|
||||
<ApplicationsSection applications={instance.instanceInfo.applications} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
)}
|
||||
{options.showServices && (
|
||||
<ServicesSection services={instance.instanceInfo.services} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
)}
|
||||
</Accordion>
|
||||
|
||||
<Group justify="space-between" p={4} style={{ borderTop: "1px solid var(--mantine-color-dark-4)" }}>
|
||||
<Text size="10px" c="dimmed">
|
||||
v{instance.instanceInfo.version}
|
||||
</Text>
|
||||
<Text size="10px" c="dimmed">
|
||||
{t("footer.updated", { when: relativeTime })}
|
||||
</Text>
|
||||
</Group>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
"use client";
|
||||
|
||||
import { ActionIcon, Anchor, Group, Indicator, Stack, Text } from "@mantine/core";
|
||||
import { IconExternalLink, IconFileText, IconLink } from "@tabler/icons-react";
|
||||
|
||||
import { cleanFqdn, getResourceTimestamp, getStatusColor, parseStatus } from "./coolify-utils";
|
||||
|
||||
interface ResourceRowProps {
|
||||
item: {
|
||||
uuid: string;
|
||||
name: string;
|
||||
status?: string | null;
|
||||
fqdn?: string | null;
|
||||
updated_at?: string | null;
|
||||
last_online_at?: string | null;
|
||||
projectName?: string;
|
||||
projectUuid?: string;
|
||||
environmentName?: string;
|
||||
environmentUuid?: string;
|
||||
};
|
||||
baseUrl: string;
|
||||
isTiny: boolean;
|
||||
resourceType: "application" | "service";
|
||||
}
|
||||
|
||||
export function ResourceRow({ item, baseUrl, isTiny, resourceType }: ResourceRowProps) {
|
||||
const status = parseStatus(item.status ?? "");
|
||||
const statusColor = getStatusColor(status);
|
||||
|
||||
const resourceUrl =
|
||||
item.projectUuid && item.environmentUuid
|
||||
? `${baseUrl}/project/${item.projectUuid}/environment/${item.environmentUuid}/${resourceType}/${item.uuid}`
|
||||
: undefined;
|
||||
|
||||
const logsUrl = resourceUrl ? `${resourceUrl}/logs` : undefined;
|
||||
|
||||
return (
|
||||
<Stack gap={0}>
|
||||
<Group wrap="nowrap" gap={isTiny ? 4 : "xs"}>
|
||||
<Indicator size={isTiny ? 4 : 8} color={statusColor} />
|
||||
{resourceUrl ? (
|
||||
<Anchor href={resourceUrl} target="_blank" fz={isTiny ? "8px" : "xs"} c="inherit" lineClamp={1}>
|
||||
{item.name}
|
||||
</Anchor>
|
||||
) : (
|
||||
<Text lineClamp={1} fz={isTiny ? "8px" : "xs"}>
|
||||
{item.name}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
<Group wrap="nowrap" gap={4} ml={16}>
|
||||
{cleanFqdn(item.fqdn) && (
|
||||
<ActionIcon component="a" href={cleanFqdn(item.fqdn)} target="_blank" size="xs" variant="subtle" c="dimmed">
|
||||
<IconLink size={12} />
|
||||
</ActionIcon>
|
||||
)}
|
||||
{resourceUrl && (
|
||||
<ActionIcon component="a" href={resourceUrl} target="_blank" size="xs" variant="subtle" c="dimmed">
|
||||
<IconExternalLink size={12} />
|
||||
</ActionIcon>
|
||||
)}
|
||||
{logsUrl && (
|
||||
<ActionIcon component="a" href={logsUrl} target="_blank" size="xs" variant="subtle" c="dimmed">
|
||||
<IconFileText size={12} />
|
||||
</ActionIcon>
|
||||
)}
|
||||
<Text fz="10px" c="dimmed" lineClamp={1}>
|
||||
{item.projectName ?? "-"} / {item.environmentName ?? "-"}
|
||||
</Text>
|
||||
{getResourceTimestamp(item, resourceType) && (
|
||||
<Text fz="10px" c="dimmed" ml="auto">
|
||||
{getResourceTimestamp(item, resourceType)}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
"use client";
|
||||
|
||||
import { Accordion, ActionIcon, Anchor, Badge, Group, Indicator, Stack, Text } from "@mantine/core";
|
||||
import { IconExternalLink, IconEye, IconEyeOff, IconServer } from "@tabler/icons-react";
|
||||
|
||||
import type { CoolifyServer } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { getBadgeColor } from "./coolify-utils";
|
||||
|
||||
interface ServersSectionProps {
|
||||
servers: CoolifyServer[];
|
||||
serverResourceCounts: Map<number, { apps: number; services: number }>;
|
||||
baseUrl: string;
|
||||
isTiny: boolean;
|
||||
showIp: boolean;
|
||||
onToggleIp: () => void;
|
||||
}
|
||||
|
||||
export function ServersSection({
|
||||
servers,
|
||||
serverResourceCounts,
|
||||
baseUrl,
|
||||
isTiny,
|
||||
showIp,
|
||||
onToggleIp,
|
||||
}: ServersSectionProps) {
|
||||
const t = useScopedI18n("widget.coolify");
|
||||
const tCommon = useScopedI18n("common");
|
||||
const onlineServers = servers.filter((server) => server.is_reachable !== false).length;
|
||||
|
||||
return (
|
||||
<Accordion.Item value="servers">
|
||||
<Accordion.Control icon={isTiny ? null : <IconServer size={16} />}>
|
||||
<Group gap="xs" justify="space-between" wrap="nowrap" style={{ flex: 1 }}>
|
||||
<Group gap="xs">
|
||||
<Text size="xs">{tCommon("servers")}</Text>
|
||||
<Badge variant="dot" color={getBadgeColor(onlineServers, servers.length)} size="xs">
|
||||
{onlineServers} / {servers.length}
|
||||
</Badge>
|
||||
</Group>
|
||||
<ActionIcon
|
||||
size="xs"
|
||||
variant="subtle"
|
||||
c="dimmed"
|
||||
onClick={(event) => {
|
||||
event.stopPropagation();
|
||||
onToggleIp();
|
||||
}}
|
||||
>
|
||||
{showIp ? <IconEye size={12} /> : <IconEyeOff size={12} />}
|
||||
</ActionIcon>
|
||||
</Group>
|
||||
</Accordion.Control>
|
||||
<Accordion.Panel p={4}>
|
||||
{servers.length > 0 ? (
|
||||
<Stack gap={4}>
|
||||
{servers.map((server) => (
|
||||
<ServerRow
|
||||
key={server.uuid}
|
||||
server={server}
|
||||
counts={
|
||||
serverResourceCounts.get(server.settings?.server_id ?? server.id ?? 0) ?? { apps: 0, services: 0 }
|
||||
}
|
||||
baseUrl={baseUrl}
|
||||
isTiny={isTiny}
|
||||
showIp={showIp}
|
||||
/>
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed" ta="center" py="xs">
|
||||
{t("empty.servers")}
|
||||
</Text>
|
||||
)}
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
);
|
||||
}
|
||||
|
||||
interface ServerRowProps {
|
||||
server: CoolifyServer;
|
||||
counts: { apps: number; services: number };
|
||||
baseUrl: string;
|
||||
isTiny: boolean;
|
||||
showIp: boolean;
|
||||
}
|
||||
|
||||
function ServerRow({ server, counts, baseUrl, isTiny, showIp }: ServerRowProps) {
|
||||
const t = useScopedI18n("widget.coolify");
|
||||
const isBuildServer = server.settings?.is_build_server === true;
|
||||
const isOnline = server.is_reachable !== false;
|
||||
const serverUrl = `${baseUrl}/server/${server.uuid}`;
|
||||
|
||||
return (
|
||||
<Stack gap={0}>
|
||||
<Group wrap="nowrap" gap={isTiny ? 4 : "xs"}>
|
||||
<Indicator size={isTiny ? 4 : 8} color={isOnline ? "green" : "red"} />
|
||||
<Anchor href={serverUrl} target="_blank" fz={isTiny ? "8px" : "xs"} c="inherit" lineClamp={1}>
|
||||
{server.name}
|
||||
</Anchor>
|
||||
{isBuildServer ? (
|
||||
<Badge size="xs" variant="light" color="violet">
|
||||
{t("server.buildServer")}
|
||||
</Badge>
|
||||
) : (
|
||||
<Text fz="10px" c="dimmed">
|
||||
({counts.apps} apps / {counts.services} svcs)
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
<Group wrap="nowrap" gap={4} ml={16}>
|
||||
<ActionIcon component="a" href={serverUrl} target="_blank" size="xs" variant="subtle" c="dimmed">
|
||||
<IconExternalLink size={12} />
|
||||
</ActionIcon>
|
||||
<Text fz="10px" c="dimmed">
|
||||
{showIp ? server.ip : "***.***.***.***"}
|
||||
</Text>
|
||||
</Group>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
"use client";
|
||||
|
||||
import { Accordion, Badge, Group, Stack, Text } from "@mantine/core";
|
||||
import { IconStack2 } from "@tabler/icons-react";
|
||||
|
||||
import type { CoolifyServiceWithContext } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { getBadgeColor, parseStatus } from "./coolify-utils";
|
||||
import { ResourceRow } from "./resource-row";
|
||||
|
||||
interface ServicesSectionProps {
|
||||
services: CoolifyServiceWithContext[];
|
||||
baseUrl: string;
|
||||
isTiny: boolean;
|
||||
}
|
||||
|
||||
export function ServicesSection({ services, baseUrl, isTiny }: ServicesSectionProps) {
|
||||
const t = useScopedI18n("widget.coolify");
|
||||
const tCommon = useScopedI18n("common");
|
||||
const runningServices = services.filter((svc) => parseStatus(svc.status ?? "") === "running").length;
|
||||
|
||||
return (
|
||||
<Accordion.Item value="services">
|
||||
<Accordion.Control icon={isTiny ? null : <IconStack2 size={16} />}>
|
||||
<Group gap="xs">
|
||||
<Text size="xs">{tCommon("services")}</Text>
|
||||
<Badge variant="dot" color={getBadgeColor(runningServices, services.length)} size="xs">
|
||||
{runningServices} / {services.length}
|
||||
</Badge>
|
||||
</Group>
|
||||
</Accordion.Control>
|
||||
<Accordion.Panel p={4}>
|
||||
{services.length > 0 ? (
|
||||
<Stack gap={4}>
|
||||
{services.map((service) => (
|
||||
<ResourceRow key={service.uuid} item={service} baseUrl={baseUrl} isTiny={isTiny} resourceType="service" />
|
||||
))}
|
||||
</Stack>
|
||||
) : (
|
||||
<Text size="sm" c="dimmed" ta="center" py="xs">
|
||||
{t("empty.services")}
|
||||
</Text>
|
||||
)}
|
||||
</Accordion.Panel>
|
||||
</Accordion.Item>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,92 @@
|
||||
"use client";
|
||||
|
||||
import { Accordion, Anchor, Group, Image, ScrollArea, Stack, Text } from "@mantine/core";
|
||||
import { useLocalStorage } from "@mantine/hooks";
|
||||
|
||||
import { useTimeAgo } from "@homarr/common";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { ApplicationsSection } from "./applications-section";
|
||||
import { buildServerResourceCounts } from "./coolify-utils";
|
||||
import { ServersSection } from "./servers-section";
|
||||
import { ServicesSection } from "./services-section";
|
||||
import type { CoolifyOptions, InstanceData } from "./types";
|
||||
import { COOLIFY_ICON_URL } from "./types";
|
||||
|
||||
interface SingleInstanceLayoutProps {
|
||||
instance: InstanceData;
|
||||
options: CoolifyOptions;
|
||||
isTiny: boolean;
|
||||
widgetKey: string;
|
||||
}
|
||||
|
||||
export function SingleInstanceLayout({ instance, options, isTiny, widgetKey }: SingleInstanceLayoutProps) {
|
||||
const t = useScopedI18n("widget.coolify");
|
||||
const [showIp, setShowIp] = useLocalStorage({
|
||||
key: `coolify-show-ip-${widgetKey}`,
|
||||
defaultValue: false,
|
||||
});
|
||||
const [openSections, setOpenSections] = useLocalStorage<string[]>({
|
||||
key: `coolify-sections-${widgetKey}`,
|
||||
defaultValue: ["applications"],
|
||||
});
|
||||
|
||||
const serverResourceCounts = buildServerResourceCounts(
|
||||
instance.instanceInfo.servers,
|
||||
instance.instanceInfo.applications,
|
||||
instance.instanceInfo.services,
|
||||
);
|
||||
|
||||
const baseUrl = instance.integrationUrl.replace(/\/+$/, "");
|
||||
const displayUrl = baseUrl.replace(/^https?:\/\//, "");
|
||||
const relativeTime = useTimeAgo(instance.updatedAt);
|
||||
|
||||
return (
|
||||
<ScrollArea h="100%">
|
||||
<Stack gap={0}>
|
||||
<Group p="xs" justify="center" gap="xs" style={{ borderBottom: "2px solid #8B5CF6" }}>
|
||||
<Group gap={2}>
|
||||
<Image src={COOLIFY_ICON_URL} alt="Coolify" w={isTiny ? 18 : 24} h={isTiny ? 18 : 24} />
|
||||
<Text fz={isTiny ? "xs" : "sm"} fw={700} style={{ color: "#8B5CF6" }}>
|
||||
oolify
|
||||
</Text>
|
||||
</Group>
|
||||
<Anchor href={baseUrl} target="_blank" fz={isTiny ? "xs" : "sm"} fw={500} c="dimmed" lineClamp={1}>
|
||||
{displayUrl}
|
||||
</Anchor>
|
||||
</Group>
|
||||
|
||||
<Accordion variant="contained" chevronPosition="right" multiple value={openSections} onChange={setOpenSections}>
|
||||
{options.showServers && (
|
||||
<ServersSection
|
||||
servers={instance.instanceInfo.servers}
|
||||
serverResourceCounts={serverResourceCounts}
|
||||
baseUrl={baseUrl}
|
||||
isTiny={isTiny}
|
||||
showIp={showIp}
|
||||
onToggleIp={() => setShowIp((prev) => !prev)}
|
||||
/>
|
||||
)}
|
||||
{options.showApplications && (
|
||||
<ApplicationsSection applications={instance.instanceInfo.applications} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
)}
|
||||
{options.showServices && (
|
||||
<ServicesSection services={instance.instanceInfo.services} baseUrl={baseUrl} isTiny={isTiny} />
|
||||
)}
|
||||
</Accordion>
|
||||
|
||||
<Group justify="space-between" p={4} style={{ borderTop: "1px solid var(--mantine-color-dark-4)" }}>
|
||||
<Group gap={2}>
|
||||
<Image src={COOLIFY_ICON_URL} alt="Coolify" w={16} h={16} />
|
||||
<Text size="xs" c="dimmed">
|
||||
v{instance.instanceInfo.version}
|
||||
</Text>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("footer.updated", { when: relativeTime })}
|
||||
</Text>
|
||||
</Group>
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
import type { CoolifyInstanceInfo } from "@homarr/integrations/types";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
|
||||
export const COOLIFY_ICON_URL = "https://cdn.jsdelivr.net/gh/homarr-labs/dashboard-icons/svg/coolify.svg";
|
||||
|
||||
export interface InstanceData {
|
||||
integrationId: string;
|
||||
integrationName: string;
|
||||
integrationUrl: string;
|
||||
instanceInfo: CoolifyInstanceInfo;
|
||||
updatedAt: Date;
|
||||
}
|
||||
|
||||
export type CoolifyOptions = WidgetComponentProps<"coolify">["options"];
|
||||
@@ -60,6 +60,19 @@ const createColumns = (
|
||||
return <ContainerStateBadge state={row.original.state} />;
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "host",
|
||||
accessorKey: "host",
|
||||
size: 100,
|
||||
header: t("field.host.label"),
|
||||
Cell({ row }) {
|
||||
return (
|
||||
<Text size="xs" truncate="end">
|
||||
{row.original.host}
|
||||
</Text>
|
||||
);
|
||||
},
|
||||
},
|
||||
{
|
||||
id: "cpuUsage",
|
||||
sortingFn: (rowA, rowB) => {
|
||||
|
||||
@@ -19,6 +19,9 @@ export const { definition, componentLoader } = createWidgetDefinition("healthMon
|
||||
memory: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
gpu: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
showUptime: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
|
||||
@@ -0,0 +1,64 @@
|
||||
import { Center, RingProgress, Stack, Text, Tooltip } from "@mantine/core";
|
||||
import { IconDeviceDesktop } from "@tabler/icons-react";
|
||||
|
||||
import { progressColor } from "../system-health";
|
||||
|
||||
interface GpuRingProps {
|
||||
gpu: {
|
||||
gpuId: string;
|
||||
name: string;
|
||||
memoryUtilization: number;
|
||||
processorUtilization: number;
|
||||
temperature: number | null;
|
||||
fanSpeed: number | null;
|
||||
};
|
||||
isTiny: boolean;
|
||||
fahrenheit: boolean;
|
||||
}
|
||||
|
||||
export const GpuRing = ({ gpu, isTiny, fahrenheit }: GpuRingProps) => {
|
||||
const tempDisplay =
|
||||
gpu.temperature != null
|
||||
? fahrenheit
|
||||
? `${(gpu.temperature * 1.8 + 32).toFixed(0)}°F`
|
||||
: `${gpu.temperature}°C`
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Tooltip
|
||||
label={
|
||||
<Stack gap={2}>
|
||||
<Text size="xs" fw={600}>
|
||||
{gpu.name}
|
||||
</Text>
|
||||
<Text size="xs">VRAM: {gpu.memoryUtilization.toFixed(1)}%</Text>
|
||||
{tempDisplay && <Text size="xs">Temp: {tempDisplay}</Text>}
|
||||
{gpu.fanSpeed != null && <Text size="xs">Fan: {gpu.fanSpeed} RPM</Text>}
|
||||
</Stack>
|
||||
}
|
||||
multiline
|
||||
>
|
||||
<RingProgress
|
||||
className={`health-monitoring-gpu health-monitoring-gpu-${gpu.gpuId}`}
|
||||
roundCaps
|
||||
size={isTiny ? 50 : 100}
|
||||
thickness={isTiny ? 4 : 8}
|
||||
label={
|
||||
<Center style={{ flexDirection: "column" }}>
|
||||
<Text
|
||||
className="health-monitoring-gpu-utilization-value"
|
||||
size={isTiny ? "8px" : "xs"}
|
||||
>{`${gpu.processorUtilization.toFixed(0)}%`}</Text>
|
||||
<IconDeviceDesktop className="health-monitoring-gpu-utilization-icon" size={isTiny ? 8 : 16} />
|
||||
</Center>
|
||||
}
|
||||
sections={[
|
||||
{
|
||||
value: Number(gpu.processorUtilization.toFixed(2)),
|
||||
color: progressColor(Number(gpu.processorUtilization.toFixed(2))),
|
||||
},
|
||||
]}
|
||||
/>
|
||||
</Tooltip>
|
||||
);
|
||||
};
|
||||
@@ -39,6 +39,7 @@ import { useI18n } from "@homarr/translation/client";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { CpuRing } from "./rings/cpu-ring";
|
||||
import { CpuTempRing } from "./rings/cpu-temp-ring";
|
||||
import { GpuRing } from "./rings/gpu-ring";
|
||||
import { formatMemoryUsage, MemoryRing } from "./rings/memory-ring";
|
||||
import classes from "./system-health.module.css";
|
||||
|
||||
@@ -187,6 +188,10 @@ export const SystemHealthMonitoring = ({
|
||||
isTiny={isTiny}
|
||||
/>
|
||||
)}
|
||||
{options.gpu &&
|
||||
healthInfo.gpu.map((gpu) => (
|
||||
<GpuRing key={gpu.gpuId} gpu={gpu} isTiny={isTiny} fahrenheit={options.fahrenheit} />
|
||||
))}
|
||||
</Flex>
|
||||
{
|
||||
<Text className="health-monitoring-status-update-time" c="dimmed" size="xs" ta="center">
|
||||
|
||||
@@ -105,6 +105,10 @@ const getSandboxFlags = (
|
||||
baseSandbox.push("allow-popups-to-escape-sandbox");
|
||||
}
|
||||
|
||||
if (permissions.allowModals) {
|
||||
baseSandbox.push("allow-modals");
|
||||
}
|
||||
|
||||
return baseSandbox;
|
||||
};
|
||||
|
||||
@@ -115,4 +119,5 @@ const permissionMapping = {
|
||||
allowGeolocation: "geolocation",
|
||||
allowMicrophone: "microphone",
|
||||
allowPayment: "payment",
|
||||
allowModals: "allow-modals",
|
||||
} satisfies Record<keyof Omit<WidgetComponentProps<"iframe">["options"], "embedUrl" | "allowScrolling">, string>;
|
||||
@@ -17,6 +17,7 @@ export const { definition, componentLoader } = createWidgetDefinition("iframe",
|
||||
allowMicrophone: factory.switch(),
|
||||
allowCamera: factory.switch(),
|
||||
allowGeolocation: factory.switch(),
|
||||
allowModals: factory.switch(),
|
||||
}));
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -0,0 +1,52 @@
|
||||
.carouselContainer {
|
||||
position: relative;
|
||||
overflow: hidden;
|
||||
background-color: var(--mantine-color-gray-9);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
}
|
||||
|
||||
.carouselImage {
|
||||
width: 100%;
|
||||
height: 100%;
|
||||
object-fit: cover;
|
||||
background-color: var(--mantine-color-gray-8);
|
||||
}
|
||||
|
||||
.photoInfo {
|
||||
position: absolute;
|
||||
bottom: 0;
|
||||
left: 0;
|
||||
right: 0;
|
||||
background: linear-gradient(to top, rgba(0, 0, 0, 0.8), transparent);
|
||||
color: white;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.dots {
|
||||
position: absolute;
|
||||
bottom: 12px;
|
||||
left: 50%;
|
||||
transform: translateX(-50%);
|
||||
z-index: 10;
|
||||
}
|
||||
|
||||
.dot {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background-color: rgba(255, 255, 255, 0.5);
|
||||
cursor: pointer;
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&[data-active="true"] {
|
||||
background-color: rgba(255, 255, 255, 1);
|
||||
width: 24px;
|
||||
border-radius: 4px;
|
||||
}
|
||||
|
||||
&:hover {
|
||||
background-color: rgba(255, 255, 255, 0.8);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
"use client";
|
||||
|
||||
import type { Dispatch, SetStateAction } from "react";
|
||||
import { useEffect, useState } from "react";
|
||||
import { Box, Center, Group, Image, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertCircle, IconCalendar } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../../definition";
|
||||
import classes from "./component.module.css";
|
||||
|
||||
export default function ImmichAlbumCarouselWidget({
|
||||
integrationIds,
|
||||
options,
|
||||
}: WidgetComponentProps<"immich-albumCarousel">) {
|
||||
const [currentPhotoIndex, setCurrentPhotoIndex] = useState(0);
|
||||
|
||||
if (!options.albumId) {
|
||||
return <NoAlbumSelected />;
|
||||
}
|
||||
|
||||
const [album] = clientApi.widget.immich.getAlbum.useSuspenseQuery({
|
||||
integrationId: integrationIds[0] ?? "",
|
||||
albumId: options.albumId,
|
||||
});
|
||||
|
||||
if (album.assets.length === 0) {
|
||||
return <NoPhotosInAlbum />;
|
||||
}
|
||||
|
||||
const photoAssets = album.assets.filter((asset) => asset.type === "IMAGE");
|
||||
|
||||
if (photoAssets.length === 0) {
|
||||
return <NoPhotosInAlbum />;
|
||||
}
|
||||
|
||||
return (
|
||||
<Carousel
|
||||
assets={photoAssets}
|
||||
currentIndex={currentPhotoIndex}
|
||||
setCurrentIndex={setCurrentPhotoIndex}
|
||||
rotationInterval={options.rotationIntervalSeconds}
|
||||
showPhotoInfo={options.showPhotoInfo}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
interface CarouselProps {
|
||||
assets: {
|
||||
id: string;
|
||||
deviceAssetId: string;
|
||||
originalPath: string;
|
||||
fileModifiedAt: string;
|
||||
publicLink: string;
|
||||
}[];
|
||||
currentIndex: number;
|
||||
setCurrentIndex: Dispatch<SetStateAction<number>>;
|
||||
rotationInterval: number;
|
||||
showPhotoInfo: boolean;
|
||||
}
|
||||
|
||||
function Carousel({ assets, currentIndex, setCurrentIndex, rotationInterval, showPhotoInfo }: CarouselProps) {
|
||||
useEffect(() => {
|
||||
const interval = setInterval(() => {
|
||||
setCurrentIndex((prev) => (prev + 1) % assets.length);
|
||||
}, rotationInterval * 1000);
|
||||
|
||||
return () => clearInterval(interval);
|
||||
}, [assets.length, rotationInterval, setCurrentIndex]);
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const currentAsset = assets[currentIndex]!;
|
||||
|
||||
return (
|
||||
<Box w="100%" h="100%" className={classes.carouselContainer}>
|
||||
<Image src={currentAsset.publicLink} alt="Album photo" className={classes.carouselImage} />
|
||||
|
||||
{showPhotoInfo && (
|
||||
<Stack gap="xs" className={classes.photoInfo} p="md">
|
||||
<Group gap="xs">
|
||||
<IconCalendar size={16} />
|
||||
<Text size="xs">{new Date(currentAsset.fileModifiedAt).toLocaleDateString()}</Text>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
{currentIndex + 1} / {assets.length}
|
||||
</Text>
|
||||
</Stack>
|
||||
)}
|
||||
</Box>
|
||||
);
|
||||
}
|
||||
|
||||
function NoAlbumSelected() {
|
||||
const t = useI18n();
|
||||
return (
|
||||
<Center h="100%">
|
||||
<Stack align="center" gap="xs">
|
||||
<IconAlertCircle size={32} />
|
||||
<Text size="sm" fw={500}>
|
||||
{t("widget.immich-albumCarousel.noAlbumSelected")}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Center>
|
||||
);
|
||||
}
|
||||
|
||||
function NoPhotosInAlbum() {
|
||||
const t = useI18n();
|
||||
return (
|
||||
<Center h="100%">
|
||||
<Stack align="center" gap="xs">
|
||||
<IconAlertCircle size={32} />
|
||||
<Text size="sm" fw={500}>
|
||||
{t("widget.immich-albumCarousel.noPhotos")}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Center>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
import { IconPhoto } from "@tabler/icons-react";
|
||||
import z from "zod";
|
||||
|
||||
import { createWidgetDefinition } from "../../definition";
|
||||
import { optionsBuilder } from "../../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("immich-albumCarousel", {
|
||||
icon: IconPhoto,
|
||||
supportedIntegrations: ["immich"],
|
||||
integrationsRequired: true,
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
albumId: factory.text({
|
||||
defaultValue: "",
|
||||
withDescription: true,
|
||||
}),
|
||||
rotationIntervalSeconds: factory.number({
|
||||
defaultValue: 5,
|
||||
validate: z.number().min(1).max(3600),
|
||||
withDescription: true,
|
||||
}),
|
||||
showPhotoInfo: factory.switch({
|
||||
defaultValue: false,
|
||||
withDescription: true,
|
||||
}),
|
||||
}));
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -0,0 +1,20 @@
|
||||
.statItem {
|
||||
padding: 12px;
|
||||
border-radius: var(--mantine-radius-md);
|
||||
background-color: var(--mantine-color-gray-0);
|
||||
transition: all 0.2s ease;
|
||||
|
||||
&:hover {
|
||||
background-color: var(--mantine-color-gray-1);
|
||||
}
|
||||
}
|
||||
|
||||
@media (prefers-color-scheme: dark) {
|
||||
.statItem {
|
||||
background-color: var(--mantine-color-dark-6);
|
||||
|
||||
&:hover {
|
||||
background-color: var(--mantine-color-dark-5);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
"use client";
|
||||
|
||||
import React from "react";
|
||||
import { Group, Stack, Text } from "@mantine/core";
|
||||
import { IconDatabase, IconPhoto, IconUsers, IconVideo } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { humanFileSize } from "@homarr/common";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../../definition";
|
||||
import classes from "./component.module.css";
|
||||
|
||||
export default function ImmichServerStatsWidget({
|
||||
integrationIds,
|
||||
options,
|
||||
}: WidgetComponentProps<"immich-serverStats">) {
|
||||
const t = useI18n();
|
||||
const [stats] = clientApi.widget.immich.getServerStats.useSuspenseQuery({
|
||||
integrationId: integrationIds[0] ?? "",
|
||||
});
|
||||
|
||||
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={humanFileSize(stats.totalLibraryUsageInBytes)}
|
||||
/>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
interface StatItemProps {
|
||||
icon: React.ReactNode;
|
||||
label: string;
|
||||
value: string | number;
|
||||
}
|
||||
|
||||
function StatItem({ icon, label, value }: StatItemProps) {
|
||||
return (
|
||||
<Group justify="space-between" align="center" className={classes.statItem}>
|
||||
<Group gap="sm" align="center">
|
||||
{icon}
|
||||
<Text size="sm" fw={500}>
|
||||
{label}
|
||||
</Text>
|
||||
</Group>
|
||||
<Text size="sm" fw={700} c="var(--mantine-primary-color)">
|
||||
{value}
|
||||
</Text>
|
||||
</Group>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
import { IconGraphFilled } from "@tabler/icons-react";
|
||||
|
||||
import { createWidgetDefinition } from "../../definition";
|
||||
import { optionsBuilder } from "../../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("immich-serverStats", {
|
||||
icon: IconGraphFilled,
|
||||
supportedIntegrations: ["immich"],
|
||||
integrationsRequired: true,
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
showUsers: factory.switch({
|
||||
defaultValue: true,
|
||||
withDescription: true,
|
||||
}),
|
||||
showPhotos: factory.switch({
|
||||
defaultValue: true,
|
||||
withDescription: true,
|
||||
}),
|
||||
showVideos: factory.switch({
|
||||
defaultValue: true,
|
||||
withDescription: true,
|
||||
}),
|
||||
showStorage: factory.switch({
|
||||
defaultValue: true,
|
||||
withDescription: true,
|
||||
}),
|
||||
}));
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -7,10 +7,12 @@ import { objectEntries } from "@homarr/common";
|
||||
import type { IntegrationKind, WidgetKind } from "@homarr/definitions";
|
||||
import type { SettingsContextProps } from "@homarr/settings/creator";
|
||||
|
||||
import * as anchorNote from "./anchor-note";
|
||||
import * as app from "./app";
|
||||
import * as bookmarks from "./bookmarks";
|
||||
import * as calendar from "./calendar";
|
||||
import * as clock from "./clock";
|
||||
import * as coolify from "./coolify";
|
||||
import type { WidgetComponentProps } from "./definition";
|
||||
import * as dnsHoleControls from "./dns-hole/controls";
|
||||
import * as dnsHoleSummary from "./dns-hole/summary";
|
||||
@@ -19,6 +21,8 @@ import * as downloads from "./downloads";
|
||||
import * as firewall from "./firewall";
|
||||
import * as healthMonitoring from "./health-monitoring";
|
||||
import * as iframe from "./iframe";
|
||||
import * as immichAlbumCarousel from "./immich/album-carousel";
|
||||
import * as immichServerStats from "./immich/server-stats";
|
||||
import type { WidgetImportRecord } from "./import";
|
||||
import * as indexerManager from "./indexer-manager";
|
||||
import * as mediaReleases from "./media-releases";
|
||||
@@ -36,8 +40,13 @@ import * as releases from "./releases";
|
||||
import * as rssFeed from "./rssFeed";
|
||||
import * as smartHomeEntityState from "./smart-home/entity-state";
|
||||
import * as smartHomeExecuteAutomation from "./smart-home/execute-automation";
|
||||
import * as speedtestTracker from "./speedtest-tracker";
|
||||
import * as stockPrice from "./stocks";
|
||||
import * as systemDisks from "./system-disks";
|
||||
import * as systemResources from "./system-resources";
|
||||
import * as timetable from "./timetable";
|
||||
import * as tracearr from "./tracearr";
|
||||
import * as umami from "./umami";
|
||||
import * as video from "./video";
|
||||
import * as weather from "./weather";
|
||||
|
||||
@@ -48,6 +57,7 @@ export const widgetImports = {
|
||||
clock,
|
||||
weather,
|
||||
app,
|
||||
anchorNote,
|
||||
notebook,
|
||||
iframe,
|
||||
video,
|
||||
@@ -75,6 +85,14 @@ export const widgetImports = {
|
||||
notifications,
|
||||
mediaReleases,
|
||||
systemResources,
|
||||
coolify,
|
||||
systemDisks,
|
||||
timetable,
|
||||
"immich-serverStats": immichServerStats,
|
||||
"immich-albumCarousel": immichAlbumCarousel,
|
||||
tracearr,
|
||||
speedtestTracker,
|
||||
umami,
|
||||
} satisfies WidgetImportRecord;
|
||||
|
||||
export type WidgetImports = typeof widgetImports;
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { ZodType } from "zod/v4";
|
||||
|
||||
import type { IntegrationKind } from "@homarr/definitions";
|
||||
|
||||
import type { DynamicSelectOption } from "./_inputs/widget-dynamic-select-input";
|
||||
import type { inferSelectOptionValue, SelectOption } from "./_inputs/widget-select-input";
|
||||
import type { ReleasesRepository } from "./releases/releases-repository";
|
||||
|
||||
@@ -18,6 +19,8 @@ interface TextInput extends CommonInput<string> {
|
||||
validate?: z.ZodType<string>;
|
||||
}
|
||||
|
||||
type AnchorNoteInput = CommonInput<string>;
|
||||
|
||||
interface MultiSelectInput<TOptions extends SelectOption[]> extends CommonInput<
|
||||
inferSelectOptionValue<TOptions[number]>[]
|
||||
> {
|
||||
@@ -47,6 +50,16 @@ interface SelectInput<TOptions extends readonly SelectOption[]> extends CommonIn
|
||||
searchable?: boolean;
|
||||
}
|
||||
|
||||
interface DynamicSelectInput extends CommonInput<DynamicSelectOption | null> {
|
||||
useOptions: (
|
||||
query: string,
|
||||
integrationIds: string[],
|
||||
) => {
|
||||
isPending: boolean;
|
||||
options: DynamicSelectOption[];
|
||||
};
|
||||
}
|
||||
|
||||
interface NumberInput extends CommonInput<number> {
|
||||
validate: z.ZodNumber;
|
||||
step?: number;
|
||||
@@ -75,6 +88,11 @@ const optionsFactory = {
|
||||
withDescription: input?.withDescription ?? false,
|
||||
validate: input?.validate,
|
||||
}),
|
||||
anchorNote: (input?: AnchorNoteInput) => ({
|
||||
type: "anchorNote" as const,
|
||||
defaultValue: input?.defaultValue ?? "",
|
||||
withDescription: input?.withDescription ?? false,
|
||||
}),
|
||||
multiSelect: <const TOptions extends SelectOption[]>(input: MultiSelectInput<TOptions>) => ({
|
||||
type: "multiSelect" as const,
|
||||
defaultValue: input.defaultValue ?? [],
|
||||
@@ -82,6 +100,12 @@ const optionsFactory = {
|
||||
searchable: input.searchable ?? false,
|
||||
withDescription: input.withDescription ?? false,
|
||||
}),
|
||||
dynamicSelect: (input: DynamicSelectInput) => ({
|
||||
type: "dynamicSelect" as const,
|
||||
defaultValue: input.defaultValue ?? null,
|
||||
useOptions: input.useOptions,
|
||||
withDescription: input.withDescription ?? false,
|
||||
}),
|
||||
select: <const TOptions extends SelectOption[]>(input: SelectInput<TOptions>) => ({
|
||||
type: "select" as const,
|
||||
defaultValue: (input.defaultValue ?? input.options[0]) as inferSelectOptionValue<TOptions[number]>,
|
||||
@@ -136,6 +160,21 @@ const optionsFactory = {
|
||||
defaultValue: "",
|
||||
withDescription: false,
|
||||
}),
|
||||
umamiEventName: () => ({
|
||||
type: "umamiEventName" as const,
|
||||
defaultValue: "",
|
||||
withDescription: true,
|
||||
}),
|
||||
umamiEventNames: () => ({
|
||||
type: "umamiEventNames" as const,
|
||||
defaultValue: [] as string[],
|
||||
withDescription: true,
|
||||
}),
|
||||
umamiWebsite: () => ({
|
||||
type: "umamiWebsite" as const,
|
||||
defaultValue: "",
|
||||
withDescription: true,
|
||||
}),
|
||||
sortableItemList: <const TItem, const TOptionValue extends UniqueIdentifier>(
|
||||
input: SortableItemListInput<TItem, TOptionValue>,
|
||||
) => ({
|
||||
|
||||
@@ -52,7 +52,7 @@ export const { definition, componentLoader } = createWidgetDefinition("releases"
|
||||
suffix: z.string().optional(),
|
||||
})
|
||||
.optional(),
|
||||
iconUrl: z.string().url().optional(),
|
||||
iconUrl: z.string().optional(),
|
||||
}),
|
||||
),
|
||||
}),
|
||||
|
||||
@@ -4,29 +4,53 @@ import { Card, Flex, Group, Image, ScrollArea, Stack, Text } from "@mantine/core
|
||||
import { IconClock } from "@tabler/icons-react";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
import type { RouterInputs } from "@homarr/api";
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import classes from "./component.module.scss";
|
||||
|
||||
export default function RssFeed({ options }: WidgetComponentProps<"rssFeed">) {
|
||||
const [feedEntries] = clientApi.widget.rssFeed.getFeeds.useSuspenseQuery(
|
||||
{
|
||||
urls: options.feedUrls,
|
||||
maximumAmountPosts: typeof options.maximumAmountPosts === "number" ? options.maximumAmountPosts : 100,
|
||||
const useLiveFeedEntries = (input: RouterInputs["widget"]["rssFeed"]["getFeeds"]) => {
|
||||
const [feedEntries] = clientApi.widget.rssFeed.getFeeds.useSuspenseQuery(input, {
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
retry: false,
|
||||
});
|
||||
const utils = clientApi.useUtils();
|
||||
|
||||
clientApi.widget.rssFeed.subscribeFeeds.useSubscription(input, {
|
||||
onData(updatedData) {
|
||||
utils.widget.rssFeed.getFeeds.setData(input, (oldData) => {
|
||||
return oldData
|
||||
?.filter((entry) => entry.feedUrl !== updatedData.url)
|
||||
.concat(updatedData.entries)
|
||||
.sort((entryA, entryB) => {
|
||||
return entryA.published && entryB.published
|
||||
? new Date(entryB.published).getTime() - new Date(entryA.published).getTime()
|
||||
: 0;
|
||||
})
|
||||
.slice(0, input.maximumAmountPosts);
|
||||
});
|
||||
},
|
||||
{
|
||||
refetchOnMount: false,
|
||||
refetchOnWindowFocus: false,
|
||||
refetchOnReconnect: false,
|
||||
retry: false,
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
return feedEntries;
|
||||
};
|
||||
|
||||
export default function RssFeed({ options, width }: WidgetComponentProps<"rssFeed">) {
|
||||
const feedEntries = useLiveFeedEntries({
|
||||
urls: options.feedUrls,
|
||||
maximumAmountPosts: typeof options.maximumAmountPosts === "number" ? options.maximumAmountPosts : 100,
|
||||
});
|
||||
|
||||
const board = useRequiredBoard();
|
||||
|
||||
const languageDir = options.enableRtl ? "RTL" : "LTR";
|
||||
|
||||
const isNarrow = width < 128 * 3;
|
||||
|
||||
return (
|
||||
<ScrollArea className="scroll-area-w100" w="100%" p="sm">
|
||||
<Stack w={"100%"} gap="sm">
|
||||
@@ -41,27 +65,33 @@ export default function RssFeed({ options }: WidgetComponentProps<"rssFeed">) {
|
||||
w="100%"
|
||||
p="sm"
|
||||
>
|
||||
{feedEntry.enclosure && (
|
||||
{feedEntry.enclosure !== undefined && (
|
||||
<Image className={classes.backgroundImage} src={feedEntry.enclosure} alt="backdrop" />
|
||||
)}
|
||||
|
||||
<Flex gap="sm" direction="column" w="100%">
|
||||
<Text dir={languageDir} fz="sm" lh="sm" lineClamp={2}>
|
||||
{feedEntry.title}
|
||||
</Text>
|
||||
{!options.hideDescription && feedEntry.description && (
|
||||
<Text
|
||||
className={feedEntry.description}
|
||||
dir={languageDir}
|
||||
c="dimmed"
|
||||
size="sm"
|
||||
lineClamp={options.textLinesClamp}
|
||||
dangerouslySetInnerHTML={{ __html: feedEntry.description }}
|
||||
/>
|
||||
<Group wrap="nowrap">
|
||||
{feedEntry.enclosure !== undefined && options.showPosterImage && !isNarrow && (
|
||||
<Image src={feedEntry.enclosure} alt={feedEntry.title} w={140} h={140} radius="sm" />
|
||||
)}
|
||||
|
||||
{feedEntry.published && <InfoDisplay date={dayjs(feedEntry.published).fromNow()} />}
|
||||
</Flex>
|
||||
<Flex gap="sm" direction="column" w="100%">
|
||||
<Text dir={languageDir} fz="sm" lh="sm" lineClamp={2}>
|
||||
{feedEntry.title}
|
||||
</Text>
|
||||
{!options.hideDescription && feedEntry.description && (
|
||||
<Text
|
||||
className={feedEntry.description}
|
||||
dir={languageDir}
|
||||
c="dimmed"
|
||||
size="sm"
|
||||
lineClamp={options.textLinesClamp}
|
||||
dangerouslySetInnerHTML={{ __html: feedEntry.description }}
|
||||
/>
|
||||
)}
|
||||
|
||||
{feedEntry.published && <InfoDisplay date={dayjs(feedEntry.published).fromNow()} />}
|
||||
</Flex>
|
||||
</Group>
|
||||
</Card>
|
||||
))}
|
||||
</Stack>
|
||||
|
||||
@@ -32,6 +32,9 @@ export const { definition, componentLoader } = createWidgetDefinition("rssFeed",
|
||||
hideDescription: factory.switch({
|
||||
defaultValue: false,
|
||||
}),
|
||||
showPosterImage: factory.switch({
|
||||
defaultValue: false,
|
||||
}),
|
||||
}));
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -76,6 +76,7 @@ export default function SmartHomeEntityStateWidget({
|
||||
|
||||
return (
|
||||
<UnstyledButton
|
||||
mod={{ "entity-state": entityState, "entity-id": options.entityId }}
|
||||
onClick={handleClick}
|
||||
w="100%"
|
||||
h="100%"
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
"use client";
|
||||
|
||||
import { SimpleGrid, Stack } from "@mantine/core";
|
||||
import { IconArrowDown, IconArrowUp, IconWaveSine } from "@tabler/icons-react";
|
||||
|
||||
import type { SpeedtestTrackerStats } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { formatStatsSpeed } from "./helpers";
|
||||
import { SectionLabel } from "./section-label";
|
||||
import { SpeedStatCard } from "./speed-stat-card";
|
||||
|
||||
export function AveragesSection({ stats }: { stats: SpeedtestTrackerStats }) {
|
||||
const t = useScopedI18n("widget.speedtestTracker");
|
||||
|
||||
return (
|
||||
<Stack gap={6} h="100%">
|
||||
<SectionLabel>
|
||||
{t("averages")} · {t("tests", { count: stats.total_results.toString() })}
|
||||
</SectionLabel>
|
||||
<SimpleGrid cols={3} spacing="xs" style={{ flex: 1, gridTemplateRows: "1fr" }}>
|
||||
<SpeedStatCard
|
||||
icon={IconArrowDown}
|
||||
color="blue"
|
||||
value={formatStatsSpeed(stats.download)}
|
||||
label={t("avgDownload")}
|
||||
compact
|
||||
/>
|
||||
<SpeedStatCard
|
||||
icon={IconArrowUp}
|
||||
color="teal"
|
||||
value={formatStatsSpeed(stats.upload)}
|
||||
label={t("avgUpload")}
|
||||
compact
|
||||
/>
|
||||
<SpeedStatCard
|
||||
icon={IconWaveSine}
|
||||
color="orange"
|
||||
value={`${stats.ping.avg.toFixed(1)} ms`}
|
||||
label={t("avgPing")}
|
||||
compact
|
||||
/>
|
||||
</SimpleGrid>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import type { SpeedtestTrackerDashboardData } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { AveragesSection } from "./averages";
|
||||
import { mergeStats } from "./helpers";
|
||||
import { LatestResultSection } from "./latest-result";
|
||||
import { RecentResultsSection } from "./recent-results";
|
||||
|
||||
export default function SpeedtestTrackerWidget({
|
||||
options,
|
||||
integrationIds,
|
||||
isEditMode,
|
||||
}: WidgetComponentProps<"speedtestTracker">) {
|
||||
const t = useScopedI18n("widget.speedtestTracker");
|
||||
const [dashboardData] = clientApi.widget.speedtestTracker.getDashboard.useSuspenseQuery({ integrationIds });
|
||||
|
||||
const utils = clientApi.useUtils();
|
||||
clientApi.widget.speedtestTracker.subscribeToDashboard.useSubscription(
|
||||
{ integrationIds },
|
||||
{
|
||||
enabled: !isEditMode,
|
||||
onData(newData) {
|
||||
utils.widget.speedtestTracker.getDashboard.setData({ integrationIds }, (prevData) => {
|
||||
if (!prevData) return prevData;
|
||||
return prevData.map((instance) =>
|
||||
instance.integrationId === newData.integrationId
|
||||
? { ...instance, dashboard: newData.dashboard, updatedAt: newData.timestamp }
|
||||
: instance,
|
||||
);
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
const combined = useMemo(
|
||||
() =>
|
||||
dashboardData.reduce<SpeedtestTrackerDashboardData>(
|
||||
(acc, item) => ({
|
||||
latestResult: item.dashboard.latestResult ?? acc.latestResult,
|
||||
stats: mergeStats(acc.stats, item.dashboard.stats),
|
||||
recentResults: [...acc.recentResults, ...item.dashboard.recentResults],
|
||||
}),
|
||||
{ latestResult: null, stats: null, recentResults: [] },
|
||||
),
|
||||
[dashboardData],
|
||||
);
|
||||
|
||||
const twelveHoursAgo = Date.now() - 12 * 60 * 60 * 1000;
|
||||
const recentFiltered = combined.recentResults.filter((result) => result.created_at.getTime() > twelveHoursAgo);
|
||||
|
||||
const hasStatSection =
|
||||
(options.showLatestResult && combined.latestResult !== null) || (options.showStats && combined.stats !== null);
|
||||
const hasChart = options.showRecentResults && recentFiltered.length > 0;
|
||||
const noSectionsEnabled = !options.showLatestResult && !options.showStats && !options.showRecentResults;
|
||||
|
||||
return (
|
||||
<Stack h="100%" gap="sm" p="xs" style={{ overflow: "hidden" }}>
|
||||
{hasStatSection && (
|
||||
<Stack gap="sm" style={{ flex: 1, minHeight: 0 }}>
|
||||
{options.showLatestResult && combined.latestResult && (
|
||||
<div style={{ flex: 1, minHeight: 0 }}>
|
||||
<LatestResultSection result={combined.latestResult} />
|
||||
</div>
|
||||
)}
|
||||
{options.showStats && combined.stats && (
|
||||
<div style={{ flex: 1, minHeight: 0 }}>
|
||||
<AveragesSection stats={combined.stats} />
|
||||
</div>
|
||||
)}
|
||||
</Stack>
|
||||
)}
|
||||
{hasChart && (
|
||||
<div style={{ flex: 2, minHeight: 0 }}>
|
||||
<RecentResultsSection results={recentFiltered} showPingGraph={options.showPingGraph} />
|
||||
</div>
|
||||
)}
|
||||
{noSectionsEnabled && (
|
||||
<Text c="dimmed" ta="center" size="sm">
|
||||
{t("noSectionsEnabled")}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
import { formatNumber } from "@homarr/common";
|
||||
import type {
|
||||
SpeedtestTrackerDashboardData,
|
||||
SpeedtestTrackerResult,
|
||||
SpeedtestTrackerStats,
|
||||
} from "@homarr/integrations/types";
|
||||
|
||||
export const mergeStats = (
|
||||
statsA: SpeedtestTrackerDashboardData["stats"],
|
||||
statsB: SpeedtestTrackerDashboardData["stats"],
|
||||
): SpeedtestTrackerDashboardData["stats"] => {
|
||||
if (!statsB) return statsA;
|
||||
if (!statsA) return statsB;
|
||||
return {
|
||||
ping: {
|
||||
avg: (statsA.ping.avg + statsB.ping.avg) / 2,
|
||||
min: Math.min(statsA.ping.min, statsB.ping.min),
|
||||
max: Math.max(statsA.ping.max, statsB.ping.max),
|
||||
},
|
||||
download: {
|
||||
avg: (statsA.download.avg + statsB.download.avg) / 2,
|
||||
avg_bits:
|
||||
statsA.download.avg_bits !== undefined && statsB.download.avg_bits !== undefined
|
||||
? (statsA.download.avg_bits + statsB.download.avg_bits) / 2
|
||||
: (statsA.download.avg_bits ?? statsB.download.avg_bits),
|
||||
min: Math.min(statsA.download.min, statsB.download.min),
|
||||
max: Math.max(statsA.download.max, statsB.download.max),
|
||||
},
|
||||
upload: {
|
||||
avg: (statsA.upload.avg + statsB.upload.avg) / 2,
|
||||
avg_bits:
|
||||
statsA.upload.avg_bits !== undefined && statsB.upload.avg_bits !== undefined
|
||||
? (statsA.upload.avg_bits + statsB.upload.avg_bits) / 2
|
||||
: (statsA.upload.avg_bits ?? statsB.upload.avg_bits),
|
||||
min: Math.min(statsA.upload.min, statsB.upload.min),
|
||||
max: Math.max(statsA.upload.max, statsB.upload.max),
|
||||
},
|
||||
total_results: statsA.total_results + statsB.total_results,
|
||||
};
|
||||
};
|
||||
|
||||
export const formatBitsPerSec = (bps: number): string => `${formatNumber(bps, 2)}bps`;
|
||||
|
||||
export const formatResultSpeed = (result: SpeedtestTrackerResult, dir: "download" | "upload"): string => {
|
||||
const bits = dir === "download" ? result.download_bits : result.upload_bits;
|
||||
if (bits != null) return formatBitsPerSec(bits);
|
||||
return "—";
|
||||
};
|
||||
|
||||
export const formatStatsSpeed = (band: SpeedtestTrackerStats["download"]): string => {
|
||||
if (band.avg_bits != null) return formatBitsPerSec(band.avg_bits);
|
||||
return formatBitsPerSec(band.avg * 8);
|
||||
};
|
||||
@@ -0,0 +1,38 @@
|
||||
import { IconServerOff, IconSpeedboat } from "@tabler/icons-react";
|
||||
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("speedtestTracker", {
|
||||
icon: IconSpeedboat,
|
||||
createOptions() {
|
||||
return optionsBuilder.from(
|
||||
(factory) => ({
|
||||
showLatestResult: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
showStats: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
showRecentResults: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
showPingGraph: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
}),
|
||||
{
|
||||
showPingGraph: {
|
||||
shouldHide: (options) => !options.showRecentResults,
|
||||
},
|
||||
},
|
||||
);
|
||||
},
|
||||
supportedIntegrations: ["speedtestTracker"],
|
||||
errors: {
|
||||
INTERNAL_SERVER_ERROR: {
|
||||
icon: IconServerOff,
|
||||
message: (t) => t("widget.speedtestTracker.error.internalServerError"),
|
||||
},
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -0,0 +1,62 @@
|
||||
"use client";
|
||||
|
||||
import { Group, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import { IconArrowDown, IconArrowUp, IconCircleCheck, IconCircleX, IconWaveSine } from "@tabler/icons-react";
|
||||
|
||||
import type { SpeedtestTrackerResult } from "@homarr/integrations/types";
|
||||
import { useCurrentLocale, useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { formatResultSpeed } from "./helpers";
|
||||
import { SectionLabel } from "./section-label";
|
||||
import { SpeedStatCard } from "./speed-stat-card";
|
||||
|
||||
export function LatestResultSection({ result }: { result: SpeedtestTrackerResult }) {
|
||||
const t = useScopedI18n("widget.speedtestTracker");
|
||||
const locale = useCurrentLocale();
|
||||
const timestamp = Intl.DateTimeFormat(locale, {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
}).format(result.created_at);
|
||||
const cols = result.healthy !== null ? 4 : 3;
|
||||
|
||||
return (
|
||||
<Stack gap={6} h="100%">
|
||||
<Group justify="space-between" align="center" wrap="nowrap">
|
||||
<SectionLabel>{t("latestResult")}</SectionLabel>
|
||||
<Text size="xs" c="dimmed">
|
||||
{timestamp}
|
||||
</Text>
|
||||
</Group>
|
||||
<SimpleGrid cols={cols} spacing="xs" style={{ flex: 1, gridTemplateRows: "1fr" }}>
|
||||
<SpeedStatCard
|
||||
icon={IconArrowDown}
|
||||
color="blue"
|
||||
value={formatResultSpeed(result, "download")}
|
||||
label={t("download")}
|
||||
/>
|
||||
<SpeedStatCard
|
||||
icon={IconArrowUp}
|
||||
color="teal"
|
||||
value={formatResultSpeed(result, "upload")}
|
||||
label={t("upload")}
|
||||
/>
|
||||
<SpeedStatCard
|
||||
icon={IconWaveSine}
|
||||
color="orange"
|
||||
value={result.ping !== null ? `${result.ping.toFixed(1)} ms` : "—"}
|
||||
label={t("ping")}
|
||||
/>
|
||||
{result.healthy !== null && (
|
||||
<SpeedStatCard
|
||||
icon={result.healthy ? IconCircleCheck : IconCircleX}
|
||||
color={result.healthy ? "green" : "red"}
|
||||
value={result.healthy ? t("healthy") : t("unhealthy")}
|
||||
label={t("status")}
|
||||
/>
|
||||
)}
|
||||
</SimpleGrid>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,364 @@
|
||||
"use client";
|
||||
|
||||
import { useMemo } from "react";
|
||||
import { AreaChart, ChartTooltip } from "@mantine/charts";
|
||||
import { Stack, useMantineTheme } from "@mantine/core";
|
||||
import { useElementSize } from "@mantine/hooks";
|
||||
import { ReferenceLine, XAxis } from "recharts";
|
||||
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import type { SpeedtestTrackerResult } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { SectionLabel } from "./section-label";
|
||||
|
||||
interface XAxisTicks {
|
||||
midnightTs: number | null;
|
||||
xTicks: number[];
|
||||
topDateTicks: number[];
|
||||
}
|
||||
|
||||
function buildXAxisTicks(data: { ts: number }[]): XAxisTicks {
|
||||
if (data.length === 0) return { midnightTs: null, xTicks: [], topDateTicks: [] };
|
||||
|
||||
const first = data[0]?.ts ?? 0;
|
||||
const last = data.at(-1)?.ts ?? 0;
|
||||
|
||||
const twoHourMs = 2 * 60 * 60 * 1000;
|
||||
const startTick = Math.ceil(first / twoHourMs) * twoHourMs;
|
||||
const tickSet = new Set<number>();
|
||||
for (let t = startTick; t <= last; t += twoHourMs) tickSet.add(t);
|
||||
|
||||
const midnightDate = new Date(first);
|
||||
midnightDate.setHours(24, 0, 0, 0);
|
||||
const mTs = midnightDate.getTime();
|
||||
const foundMidnight = mTs > first && mTs < last ? mTs : null;
|
||||
if (foundMidnight) tickSet.add(foundMidnight);
|
||||
|
||||
const topTicks: number[] = [first];
|
||||
if (foundMidnight) topTicks.push(foundMidnight);
|
||||
|
||||
return {
|
||||
midnightTs: foundMidnight,
|
||||
xTicks: Array.from(tickSet).sort((tsA, tsB) => tsA - tsB),
|
||||
topDateTicks: topTicks,
|
||||
};
|
||||
}
|
||||
|
||||
function makeXTickRenderer(midnightTs: number | null) {
|
||||
return ({ x, y, payload }: { x: number | string; y: number | string; payload: { value: number } }) => {
|
||||
const date = new Date(payload.value);
|
||||
const timeStr = date.toLocaleTimeString([], { hour: "2-digit", minute: "2-digit" });
|
||||
const isMidnight = midnightTs !== null && payload.value === midnightTs;
|
||||
const dateStr = isMidnight ? date.toLocaleDateString([], { month: "short", day: "numeric" }) : null;
|
||||
|
||||
return (
|
||||
<g transform={`translate(${x},${y})`}>
|
||||
<text x={0} y={12} textAnchor="middle" fontSize={10} fill="var(--mantine-color-dimmed)">
|
||||
{timeStr}
|
||||
</text>
|
||||
{dateStr && (
|
||||
<text x={0} y={23} textAnchor="middle" fontSize={9} fill="var(--mantine-color-dimmed)">
|
||||
{dateStr}
|
||||
</text>
|
||||
)}
|
||||
</g>
|
||||
);
|
||||
};
|
||||
}
|
||||
|
||||
function renderTopDateTick(props: {
|
||||
x: number | string;
|
||||
y: number | string;
|
||||
payload: { value: number };
|
||||
index: number;
|
||||
}) {
|
||||
const { x, y, payload, index } = props;
|
||||
const date = new Date(payload.value);
|
||||
const dateStr = date.toLocaleDateString([], { weekday: "short", month: "short", day: "numeric" });
|
||||
const anchor = index === 0 ? "start" : "middle";
|
||||
return (
|
||||
<g transform={`translate(${x},${y})`}>
|
||||
<text x={0} y={-4} textAnchor={anchor} fontSize={10} fill="var(--mantine-color-dimmed)">
|
||||
{dateStr}
|
||||
</text>
|
||||
</g>
|
||||
);
|
||||
}
|
||||
|
||||
function buildYAxisConfig(maxVal: number, stepOptions: { threshold: number; step: number }[]) {
|
||||
const step = (stepOptions.find((opt) => maxVal <= opt.threshold) ?? stepOptions.at(-1))?.step ?? 1;
|
||||
const roundedMax = Math.ceil(maxVal / step) * step || step;
|
||||
const ticks: number[] = [];
|
||||
for (let val = 0; val <= roundedMax; val += step) ticks.push(val);
|
||||
return { ticks, domain: [0, roundedMax] as [number, number] };
|
||||
}
|
||||
|
||||
function formatTooltipDate(label: number | string | undefined): string {
|
||||
const timestamp = typeof label === "number" ? label : Number(label);
|
||||
if (Number.isNaN(timestamp)) return "";
|
||||
return new Date(timestamp).toLocaleString([], {
|
||||
month: "short",
|
||||
day: "numeric",
|
||||
hour: "2-digit",
|
||||
minute: "2-digit",
|
||||
});
|
||||
}
|
||||
|
||||
export function RecentResultsSection({
|
||||
results,
|
||||
showPingGraph,
|
||||
}: {
|
||||
results: SpeedtestTrackerResult[];
|
||||
showPingGraph: boolean;
|
||||
}) {
|
||||
const t = useScopedI18n("widget.speedtestTracker");
|
||||
|
||||
return (
|
||||
<Stack gap={4} h="100%" style={{ minHeight: 0 }}>
|
||||
<SectionLabel>{t("recentResults")}</SectionLabel>
|
||||
<div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column", gap: 4 }}>
|
||||
<SpeedSubChart results={results} showLabel={showPingGraph} />
|
||||
{showPingGraph && <PingSubChart results={results} />}
|
||||
</div>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function SpeedSubChart({ results, showLabel }: { results: SpeedtestTrackerResult[]; showLabel: boolean }) {
|
||||
const t = useScopedI18n("widget.speedtestTracker");
|
||||
const { ref, height } = useElementSize<HTMLDivElement>();
|
||||
|
||||
return (
|
||||
<div style={{ flex: 2, minHeight: 0, display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
{showLabel && <SectionLabel>{t("recentResultsSpeed")}</SectionLabel>}
|
||||
<div ref={ref} style={{ flex: 1, minHeight: 0 }}>
|
||||
{height > 0 && <SpeedHistoryChart results={results} height={height} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function PingSubChart({ results }: { results: SpeedtestTrackerResult[] }) {
|
||||
const t = useScopedI18n("widget.speedtestTracker");
|
||||
const { ref, height } = useElementSize<HTMLDivElement>();
|
||||
|
||||
return (
|
||||
<div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column", gap: 2 }}>
|
||||
<SectionLabel>{t("recentResultsPing")}</SectionLabel>
|
||||
<div ref={ref} style={{ flex: 1, minHeight: 0 }}>
|
||||
{height > 0 && <PingHistoryChart results={results} height={height} />}
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
||||
function SpeedHistoryChart({ results, height }: { results: SpeedtestTrackerResult[]; height: number }) {
|
||||
const board = useRequiredBoard();
|
||||
const theme = useMantineTheme();
|
||||
const t = useScopedI18n("widget.speedtestTracker");
|
||||
|
||||
const data = useMemo(
|
||||
() =>
|
||||
[...results]
|
||||
.sort((resultA, resultB) => resultA.created_at.getTime() - resultB.created_at.getTime())
|
||||
.filter((result) => (result.download_bits ?? 0) > 0)
|
||||
.map((result) => ({
|
||||
ts: result.created_at.getTime(),
|
||||
Download: parseFloat(((result.download_bits ?? 0) / 1_000_000).toFixed(2)),
|
||||
Upload:
|
||||
result.upload_bits != null && result.upload_bits > 0
|
||||
? parseFloat((result.upload_bits / 1_000_000).toFixed(2))
|
||||
: 0,
|
||||
})),
|
||||
[results],
|
||||
);
|
||||
|
||||
const yConfig = useMemo(
|
||||
() =>
|
||||
buildYAxisConfig(Math.max(...data.map((item) => Math.max(item.Download, item.Upload)), 0), [
|
||||
{ threshold: 400, step: 100 },
|
||||
{ threshold: Infinity, step: 200 },
|
||||
]),
|
||||
[data],
|
||||
);
|
||||
|
||||
const { midnightTs, xTicks, topDateTicks } = useMemo(() => buildXAxisTicks(data), [data]);
|
||||
const renderXTick = useMemo(() => makeXTickRenderer(midnightTs), [midnightTs]);
|
||||
|
||||
if (data.length === 0) return null;
|
||||
|
||||
return (
|
||||
<AreaChart
|
||||
h={height}
|
||||
data={data}
|
||||
dataKey="ts"
|
||||
series={[
|
||||
{ name: "Download", label: t("download"), color: "blue" },
|
||||
{ name: "Upload", label: t("upload"), color: "teal" },
|
||||
]}
|
||||
curveType="monotone"
|
||||
gridAxis="y"
|
||||
tickLine="none"
|
||||
withLegend
|
||||
fillOpacity={0.2}
|
||||
styles={{ root: { padding: 5, borderRadius: theme.radius[board.itemRadius] } }}
|
||||
valueFormatter={(val: number) => `${val} Mbps`}
|
||||
xAxisProps={{
|
||||
type: "number",
|
||||
domain: ["dataMin", "dataMax"],
|
||||
ticks: xTicks,
|
||||
tick: renderXTick,
|
||||
interval: 0,
|
||||
height: midnightTs !== null ? 38 : 28,
|
||||
}}
|
||||
yAxisProps={{
|
||||
ticks: yConfig.ticks,
|
||||
domain: yConfig.domain,
|
||||
tickFormatter: (val: number) => `${val}`,
|
||||
width: 50,
|
||||
tick: { fontSize: 10 },
|
||||
}}
|
||||
tooltipProps={{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
content: (props: any) => {
|
||||
const { label, payload, active } = props as {
|
||||
label?: number | string;
|
||||
payload?: Record<string, unknown>[];
|
||||
active?: boolean;
|
||||
};
|
||||
if (!active || !payload?.length) return null;
|
||||
return (
|
||||
<ChartTooltip
|
||||
label={formatTooltipDate(label)}
|
||||
payload={payload}
|
||||
valueFormatter={(val: number) => `${val} Mbps`}
|
||||
/>
|
||||
);
|
||||
},
|
||||
}}
|
||||
>
|
||||
<XAxis
|
||||
xAxisId="topDates"
|
||||
orientation="top"
|
||||
type="number"
|
||||
dataKey="ts"
|
||||
domain={["dataMin", "dataMax"]}
|
||||
ticks={topDateTicks}
|
||||
tick={renderTopDateTick}
|
||||
height={20}
|
||||
axisLine={false}
|
||||
tickLine={false}
|
||||
interval={0}
|
||||
/>
|
||||
{xTicks.map((tickTs) => (
|
||||
<ReferenceLine
|
||||
key={tickTs}
|
||||
x={tickTs}
|
||||
yAxisId="left"
|
||||
stroke="var(--mantine-color-dimmed)"
|
||||
strokeDasharray="3 3"
|
||||
strokeOpacity={0.35}
|
||||
/>
|
||||
))}
|
||||
</AreaChart>
|
||||
);
|
||||
}
|
||||
|
||||
function PingHistoryChart({ results, height }: { results: SpeedtestTrackerResult[]; height: number }) {
|
||||
const board = useRequiredBoard();
|
||||
const theme = useMantineTheme();
|
||||
const t = useScopedI18n("widget.speedtestTracker");
|
||||
|
||||
const data = useMemo(
|
||||
() =>
|
||||
[...results]
|
||||
.sort((resultA, resultB) => resultA.created_at.getTime() - resultB.created_at.getTime())
|
||||
.map((result) =>
|
||||
result.ping === null
|
||||
? null
|
||||
: {
|
||||
ts: result.created_at.getTime(),
|
||||
Ping: result.ping,
|
||||
},
|
||||
)
|
||||
.filter((result) => result !== null),
|
||||
[results],
|
||||
);
|
||||
|
||||
const yConfig = useMemo(
|
||||
() =>
|
||||
buildYAxisConfig(Math.max(...data.map((item) => item.Ping), 0), [
|
||||
{ threshold: 10, step: 2 },
|
||||
{ threshold: 50, step: 10 },
|
||||
{ threshold: 200, step: 50 },
|
||||
{ threshold: Infinity, step: 100 },
|
||||
]),
|
||||
[data],
|
||||
);
|
||||
|
||||
const { midnightTs, xTicks } = useMemo(() => buildXAxisTicks(data), [data]);
|
||||
const renderXTick = useMemo(() => makeXTickRenderer(midnightTs), [midnightTs]);
|
||||
|
||||
if (data.length === 0) return null;
|
||||
|
||||
return (
|
||||
<AreaChart
|
||||
h={height}
|
||||
data={data}
|
||||
dataKey="ts"
|
||||
series={[{ name: "Ping", label: t("ping"), color: "orange" }]}
|
||||
curveType="monotone"
|
||||
gridAxis="y"
|
||||
tickLine="none"
|
||||
withLegend={false}
|
||||
fillOpacity={0.2}
|
||||
styles={{ root: { padding: 5, borderRadius: theme.radius[board.itemRadius] } }}
|
||||
valueFormatter={(val: number) => `${val} ms`}
|
||||
xAxisProps={{
|
||||
type: "number",
|
||||
domain: ["dataMin", "dataMax"],
|
||||
ticks: xTicks,
|
||||
tick: renderXTick,
|
||||
interval: 0,
|
||||
height: midnightTs !== null ? 38 : 28,
|
||||
}}
|
||||
yAxisProps={{
|
||||
ticks: yConfig.ticks,
|
||||
domain: yConfig.domain,
|
||||
tickFormatter: (val: number) => `${val}`,
|
||||
width: 50,
|
||||
tick: { fontSize: 10 },
|
||||
}}
|
||||
tooltipProps={{
|
||||
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||
content: (props: any) => {
|
||||
const { label, payload, active } = props as {
|
||||
label?: number | string;
|
||||
payload?: Record<string, unknown>[];
|
||||
active?: boolean;
|
||||
};
|
||||
if (!active || !payload?.length) return null;
|
||||
return (
|
||||
<ChartTooltip
|
||||
label={formatTooltipDate(label)}
|
||||
payload={payload}
|
||||
valueFormatter={(val: number) => `${val} ms`}
|
||||
/>
|
||||
);
|
||||
},
|
||||
}}
|
||||
>
|
||||
{xTicks.map((tickTs) => (
|
||||
<ReferenceLine
|
||||
key={tickTs}
|
||||
x={tickTs}
|
||||
yAxisId="left"
|
||||
stroke="var(--mantine-color-dimmed)"
|
||||
strokeDasharray="3 3"
|
||||
strokeOpacity={0.35}
|
||||
/>
|
||||
))}
|
||||
</AreaChart>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
import type { ReactNode } from "react";
|
||||
import { Text } from "@mantine/core";
|
||||
|
||||
export function SectionLabel({ children }: { children: ReactNode }) {
|
||||
return (
|
||||
<Text size="xs" fw={600} c="dimmed" tt="uppercase" style={{ letterSpacing: "0.05em" }}>
|
||||
{children}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,54 @@
|
||||
"use client";
|
||||
|
||||
import { Card, Flex, Text } from "@mantine/core";
|
||||
import { useElementSize } from "@mantine/hooks";
|
||||
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import type { TablerIcon } from "@homarr/ui";
|
||||
|
||||
export interface SpeedStatCardProps {
|
||||
icon: TablerIcon;
|
||||
color: string;
|
||||
value: string;
|
||||
label: string;
|
||||
compact?: boolean;
|
||||
}
|
||||
|
||||
export function SpeedStatCard({ icon: Icon, color, value, label, compact = false }: SpeedStatCardProps) {
|
||||
const { ref, height, width } = useElementSize<HTMLDivElement>();
|
||||
const board = useRequiredBoard();
|
||||
const isWide = width > height + 20;
|
||||
const hideLabel = height > 0 && height <= 38;
|
||||
|
||||
return (
|
||||
<Card
|
||||
ref={ref}
|
||||
p={compact ? "xs" : "sm"}
|
||||
radius={board.itemRadius}
|
||||
bg={`var(--mantine-color-${color}-light)`}
|
||||
h="100%"
|
||||
style={{ flex: 1 }}
|
||||
>
|
||||
<Flex
|
||||
h="100%"
|
||||
w="100%"
|
||||
align="center"
|
||||
justify="center"
|
||||
direction={isWide ? "row" : "column"}
|
||||
gap={isWide ? 8 : 4}
|
||||
>
|
||||
<Icon size={compact ? 16 : 20} color={`var(--mantine-color-${color}-5)`} style={{ flexShrink: 0 }} />
|
||||
<Flex direction="column" align={isWide ? "flex-start" : "center"} gap={0}>
|
||||
<Text size={compact ? "sm" : "md"} fw={700} ta="center" lh={1.1}>
|
||||
{value}
|
||||
</Text>
|
||||
{!hideLabel && (
|
||||
<Text size="xs" c="dimmed" ta="center" lh={1.3}>
|
||||
{label}
|
||||
</Text>
|
||||
)}
|
||||
</Flex>
|
||||
</Flex>
|
||||
</Card>
|
||||
);
|
||||
}
|
||||
@@ -33,6 +33,7 @@ export default function StockPriceWidget({ options, width, height }: WidgetCompo
|
||||
|
||||
const stockValuesMin = Math.min(...data.priceHistory);
|
||||
const stockGraphValues = data.priceHistory.map((value) => value - stockValuesMin + 50);
|
||||
const trendColor = stockValuesChange > 0 ? "green.7" : stockValuesChange < 0 ? "red.7" : "gray.6";
|
||||
|
||||
return (
|
||||
<Flex h="100%" w="100%">
|
||||
@@ -43,7 +44,7 @@ export default function StockPriceWidget({ options, width, height }: WidgetCompo
|
||||
h={height > 280 ? "75%" : "50%"}
|
||||
data={stockGraphValues}
|
||||
curveType="linear"
|
||||
trendColors={{ positive: "green.7", negative: "red.7", neutral: "gray.6" }}
|
||||
color={trendColor}
|
||||
fillOpacity={0.6}
|
||||
strokeWidth={2.5}
|
||||
/>
|
||||
|
||||
@@ -0,0 +1,106 @@
|
||||
"use client";
|
||||
|
||||
import { Box, Card, Group, Stack, useMantineColorScheme } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useRequiredBoard } from "@homarr/boards/context";
|
||||
import { humanFileSize } from "@homarr/common";
|
||||
import { useI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { NoIntegrationDataError } from "../errors/no-data-integration";
|
||||
|
||||
type DisplayMode = WidgetComponentProps<"systemDisks">["options"]["displayMode"];
|
||||
|
||||
const getDisplayText = (item: { used: string; available: string; percentage: number }, displayMode: DisplayMode) => {
|
||||
switch (displayMode) {
|
||||
case "percentage":
|
||||
return `${Math.round(item.percentage)}%`;
|
||||
case "absolute": {
|
||||
const availableInBytes = Number(item.available);
|
||||
const availableText = Number.isFinite(availableInBytes)
|
||||
? humanFileSize(Math.round(availableInBytes))
|
||||
: item.available;
|
||||
return `${item.used} / ${availableText}`;
|
||||
}
|
||||
case "free":
|
||||
return `${Math.round(100 - item.percentage)}% free`;
|
||||
default:
|
||||
return `${Math.round(item.percentage)}%`;
|
||||
}
|
||||
};
|
||||
|
||||
export default function SystemResources({ integrationIds, options }: WidgetComponentProps<"systemDisks">) {
|
||||
const queryInput = { integrationIds };
|
||||
const [data] = clientApi.widget.healthMonitoring.getSystemHealthStatus.useSuspenseQuery(queryInput);
|
||||
const utils = clientApi.useUtils();
|
||||
|
||||
const board = useRequiredBoard();
|
||||
const scheme = useMantineColorScheme();
|
||||
const t = useI18n();
|
||||
|
||||
const lastItem = data.at(-1);
|
||||
|
||||
if (!lastItem) return null;
|
||||
const { fileSystem, smart } = lastItem.healthInfo;
|
||||
|
||||
clientApi.widget.healthMonitoring.subscribeSystemHealthStatus.useSubscription(queryInput, {
|
||||
onData(data) {
|
||||
utils.widget.healthMonitoring.getSystemHealthStatus.setData(queryInput, (oldData) =>
|
||||
oldData?.map((item) => (item.integrationId === data.integrationId ? { ...item, ...data } : item)),
|
||||
);
|
||||
},
|
||||
});
|
||||
|
||||
if (fileSystem.length === 0) {
|
||||
throw new NoIntegrationDataError();
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap="xs" p="xs" h="100%">
|
||||
{fileSystem.map((item) => {
|
||||
const smartItem = smart.find((smart) => smart.deviceName === item.deviceName);
|
||||
const healthy = smartItem?.healthy ?? true; // fall back to healthy if no information is available
|
||||
|
||||
return (
|
||||
<Card
|
||||
radius={board.itemRadius}
|
||||
py={"xs"}
|
||||
bg={scheme.colorScheme === "dark" ? "dark.7" : "gray.1"}
|
||||
key={`disk-${item.deviceName}`}
|
||||
style={{ overflow: "hidden", position: "relative" }}
|
||||
>
|
||||
<Group justify="space-between" style={{ zIndex: 1 }}>
|
||||
<div>
|
||||
<p style={{ margin: 0 }}>
|
||||
<b>{item.deviceName}</b>
|
||||
</p>
|
||||
<p style={{ margin: 0 }}>
|
||||
<span>{getDisplayText(item, options.displayMode)}</span>
|
||||
{!healthy && <span style={{ marginLeft: 5 }}>{t("widget.systemDisks.status.unhealthy")}</span>}
|
||||
</p>
|
||||
</div>
|
||||
<div>
|
||||
{smartItem?.temperature && options.showTemperatureIfAvailable ? (
|
||||
<p style={{ margin: 0 }}>{smartItem.temperature}°C</p>
|
||||
) : null}
|
||||
</div>
|
||||
</Group>
|
||||
<Box
|
||||
bg={healthy ? "green" : "red"}
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
left: 0,
|
||||
width: `${item.percentage}%`,
|
||||
height: "100%",
|
||||
zIndex: 0,
|
||||
display: options.showBackgroundBar ? "block" : "none",
|
||||
}}
|
||||
></Box>
|
||||
</Card>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
import { IconServer2 } from "@tabler/icons-react";
|
||||
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("systemDisks", {
|
||||
icon: IconServer2,
|
||||
supportedIntegrations: ["dashDot", "openmediavault", "truenas", "unraid"],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
showTemperatureIfAvailable: factory.switch({ defaultValue: true }),
|
||||
displayMode: factory.select({
|
||||
options: (["percentage", "absolute", "free"] as const).map((value) => ({
|
||||
value,
|
||||
label: (t) => t(`widget.systemDisks.option.displayMode.option.${value}.label`),
|
||||
})),
|
||||
defaultValue: "percentage",
|
||||
}),
|
||||
showBackgroundBar: factory.switch({ defaultValue: true }),
|
||||
}));
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -37,9 +37,6 @@ export const CombinedNetworkTrafficChart = ({
|
||||
labelDisplayMode={labelDisplayMode}
|
||||
tooltipProps={{
|
||||
content: ({ payload }) => {
|
||||
if (!payload) {
|
||||
return null;
|
||||
}
|
||||
return (
|
||||
<Paper px={3} py={2} withBorder shadow="md" radius="md">
|
||||
<Stack gap={0}>
|
||||
@@ -50,7 +47,7 @@ export const CombinedNetworkTrafficChart = ({
|
||||
{payloadData.value === undefined ? (
|
||||
<>N/A</>
|
||||
) : (
|
||||
<>{humanFileSize(Math.round(payloadData.value))}/s</>
|
||||
<>{humanFileSize(Math.round(Number(payloadData.value)))}/s</>
|
||||
)}
|
||||
</Text>
|
||||
</Group>
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
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 { Card, Center, Group, Loader, Stack, Text, useComputedColorScheme, useMantineTheme } from "@mantine/core";
|
||||
import { useElementSize, useHover, useMergedRef } from "@mantine/hooks";
|
||||
import type { TooltipProps, YAxisProps } from "recharts";
|
||||
|
||||
@@ -36,14 +36,13 @@ export const CommonChart = ({
|
||||
}) => {
|
||||
const { ref: elementSizeRef, height } = useElementSize();
|
||||
const theme = useMantineTheme();
|
||||
const scheme = useMantineColorScheme();
|
||||
const colorScheme = useComputedColorScheme("light");
|
||||
const board = useRequiredBoard();
|
||||
const { hovered, ref: hoverRef } = useHover();
|
||||
const ref = useMergedRef(elementSizeRef, hoverRef);
|
||||
|
||||
const opacity = board.opacity / 100;
|
||||
const backgroundColor =
|
||||
scheme.colorScheme === "dark" ? `rgba(57, 57, 57, ${opacity})` : `rgba(246, 247, 248, ${opacity})`;
|
||||
const backgroundColor = colorScheme === "dark" ? `rgba(57, 57, 57, ${opacity})` : `rgba(246, 247, 248, ${opacity})`;
|
||||
|
||||
const ChartComponent = chartType === "line" ? LineChart : AreaChart;
|
||||
const showIcon = labelDisplayMode === "icon" || labelDisplayMode === "textWithIcon";
|
||||
|
||||
@@ -34,9 +34,6 @@ export const SystemResourceCPUChart = ({
|
||||
labelDisplayMode={labelDisplayMode}
|
||||
tooltipProps={{
|
||||
content: ({ payload }) => {
|
||||
if (!payload) {
|
||||
return null;
|
||||
}
|
||||
const value = payload[0] ? Number(payload[0].value) : 0;
|
||||
return (
|
||||
<Paper px={3} py={2} withBorder shadow="md" radius="md">
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Paper, Text } from "@mantine/core";
|
||||
import { IconDeviceDesktop } from "@tabler/icons-react";
|
||||
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { LabelDisplayModeOption } from "..";
|
||||
import { CommonChart } from "./common-chart";
|
||||
|
||||
export const SystemResourceGPUChart = ({
|
||||
gpuUsageOverTime,
|
||||
hasShadow,
|
||||
labelDisplayMode,
|
||||
}: {
|
||||
gpuUsageOverTime: number[];
|
||||
hasShadow: boolean;
|
||||
labelDisplayMode: LabelDisplayModeOption;
|
||||
}) => {
|
||||
const chartData = gpuUsageOverTime.map((usage, index) => ({ index, usage }));
|
||||
const t = useScopedI18n("widget.systemResources.card");
|
||||
|
||||
return (
|
||||
<CommonChart
|
||||
data={chartData}
|
||||
dataKey={"index"}
|
||||
series={[{ name: "usage", color: "grape.5" }]}
|
||||
title={t("gpu")}
|
||||
icon={IconDeviceDesktop}
|
||||
lastValue={
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
gpuUsageOverTime.length > 0 ? `${Math.round(gpuUsageOverTime[gpuUsageOverTime.length - 1]!)}%` : undefined
|
||||
}
|
||||
chartType={hasShadow ? "area" : "line"}
|
||||
yAxisProps={{ domain: [0, 100] }}
|
||||
labelDisplayMode={labelDisplayMode}
|
||||
tooltipProps={{
|
||||
content: ({ payload }) => {
|
||||
const value = payload[0] ? Number(payload[0].value) : 0;
|
||||
return (
|
||||
<Paper px={3} py={2} withBorder shadow="md" radius="md">
|
||||
<Text c="dimmed" size="xs">
|
||||
{value.toFixed(0)}%
|
||||
</Text>
|
||||
</Paper>
|
||||
);
|
||||
},
|
||||
}}
|
||||
/>
|
||||
);
|
||||
};
|
||||
@@ -40,9 +40,6 @@ export const SystemResourceMemoryChart = ({
|
||||
chartType={hasShadow ? "area" : "line"}
|
||||
tooltipProps={{
|
||||
content: ({ payload }) => {
|
||||
if (!payload) {
|
||||
return null;
|
||||
}
|
||||
const value = payload[0] ? Number(payload[0].value) : 0;
|
||||
return (
|
||||
<Paper px={3} py={2} withBorder shadow="md" radius="md">
|
||||
|
||||
@@ -37,9 +37,6 @@ export const NetworkTrafficChart = ({
|
||||
labelDisplayMode={labelDisplayMode}
|
||||
tooltipProps={{
|
||||
content: ({ payload }) => {
|
||||
if (!payload) {
|
||||
return null;
|
||||
}
|
||||
const value = payload[0] ? Number(payload[0].value) : 0;
|
||||
return (
|
||||
<Paper px={3} py={2} withBorder shadow="md" radius="md">
|
||||
|
||||
@@ -9,6 +9,7 @@ import { clientApi } from "@homarr/api/client";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { CombinedNetworkTrafficChart } from "./chart/combined-network-traffic";
|
||||
import { SystemResourceCPUChart } from "./chart/cpu-chart";
|
||||
import { SystemResourceGPUChart } from "./chart/gpu-chart";
|
||||
import { SystemResourceMemoryChart } from "./chart/memory-chart";
|
||||
import { NetworkTrafficChart } from "./chart/network-traffic";
|
||||
|
||||
@@ -23,10 +24,16 @@ export default function SystemResources({ integrationIds, options }: WidgetCompo
|
||||
const memoryCapacityInBytes =
|
||||
(data[0]?.healthInfo.memAvailableInBytes ?? 0) + (data[0]?.healthInfo.memUsedInBytes ?? 0);
|
||||
|
||||
const [items, setItems] = useState<{ cpu: number; memory: number; network: { up: number; down: number } | null }[]>(
|
||||
const [items, setItems] = useState<
|
||||
{ cpu: number; memory: number; gpu: number; network: { up: number; down: number } | null }[]
|
||||
>(
|
||||
data.map((item) => ({
|
||||
cpu: item.healthInfo.cpuUtilization,
|
||||
memory: item.healthInfo.memUsedInBytes,
|
||||
gpu:
|
||||
item.healthInfo.gpu.length > 0
|
||||
? item.healthInfo.gpu.reduce((acc, g) => acc + g.processorUtilization, 0) / item.healthInfo.gpu.length
|
||||
: 0,
|
||||
network: item.healthInfo.network,
|
||||
})),
|
||||
);
|
||||
@@ -41,6 +48,10 @@ export default function SystemResources({ integrationIds, options }: WidgetCompo
|
||||
const next = {
|
||||
cpu: data.healthInfo.cpuUtilization,
|
||||
memory: data.healthInfo.memUsedInBytes,
|
||||
gpu:
|
||||
data.healthInfo.gpu.length > 0
|
||||
? data.healthInfo.gpu.reduce((acc, g) => acc + g.processorUtilization, 0) / data.healthInfo.gpu.length
|
||||
: 0,
|
||||
network: data.healthInfo.network,
|
||||
};
|
||||
|
||||
@@ -75,6 +86,15 @@ export default function SystemResources({ integrationIds, options }: WidgetCompo
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
{options.visibleCharts.includes("gpu") && (
|
||||
<Box h={rowHeight}>
|
||||
<SystemResourceGPUChart
|
||||
gpuUsageOverTime={items.map((item) => item.gpu)}
|
||||
hasShadow={options.hasShadow}
|
||||
labelDisplayMode={options.labelDisplayMode}
|
||||
/>
|
||||
</Box>
|
||||
)}
|
||||
{showNetwork &&
|
||||
(width > 256 ? (
|
||||
<Group h={rowHeight} gap="xs" grow>
|
||||
|
||||
@@ -14,12 +14,12 @@ const labelDisplayModeOptions = {
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("systemResources", {
|
||||
icon: IconGraphFilled,
|
||||
supportedIntegrations: ["dashDot", "openmediavault", "truenas", "unraid"],
|
||||
supportedIntegrations: ["dashDot", "openmediavault", "truenas", "unraid", "glances"],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
hasShadow: factory.switch({ defaultValue: true }),
|
||||
visibleCharts: factory.multiSelect({
|
||||
options: (["cpu", "memory", "network"] as const).map((key) => ({
|
||||
options: (["cpu", "memory", "gpu", "network"] as const).map((key) => ({
|
||||
value: key,
|
||||
label: (t) => t(`widget.systemResources.option.visibleCharts.option.${key}`),
|
||||
})),
|
||||
|
||||
@@ -0,0 +1,75 @@
|
||||
import { Badge, Center, Group, Stack, Text } from "@mantine/core";
|
||||
import dayjs from "dayjs";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { DynamicSelectOption } from "../_inputs/widget-dynamic-select-input";
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
|
||||
export default function TimetableWidget({ options, integrationIds }: WidgetComponentProps<"timetable">) {
|
||||
// It will always have at least one integration as otherwise the NoIntegrationSelectedError would be thrown in item-content.tsx
|
||||
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
||||
const integrationId = integrationIds[0]!;
|
||||
const t = useScopedI18n("widget.timetable");
|
||||
|
||||
if (!options.station) {
|
||||
return <Center h="100%">{t("noStation")}</Center>;
|
||||
}
|
||||
|
||||
return <TimetableWidgetInner station={options.station} integrationId={integrationId} />;
|
||||
}
|
||||
|
||||
interface TimetableWidgetInnerProps {
|
||||
station: DynamicSelectOption;
|
||||
integrationId: string;
|
||||
}
|
||||
|
||||
const TimetableWidgetInner = ({ station, integrationId }: TimetableWidgetInnerProps) => {
|
||||
const [timetable] = clientApi.widget.timetable.getTimetable.useSuspenseQuery({
|
||||
integrationId,
|
||||
stationId: station.value,
|
||||
limit: 10,
|
||||
});
|
||||
const t = useScopedI18n("widget.timetable");
|
||||
|
||||
return (
|
||||
<Stack w="100%" gap="xs" p="sm">
|
||||
<Text fw="bold">{t("title", { station: station.label })}</Text>
|
||||
{timetable.entries.map((entry) => (
|
||||
<Group key={`${entry.timestamp.toISOString()}-${entry.location}`} justify="space-between" w="100%">
|
||||
<Group gap="sm">
|
||||
{entry.line && (
|
||||
<Badge
|
||||
size="sm"
|
||||
color={entry.line.color ?? undefined}
|
||||
variant={entry.line.color ? "filled" : "default"}
|
||||
w={32}
|
||||
p={0}
|
||||
radius={0}
|
||||
>
|
||||
{entry.line.name}
|
||||
</Badge>
|
||||
)}
|
||||
<Text size="sm">
|
||||
{dayjs(entry.timestamp).format("HH:mm")}{" "}
|
||||
{entry.delay >= 1 && (
|
||||
<Text size="sm" span c="red">
|
||||
+{entry.delay}'
|
||||
</Text>
|
||||
)}
|
||||
</Text>
|
||||
|
||||
<Text size="sm">{entry.location}</Text>
|
||||
</Group>
|
||||
|
||||
{entry.platform && (
|
||||
<Text size="sm" c={entry.platform.hasChanged ? "red" : undefined}>
|
||||
{entry.platform.name}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
};
|
||||
@@ -0,0 +1,37 @@
|
||||
import { IconBusStop } from "@tabler/icons-react";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
|
||||
export const { componentLoader, definition } = createWidgetDefinition("timetable", {
|
||||
icon: IconBusStop,
|
||||
supportedIntegrations: ["searchCh"],
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
station: factory.dynamicSelect({
|
||||
useOptions(query, integrationIds) {
|
||||
const { data: stations, isPending } = clientApi.widget.timetable.searchStations.useQuery(
|
||||
{
|
||||
integrationId: integrationIds[0] ?? "",
|
||||
query,
|
||||
},
|
||||
{
|
||||
enabled: integrationIds.length > 0,
|
||||
},
|
||||
);
|
||||
|
||||
return {
|
||||
isPending,
|
||||
options:
|
||||
stations?.map((station) => ({
|
||||
label: station.name,
|
||||
value: station.id,
|
||||
})) ?? [],
|
||||
};
|
||||
},
|
||||
}),
|
||||
}));
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -0,0 +1,131 @@
|
||||
"use client";
|
||||
|
||||
import { ScrollArea, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import type { TracearrDashboardData } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { NoIntegrationDataError } from "../errors/no-data-integration";
|
||||
import { RecentActivityList } from "./recent-activity-section";
|
||||
import { StatsBar } from "./stats-section";
|
||||
import { StreamsList } from "./streams-section";
|
||||
import { ViolationsList } from "./violations-section";
|
||||
|
||||
export default function TracearrWidget({
|
||||
options,
|
||||
integrationIds,
|
||||
width,
|
||||
isEditMode,
|
||||
}: WidgetComponentProps<"tracearr">) {
|
||||
if (integrationIds.length === 0) {
|
||||
throw new NoIntegrationDataError();
|
||||
}
|
||||
|
||||
return <TracearrContent integrationIds={integrationIds} options={options} width={width} isEditMode={isEditMode} />;
|
||||
}
|
||||
|
||||
interface TracearrContentProps {
|
||||
integrationIds: string[];
|
||||
options: WidgetComponentProps<"tracearr">["options"];
|
||||
width: number;
|
||||
isEditMode: boolean;
|
||||
}
|
||||
|
||||
function TracearrContent({ integrationIds, options, width, isEditMode }: TracearrContentProps) {
|
||||
const t = useScopedI18n("widget.tracearr");
|
||||
const [dashboardData] = clientApi.widget.tracearr.getDashboard.useSuspenseQuery({ integrationIds });
|
||||
|
||||
const utils = clientApi.useUtils();
|
||||
clientApi.widget.tracearr.subscribeToDashboard.useSubscription(
|
||||
{ integrationIds },
|
||||
{
|
||||
enabled: !isEditMode,
|
||||
onData(newData) {
|
||||
utils.widget.tracearr.getDashboard.setData({ integrationIds }, (prevData) => {
|
||||
if (!prevData) return prevData;
|
||||
return prevData.map((instance) =>
|
||||
instance.integrationId === newData.integrationId
|
||||
? { ...instance, dashboard: newData.dashboard, updatedAt: newData.timestamp }
|
||||
: instance,
|
||||
);
|
||||
});
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// Merge data from all integrations
|
||||
const combined = dashboardData.reduce<TracearrDashboardData>(
|
||||
(acc, item) => {
|
||||
const { stats, streams, violations, recentActivity } = item.dashboard;
|
||||
const vData = violations ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
|
||||
const aData = recentActivity ?? { data: [], meta: { total: 0, page: 1, pageSize: 5 } };
|
||||
|
||||
return {
|
||||
stats: {
|
||||
activeStreams: acc.stats.activeStreams + stats.activeStreams,
|
||||
totalUsers: acc.stats.totalUsers + stats.totalUsers,
|
||||
totalSessions: acc.stats.totalSessions + stats.totalSessions,
|
||||
recentViolations: acc.stats.recentViolations + stats.recentViolations,
|
||||
timestamp: stats.timestamp,
|
||||
},
|
||||
streams: {
|
||||
data: [...acc.streams.data, ...streams.data],
|
||||
summary: {
|
||||
total: acc.streams.summary.total + streams.summary.total,
|
||||
transcodes: acc.streams.summary.transcodes + streams.summary.transcodes,
|
||||
directStreams: acc.streams.summary.directStreams + streams.summary.directStreams,
|
||||
directPlays: acc.streams.summary.directPlays + streams.summary.directPlays,
|
||||
totalBitrate: streams.summary.totalBitrate,
|
||||
byServer: [...acc.streams.summary.byServer, ...streams.summary.byServer],
|
||||
},
|
||||
},
|
||||
violations: {
|
||||
data: [...(acc.violations?.data ?? []), ...vData.data],
|
||||
meta: {
|
||||
total: (acc.violations?.meta.total ?? 0) + vData.meta.total,
|
||||
page: 1,
|
||||
pageSize: 5,
|
||||
},
|
||||
},
|
||||
recentActivity: {
|
||||
data: [...(acc.recentActivity?.data ?? []), ...aData.data],
|
||||
meta: {
|
||||
total: (acc.recentActivity?.meta.total ?? 0) + aData.meta.total,
|
||||
page: 1,
|
||||
pageSize: 5,
|
||||
},
|
||||
},
|
||||
};
|
||||
},
|
||||
{
|
||||
stats: { activeStreams: 0, totalUsers: 0, totalSessions: 0, recentViolations: 0, timestamp: "" },
|
||||
streams: {
|
||||
data: [],
|
||||
summary: { total: 0, transcodes: 0, directStreams: 0, directPlays: 0, totalBitrate: "0", byServer: [] },
|
||||
},
|
||||
violations: null,
|
||||
recentActivity: null,
|
||||
},
|
||||
);
|
||||
|
||||
const noSectionsEnabled =
|
||||
!options.showStats && !options.showStreams && !options.showRecentActivity && !options.showViolations;
|
||||
|
||||
return (
|
||||
<ScrollArea h="100%">
|
||||
<Stack gap="xs" p="xs">
|
||||
{options.showStats && <StatsBar stats={combined.stats} summary={combined.streams.summary} width={width} />}
|
||||
{options.showStreams && <StreamsList streams={combined.streams.data} width={width} />}
|
||||
{options.showViolations && <ViolationsList violations={combined.violations?.data ?? []} />}
|
||||
{options.showRecentActivity && <RecentActivityList sessions={combined.recentActivity?.data ?? []} />}
|
||||
{noSectionsEnabled && (
|
||||
<Text c="dimmed" ta="center">
|
||||
{t("noSectionsEnabled")}
|
||||
</Text>
|
||||
)}
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import { IconActivityHeartbeat, IconServerOff } from "@tabler/icons-react";
|
||||
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("tracearr", {
|
||||
icon: IconActivityHeartbeat,
|
||||
createOptions() {
|
||||
return optionsBuilder.from((factory) => ({
|
||||
showStreams: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
showStats: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
|
||||
showRecentActivity: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
showViolations: factory.switch({
|
||||
defaultValue: true,
|
||||
}),
|
||||
}));
|
||||
},
|
||||
supportedIntegrations: ["tracearr"],
|
||||
errors: {
|
||||
INTERNAL_SERVER_ERROR: {
|
||||
icon: IconServerOff,
|
||||
message: (t) => t("widget.tracearr.error.internalServerError"),
|
||||
},
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -0,0 +1,56 @@
|
||||
import { Avatar, Badge, Group, Paper, Stack, Text } from "@mantine/core";
|
||||
|
||||
import type { TracearrHistorySession } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
export function RecentActivityList({ sessions }: { sessions: TracearrHistorySession[] }) {
|
||||
const t = useScopedI18n("widget.tracearr");
|
||||
|
||||
return (
|
||||
<Stack gap={4}>
|
||||
<Text size="xs" fw={600} c="dimmed" tt="uppercase">
|
||||
{t("recentActivity.title")}
|
||||
</Text>
|
||||
{sessions.length === 0 ? (
|
||||
<Text size="xs" c="dimmed" ta="center">
|
||||
{t("recentActivity.empty")}
|
||||
</Text>
|
||||
) : (
|
||||
<Stack gap="xs">
|
||||
{sessions.map((session) => {
|
||||
const mediaLabel =
|
||||
session.mediaType === "episode" && session.showTitle
|
||||
? `${session.showTitle} - S${session.seasonNumber ?? 0}E${session.episodeNumber ?? 0}`
|
||||
: session.mediaTitle;
|
||||
|
||||
return (
|
||||
<Paper key={session.id} p="sm" radius="lg" withBorder>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Group gap="xs" wrap="nowrap" style={{ overflow: "hidden" }}>
|
||||
<Avatar src={session.user.avatarUrl} alt={session.user.username} radius="xl" size="sm" />
|
||||
<Stack gap={0} style={{ overflow: "hidden" }}>
|
||||
<Text size="sm" fw={500} lineClamp={1}>
|
||||
{mediaLabel}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{session.user.username} • {session.serverName}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
<Stack gap={4} align="center">
|
||||
<Badge size="xs" variant="light" color={session.watched ? "green" : "blue"}>
|
||||
{session.watched ? t("recentActivity.watched") : t("recentActivity.partial")}
|
||||
</Badge>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{new Date(session.startedAt).toLocaleDateString()}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
</Paper>
|
||||
);
|
||||
})}
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Group, Paper, SimpleGrid, Stack, Text } from "@mantine/core";
|
||||
import { IconDevices, IconNetwork, IconUsers, IconVideo } from "@tabler/icons-react";
|
||||
|
||||
import type { TracearrDashboardData } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
export function StatsBar({
|
||||
stats,
|
||||
summary,
|
||||
width,
|
||||
}: {
|
||||
stats: TracearrDashboardData["stats"];
|
||||
summary: TracearrDashboardData["streams"]["summary"];
|
||||
width: number;
|
||||
}) {
|
||||
const t = useScopedI18n("widget.tracearr");
|
||||
const cols = width > 400 ? 4 : width > 250 ? 2 : 1;
|
||||
|
||||
return (
|
||||
<SimpleGrid cols={cols} spacing="xs">
|
||||
<StatCard icon={<IconVideo size={16} />} label={t("stats.activeStreams")} value={stats.activeStreams} />
|
||||
<StatCard icon={<IconUsers size={16} />} label={t("stats.totalUsers")} value={stats.totalUsers} />
|
||||
<StatCard
|
||||
icon={<IconDevices size={16} />}
|
||||
label={t("stats.transcodes")}
|
||||
value={`${summary.transcodes}/${summary.total}`}
|
||||
/>
|
||||
<StatCard icon={<IconNetwork size={16} />} label={t("stats.bandwidth")} value={summary.totalBitrate} />
|
||||
</SimpleGrid>
|
||||
);
|
||||
}
|
||||
|
||||
function StatCard({ icon, label, value }: { icon: React.ReactNode; label: string; value: string | number }) {
|
||||
return (
|
||||
<Paper p="xs" radius="lg" withBorder>
|
||||
<Group gap={4} wrap="nowrap">
|
||||
{icon}
|
||||
<Stack gap={0} style={{ overflow: "hidden" }}>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{label}
|
||||
</Text>
|
||||
<Text size="sm" fw={600}>
|
||||
{value}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,128 @@
|
||||
import { Badge, Box, Group, Paper, Progress, Stack, Text, Tooltip } from "@mantine/core";
|
||||
import { IconPlayerPause, IconPlayerPlay } from "@tabler/icons-react";
|
||||
|
||||
import { formatDuration } from "@homarr/common";
|
||||
import type { TracearrStream } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
export function StreamsList({ streams, width }: { streams: TracearrStream[]; width: number }) {
|
||||
const t = useScopedI18n("widget.tracearr");
|
||||
|
||||
if (streams.length === 0) {
|
||||
return (
|
||||
<Text c="dimmed" ta="center" size="sm">
|
||||
{t("streams.empty")}
|
||||
</Text>
|
||||
);
|
||||
}
|
||||
|
||||
return (
|
||||
<Stack gap="xs">
|
||||
{streams.map((stream) => (
|
||||
<StreamCard key={stream.id} stream={stream} compact={width < 300} />
|
||||
))}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
function StreamCard({ stream, compact }: { stream: TracearrStream; compact: boolean }) {
|
||||
const t = useScopedI18n("widget.tracearr");
|
||||
const progressPercent =
|
||||
stream.durationMs && stream.durationMs > 0 ? (stream.progressMs / stream.durationMs) * 100 : 0;
|
||||
|
||||
const mediaLabel =
|
||||
stream.mediaType === "episode" && stream.showTitle
|
||||
? `${stream.showTitle} - S${stream.seasonNumber ?? 0}E${stream.episodeNumber ?? 0} - ${stream.mediaTitle}`
|
||||
: stream.mediaTitle;
|
||||
|
||||
const videoDecisionLabel =
|
||||
stream.videoDecision === "directplay"
|
||||
? t("streams.videoDecision.directPlay")
|
||||
: stream.videoDecision === "transcode"
|
||||
? t("streams.videoDecision.transcode")
|
||||
: stream.videoDecision === "copy"
|
||||
? t("streams.videoDecision.directStream")
|
||||
: null;
|
||||
|
||||
return (
|
||||
<Paper p="xs" radius="lg" withBorder style={{ position: "relative", overflow: "hidden" }}>
|
||||
{stream.posterUrl && (
|
||||
<Box
|
||||
style={{
|
||||
position: "absolute",
|
||||
top: 0,
|
||||
right: 0,
|
||||
bottom: 0,
|
||||
width: "50%",
|
||||
backgroundImage: `url(${stream.posterUrl})`,
|
||||
backgroundSize: "cover",
|
||||
backgroundPosition: "center right",
|
||||
opacity: 0.25,
|
||||
maskImage: "linear-gradient(to left, black 20%, transparent 100%)",
|
||||
WebkitMaskImage: "linear-gradient(to left, black 20%, transparent 100%)",
|
||||
pointerEvents: "none",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
<Stack gap={4} style={{ position: "relative" }}>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Group gap="xs" wrap="nowrap" style={{ overflow: "hidden" }}>
|
||||
{stream.state === "playing" ? (
|
||||
<IconPlayerPlay size={14} color="var(--mantine-color-green-6)" />
|
||||
) : (
|
||||
<IconPlayerPause size={14} color="var(--mantine-color-yellow-6)" />
|
||||
)}
|
||||
<Text size="sm" fw={600} lineClamp={1}>
|
||||
{stream.username}
|
||||
</Text>
|
||||
</Group>
|
||||
<Group gap={4} wrap={compact ? "wrap" : "nowrap"}>
|
||||
{stream.resolution && (
|
||||
<Badge size="xs" variant="light">
|
||||
{stream.resolution}
|
||||
</Badge>
|
||||
)}
|
||||
{videoDecisionLabel && (
|
||||
<Badge
|
||||
size="xs"
|
||||
variant="light"
|
||||
color={
|
||||
stream.videoDecision === "directplay"
|
||||
? "green"
|
||||
: stream.videoDecision === "transcode"
|
||||
? "orange"
|
||||
: "blue"
|
||||
}
|
||||
>
|
||||
{videoDecisionLabel}
|
||||
</Badge>
|
||||
)}
|
||||
</Group>
|
||||
</Group>
|
||||
|
||||
<Tooltip label={mediaLabel} openDelay={300}>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{mediaLabel}
|
||||
</Text>
|
||||
</Tooltip>
|
||||
|
||||
{stream.durationMs && stream.durationMs > 0 && (
|
||||
<Group gap="xs" align="center">
|
||||
<Progress value={progressPercent} size="xs" style={{ flex: 1 }} radius="xl" />
|
||||
<Text size="xs" c="dimmed" style={{ whiteSpace: "nowrap" }}>
|
||||
{formatDuration(stream.progressMs)} / {formatDuration(stream.durationMs)}
|
||||
</Text>
|
||||
</Group>
|
||||
)}
|
||||
|
||||
<Group gap="xs" wrap="nowrap">
|
||||
{stream.device && (
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{stream.player ?? stream.device}
|
||||
</Text>
|
||||
)}
|
||||
</Group>
|
||||
</Stack>
|
||||
</Paper>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,66 @@
|
||||
import { Avatar, Badge, Group, Paper, Stack, Text } from "@mantine/core";
|
||||
import { IconAlertTriangle } from "@tabler/icons-react";
|
||||
|
||||
import type { TracearrViolation } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
export function ViolationsList({ violations }: { violations: TracearrViolation[] }) {
|
||||
const t = useScopedI18n("widget.tracearr");
|
||||
|
||||
return (
|
||||
<Stack gap={4}>
|
||||
<Text size="xs" fw={600} c="dimmed" tt="uppercase">
|
||||
{t("violations.title")}
|
||||
</Text>
|
||||
{violations.length === 0 ? (
|
||||
<Text size="xs" c="dimmed" ta="center">
|
||||
{t("violations.empty")}
|
||||
</Text>
|
||||
) : (
|
||||
<Stack gap="xs">
|
||||
{violations.map((violation) => (
|
||||
<Paper key={violation.id} p="xs" radius="lg" withBorder>
|
||||
<Group justify="space-between" wrap="nowrap">
|
||||
<Group gap="xs" wrap="nowrap" style={{ overflow: "hidden" }}>
|
||||
<IconAlertTriangle
|
||||
size={14}
|
||||
color={
|
||||
violation.severity === "high"
|
||||
? "var(--mantine-color-red-6)"
|
||||
: violation.severity === "medium"
|
||||
? "var(--mantine-color-orange-6)"
|
||||
: "var(--mantine-color-yellow-6)"
|
||||
}
|
||||
/>
|
||||
<Avatar src={violation.user.avatarUrl} alt={violation.user.username} radius="xl" size="sm" />
|
||||
<Stack gap={0} style={{ overflow: "hidden" }}>
|
||||
<Text size="sm" fw={500} lineClamp={1}>
|
||||
{violation.user.username}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{t("violations.rule")}: {violation.rule.name}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
<Stack gap={4} align="center">
|
||||
<Badge
|
||||
size="xs"
|
||||
variant="light"
|
||||
color={
|
||||
violation.severity === "high" ? "red" : violation.severity === "medium" ? "orange" : "yellow"
|
||||
}
|
||||
>
|
||||
{violation.severity}
|
||||
</Badge>
|
||||
<Text size="xs" c="dimmed" lineClamp={1}>
|
||||
{new Date(violation.createdAt).toLocaleDateString()}
|
||||
</Text>
|
||||
</Stack>
|
||||
</Group>
|
||||
</Paper>
|
||||
))}
|
||||
</Stack>
|
||||
)}
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
"use client";
|
||||
|
||||
import { Stack, Text } from "@mantine/core";
|
||||
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import type { WidgetComponentProps } from "../definition";
|
||||
import { UmamiContent } from "./umami-content";
|
||||
|
||||
export default function UmamiWidget({ options, integrationIds }: WidgetComponentProps<"umami">) {
|
||||
if (!options.websiteId || options.websiteId.trim() === "") {
|
||||
return <NoWebsiteConfigured />;
|
||||
}
|
||||
|
||||
return (
|
||||
<UmamiContent
|
||||
integrationIds={integrationIds}
|
||||
websiteId={options.websiteId}
|
||||
timeFrame={options.timeFrame}
|
||||
eventName={options.eventName || undefined}
|
||||
eventNames={options.eventNames}
|
||||
chartStyle={options.chartStyle}
|
||||
chartType={options.chartType}
|
||||
viewMode={options.viewMode}
|
||||
topCount={options.topCount}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function NoWebsiteConfigured() {
|
||||
const t = useScopedI18n("widget.umami");
|
||||
return (
|
||||
<Stack align="center" justify="center" h="100%">
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("error.noWebsite")}
|
||||
</Text>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,88 @@
|
||||
import { IconChartBar, IconServerOff } from "@tabler/icons-react";
|
||||
import { z } from "zod/v4";
|
||||
|
||||
import { createWidgetDefinition } from "../definition";
|
||||
import { optionsBuilder } from "../options";
|
||||
|
||||
export const timeFrameValues = ["today", "24h", "7d", "30d", "month", "lastMonth"] as const;
|
||||
|
||||
export const { definition, componentLoader } = createWidgetDefinition("umami", {
|
||||
icon: IconChartBar,
|
||||
supportedIntegrations: ["umami"],
|
||||
createOptions() {
|
||||
return optionsBuilder.from(
|
||||
(factory) => ({
|
||||
websiteId: factory.umamiWebsite(),
|
||||
timeFrame: factory.select({
|
||||
options: timeFrameValues.map((value) => ({
|
||||
value,
|
||||
label: (t) => t(`widget.umami.option.timeFrame.option.${value}`),
|
||||
})),
|
||||
defaultValue: "24h",
|
||||
withDescription: true,
|
||||
}),
|
||||
viewMode: factory.select({
|
||||
options: [
|
||||
{ value: "chart", label: (t) => t("widget.umami.option.viewMode.option.chart") },
|
||||
{ value: "events", label: (t) => t("widget.umami.option.viewMode.option.events") },
|
||||
{ value: "topPages", label: (t) => t("widget.umami.option.viewMode.option.topPages") },
|
||||
{ value: "topReferrers", label: (t) => t("widget.umami.option.viewMode.option.topReferrers") },
|
||||
] as const,
|
||||
defaultValue: "chart",
|
||||
withDescription: true,
|
||||
}),
|
||||
chartType: factory.select({
|
||||
options: [
|
||||
{ value: "bar", label: (t) => t("widget.umami.option.chartType.option.bar") },
|
||||
{ value: "sparkline", label: (t) => t("widget.umami.option.chartType.option.sparkline") },
|
||||
] as const,
|
||||
defaultValue: "bar",
|
||||
withDescription: true,
|
||||
}),
|
||||
chartStyle: factory.select({
|
||||
options: [
|
||||
{ value: "grouped", label: (t) => t("widget.umami.option.chartStyle.option.grouped") },
|
||||
{ value: "overlay", label: (t) => t("widget.umami.option.chartStyle.option.overlay") },
|
||||
] as const,
|
||||
defaultValue: "grouped",
|
||||
withDescription: true,
|
||||
}),
|
||||
eventName: factory.umamiEventName(),
|
||||
eventNames: factory.umamiEventNames(),
|
||||
topCount: factory.number({
|
||||
validate: z.number().int().min(1).max(500),
|
||||
defaultValue: 5,
|
||||
step: 1,
|
||||
withDescription: true,
|
||||
}),
|
||||
}),
|
||||
{
|
||||
viewMode: {
|
||||
shouldHide: (options) => !options.websiteId,
|
||||
},
|
||||
chartType: {
|
||||
shouldHide: (options) =>
|
||||
!options.websiteId || (options.viewMode !== "chart" && options.viewMode !== "events"),
|
||||
},
|
||||
chartStyle: {
|
||||
shouldHide: (options) => options.viewMode !== "chart" || !options.eventName || options.chartType !== "bar",
|
||||
},
|
||||
eventName: {
|
||||
shouldHide: (options) => !options.websiteId || options.viewMode !== "chart",
|
||||
},
|
||||
eventNames: {
|
||||
shouldHide: (options) => !options.websiteId || options.viewMode !== "events",
|
||||
},
|
||||
topCount: {
|
||||
shouldHide: (options) => !options.websiteId || options.viewMode === "chart" || options.viewMode === "events",
|
||||
},
|
||||
},
|
||||
);
|
||||
},
|
||||
errors: {
|
||||
INTERNAL_SERVER_ERROR: {
|
||||
icon: IconServerOff,
|
||||
message: (t) => t("widget.umami.error.internalServerError"),
|
||||
},
|
||||
},
|
||||
}).withDynamicImport(() => import("./component"));
|
||||
@@ -0,0 +1,220 @@
|
||||
"use client";
|
||||
|
||||
import { BarChart, LineChart } from "@mantine/charts";
|
||||
import { Box, Group, Stack, Text, useMantineColorScheme } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import { formatDuration } from "@homarr/common";
|
||||
import type { UmamiVisitorStats } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { UmamiEventsContent } from "./umami-events-content";
|
||||
import { UmamiTopPagesContent, UmamiTopReferrersContent } from "./umami-top-list";
|
||||
import { formatTimeFrameLabel, formatXLabel } from "./umami-utils";
|
||||
import type { TimeFrame } from "./umami-utils";
|
||||
|
||||
interface UmamiContentProps {
|
||||
integrationIds: string[];
|
||||
websiteId: string;
|
||||
timeFrame: TimeFrame;
|
||||
eventName?: string;
|
||||
eventNames: string[];
|
||||
chartStyle: string;
|
||||
chartType: string;
|
||||
viewMode: string;
|
||||
topCount: number;
|
||||
}
|
||||
|
||||
export function UmamiContent({
|
||||
integrationIds,
|
||||
websiteId,
|
||||
timeFrame,
|
||||
eventName,
|
||||
eventNames,
|
||||
chartStyle,
|
||||
chartType,
|
||||
viewMode,
|
||||
topCount,
|
||||
}: UmamiContentProps) {
|
||||
const t = useScopedI18n("widget.umami");
|
||||
const { colorScheme } = useMantineColorScheme();
|
||||
const tickColor = colorScheme === "dark" ? "#c1c2c5" : "#495057";
|
||||
|
||||
const [results] = clientApi.widget.umami.getVisitorStats.useSuspenseQuery({
|
||||
integrationIds,
|
||||
websiteId,
|
||||
timeFrame,
|
||||
eventName,
|
||||
});
|
||||
|
||||
const activeVisitorsInput = { integrationId: integrationIds[0] ?? "", websiteId };
|
||||
const [activeVisitors] = clientApi.widget.umami.getActiveVisitors.useSuspenseQuery(activeVisitorsInput);
|
||||
const utils = clientApi.useUtils();
|
||||
clientApi.widget.umami.subscribeActiveVisitors.useSubscription(activeVisitorsInput, {
|
||||
onData(count) {
|
||||
utils.widget.umami.getActiveVisitors.setData(activeVisitorsInput, () => count);
|
||||
},
|
||||
});
|
||||
|
||||
const { data: multiEventSeries } = clientApi.widget.umami.getMultiEventTimeSeries.useQuery(
|
||||
{ integrationId: integrationIds[0] ?? "", websiteId, timeFrame, eventNames: [...eventNames].sort() },
|
||||
{ enabled: viewMode === "events" && eventNames.length > 0 },
|
||||
);
|
||||
|
||||
const multiEventTotal = multiEventSeries
|
||||
? multiEventSeries.flatMap(({ dataPoints }) => dataPoints).reduce((sum, { y }) => sum + y, 0)
|
||||
: undefined;
|
||||
|
||||
const firstResult = results[0];
|
||||
if (!firstResult) {
|
||||
return (
|
||||
<Stack align="center" justify="center" h="100%">
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("error.noData")}
|
||||
</Text>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
const { visitorStats } = firstResult;
|
||||
|
||||
const chartData = visitorStats.dataPoints.map((point: UmamiVisitorStats["dataPoints"][number]) => ({
|
||||
label: formatXLabel(point.timestamp, timeFrame),
|
||||
visitors: point.visitors,
|
||||
...(point.events !== undefined ? { events: point.events } : {}),
|
||||
}));
|
||||
|
||||
const hasEventSeries = visitorStats.dataPoints.some(({ events }) => events !== undefined);
|
||||
const series = [
|
||||
{ name: "visitors", color: "blue.5" },
|
||||
...(hasEventSeries ? [{ name: "events", color: "orange.5" }] : []),
|
||||
];
|
||||
|
||||
const isOverlay = chartStyle === "overlay" && hasEventSeries;
|
||||
const overlayBarSize = 16;
|
||||
|
||||
return (
|
||||
<Stack gap={4} p="xs" h="100%">
|
||||
<Group justify="space-between" align="baseline" wrap="nowrap">
|
||||
<Text size="xs" c="dimmed" truncate="end" style={{ maxWidth: "55%" }}>
|
||||
{visitorStats.domain} ({formatTimeFrameLabel(timeFrame, t)})
|
||||
</Text>
|
||||
{(eventName && viewMode === "chart" && visitorStats.eventCount !== undefined) ||
|
||||
(viewMode === "events" && multiEventTotal !== undefined) ? (
|
||||
<Group gap={6} align="baseline" wrap="nowrap">
|
||||
<Group gap={4} align="baseline">
|
||||
<Text size="lg" fw={700} lh={1}>
|
||||
{viewMode === "events"
|
||||
? (multiEventTotal ?? 0).toLocaleString()
|
||||
: (visitorStats.eventCount ?? 0).toLocaleString()}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("event.label")}
|
||||
</Text>
|
||||
</Group>
|
||||
<Text size="xs" c="dimmed">
|
||||
/
|
||||
</Text>
|
||||
<Group gap={4} align="baseline">
|
||||
<Text size="lg" fw={700} lh={1}>
|
||||
{visitorStats.totalVisitors.toLocaleString()}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("visitors")}
|
||||
</Text>
|
||||
</Group>
|
||||
</Group>
|
||||
) : (
|
||||
<Group gap={4} align="baseline">
|
||||
<Text size="xl" fw={700} lh={1}>
|
||||
{visitorStats.totalVisitors.toLocaleString()}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{t("visitors")}
|
||||
</Text>
|
||||
</Group>
|
||||
)}
|
||||
</Group>
|
||||
<Group wrap="wrap" style={{ columnGap: 12, rowGap: 4 }}>
|
||||
<Text size="xs" c="green">
|
||||
● {activeVisitors.toLocaleString()} {t("active")}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{visitorStats.totalPageviews.toLocaleString()} {t("pageviews")}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{visitorStats.totalVisits.toLocaleString()} {t("visits")}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{visitorStats.bounceRate}% {t("bounceRate")}
|
||||
</Text>
|
||||
<Text size="xs" c="dimmed">
|
||||
{formatDuration(visitorStats.avgDuration * 1000)} {t("avgDuration")}
|
||||
</Text>
|
||||
</Group>
|
||||
<Box mt={4} style={{ flex: 1, minHeight: 0 }}>
|
||||
{viewMode === "events" ? (
|
||||
<UmamiEventsContent
|
||||
integrationIds={integrationIds}
|
||||
websiteId={websiteId}
|
||||
timeFrame={timeFrame}
|
||||
eventNames={eventNames}
|
||||
chartType={chartType}
|
||||
/>
|
||||
) : viewMode === "topPages" ? (
|
||||
<UmamiTopPagesContent
|
||||
integrationIds={integrationIds}
|
||||
websiteId={websiteId}
|
||||
timeFrame={timeFrame}
|
||||
limit={topCount}
|
||||
/>
|
||||
) : viewMode === "topReferrers" ? (
|
||||
<UmamiTopReferrersContent
|
||||
integrationIds={integrationIds}
|
||||
websiteId={websiteId}
|
||||
timeFrame={timeFrame}
|
||||
limit={topCount}
|
||||
/>
|
||||
) : chartType === "sparkline" ? (
|
||||
<LineChart
|
||||
h="100%"
|
||||
data={chartData}
|
||||
dataKey="label"
|
||||
series={series}
|
||||
withDots={false}
|
||||
curveType="monotone"
|
||||
tickLine="none"
|
||||
gridAxis="none"
|
||||
withLegend={false}
|
||||
withTooltip
|
||||
withXAxis
|
||||
withYAxis={false}
|
||||
xAxisProps={{
|
||||
tick: { fontSize: 9, fill: tickColor },
|
||||
interval: "preserveStartEnd",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<BarChart
|
||||
h="100%"
|
||||
data={chartData}
|
||||
dataKey="label"
|
||||
series={series}
|
||||
tickLine="none"
|
||||
gridAxis="none"
|
||||
withLegend={false}
|
||||
withTooltip
|
||||
withXAxis
|
||||
withYAxis={false}
|
||||
barProps={isOverlay ? { barSize: overlayBarSize, radius: 2 } : { radius: 2 }}
|
||||
barChartProps={isOverlay ? { barGap: -overlayBarSize } : undefined}
|
||||
xAxisProps={{
|
||||
tick: { fontSize: 9, fill: tickColor },
|
||||
interval: "preserveStartEnd",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,138 @@
|
||||
"use client";
|
||||
|
||||
import { BarChart, LineChart } from "@mantine/charts";
|
||||
import { Box, Group, Stack, Text, useMantineColorScheme } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import type { UmamiEventSeries } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { EVENT_COLORS, formatXLabel } from "./umami-utils";
|
||||
|
||||
interface UmamiEventsContentProps {
|
||||
integrationIds: string[];
|
||||
websiteId: string;
|
||||
timeFrame: string;
|
||||
eventNames: string[];
|
||||
chartType: string;
|
||||
}
|
||||
|
||||
export function UmamiEventsContent({
|
||||
integrationIds,
|
||||
websiteId,
|
||||
timeFrame,
|
||||
eventNames,
|
||||
chartType,
|
||||
}: UmamiEventsContentProps) {
|
||||
const t = useScopedI18n("widget.umami");
|
||||
const { colorScheme } = useMantineColorScheme();
|
||||
const tickColor = colorScheme === "dark" ? "#c1c2c5" : "#495057";
|
||||
|
||||
const [series] = clientApi.widget.umami.getMultiEventTimeSeries.useSuspenseQuery({
|
||||
integrationId: integrationIds[0] ?? "",
|
||||
websiteId,
|
||||
timeFrame,
|
||||
eventNames: [...eventNames].sort(),
|
||||
});
|
||||
|
||||
if (eventNames.length === 0) {
|
||||
return (
|
||||
<Stack align="center" justify="center" h="100%">
|
||||
<Text c="dimmed" size="sm">
|
||||
{t("events.selectPrompt")}
|
||||
</Text>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
|
||||
// Collect all unique timestamps across all series
|
||||
const allTimestamps = Array.from(
|
||||
new Set(series.flatMap(({ dataPoints }) => dataPoints.map(({ x: xPoint }) => xPoint))),
|
||||
).sort();
|
||||
|
||||
// Build per-event lookup by timestamp string
|
||||
const byEvent = new Map(
|
||||
series.map((serie: UmamiEventSeries) => [
|
||||
serie.eventName,
|
||||
new Map(serie.dataPoints.map((point) => [point.x, point.y])),
|
||||
]),
|
||||
);
|
||||
|
||||
const chartData = allTimestamps.map((timestamp) => {
|
||||
const row: Record<string, string | number> = { label: formatXLabel(timestamp, timeFrame) };
|
||||
for (const serie of series) {
|
||||
row[serie.eventName] = byEvent.get(serie.eventName)?.get(timestamp) ?? 0;
|
||||
}
|
||||
return row;
|
||||
});
|
||||
|
||||
const chartSeries = series.map((serie: UmamiEventSeries, index: number) => ({
|
||||
name: serie.eventName,
|
||||
color: EVENT_COLORS[index % EVENT_COLORS.length] ?? "blue.5",
|
||||
}));
|
||||
|
||||
return (
|
||||
<Stack gap={4} h="100%">
|
||||
{chartSeries.length > 1 && (
|
||||
<Group gap={12} justify="center" wrap="wrap" style={{ flexShrink: 0, rowGap: 2 }}>
|
||||
{chartSeries.map((serie) => (
|
||||
<Group key={serie.name} gap={4} align="center" wrap="nowrap">
|
||||
<Box
|
||||
w={8}
|
||||
h={8}
|
||||
style={{
|
||||
borderRadius: "50%",
|
||||
backgroundColor: `var(--mantine-color-${serie.color.replace(".", "-")})`,
|
||||
flexShrink: 0,
|
||||
}}
|
||||
/>
|
||||
<Text size="xs" c="dimmed" truncate>
|
||||
{serie.name}
|
||||
</Text>
|
||||
</Group>
|
||||
))}
|
||||
</Group>
|
||||
)}
|
||||
<Box style={{ flex: 1, minHeight: 0 }}>
|
||||
{chartType === "sparkline" ? (
|
||||
<LineChart
|
||||
h="100%"
|
||||
data={chartData}
|
||||
dataKey="label"
|
||||
series={chartSeries}
|
||||
withDots={false}
|
||||
curveType="monotone"
|
||||
tickLine="none"
|
||||
gridAxis="none"
|
||||
withLegend={false}
|
||||
withTooltip
|
||||
withXAxis
|
||||
withYAxis={false}
|
||||
xAxisProps={{
|
||||
tick: { fontSize: 9, fill: tickColor },
|
||||
interval: "preserveStartEnd",
|
||||
}}
|
||||
/>
|
||||
) : (
|
||||
<BarChart
|
||||
h="100%"
|
||||
data={chartData}
|
||||
dataKey="label"
|
||||
series={chartSeries}
|
||||
tickLine="none"
|
||||
gridAxis="none"
|
||||
withLegend={false}
|
||||
withTooltip
|
||||
withXAxis
|
||||
withYAxis={false}
|
||||
barProps={{ radius: 2 }}
|
||||
xAxisProps={{
|
||||
tick: { fontSize: 9, fill: tickColor },
|
||||
interval: "preserveStartEnd",
|
||||
}}
|
||||
/>
|
||||
)}
|
||||
</Box>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
"use client";
|
||||
|
||||
import { Group, ScrollArea, Stack, Text } from "@mantine/core";
|
||||
|
||||
import { clientApi } from "@homarr/api/client";
|
||||
import type { UmamiMetricItem } from "@homarr/integrations/types";
|
||||
import { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
interface UmamiTopListProps {
|
||||
integrationIds: string[];
|
||||
websiteId: string;
|
||||
timeFrame: string;
|
||||
limit: number;
|
||||
}
|
||||
|
||||
export function UmamiTopPagesContent({ integrationIds, websiteId, timeFrame, limit }: UmamiTopListProps) {
|
||||
const t = useScopedI18n("widget.umami");
|
||||
const [data] = clientApi.widget.umami.getTopPages.useSuspenseQuery({
|
||||
integrationId: integrationIds[0] ?? "",
|
||||
websiteId,
|
||||
timeFrame,
|
||||
limit,
|
||||
});
|
||||
return <UmamiTopList items={data} heading={t("option.viewMode.option.topPages")} emptyLabel={t("topPages.direct")} />;
|
||||
}
|
||||
|
||||
export function UmamiTopReferrersContent({ integrationIds, websiteId, timeFrame, limit }: UmamiTopListProps) {
|
||||
const t = useScopedI18n("widget.umami");
|
||||
const [data] = clientApi.widget.umami.getTopReferrers.useSuspenseQuery({
|
||||
integrationId: integrationIds[0] ?? "",
|
||||
websiteId,
|
||||
timeFrame,
|
||||
limit,
|
||||
});
|
||||
return (
|
||||
<UmamiTopList
|
||||
items={data}
|
||||
heading={t("option.viewMode.option.topReferrers")}
|
||||
emptyLabel={t("topReferrers.direct")}
|
||||
/>
|
||||
);
|
||||
}
|
||||
|
||||
function UmamiTopList({
|
||||
items,
|
||||
heading,
|
||||
emptyLabel,
|
||||
}: {
|
||||
items: UmamiMetricItem[];
|
||||
heading: string;
|
||||
emptyLabel: string;
|
||||
}) {
|
||||
return (
|
||||
<Stack gap={2} h="100%">
|
||||
<Text size="xs" c="dimmed" fw={500}>
|
||||
{heading}
|
||||
</Text>
|
||||
<ScrollArea style={{ flex: 1 }} scrollbars="y">
|
||||
<Stack gap={2}>
|
||||
{items.map((item, i) => (
|
||||
<Group key={item.x} gap="xs" wrap="nowrap" px={2}>
|
||||
<Text size="xs" c="dimmed" w={18} ta="right" flex="0 0 auto">
|
||||
{i + 1}.
|
||||
</Text>
|
||||
<Text size="xs" truncate="end" style={{ flex: 1 }}>
|
||||
{item.x || emptyLabel}
|
||||
</Text>
|
||||
<Text size="xs" fw={600} flex="0 0 auto">
|
||||
{item.y.toLocaleString()}
|
||||
</Text>
|
||||
</Group>
|
||||
))}
|
||||
</Stack>
|
||||
</ScrollArea>
|
||||
</Stack>
|
||||
);
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
import type { useScopedI18n } from "@homarr/translation/client";
|
||||
|
||||
import { timeFrameValues } from "./index";
|
||||
|
||||
export const EVENT_COLORS = ["blue.5", "orange.5", "green.5", "red.5", "violet.5", "teal.5", "yellow.5", "pink.5"];
|
||||
|
||||
export function formatXLabel(timestamp: string, timeFrame: string): string {
|
||||
const date = new Date(timestamp);
|
||||
switch (timeFrame) {
|
||||
case "today":
|
||||
case "24h":
|
||||
return `${date.getHours().toString().padStart(2, "0")}:00`;
|
||||
case "7d":
|
||||
case "30d":
|
||||
case "month":
|
||||
case "lastMonth":
|
||||
return date.toLocaleDateString(undefined, { month: "short", day: "numeric" });
|
||||
default:
|
||||
return timestamp;
|
||||
}
|
||||
}
|
||||
|
||||
export type TimeFrame = (typeof timeFrameValues)[number];
|
||||
|
||||
export function formatTimeFrameLabel(
|
||||
timeFrame: TimeFrame,
|
||||
t: ReturnType<typeof useScopedI18n<"widget.umami">>,
|
||||
): string {
|
||||
if (timeFrameValues.includes(timeFrame)) {
|
||||
return t(`option.timeFrame.option.${timeFrame}`);
|
||||
}
|
||||
return timeFrame;
|
||||
}
|
||||
@@ -79,7 +79,6 @@ const Feed = ({ options }: Pick<WidgetComponentProps<"video">, "options">) => {
|
||||
],
|
||||
});
|
||||
// All other properties are updated with other useEffect
|
||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||
}, [videoRef]);
|
||||
|
||||
useEffect(() => {
|
||||
|
||||
Reference in new issue
Block a user