A modern and easy to use dashboard. 80+ integrations. 20K+ icons built in. Authentication out of the box. No YAML, drag and drop configuration.
feat(uptime-kuma): rework integration and widget around status page heartbeats (#7213)
Thomas03408894ac3b
diff --git a/apps/docs/docs/widgets/uptime-kuma/index.mdx b/apps/docs/docs/widgets/uptime-kuma/index.mdxindex 6b9188b88..d7bf0e703 100644--- a/apps/docs/docs/widgets/uptime-kuma/index.mdx+++ b/apps/docs/docs/widgets/uptime-kuma/index.mdx@@ -1,6 +1,6 @@---title: "Uptime Kuma"-description: "Displays monitor uptime statistics, average uptime percentage, and service status counts."+description: "Displays the live status, heartbeats and uptime of the monitors on an Uptime Kuma status page."hide_title: true---@@ -15,11 +15,15 @@ import { uptimeKumaIntegration } from "@site/docs/integrations/uptime-kuma";<WidgetHeader widget={uptimeKumaWidget} categories={["Monitoring"]} />-This widget displays uptime statistics from your Uptime Kuma status page, including a visual uptime ring, average uptime percentage, and per-status monitor counts. Compact mode shows every configured ring and statistic without dropping them based on widget height.+This widget shows the monitors of an Uptime Kuma status page: the overall status, each monitor's recent heartbeats, its 24-hour uptime and response time, and pinned incidents or active maintenance.-Advanced view always shows the uptime ring, all status totals, and the complete monitor list with source identity, regardless of compact visibility switches.+The widget only sees what the status page publishes:-When multiple Uptime Kuma integrations are selected, monitors from healthy sources remain visible if another source fails. A warning indicator identifies each unavailable integration without exposing private request details. If every selected integration fails, the widget reports an error; if cached data remains visible after a later total failure, a stale-data warning is shown.+- Only monitors in the status page's groups are shown.+- Certificate expiry is only available when **Show Certificate Expiry** is enabled on the status page.+- The status page does not publish pause state. Monitors with old heartbeats show **No recent data** and are excluded from average uptime.++When multiple Uptime Kuma integrations are selected, monitors from healthy sources remain visible if another source fails. A warning indicator identifies each unavailable integration. If every selected integration fails, the widget reports an error.### Supported Integrations@@ -27,7 +31,7 @@ When multiple Uptime Kuma integrations are selected, monitors from healthy sourcitems={[{integration: uptimeKumaIntegration,- note: "Displays monitors from the configured status page",+ note: "Displays the monitors of the configured status page",},]}/>diff --git a/apps/docs/docs/widgets/uptime-kuma/index.ts b/apps/docs/docs/widgets/uptime-kuma/index.tsindex 69c8468e5..87d1732b9 100644--- a/apps/docs/docs/widgets/uptime-kuma/index.ts+++ b/apps/docs/docs/widgets/uptime-kuma/index.ts@@ -4,43 +4,64 @@ import { IconHeartbeat } from "@tabler/icons-react";export const uptimeKumaWidget: WidgetDefinition = {icon: IconHeartbeat,name: "Uptime Kuma",- description: "Displays monitor uptime statistics, average uptime percentage, and service status counts.",+ description: "Displays the live status, heartbeats and uptime of the monitors on an Uptime Kuma status page.",path: "../../widgets/uptime-kuma",configuration: {items: [{- name: "Show average uptime",- description: "Displays the average uptime percentage across all monitors",+ name: "Show summary",+ description: "Displays the overall status, monitor counts and averages above the monitor list",values: { type: "boolean" },defaultValue: "yes",},{- name: "Show uptime ring",- description: "Displays a ring progress indicator for average uptime",+ name: "Show incidents",+ description: "Displays pinned incidents and active maintenance from the status page",values: { type: "boolean" },defaultValue: "yes",},{- name: "Show total monitors",- description: "Displays the total number of monitors",+ name: "Group monitors",+ description: "Groups monitors like the status page does",+ values: { type: "boolean" },+ defaultValue: "no",+ },+ {+ name: "Only show issues",+ description: "Hides monitors that are up. The advanced view still lists every monitor",+ values: { type: "boolean" },+ defaultValue: "no",+ },+ {+ name: "Sort monitors by",+ description: "Order of the monitors in the list",+ values: {+ type: "select",+ options: ["Status, issues first", "Status page order", "Name", "Uptime, lowest first"],+ },+ defaultValue: "Status, issues first",+ },+ {+ name: "Show heartbeat bar",+ description: "Displays recent checks as colored bars, newest on the right",values: { type: "boolean" },defaultValue: "yes",},{- name: "Show up count",- description: "Displays the number of monitors that are up",+ name: "Show 24-hour uptime",+ description: "Displays the uptime of each monitor and the average over all monitors",values: { type: "boolean" },defaultValue: "yes",},{- name: "Show down count",- description: "Displays the number of monitors that are down",+ name: "Show response time",+ description: "Displays the latest response time of each monitor",values: { type: "boolean" },defaultValue: "yes",},{- name: "Show paused count",- description: "Displays the number of paused monitors",+ name: "Certificate warnings",+ description: "Flags certificates that expire within 14 days",values: { type: "boolean" },defaultValue: "yes",},diff --git a/bun.lock b/bun.lockindex 89f857ad0..d5e622cd8 100644--- a/bun.lock+++ b/bun.lock@@ -1010,6 +1010,7 @@"mantine-datatable": "catalog:","mantine-react-table": "catalog:","next": "catalog:",+ "next-intl": "catalog:","react": "catalog:","react-dom": "catalog:","react-markdown": "catalog:",diff --git a/packages/api/src/router/test/widgets/partial-integration-failures.spec.ts b/packages/api/src/router/test/widgets/partial-integration-failures.spec.tsindex 8c1cd8e2d..6b937e42d 100644--- a/packages/api/src/router/test/widgets/partial-integration-failures.spec.ts+++ b/packages/api/src/router/test/widgets/partial-integration-failures.spec.ts@@ -16,7 +16,7 @@ import type {TracearrDashboardData,TraefikDashboardData,UpsSummary,- UptimeKumaDashboardData,+ UptimeKumaStatusPage,} from "@homarr/integrations/types";import type * as MediaRequestListHandlerModule from "@homarr/request-handler/media-request-list";@@ -235,13 +235,12 @@ vi.mock("@homarr/request-handler/uptime-kuma", () => ({uptimeKumaRequestHandler: {handler: (integration: { name: string }) =>createHandler(integration, {- totalMonitors: 1,- upCount: 1,- downCount: 0,- pausedCount: 0,- averageUptimePercent: 100,- monitors: [{ id: 1, name: "Healthy monitor", status: "up", uptimePercent24h: 100 }],- } satisfies UptimeKumaDashboardData),+ title: "Healthy status page",+ url: "https://kuma.example.com/status/default",+ incidents: [],+ maintenances: [],+ groups: [{ id: 1, name: "Services", monitors: [] }],+ } satisfies UptimeKumaStatusPage),},}));@@ -364,12 +363,12 @@ const dashboardPartialFailureCases = [},{kind: "uptimeKuma" as const,- payloadKey: "dashboard",+ payloadKey: "statusPage",fallbackValue: null,run: async (setup: IntegrationSetup) =>await uptimeKumaRouter.createCaller({ db: setup.db, deviceType: undefined, session: setup.session })- .getDashboard({ integrationIds: setup.integrationIds }),+ .getStatusPages({ integrationIds: setup.integrationIds }),},] as const;diff --git a/packages/api/src/router/widgets/uptime-kuma.ts b/packages/api/src/router/widgets/uptime-kuma.tsindex 9e41f2da4..23304f12c 100644--- a/packages/api/src/router/widgets/uptime-kuma.ts+++ b/packages/api/src/router/widgets/uptime-kuma.ts@@ -6,7 +6,7 @@ import { settleIntegrationQueries, toPublicIntegrationError } from "../../settleimport { createTRPCRouter, publicProcedure } from "../../trpc";export const uptimeKumaRouter = createTRPCRouter({- getDashboard: publicProcedure+ getStatusPages: publicProcedure.concat(createManyWidgetIntegrationMiddleware("query", "uptimeKuma")).query(async ({ ctx }) => {return await settleIntegrationQueries(@@ -17,7 +17,7 @@ export const uptimeKumaRouter = createTRPCRouter({integrationId: integration.id,integrationName: integration.name,integrationUrl: integration.url,- dashboard: mockWidgetData.uptimeKuma,+ statusPage: mockWidgetData.uptimeKuma,updatedAt: new Date(mockWidgetData.timestamp),error: undefined,};@@ -29,7 +29,7 @@ export const uptimeKumaRouter = createTRPCRouter({integrationId: integration.id,integrationName: integration.name,integrationUrl: integration.url,- dashboard: data,+ statusPage: data,updatedAt: timestamp,error: undefined,};@@ -39,7 +39,7 @@ export const uptimeKumaRouter = createTRPCRouter({integrationId: integration.id,integrationName: integration.name,integrationUrl: integration.url,- dashboard: null,+ statusPage: null,updatedAt: new Date(0),error: toPublicIntegrationError(error),}),diff --git a/packages/integrations/src/index.ts b/packages/integrations/src/index.tsindex 1860a6582..e7596fcec 100644--- a/packages/integrations/src/index.ts+++ b/packages/integrations/src/index.ts@@ -91,7 +91,7 @@ export type { TracearrDashboardData } from "./tracearr/tracearr-types";export type { SpeedtestTrackerDashboardData } from "./speedtest-tracker/speedtest-tracker-types";export type { AudiobookshelfDashboardData } from "./audiobookshelf/audiobookshelf-types";export type { NavidromeDashboardData } from "./navidrome/navidrome-types";-export type { UptimeKumaDashboardData } from "./uptime-kuma/uptime-kuma-types";+export type { UptimeKumaStatusPage } from "./uptime-kuma/uptime-kuma-types";export type { UmamiVisitorStats } from "./umami/umami-types";export type { BazarrBadges } from "./bazarr/bazarr-types";export type { TraefikDashboardData, TraefikProtocolSummary, TraefikResourceSummary } from "./traefik/traefik-types";diff --git a/packages/integrations/src/mock/widget-data.ts b/packages/integrations/src/mock/widget-data.tsindex 5677503a6..70f8d75f8 100644--- a/packages/integrations/src/mock/widget-data.ts+++ b/packages/integrations/src/mock/widget-data.ts@@ -10,7 +10,7 @@ import type { SpeedtestTrackerDashboardData } from "../speedtest-tracker/speedteimport type { TracearrDashboardData } from "../tracearr/tracearr-types";import type { TraefikDashboardData } from "../traefik/traefik-types";import type { UmamiEventSeries, UmamiMetricItem, UmamiVisitorStats, UmamiWebsite } from "../umami/umami-types";-import type { UptimeKumaDashboardData } from "../uptime-kuma/uptime-kuma-types";+import { createUptimeKumaMockStatusPage } from "../uptime-kuma/uptime-kuma-mock";import type { LlamacppStats } from "../llama-cpp/llamacpp-types";import type { WudStats } from "../wud/wud-types";import { createWazuhMockData } from "../wazuh/wazuh-mock";@@ -317,21 +317,7 @@ export const mockWidgetData = {],},] satisfies UmamiEventSeries[],- uptimeKuma: {- totalMonitors: 6,- upCount: 5,- downCount: 1,- pausedCount: 0,- averageUptimePercent: 99.72,- monitors: [- { id: 1, name: "Homarr", status: "up", uptimePercent24h: 100 },- { id: 2, name: "Media server", status: "up", uptimePercent24h: 99.98 },- { id: 3, name: "Home cloud", status: "up", uptimePercent24h: 99.91 },- { id: 4, name: "Backups", status: "up", uptimePercent24h: 99.62 },- { id: 5, name: "VPN", status: "up", uptimePercent24h: 99.8 },- { id: 6, name: "Lab service", status: "down", uptimePercent24h: 98.99 },- ],- } satisfies UptimeKumaDashboardData,+ uptimeKuma: createUptimeKumaMockStatusPage(Date.parse(demoTimestamp)),vpn: {vpnStatus: "running",dnsStatus: "running",diff --git a/packages/integrations/src/stats/existing.ts b/packages/integrations/src/stats/existing.tsindex ebffb4919..a1ea7b8d6 100644--- a/packages/integrations/src/stats/existing.ts+++ b/packages/integrations/src/stats/existing.ts@@ -5,6 +5,7 @@ import type { IntegrationKind } from "@homarr/definitions";import type { IntegrationInput } from "../base/integration";import { createIntegrationAsync } from "../factory";+import { getUniqueUptimeKumaMonitors, summarizeUptimeKumaMonitors } from "../uptime-kuma/uptime-kuma-summary";import type { StatsMetric, StatsUnit, StatsValue } from "./types";export interface ExistingStatsProvider {@@ -301,15 +302,24 @@ existingStatsProviders.uptimeKuma = adapter(metric("totalMonitors", "Monitors"),metric("upCount", "Up"),metric("downCount", "Down"),+ metric("pendingCount", "Pending"),+ metric("maintenanceCount", "Maintenance"),+ metric("staleCount", "No recent data"),metric("averageUptimePercent", "Average uptime", "percent"),],- (client) => client.getDashboardDataAsync(),- ({ totalMonitors, upCount, downCount, averageUptimePercent }) => ({- totalMonitors,- upCount,- downCount,- averageUptimePercent,- }),+ (client) => client.getStatusPageAsync(),+ (statusPage) => {+ const summary = summarizeUptimeKumaMonitors(getUniqueUptimeKumaMonitors(statusPage.groups));+ return {+ totalMonitors: summary.total,+ upCount: summary.counts.up,+ downCount: summary.counts.down,+ pendingCount: summary.counts.pending,+ maintenanceCount: summary.counts.maintenance,+ staleCount: summary.counts.stale,+ averageUptimePercent: summary.averageUptime24h,+ };+ },);existingStatsProviders.tdarr = adapter("tdarr",diff --git a/packages/integrations/src/types.ts b/packages/integrations/src/types.tsindex eb1beee8d..f96635ee6 100644--- a/packages/integrations/src/types.ts+++ b/packages/integrations/src/types.ts@@ -21,6 +21,7 @@ export * from "./anchor/anchor-types";export * from "./tracearr/tracearr-types";export * from "./speedtest-tracker/speedtest-tracker-types";export * from "./uptime-kuma/uptime-kuma-types";+export * from "./uptime-kuma/uptime-kuma-summary";export * from "./audiobookshelf/audiobookshelf-types";export * from "./navidrome/navidrome-types";export * from "./paperless-ngx/paperless-ngx-types";diff --git a/packages/integrations/src/uptime-kuma/test/uptime-kuma-integration.spec.ts b/packages/integrations/src/uptime-kuma/test/uptime-kuma-integration.spec.tsindex f21c522b6..1f889325e 100644--- a/packages/integrations/src/uptime-kuma/test/uptime-kuma-integration.spec.ts+++ b/packages/integrations/src/uptime-kuma/test/uptime-kuma-integration.spec.ts@@ -1,162 +1,284 @@+// @vitest-environment node+import { Response } from "undici";-import { beforeEach, describe, expect, test, vi } from "vitest";+import { afterEach, beforeEach, describe, expect, test, vi } from "vitest";++vi.hoisted(() => {+ process.env.SECRET_ENCRYPTION_KEY = "0".repeat(64);+ process.env.DB_DRIVER = "better-sqlite3";+ process.env.DB_URL = ":memory:";+});import { fetchWithTrustedCertificatesAsync } from "@homarr/core/infrastructure/http";import type { IntegrationSecret } from "../../base/types";import { UptimeKumaIntegration } from "../uptime-kuma-integration";-import { uptimeKumaHeartbeatCategoryMap } from "../uptime-kuma-types";vi.mock("@homarr/core/infrastructure/http", () => ({fetchWithTrustedCertificatesAsync: vi.fn(),}));-const TEST_URL = "https://uptime.example.com";const mockFetch = vi.mocked(fetchWithTrustedCertificatesAsync);-const toUrlString = (url: unknown): string => String(url);-const createIntegration = (secrets: IntegrationSecret[] = []) =>new UptimeKumaIntegration({id: "test-uptime-kuma",name: "Test Uptime Kuma",- url: TEST_URL,- externalUrl: null,+ url: "http://kuma.internal:3001",+ externalUrl: "https://status.example.com",decryptedSecrets: secrets,});-beforeEach(() => {- mockFetch.mockReset();-});--describe("uptimeKumaHeartbeatCategoryMap", () => {- test("maps status 0 (down) to 'down'", () => {- expect(uptimeKumaHeartbeatCategoryMap[0]).toBe("down");+const respondWith = (statusPage: unknown, heartbeat: unknown) => {+ mockFetch.mockImplementation((url) => {+ const body = String(url).includes("/heartbeat/") ? heartbeat : statusPage;+ return Promise.resolve(new Response(JSON.stringify(body), { status: 200 })) as unknown as ReturnType<+ typeof fetchWithTrustedCertificatesAsync+ >;});+};- test("maps status 1 (up) to 'up'", () => {- expect(uptimeKumaHeartbeatCategoryMap[1]).toBe("up");- });+const requestedUrls = () => mockFetch.mock.calls.map(([url]) => String(url));- test("maps status 2 (pending) to 'paused'", () => {- expect(uptimeKumaHeartbeatCategoryMap[2]).toBe("paused");- });+const beat = (status: number, time: string, ping: number | null = null) => ({ status, time, msg: "", ping });- test("maps status 3 (maintenance) to 'paused'", () => {- expect(uptimeKumaHeartbeatCategoryMap[3]).toBe("paused");- });+beforeEach(() => {+ mockFetch.mockReset();+ vi.useFakeTimers({ toFake: ["Date"], now: Date.UTC(2026, 9, 17, 9, 5) });+});- test("returns undefined for unknown status codes", () => {- expect(uptimeKumaHeartbeatCategoryMap[99]).toBeUndefined();- });+afterEach(() => {+ vi.useRealTimers();});-describe("UptimeKumaIntegration.getDashboardDataAsync", () => {- const statusPageResponse = {- publicGroupList: [+describe("UptimeKumaIntegration.getStatusPageAsync", () => {+ test("maps an Uptime Kuma 2 status page with heartbeats, certificates, incidents and maintenance", async () => {+ respondWith({- id: 1,- name: "Services",- monitorList: [- { id: 10, name: "Web" },- { id: 20, name: "API" },- { id: 30, name: "DB" },+ config: { slug: "homelab", title: "Homelab" },+ incidents: [+ {+ id: 4,+ style: "danger",+ title: "NAS outage",+ content: "Disk replacement in progress",+ pin: true,+ active: true,+ createdDate: "2026-10-17 08:00:00",+ lastUpdatedDate: null,+ },+ ],+ maintenanceList: [{ id: 2, title: "Router firmware", description: "", strategy: "manual" }],+ publicGroupList: [+ {+ id: 1,+ name: "Core",+ weight: 1,+ monitorList: [+ {+ id: 10,+ name: "Docs",+ sendUrl: 1,+ type: "http",+ url: "https://docs.example.com",+ tags: [{ id: 1, monitor_id: 10, tag_id: 3, value: "", name: "web", color: "#2563eb" }],+ certExpiryDaysRemaining: 41,+ validCert: true,+ },+ { id: 20, name: "NAS", sendUrl: 0, type: "ping", certExpiryDaysRemaining: "", validCert: false },+ ],+ },],},- ],- };-- const heartbeatResponse = {- heartbeatList: {- "10": [{ status: 1, time: "2025-01-01" }],- "20": [{ status: 0, time: "2025-01-01" }],- "30": [{ status: 2, time: "2025-01-01" }],- },- uptimeList: {- "10_24": 0.995,- "20_24": 0.5,- "30_24": 0.8,- },- };-- const mockResponses = () => {- mockFetch.mockImplementation((url) => {- const urlStr = toUrlString(url);-- if (urlStr.includes("/heartbeat/")) {- return Promise.resolve(- new Response(JSON.stringify(heartbeatResponse), { status: 200 }),- ) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;- }-- return Promise.resolve(- new Response(JSON.stringify(statusPageResponse), { status: 200 }),- ) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;- });- };+ {+ heartbeatList: {+ "10": [beat(1, "2026-10-17 09:00:00.000", 120), beat(1, "2026-10-17 09:01:00.000", 80)],+ "20": [+ beat(1, "2026-10-17 09:00:00.000", 2),+ beat(0, "2026-10-17 09:01:00.000"),+ beat(0, "2026-10-17 09:02:00.000"),+ ],+ },+ uptimeList: { "10_24": 1, "20_24": 0.875 },+ },+ );- test("aggregates monitor counts correctly", async () => {- mockResponses();- const integration = createIntegration([{ kind: "slug", value: "default" }]);- const result = await integration.getDashboardDataAsync();+ const statusPage = await createIntegration([{ kind: "slug", value: "Homelab" }]).getStatusPageAsync();- expect(result.totalMonitors).toBe(3);- expect(result.upCount).toBe(1);- expect(result.downCount).toBe(1);- expect(result.pausedCount).toBe(1);+ expect(requestedUrls()).toEqual([+ "http://kuma.internal:3001/api/status-page/homelab",+ "http://kuma.internal:3001/api/status-page/heartbeat/homelab",+ ]);+ expect(statusPage).toEqual({+ title: "Homelab",+ url: "https://status.example.com/status/homelab",+ incidents: [+ {+ id: 4,+ title: "NAS outage",+ content: "Disk replacement in progress",+ style: "danger",+ createdAt: Date.UTC(2026, 9, 17, 8),+ updatedAt: null,+ },+ ],+ maintenances: [{ id: 2, title: "Router firmware", description: null }],+ groups: [+ {+ id: 1,+ name: "Core",+ monitors: [+ {+ id: 10,+ name: "Docs",+ type: "http",+ url: "https://docs.example.com",+ status: "up",+ uptime24h: 100,+ ping: 80,+ lastCheckAt: Date.UTC(2026, 9, 17, 9, 1),+ statusSince: null,+ certificateDaysRemaining: 41,+ tags: [{ name: "web", color: "#2563eb", value: null }],+ heartbeats: [+ { status: "up", time: Date.UTC(2026, 9, 17, 9), ping: 120 },+ { status: "up", time: Date.UTC(2026, 9, 17, 9, 1), ping: 80 },+ ],+ },+ {+ id: 20,+ name: "NAS",+ type: "ping",+ url: null,+ status: "down",+ uptime24h: 87.5,+ ping: null,+ lastCheckAt: Date.UTC(2026, 9, 17, 9, 2),+ statusSince: Date.UTC(2026, 9, 17, 9, 1),+ certificateDaysRemaining: null,+ tags: [],+ heartbeats: [+ { status: "up", time: Date.UTC(2026, 9, 17, 9), ping: 2 },+ { status: "down", time: Date.UTC(2026, 9, 17, 9, 1), ping: null },+ { status: "down", time: Date.UTC(2026, 9, 17, 9, 2), ping: null },+ ],+ },+ ],+ },+ ],+ });});- test("computes average uptime from uptimeList", async () => {- mockResponses();- const integration = createIntegration([{ kind: "slug", value: "default" }]);- const result = await integration.getDashboardDataAsync();+ test("supports the Uptime Kuma 1 response shape and the default slug", async () => {+ vi.setSystemTime(Date.UTC(2024, 0, 1, 12));+ respondWith(+ {+ config: { slug: "default", title: "" },+ incident: { id: 1, style: "info", title: "Planned work", content: null, createdDate: "2024-01-01 10:00:00" },+ maintenanceList: [],+ publicGroupList: [+ {+ id: 1,+ name: "Services",+ monitorList: [+ { id: 1, name: "Pending", type: "http" },+ { id: 2, name: "Maintenance", type: "http" },+ { id: 3, name: "Never checked", type: "http" },+ { id: 4, name: "Last checked last week", type: "http" },+ ],+ },+ ],+ },+ {+ heartbeatList: {+ "1": [beat(2, "2024-01-01 10:00:00")],+ "2": [beat(3, "2024-01-01 10:00:00")],+ "4": [beat(1, "2023-12-24 10:00:00")],+ },+ uptimeList: { "1_24": 0.5, "3_24": 0, "4_24": 0 },+ },+ );++ const statusPage = await createIntegration().getStatusPageAsync();- const expectedAverage = ((0.995 + 0.5 + 0.8) * 100) / 3;- expect(result.averageUptimePercent).toBeCloseTo(expectedAverage, 5);+ expect(requestedUrls()).toContain("http://kuma.internal:3001/api/status-page/default");+ expect(statusPage.title).toBe("default");+ expect(statusPage.incidents).toEqual([+ {+ id: 1,+ title: "Planned work",+ content: null,+ style: "info",+ createdAt: Date.UTC(2024, 0, 1, 10),+ updatedAt: null,+ },+ ]);+ expect(statusPage.groups[0]?.monitors.map(({ name, status, uptime24h }) => ({ name, status, uptime24h }))).toEqual([+ { name: "Pending", status: "pending", uptime24h: 50 },+ { name: "Maintenance", status: "maintenance", uptime24h: null },+ { name: "Never checked", status: "unknown", uptime24h: null },+ { name: "Last checked last week", status: "stale", uptime24h: null },+ ]);});- test("defaults unknown heartbeat status to 'down'", async () => {- const unknownHeartbeat = {- heartbeatList: { "10": [{ status: 99, time: "2025-01-01" }] },- uptimeList: { "10_24": 1 },- };-- mockFetch.mockImplementation((url) => {- const urlStr = toUrlString(url);- if (urlStr.includes("/heartbeat/")) {- return Promise.resolve(- new Response(JSON.stringify(unknownHeartbeat), { status: 200 }),- ) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;- }- return Promise.resolve(- new Response(- JSON.stringify({- publicGroupList: [{ id: 1, name: "G", monitorList: [{ id: 10, name: "Svc" }] }],- }),- { status: 200 },- ),- ) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>;- });+ test("marks monitors with old heartbeats as stale", async () => {+ const everyMinuteUntil = (hour: number, minute: number) =>+ Array.from({ length: 5 }, (_, index) =>+ beat(1, new Date(Date.UTC(2026, 9, 17, hour, minute - 4 + index)).toISOString()),+ );+ respondWith(+ {+ publicGroupList: [+ {+ id: 1,+ name: "Group",+ monitorList: [+ { id: 1, name: "Active" },+ { id: 2, name: "Stopped 35 minutes ago" },+ { id: 3, name: "Single check an hour ago" },+ { id: 4, name: "Checked every two hours" },+ { id: 5, name: "Single check two days ago" },+ ],+ },+ ],+ },+ {+ heartbeatList: {+ "1": everyMinuteUntil(9, 4),+ "2": everyMinuteUntil(8, 30),+ "3": [beat(0, "2026-10-17 08:00:00")],+ "4": [beat(1, "2026-10-17 06:00:00"), beat(1, "2026-10-17 08:00:00")],+ "5": [beat(1, "2026-10-15 09:00:00")],+ },+ uptimeList: { "1_24": 1, "2_24": 0.99, "3_24": 0, "4_24": 1, "5_24": 1 },+ },+ );- const integration = createIntegration([{ kind: "slug", value: "default" }]);- const result = await integration.getDashboardDataAsync();+ const statusPage = await createIntegration().getStatusPageAsync();- expect(result.monitors[0]?.status).toBe("down");- expect(result.downCount).toBe(1);+ expect(statusPage.groups[0]?.monitors.map(({ name, status, uptime24h }) => ({ name, status, uptime24h }))).toEqual([+ { name: "Active", status: "up", uptime24h: 100 },+ { name: "Stopped 35 minutes ago", status: "stale", uptime24h: 99 },+ { name: "Single check an hour ago", status: "down", uptime24h: 0 },+ { name: "Checked every two hours", status: "up", uptime24h: 100 },+ { name: "Single check two days ago", status: "stale", uptime24h: null },+ ]);});- test("handles empty monitor list gracefully", async () => {- mockFetch.mockImplementation(- () =>- Promise.resolve(- new Response(JSON.stringify({ publicGroupList: [], heartbeatList: {}, uptimeList: {} }), { status: 200 }),- ) as unknown as ReturnType<typeof fetchWithTrustedCertificatesAsync>,+ test("keeps only the 50 newest heartbeats, oldest first", async () => {+ const heartbeats = Array.from({ length: 100 }, (_, minute) =>+ beat(1, new Date(Date.UTC(2026, 0, 1, 0, minute)).toISOString(), minute),+ );+ respondWith(+ { publicGroupList: [{ id: 1, name: "Group", monitorList: [{ id: 7, name: "Busy" }] }] },+ { heartbeatList: { "7": heartbeats.toReversed() }, uptimeList: {} },);- const integration = createIntegration([{ kind: "slug", value: "default" }]);- const result = await integration.getDashboardDataAsync();+ const statusPage = await createIntegration().getStatusPageAsync();+ const monitor = statusPage.groups[0]?.monitors[0];- expect(result.totalMonitors).toBe(0);- expect(result.averageUptimePercent).toBe(0);+ expect(monitor?.heartbeats).toHaveLength(50);+ expect(monitor?.heartbeats[0]?.time).toBe(Date.UTC(2026, 0, 1, 0, 50));+ expect(monitor?.heartbeats.at(-1)?.time).toBe(Date.UTC(2026, 0, 1, 1, 39));});});diff --git a/packages/integrations/src/uptime-kuma/uptime-kuma-integration.ts b/packages/integrations/src/uptime-kuma/uptime-kuma-integration.tsindex ce494e599..017b098ab 100644--- a/packages/integrations/src/uptime-kuma/uptime-kuma-integration.ts+++ b/packages/integrations/src/uptime-kuma/uptime-kuma-integration.ts@@ -6,36 +6,51 @@ import { Integration } from "../base/integration";import { TestConnectionError } from "../base/test-connection/test-connection-error";import type { TestingResult } from "../base/test-connection/test-connection-service";import {- uptimeKumaHeartbeatCategoryMap,+ toUptimeKumaMonitorStatus,uptimeKumaHeartbeatResponseSchema,+ uptimeKumaIncidentStyles,+ uptimeKumaMaxHeartbeats,uptimeKumaStatusPageResponseSchema,} from "./uptime-kuma-types";-import type { UptimeKumaDashboardData, UptimeKumaMonitor, UptimeKumaMonitorCategory } from "./uptime-kuma-types";+import type {+ UptimeKumaHeartbeat,+ UptimeKumaHeartbeatResponse,+ UptimeKumaIncident,+ UptimeKumaIncidentStyle,+ UptimeKumaMonitor,+ UptimeKumaMonitorStatus,+ UptimeKumaStatusPage,+ UptimeKumaStatusPageResponse,+} from "./uptime-kuma-types";++const uptimeWindowMs = 24 * 60 * 60 * 1000;+const minimumStaleAgeMs = 10 * 60 * 1000;+const missedChecksUntilStale = 5;++type StatusPageMonitor = UptimeKumaStatusPageResponse["publicGroupList"][number]["monitorList"][number];+type StatusPageIncident = NonNullable<UptimeKumaStatusPageResponse["incident"]>;+type RawHeartbeat = UptimeKumaHeartbeatResponse["heartbeatList"][string][number];export class UptimeKumaIntegration extends Integration {protected async testingAsync(input: IntegrationTestingInput): Promise<TestingResult> {- const statusPageResponse = await input.fetchAsync(this.statusPageUrl());-+ const statusPageResponse = await input.fetchAsync(this.statusPageApiUrl());if (!statusPageResponse.ok) {return TestConnectionError.StatusResult(statusPageResponse);}const statusPageParsed = uptimeKumaStatusPageResponseSchema.safeParse(await statusPageResponse.json());-if (!statusPageParsed.success) {return TestConnectionError.ParseResult(new ParseError("Invalid Uptime Kuma status page response", { cause: statusPageParsed.error }),);}- const heartbeatResponse = await input.fetchAsync(this.heartbeatUrl());-+ const heartbeatResponse = await input.fetchAsync(this.heartbeatApiUrl());if (!heartbeatResponse.ok) {return TestConnectionError.StatusResult(heartbeatResponse);}const heartbeatParsed = uptimeKumaHeartbeatResponseSchema.safeParse(await heartbeatResponse.json());-if (!heartbeatParsed.success) {return TestConnectionError.ParseResult(new ParseError("Invalid Uptime Kuma heartbeat response", { cause: heartbeatParsed.error }),@@ -45,96 +60,174 @@ export class UptimeKumaIntegration extends Integration {return { success: true };}- public async getDashboardDataAsync(): Promise<UptimeKumaDashboardData> {+ public async getStatusPageAsync(signal?: AbortSignal): Promise<UptimeKumaStatusPage> {const [statusPageResponse, heartbeatResponse] = await Promise.all([- this.getStatusPageAsync(),- this.getHeartbeatAsync(),+ this.fetchOkAsync(this.statusPageApiUrl(), signal),+ this.fetchOkAsync(this.heartbeatApiUrl(), signal),]);const statusPage = uptimeKumaStatusPageResponseSchema.parse(await statusPageResponse.json());const heartbeat = uptimeKumaHeartbeatResponseSchema.parse(await heartbeatResponse.json());-- const monitors = statusPage.publicGroupList.flatMap((group) =>- group.monitorList.map((monitor) => this.mapMonitor(monitor, heartbeat)),+ const slug = this.getSlug();+ const heartbeatsByMonitor = new Map(+ Object.entries(heartbeat.heartbeatList).map(([monitorId, heartbeats]) => [+ Number(monitorId),+ heartbeats+ .flatMap(mapHeartbeat)+ .toSorted((left, right) => left.time - right.time)+ .slice(-uptimeKumaMaxHeartbeats),+ ]),);- return this.buildDashboardData(monitors);- }-- private mapMonitor(- monitor: { id: number; name: string },- heartbeat: { heartbeatList: Record<string, { status: number }[]>; uptimeList: Record<string, number> },- ): UptimeKumaMonitor {- const heartbeats = heartbeat.heartbeatList[String(monitor.id)] ?? [];- const latestHeartbeat = heartbeats.at(-1);- const uptimeKey = `${monitor.id}_24`;- const uptimeRaw = heartbeat.uptimeList[uptimeKey];- const uptimePercent24h = typeof uptimeRaw === "number" ? uptimeRaw * 100 : null;- const status: UptimeKumaMonitorCategory =- (latestHeartbeat && (uptimeKumaHeartbeatCategoryMap[latestHeartbeat.status] ?? "down")) || "paused";-return {- id: monitor.id,- name: monitor.name,- status,- uptimePercent24h,+ title: statusPage.config?.title?.trim() || slug,+ url: this.externalUrl(`/status/${encodeURIComponent(slug)}`).toString(),+ groups: statusPage.publicGroupList.map((group) => ({+ id: group.id,+ name: group.name,+ monitors: group.monitorList.map((monitor) =>+ mapMonitor(monitor, {+ heartbeats: heartbeatsByMonitor.get(monitor.id) ?? [],+ uptimeRatio: heartbeat.uptimeList[`${monitor.id}_24`],+ }),+ ),+ })),+ incidents: uniqueById([statusPage.incidents ?? [], statusPage.incident ?? []].flat()).map(mapIncident),+ maintenances: (statusPage.maintenanceList ?? []).map((maintenance) => ({+ id: maintenance.id,+ title: maintenance.title?.trim() || "",+ description: maintenance.description?.trim() || null,+ })),};}- private buildDashboardData(monitors: UptimeKumaMonitor[]): UptimeKumaDashboardData {- const counts = monitors.reduce(- (acc, monitor) => {- acc[monitor.status] += 1;- return acc;- },- { up: 0, down: 0, paused: 0 },- );-- const uptimeValues = monitors- .map((monitor) => monitor.uptimePercent24h)- .filter((value): value is number => value !== null);-- const averageUptimePercent = uptimeValues.reduce((sum, value) => sum + value, 0) / Math.max(uptimeValues.length, 1);-- return {- totalMonitors: monitors.length,- upCount: counts.up,- downCount: counts.down,- pausedCount: counts.paused,- averageUptimePercent,- monitors,- };- }-- private async fetchOkAsync(url: string | URL) {- const response = await fetchWithTrustedCertificatesAsync(url);+ private async fetchOkAsync(url: URL, signal?: AbortSignal) {+ const response = await fetchWithTrustedCertificatesAsync(url, { signal });if (!response.ok) {throw new ResponseError(response);}return response;}- private getStatusPageAsync() {- return this.fetchOkAsync(this.statusPageUrl());- }-- private getHeartbeatAsync() {- return this.fetchOkAsync(this.heartbeatUrl());+ private statusPageApiUrl() {+ return this.url(`/api/status-page/${encodeURIComponent(this.getSlug())}`);}- private statusPageUrl() {- return this.url(`/api/status-page/${this.getSlug()}`);- }-- private heartbeatUrl() {- return this.url(`/api/status-page/heartbeat/${this.getSlug()}`);+ private heartbeatApiUrl() {+ return this.url(`/api/status-page/heartbeat/${encodeURIComponent(this.getSlug())}`);}private getSlug() {if (this.hasSecretValue("slug")) {- return this.getSecretValue("slug").toLowerCase();+ return this.getSecretValue("slug").trim().toLowerCase();}return "default";}}++interface MonitorHeartbeatData {+ heartbeats: UptimeKumaHeartbeat[];+ uptimeRatio: number | undefined;+}++const mapMonitor = (+ monitor: StatusPageMonitor,+ { heartbeats, uptimeRatio }: MonitorHeartbeatData,+): UptimeKumaMonitor => {+ const latest = heartbeats.at(-1);+ const checkedWithinUptimeWindow = latest !== undefined && Date.now() - latest.time <= uptimeWindowMs;+ const status = getMonitorStatus(latest, getCheckInterval(heartbeats));+ let statusSince: number | null = null;+ if (status !== "stale") statusSince = getStatusSince(heartbeats);++ return {+ id: monitor.id,+ name: monitor.name,+ type: monitor.type ?? null,+ url: monitor.url?.trim() || null,+ status,+ uptime24h:+ checkedWithinUptimeWindow && typeof uptimeRatio === "number"+ ? Math.min(100, Math.max(0, uptimeRatio * 100))+ : null,+ ping: latest?.ping ?? null,+ lastCheckAt: latest?.time ?? null,+ statusSince,+ certificateDaysRemaining: getCertificateDaysRemaining(monitor),+ tags: (monitor.tags ?? []).map((tag) => ({+ name: tag.name,+ color: tag.color ?? null,+ value: tag.value?.trim() || null,+ })),+ heartbeats,+ };+};++const getMonitorStatus = (+ latest: UptimeKumaHeartbeat | undefined,+ checkInterval: number | null,+): UptimeKumaMonitorStatus => {+ if (!latest) return "unknown";+ if (Date.now() - latest.time > getStaleAfter(checkInterval)) return "stale";+ return latest.status;+};++const getStaleAfter = (checkInterval: number | null) => {+ if (checkInterval === null) return uptimeWindowMs;+ return Math.max(minimumStaleAgeMs, checkInterval * missedChecksUntilStale);+};++const getCheckInterval = (heartbeats: readonly UptimeKumaHeartbeat[]) =>+ median(heartbeats.slice(1).map((heartbeat, index) => heartbeat.time - (heartbeats[index]?.time ?? heartbeat.time)));++const median = (values: readonly number[]) => {+ if (values.length === 0) return null;+ const sorted = values.toSorted((left, right) => left - right);+ return sorted[Math.floor(sorted.length / 2)] ?? null;+};++const uniqueById = <TItem extends { id: number }>(items: readonly TItem[]) => [+ ...new Map(items.map((item) => [item.id, item])).values(),+];++const mapHeartbeat = (heartbeat: RawHeartbeat): UptimeKumaHeartbeat[] => {+ const time = parseUptimeKumaDate(heartbeat.time);+ if (time === null) return [];+ return [{ status: toUptimeKumaMonitorStatus(heartbeat.status), time, ping: heartbeat.ping ?? null }];+};++const mapIncident = (incident: StatusPageIncident): UptimeKumaIncident => ({+ id: incident.id,+ title: incident.title?.trim() || "",+ content: incident.content?.trim() || null,+ style: isIncidentStyle(incident.style) ? incident.style : "warning",+ createdAt: parseUptimeKumaDate(incident.createdDate),+ updatedAt: parseUptimeKumaDate(incident.lastUpdatedDate),+});++const isIncidentStyle = (style: string | null | undefined): style is UptimeKumaIncidentStyle =>+ uptimeKumaIncidentStyles.some((value) => value === style);++const getStatusSince = (heartbeats: readonly UptimeKumaHeartbeat[]) => {+ const latest = heartbeats.at(-1);+ if (!latest) return null;++ for (let index = heartbeats.length - 2; index >= 0; index--) {+ if (heartbeats[index]?.status !== latest.status) return heartbeats[index + 1]?.time ?? null;+ }+ return null;+};++const getCertificateDaysRemaining = (monitor: StatusPageMonitor) => {+ if (monitor.validCert !== true || typeof monitor.certExpiryDaysRemaining !== "number") return null;+ return monitor.certExpiryDaysRemaining;+};++const parseUptimeKumaDate = (value: string | null | undefined) => {+ if (!value) return null;+ const normalized = value.includes("T") ? value : value.replace(" ", "T");+ const hasOffset = /(?:Z|[+-]\d{2}:?\d{2})$/i.test(normalized);+ const time = Date.parse(hasOffset ? normalized : `${normalized}Z`);+ return Number.isNaN(time) ? null : time;+};diff --git a/packages/integrations/src/uptime-kuma/uptime-kuma-mock.ts b/packages/integrations/src/uptime-kuma/uptime-kuma-mock.tsnew file mode 100644index 000000000..afc3ab853--- /dev/null+++ b/packages/integrations/src/uptime-kuma/uptime-kuma-mock.ts@@ -0,0 +1,137 @@+import { uptimeKumaMaxHeartbeats as heartbeatCount } from "./uptime-kuma-types";+import type {+ UptimeKumaHeartbeat,+ UptimeKumaMonitor,+ UptimeKumaMonitorStatus,+ UptimeKumaStatusPage,+} from "./uptime-kuma-types";++const heartbeatIntervalMs = 60_000;++interface MockMonitor {+ id: number;+ name: string;+ type: string;+ basePing: number;+ uptime24h: number;+ certificateDaysRemaining?: number;+ statusAt: (index: number) => UptimeKumaMonitorStatus;+}++const steady = (): UptimeKumaMonitorStatus => "up";+const failingFrom =+ (start: number): MockMonitor["statusAt"] =>+ (index) =>+ index >= start ? "down" : "up";+const blipsAt =+ (indices: readonly number[], status: UptimeKumaMonitorStatus): MockMonitor["statusAt"] =>+ (index) =>+ indices.includes(index) ? status : "up";++const groups: { id: number; name: string; monitors: MockMonitor[] }[] = [+ {+ id: 1,+ name: "Services",+ monitors: [+ {+ id: 1,+ name: "Homarr",+ type: "http",+ basePing: 42,+ uptime24h: 100,+ certificateDaysRemaining: 61,+ statusAt: steady,+ },+ {+ id: 2,+ name: "Media server",+ type: "http",+ basePing: 118,+ uptime24h: 99.98,+ statusAt: blipsAt([17], "pending"),+ },+ {+ id: 3,+ name: "Home cloud",+ type: "keyword",+ basePing: 236,+ uptime24h: 99.91,+ certificateDaysRemaining: 9,+ statusAt: blipsAt([31, 32], "down"),+ },+ {+ id: 4,+ name: "Backups",+ type: "push",+ basePing: 12,+ uptime24h: 99.62,+ statusAt: blipsAt([heartbeatCount - 1], "pending"),+ },+ ],+ },+ {+ id: 2,+ name: "Network",+ monitors: [+ { id: 5, name: "VPN", type: "port", basePing: 21, uptime24h: 99.8, statusAt: steady },+ { id: 6, name: "DNS resolver", type: "dns", basePing: 8, uptime24h: 100, statusAt: steady },+ {+ id: 7,+ name: "Lab service",+ type: "ping",+ basePing: 64,+ uptime24h: 98.99,+ statusAt: failingFrom(heartbeatCount - 6),+ },+ ],+ },+];++export const createUptimeKumaMockStatusPage = (now: number): UptimeKumaStatusPage => ({+ title: "Homelab",+ url: "https://status.homarr.dev/status/homelab",+ incidents: [+ {+ id: 1,+ title: "Lab service unreachable",+ content: "The lab host is being re-cabled.",+ style: "warning",+ createdAt: now - 6 * heartbeatIntervalMs,+ updatedAt: null,+ },+ ],+ maintenances: [],+ groups: groups.map((group) => ({+ id: group.id,+ name: group.name,+ monitors: group.monitors.map((monitor) => createMockMonitor(monitor, now)),+ })),+});++const createMockMonitor = (monitor: MockMonitor, now: number): UptimeKumaMonitor => {+ const heartbeats: UptimeKumaHeartbeat[] = Array.from({ length: heartbeatCount }, (_, index) => {+ const status = monitor.statusAt(index);+ return {+ status,+ time: now - (heartbeatCount - 1 - index) * heartbeatIntervalMs,+ ping: status === "down" ? null : monitor.basePing + ((index * 37) % 23),+ };+ });+ const latest = heartbeats.at(-1);+ const firstOfStreak = heartbeats.findLastIndex((heartbeat) => heartbeat.status !== latest?.status) + 1;++ return {+ id: monitor.id,+ name: monitor.name,+ type: monitor.type,+ url: null,+ status: latest?.status ?? "unknown",+ uptime24h: monitor.uptime24h,+ ping: latest?.ping ?? null,+ lastCheckAt: latest?.time ?? null,+ statusSince: firstOfStreak === 0 ? null : (heartbeats[firstOfStreak]?.time ?? null),+ certificateDaysRemaining: monitor.certificateDaysRemaining ?? null,+ tags: [],+ heartbeats,+ };+};diff --git a/packages/integrations/src/uptime-kuma/uptime-kuma-summary.ts b/packages/integrations/src/uptime-kuma/uptime-kuma-summary.tsnew file mode 100644index 000000000..9eed34f6d--- /dev/null+++ b/packages/integrations/src/uptime-kuma/uptime-kuma-summary.ts@@ -0,0 +1,58 @@+import type { UptimeKumaGroup, UptimeKumaMonitor, UptimeKumaMonitorStatus } from "./uptime-kuma-types";++export type UptimeKumaOverallStatus = "operational" | "degraded" | "outage" | "maintenance" | "unknown";++export interface UptimeKumaSummary {+ total: number;+ counts: Record<UptimeKumaMonitorStatus, number>;+ averageUptime24h: number | null;+ overallStatus: UptimeKumaOverallStatus;+}++type SummarizableMonitor = Pick<UptimeKumaMonitor, "status" | "uptime24h">;++const inactiveStatuses = new Set<UptimeKumaMonitorStatus>(["stale", "unknown"]);++export const isInactiveUptimeKumaStatus = (status: UptimeKumaMonitorStatus) => inactiveStatuses.has(status);++export const getUniqueUptimeKumaMonitors = (groups: readonly UptimeKumaGroup[]): UptimeKumaMonitor[] => [+ ...new Map(groups.flatMap((group) => group.monitors).map((monitor) => [monitor.id, monitor])).values(),+];++export const summarizeUptimeKumaMonitors = (monitors: readonly SummarizableMonitor[]): UptimeKumaSummary => {+ const counts: Record<UptimeKumaMonitorStatus, number> = {+ up: 0,+ down: 0,+ pending: 0,+ maintenance: 0,+ stale: 0,+ unknown: 0,+ };+ for (const monitor of monitors) counts[monitor.status] += 1;+ const activeMonitors = monitors.filter((monitor) => !isInactiveUptimeKumaStatus(monitor.status));++ return {+ total: monitors.length,+ counts,+ averageUptime24h: average(activeMonitors.map((monitor) => monitor.uptime24h)),+ overallStatus: getOverallStatus(counts, activeMonitors.length),+ };+};++const getOverallStatus = (+ counts: Record<UptimeKumaMonitorStatus, number>,+ activeCount: number,+): UptimeKumaOverallStatus => {+ if (activeCount === 0) return "unknown";+ if (counts.down === activeCount) return "outage";+ if (counts.down + counts.pending > 0) return "degraded";+ if (counts.maintenance > 0) return "maintenance";+ if (counts.stale + counts.unknown > 0) return "unknown";+ return "operational";+};++const average = (values: readonly (number | null)[]) => {+ const numbers = values.filter((value): value is number => value !== null);+ if (numbers.length === 0) return null;+ return numbers.reduce((sum, value) => sum + value, 0) / numbers.length;+};diff --git a/packages/integrations/src/uptime-kuma/uptime-kuma-types.ts b/packages/integrations/src/uptime-kuma/uptime-kuma-types.tsindex f029754a8..7b87035f5 100644--- a/packages/integrations/src/uptime-kuma/uptime-kuma-types.ts+++ b/packages/integrations/src/uptime-kuma/uptime-kuma-types.ts@@ -1,62 +1,130 @@import { z } from "zod";-export const uptimeKumaHeartbeatStatus = {- down: 0,- up: 1,- pending: 2,- maintenance: 3,-} as const;--export type UptimeKumaMonitorCategory = "up" | "down" | "paused";--export const uptimeKumaHeartbeatCategoryMap: Record<number, UptimeKumaMonitorCategory> = {- [uptimeKumaHeartbeatStatus.down]: "down",- [uptimeKumaHeartbeatStatus.up]: "up",- [uptimeKumaHeartbeatStatus.pending]: "paused",- [uptimeKumaHeartbeatStatus.maintenance]: "paused",+export type UptimeKumaMonitorStatus = "up" | "down" | "pending" | "maintenance" | "stale" | "unknown";++export const uptimeKumaMaxHeartbeats = 50;++const monitorStatusByHeartbeatCode: Record<number, UptimeKumaMonitorStatus> = {+ 0: "down",+ 1: "up",+ 2: "pending",+ 3: "maintenance",};-export const uptimeKumaStatusPageMonitorSchema = z.object({+export const toUptimeKumaMonitorStatus = (heartbeatCode: number): UptimeKumaMonitorStatus =>+ monitorStatusByHeartbeatCode[heartbeatCode] ?? "unknown";++export const uptimeKumaIncidentStyles = ["info", "warning", "danger", "primary", "light", "dark"] as const;+export type UptimeKumaIncidentStyle = (typeof uptimeKumaIncidentStyles)[number];++const tagSchema = z.object({+ name: z.string(),+ color: z.string().nullish(),+ value: z.string().nullish(),+});++const statusPageMonitorSchema = z.object({id: z.number().int(),name: z.string(),+ type: z.string().nullish(),+ url: z.string().nullish(),+ tags: z.array(tagSchema).nullish(),+ certExpiryDaysRemaining: z.union([z.number(), z.string()]).nullish(),+ validCert: z.boolean().nullish(),});-export const uptimeKumaStatusPageGroupSchema = z.object({+const statusPageGroupSchema = z.object({id: z.number().int(),name: z.string(),- monitorList: z.array(uptimeKumaStatusPageMonitorSchema),+ monitorList: z.array(statusPageMonitorSchema),});-export const uptimeKumaStatusPageResponseSchema = z.object({- publicGroupList: z.array(uptimeKumaStatusPageGroupSchema),+const incidentSchema = z.object({+ id: z.number().int(),+ title: z.string().nullish(),+ content: z.string().nullish(),+ style: z.string().nullish(),+ createdDate: z.string().nullish(),+ lastUpdatedDate: z.string().nullish(),+});++const maintenanceSchema = z.object({+ id: z.number().int(),+ title: z.string().nullish(),+ description: z.string().nullish(),});-export const uptimeKumaHeartbeatEntrySchema = z.object({- status: z.number().int(),- time: z.string(),- ping: z.number().nullable().optional(),+export const uptimeKumaStatusPageResponseSchema = z.object({+ config: z.object({ title: z.string().nullish() }).nullish(),+ incident: incidentSchema.nullish(),+ incidents: z.array(incidentSchema).nullish(),+ maintenanceList: z.array(maintenanceSchema).nullish(),+ publicGroupList: z.array(statusPageGroupSchema),});export const uptimeKumaHeartbeatResponseSchema = z.object({- heartbeatList: z.record(z.string(), z.array(uptimeKumaHeartbeatEntrySchema)),+ heartbeatList: z.record(+ z.string(),+ z.array(z.object({ status: z.number().int(), time: z.string(), ping: z.number().nullish() })),+ ),uptimeList: z.record(z.string(), z.number()),});+export type UptimeKumaStatusPageResponse = z.infer<typeof uptimeKumaStatusPageResponseSchema>;+export type UptimeKumaHeartbeatResponse = z.infer<typeof uptimeKumaHeartbeatResponseSchema>;++export interface UptimeKumaHeartbeat {+ status: UptimeKumaMonitorStatus;+ time: number;+ ping: number | null;+}++export interface UptimeKumaTag {+ name: string;+ color: string | null;+ value: string | null;+}+export interface UptimeKumaMonitor {id: number;name: string;- status: UptimeKumaMonitorCategory;- uptimePercent24h: number | null;+ type: string | null;+ url: string | null;+ status: UptimeKumaMonitorStatus;+ uptime24h: number | null;+ ping: number | null;+ lastCheckAt: number | null;+ statusSince: number | null;+ certificateDaysRemaining: number | null;+ tags: UptimeKumaTag[];+ heartbeats: UptimeKumaHeartbeat[];}-export interface UptimeKumaDashboardData {- totalMonitors: number;- upCount: number;- downCount: number;- pausedCount: number;- averageUptimePercent: number;+export interface UptimeKumaGroup {+ id: number;+ name: string;monitors: UptimeKumaMonitor[];}-export type UptimeKumaStatusPageResponse = z.infer<typeof uptimeKumaStatusPageResponseSchema>;-export type UptimeKumaHeartbeatResponse = z.infer<typeof uptimeKumaHeartbeatResponseSchema>;+export interface UptimeKumaIncident {+ id: number;+ title: string;+ content: string | null;+ style: UptimeKumaIncidentStyle;+ createdAt: number | null;+ updatedAt: number | null;+}++export interface UptimeKumaMaintenance {+ id: number;+ title: string;+ description: string | null;+}++export interface UptimeKumaStatusPage {+ title: string;+ url: string;+ groups: UptimeKumaGroup[];+ incidents: UptimeKumaIncident[];+ maintenances: UptimeKumaMaintenance[];+}diff --git a/packages/request-handler/src/uptime-kuma.ts b/packages/request-handler/src/uptime-kuma.tsindex 4fd613586..06c3edead 100644--- a/packages/request-handler/src/uptime-kuma.ts+++ b/packages/request-handler/src/uptime-kuma.ts@@ -1,16 +1,18 @@import { createIntegrationAsync } from "@homarr/integrations/factory";-import type { UptimeKumaDashboardData } from "@homarr/integrations/types";+import type { UptimeKumaStatusPage } from "@homarr/integrations/types";import { createIntegrationRequestHandler } from "./lib/integration-request-handler";export const uptimeKumaRequestHandler = createIntegrationRequestHandler<- UptimeKumaDashboardData,+ UptimeKumaStatusPage,"uptimeKuma",Record<string, never>>({- cacheNamespace: "uptime-kuma:monitors",- async requestAsync(integration, _input) {+ cacheNamespace: "uptime-kuma:status-page",+ cacheVersion: "stale-status-v1",+ cacheTtlMs: 30_000,+ async requestAsync(integration, _input, signal) {const integrationInstance = await createIntegrationAsync(integration);- return await integrationInstance.getDashboardDataAsync();+ return await integrationInstance.getStatusPageAsync(signal);},});diff --git a/packages/translation/src/lang/en.json b/packages/translation/src/lang/en.jsonindex b8848b029..aadb1756c 100644--- a/packages/translation/src/lang/en.json+++ b/packages/translation/src/lang/en.json@@ -4946,47 +4946,110 @@}},"uptimeKuma": {- "description": "Monitor uptime statistics from your Uptime Kuma status page",+ "description": "Live status, heartbeats and uptime of the monitors on an Uptime Kuma status page","option": {- "showAverageUptime": {- "label": "Show average uptime",- "description": "Display the combined 24-hour average uptime percentage"+ "showSummary": {+ "label": "Show summary",+ "description": "Overall status, counts and averages"},- "showUptimeRing": {- "label": "Show uptime ring",- "description": "Display a progress ring alongside the average uptime value"+ "showIncidents": {+ "label": "Show incidents",+ "description": "Incidents and active maintenance"},- "showTotalMonitors": {- "label": "Show total monitors",- "description": "Display the total number of configured monitors"+ "groupByStatusPageGroup": {+ "label": "Group monitors",+ "description": "Use the groups defined on the status page"},- "showUpCount": {- "label": "Show up count",- "description": "Display how many monitors are currently up"+ "showOnlyProblems": {+ "label": "Only show issues",+ "description": "Hide monitors that are up, except in the advanced view"},- "showDownCount": {- "label": "Show down count",- "description": "Display how many monitors are currently down"+ "sortBy": {+ "label": "Sort monitors by",+ "option": {+ "status": "Status, issues first",+ "statusPage": "Status page order",+ "name": "Name",+ "uptime": "Uptime, lowest first"+ }+ },+ "showHeartbeatBar": {+ "label": "Show heartbeat bar",+ "description": "Recent checks as colored bars, newest on the right"+ },+ "showUptime": {+ "label": "Show 24-hour uptime"},- "showPausedCount": {- "label": "Show paused count",- "description": "Display how many monitors are currently paused"+ "showResponseTime": {+ "label": "Show response time"+ },+ "showCertificateExpiry": {+ "label": "Certificate warnings",+ "description": "Flag certificates expiring within 14 days"}},- "averageUptime": "Average uptime (24h)",- "stats": {- "totalMonitors": "Total monitors",- "upCount": "Up",- "downCount": "Down",- "pausedCount": "Paused"- },- "error": {- "internalServerError": "Failed to fetch uptime data"- },"status": {"up": "Up","down": "Down",- "paused": "Paused"+ "pending": "Pending",+ "maintenance": "Maintenance",+ "stale": "No recent data",+ "unknown": "No data"+ },+ "overall": {+ "operational": "All systems operational",+ "degraded": "Partially degraded service",+ "outage": "Major outage",+ "maintenance": "Under maintenance",+ "unknown": "Waiting for first checks"+ },+ "short": {+ "operational": "All up",+ "down": "{count} down",+ "pending": "{count} pending",+ "maintenance": "Maintenance",+ "unknown": "No data"+ },+ "summary": {+ "upRatio": "{up} of {total} monitors up",+ "upRatioShort": "{up}/{total} up",+ "averageUptime": "uptime 24h",+ "uptimeShort": "{value} uptime",+ "statusCount": "{count} {status}"+ },+ "unit": {+ "milliseconds": "{value} ms"+ },+ "heartbeatBar": {+ "label": "{count, plural, one {# recent check} other {# recent checks}}, {down} down"+ },+ "detail": {+ "checked": "checked {time}",+ "certificate": "{count, plural, one {certificate expires in # day} other {certificate expires in # days}}"+ },+ "notice": {+ "label": "{count, plural, one {# incident or maintenance} other {# incidents or maintenances}}",+ "untitled": "Untitled"+ },+ "empty": {+ "title": "No monitors",+ "description": "Add monitors to the status page to see them here"+ },+ "allClear": "{count, plural, one {The monitor is up} other {All # monitors are up}}",+ "error": {+ "internalServerError": "Failed to fetch the Uptime Kuma status page"+ },+ "monitorType": {+ "http": "HTTP",+ "keyword": "HTTP keyword",+ "jsonQuery": "HTTP JSON query",+ "port": "TCP port",+ "ping": "Ping",+ "dns": "DNS",+ "docker": "Docker container",+ "push": "Push",+ "group": "Group",+ "realBrowser": "Browser"}},"traefik": {diff --git a/packages/widgets/package.json b/packages/widgets/package.jsonindex b809ea19c..e1b7728ef 100644--- a/packages/widgets/package.json+++ b/packages/widgets/package.json@@ -101,6 +101,7 @@"mantine-datatable": "catalog:","mantine-react-table": "catalog:","next": "catalog:",+ "next-intl": "catalog:","react": "catalog:","react-dom": "catalog:","react-markdown": "catalog:",diff --git a/packages/widgets/src/uptime-kuma/aggregate.spec.ts b/packages/widgets/src/uptime-kuma/aggregate.spec.tsdeleted file mode 100644index c4aaf9f18..000000000--- a/packages/widgets/src/uptime-kuma/aggregate.spec.ts+++ /dev/null@@ -1,31 +0,0 @@-import { describe, expect, it } from "vitest";--import { aggregateUptimeKumaDashboards } from "./aggregate";--describe("aggregateUptimeKumaDashboards", () => {- it("weights uptime by monitors instead of integrations", () => {- const combined = aggregateUptimeKumaDashboards([- {- totalMonitors: 1,- upCount: 1,- downCount: 0,- pausedCount: 0,- averageUptimePercent: 100,- monitors: [{ id: 1, name: "one", status: "up", uptimePercent24h: 100 }],- },- {- totalMonitors: 3,- upCount: 0,- downCount: 3,- pausedCount: 0,- averageUptimePercent: 0,- monitors: [- { id: 2, name: "two", status: "down", uptimePercent24h: 0 },- { id: 3, name: "three", status: "down", uptimePercent24h: 0 },- { id: 4, name: "four", status: "down", uptimePercent24h: 0 },- ],- },- ]);- expect(combined.averageUptimePercent).toBe(25);- });-});diff --git a/packages/widgets/src/uptime-kuma/aggregate.ts b/packages/widgets/src/uptime-kuma/aggregate.tsdeleted file mode 100644index c8c77fc29..000000000--- a/packages/widgets/src/uptime-kuma/aggregate.ts+++ /dev/null@@ -1,20 +0,0 @@-import type { UptimeKumaDashboardData } from "@homarr/integrations/types";--export function aggregateUptimeKumaDashboards(dashboards: UptimeKumaDashboardData[]) {- const combined = { totalMonitors: 0, upCount: 0, downCount: 0, pausedCount: 0, averageUptimePercent: 0 };- let uptimeTotal = 0;- let uptimeCount = 0;- for (const dashboard of dashboards) {- combined.totalMonitors += dashboard.totalMonitors;- combined.upCount += dashboard.upCount;- combined.downCount += dashboard.downCount;- combined.pausedCount += dashboard.pausedCount;- for (const monitor of dashboard.monitors) {- if (monitor.uptimePercent24h === null) continue;- uptimeTotal += monitor.uptimePercent24h;- uptimeCount++;- }- }- combined.averageUptimePercent = uptimeTotal / Math.max(uptimeCount, 1);- return combined;-}diff --git a/packages/widgets/src/uptime-kuma/component.module.css b/packages/widgets/src/uptime-kuma/component.module.cssindex eb8e37b94..6198561b8 100644--- a/packages/widgets/src/uptime-kuma/component.module.css+++ b/packages/widgets/src/uptime-kuma/component.module.css@@ -1,135 +1,537 @@-.root {- container-type: size;- display: flex;- flex-direction: column;+.frame {+ position: relative;height: 100%;min-height: 0;- padding: clamp(6px, 3cqmin, 14px);- gap: clamp(4px, 2cqmin, 10px);- overflow: hidden;}-.hero {- display: flex;- align-items: center;- justify-content: space-between;- gap: clamp(8px, 3cqmin, 18px);+.overlay {+ position: absolute;+ top: rem(4px);+ right: rem(6px);+ z-index: 2;+}++:is(.dot, .beat, .monitorRow)[data-status="up"] {+ --status-color: var(--mantine-color-green-6);+ --status-text-color: light-dark(var(--mantine-color-green-8), var(--mantine-color-green-6));+}++:is(.dot, .beat, .monitorRow)[data-status="down"] {+ --status-color: var(--mantine-color-red-6);+ --status-text-color: light-dark(var(--mantine-color-red-8), var(--mantine-color-red-6));+}++:is(.dot, .beat, .monitorRow)[data-status="pending"] {+ --status-color: var(--mantine-color-orange-6);+ --status-text-color: light-dark(var(--mantine-color-orange-9), var(--mantine-color-orange-6));+}++:is(.dot, .beat, .monitorRow)[data-status="maintenance"] {+ --status-color: var(--mantine-color-blue-6);+ --status-text-color: light-dark(var(--mantine-color-blue-8), var(--mantine-color-blue-5));+}++:is(.dot, .beat, .monitorRow):is([data-status="stale"], [data-status="unknown"], [data-status="empty"]) {+ --status-color: var(--mantine-color-gray-6);+ --status-text-color: var(--mantine-color-dimmed);+}++.dot[data-status="unknown"] {+ opacity: 0.5;+}++.dot {+ position: relative;flex-shrink: 0;- padding-bottom: clamp(4px, 2cqmin, 10px);- border-bottom: 1px solid rgb(from var(--mantine-color-default-border) r g b / calc(var(--opacity, 1) * 0.45));+ width: rem(9px);+ height: rem(9px);+ border-radius: 50%;+ background-color: var(--status-color);}-.heroExpanded {- flex: 1;- border-bottom: none;+.centeredState {+ display: flex;+ flex-direction: column;+ align-items: center;justify-content: center;- padding-bottom: 0;+ gap: rem(4px);+ height: 100%;+ padding: var(--mantine-spacing-sm);+ color: var(--mantine-color-dimmed);+}++.stateIcon {+ width: rem(32px);+ height: rem(32px);+ opacity: 0.6;}-.heroTextOnly {+.stateIcon[data-tone="success"] {+ color: var(--mantine-color-green-6);+ opacity: 1;+}++.ringLabel {+ display: flex;+ align-items: baseline;justify-content: center;+ line-height: 1;+ font-variant-numeric: tabular-nums;}-.heroTextOnly .heroText {+.ringValue {+ font-weight: 700;+}++.ringTotal {+ font-size: 0.6em;+ font-weight: 600;+ color: var(--mantine-color-dimmed);+}++.overallStatus {+ display: flex;align-items: center;- text-align: center;+ gap: rem(6px);+ min-width: 0;}-.heroTextOnly .heroValue {- font-size: clamp(var(--mantine-font-size-2xl), 10cqmin, var(--mantine-font-size-4xl));+.overallStatusIcon {+ flex-shrink: 0;+ width: var(--mantine-font-size-lg);+ height: var(--mantine-font-size-lg);+}++.overallStatus[data-size="sm"] .overallStatusIcon {+ width: var(--mantine-font-size-md);+ height: var(--mantine-font-size-md);}-.heroText {+.breakdown {display: flex;- flex-direction: column;- gap: clamp(2px, 1cqmin, 4px);+ align-items: center;+ column-gap: rem(12px);+ row-gap: rem(4px);min-width: 0;- flex: 1;+ font-size: var(--mantine-font-size-xs);+ line-height: 1.4;}-.heroLabel {- font-size: clamp(var(--mantine-font-size-xs), 2.8cqmin, var(--mantine-font-size-sm));- color: var(--mantine-color-dimmed);- line-height: 1.2;+.breakdown[data-layout="grid"] {+ display: grid;+ grid-template-columns: repeat(2, max-content);}-.heroValue {- font-size: clamp(var(--mantine-font-size-xl), 8cqmin, var(--mantine-font-size-4xl));+.breakdown[data-layout="list"] {+ flex-direction: column;+ align-items: flex-start;+}++.breakdownItem {+ display: inline-flex;+ align-items: center;+ gap: rem(5px);+ white-space: nowrap;+}++.breakdownValue {font-weight: 700;- line-height: 1.1;+ font-variant-numeric: tabular-nums;}-.ring {+.breakdownLabel {+ color: var(--mantine-color-dimmed);+}++.distribution {flex-shrink: 0;}-.statGrid {- display: grid;+.summaryLine {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: rem(12px);+ min-width: 0;+ font-size: var(--mantine-font-size-xs);+ line-height: 1.4;+}++.summaryRatio {flex: 1;- min-height: 0;- gap: clamp(4px, 2cqmin, 10px);- grid-template-columns: repeat(var(--stat-cols, 2), minmax(0, 1fr));- grid-auto-rows: 1fr;- align-content: stretch;+ min-width: 0;+}++.metric {+ display: inline-flex;+ flex-shrink: 0;+ align-items: baseline;+ gap: rem(4px);+ font-size: var(--mantine-font-size-xs);+ white-space: nowrap;}-.statTile {+.metricValue {+ font-weight: 700;+ font-variant-numeric: tabular-nums;+}++.metricLabel {+ color: var(--mantine-color-dimmed);+}++.tile {+ position: relative;display: flex;flex-direction: column;align-items: center;justify-content: center;+ gap: rem(4px);+ height: 100%;+ padding: rem(8px);+}++.tileText {+ display: flex;+ flex-direction: column;+ align-items: center;+ max-width: 100%;+ min-width: 0;+}++.tileNotice {+ position: absolute;+ top: rem(6px);+ left: rem(6px);+}++.strip {+ display: flex;+ align-items: center;+ gap: var(--mantine-spacing-md);+ height: 100%;+ padding: var(--mantine-spacing-sm) var(--mantine-spacing-md);+}++.stripBody {+ display: flex;+ flex: 1;+ flex-direction: column;+ justify-content: safe center;+ gap: rem(6px);+ align-self: stretch;+ min-width: 0;+ overflow: hidden;+}++.stripHeader {+ display: flex;+ align-items: center;+ gap: rem(8px);+ min-width: 0;+ padding-right: rem(20px);+}++.list {+ position: relative;+ display: flex;+ flex-direction: column;+ height: 100%;min-height: 0;+}++.header {+ display: flex;+ flex-direction: column;+ flex-shrink: 0;+ gap: rem(8px);+ padding: var(--mantine-spacing-sm) var(--mantine-spacing-md) var(--mantine-spacing-xs);+}++.list[data-layout="column"] .header {+ gap: rem(6px);+ padding: var(--mantine-spacing-xs) var(--mantine-spacing-sm);+}++.headerTop {+ display: flex;+ align-items: center;+ gap: rem(8px);+ min-width: 0;+ min-height: rem(28px);+}++.statusPageLink {+ display: inline-flex;+ align-items: center;+ gap: rem(4px);+ margin-left: auto;min-width: 0;- gap: clamp(2px, 1.5cqmin, 5px);- padding: clamp(4px, 2.5cqmin, 10px);- border-radius: var(--mantine-radius-md);- border: 1px solid rgb(from var(--mantine-color-default-border) r g b / calc(var(--opacity, 1) * 0.45));- background-color: transparent;+ flex-shrink: 1;+}++.statusPageTitle {overflow: hidden;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.scroll {+ --scroll-fade: rem(14px);+ flex: 1;+ min-height: 0;+}++.scrollViewport {+ mask-image: linear-gradient(to bottom, #000 calc(100% - var(--scroll-fade)), transparent);+}++.scrollContent {+ display: flex;+ flex-direction: column;+ gap: var(--mantine-spacing-xs);+ min-height: 100%;+ padding: rem(2px) calc(var(--mantine-spacing-md) - rem(6px)) var(--scroll-fade) var(--mantine-spacing-md);+}++.list[data-layout="column"] .scrollContent {+ padding: rem(2px) var(--mantine-spacing-sm) var(--scroll-fade);}-.root[data-short] .statTile {- flex-direction: row;+.list[data-layout="column"] .monitorRow {+ --title-gap: rem(6px);}-.root[data-short] .statValue {+.scrollContent > .centeredState {+ flex: 1;+}++.notices {+ display: flex;+ flex-direction: column;+ gap: rem(6px);+}++.notice {+ display: flex;+ align-items: flex-start;+ gap: rem(8px);+ padding: rem(6px) rem(10px);+ border-radius: var(--mantine-radius-sm);+ background-color: color-mix(in srgb, var(--mantine-color-text) 5%, transparent);+}++.noticeIcon {flex-shrink: 0;+ width: var(--mantine-font-size-md);+ height: var(--mantine-font-size-md);+ margin-top: rem(2px);+ color: var(--notice-color);}-.root[data-short] .statLabel {+.noticeBody {+ flex: 1;+ min-width: 0;+}++.noticeHeading {+ display: flex;+ align-items: baseline;+ gap: rem(8px);min-width: 0;- text-align: left;}-.statIcon {+.noticeAge {flex-shrink: 0;+ margin-left: auto;+ white-space: nowrap;}-.statValue {- font-size: clamp(var(--mantine-font-size-lg), 5.5cqmin, var(--mantine-font-size-2xl));- font-weight: 700;- line-height: 1.1;- text-align: center;+.section {+ display: flex;+ flex-direction: column;+ gap: rem(2px);}-.statLabel {- font-size: clamp(var(--mantine-font-size-xs), 2.5cqmin, var(--mantine-font-size-sm));+.sectionTitle {+ margin: rem(6px) 0 rem(2px);+ font-size: var(--mantine-font-size-xs);+ font-weight: 600;color: var(--mantine-color-dimmed);- line-height: 1.2;- text-align: center;- max-width: 100%;+}++.monitorGrid {+ display: grid;+ grid-template-columns: repeat(var(--monitor-columns, 1), minmax(0, 1fr));+ column-gap: var(--mantine-spacing-xl);+}++.monitorRow {+ --title-gap: rem(8px);+ --dot-size: rem(8px);+ display: grid;+ grid-template-columns: var(--monitor-row-template);+ align-items: center;+ column-gap: rem(12px);+ row-gap: rem(4px);+ min-width: 0;+ padding: rem(7px) 0;+ border-top: rem(1px) solid var(--mantine-color-default-border);+ font-size: var(--mantine-font-size-sm);+}++.monitorGrid[data-columns="1"] > .monitorRow:first-child,+.monitorGrid[data-columns="2"] > .monitorRow:nth-child(-n + 2),+.monitorGrid[data-columns="3"] > .monitorRow:nth-child(-n + 3) {+ border-top: 0;+}++.monitorMain {+ display: flex;+ flex-direction: column;+ gap: rem(1px);+ min-width: 0;+}++.monitorTitle {+ display: flex;+ align-items: center;+ gap: var(--title-gap);+ min-width: 0;+ line-height: 1.3;+}++.monitorTitle > .dot {+ width: var(--dot-size);+ height: var(--dot-size);+}++.monitorName {+ flex-shrink: 1;+ min-width: 0;overflow: hidden;+ font-weight: 500;text-overflow: ellipsis;white-space: nowrap;}-.emptyState {+.monitorStatus {+ flex-shrink: 0;+ color: var(--status-text-color);+ font-size: var(--mantine-font-size-xs);+ font-weight: 500;+ white-space: nowrap;+}++.tags {display: flex;- flex: 1;- align-items: center;- justify-content: center;- min-height: 0;+ flex: 1 1 0;+ gap: rem(4px);+ min-width: 0;+ overflow: hidden;+ mask-image: linear-gradient(to left, transparent, #000 rem(12px));+}++.tags > * {+ flex-shrink: 0;+}++.monitorDetails {+ overflow: hidden;+ padding-left: calc(var(--dot-size) + var(--title-gap));color: var(--mantine-color-dimmed);- font-size: clamp(11px, 3cqmin, 14px);- text-align: center;+ font-size: var(--mantine-font-size-xs);+ line-height: 1.3;+ text-overflow: ellipsis;+ white-space: nowrap;+}++.monitorDetails[data-warning] {+ color: light-dark(var(--mantine-color-orange-9), var(--mantine-color-orange-6));+}++.ping {+ font-size: var(--mantine-font-size-xs);+ color: var(--mantine-color-dimmed);+ text-align: right;+ white-space: nowrap;+ font-variant-numeric: tabular-nums;+}++.uptime {+ font-size: var(--mantine-font-size-xs);+ font-weight: 600;+ text-align: right;+ white-space: nowrap;+ font-variant-numeric: tabular-nums;+}++.uptime[data-tone="warning"] {+ color: light-dark(var(--mantine-color-yellow-9), var(--mantine-color-yellow-6));+}++.uptime[data-tone="critical"] {+ color: light-dark(var(--mantine-color-red-8), var(--mantine-color-red-6));+}++.uptime[data-tone="inactive"] {+ color: var(--mantine-color-dimmed);+ font-weight: 500;+}++.stackedFooter {+ display: flex;+ align-items: center;+ gap: rem(8px);+ min-width: 0;+ padding-left: calc(var(--dot-size) + var(--title-gap));+}++.stackedFooter > .heartbeatBar {+ flex: 1;+}++.heartbeatBar {+ display: flex;+ justify-content: flex-end;+ gap: rem(3px);+ height: rem(18px);+ min-width: 0;+ overflow: hidden;+ mask-image: linear-gradient(to right, transparent, #000 rem(12px));+}++.beats {+ display: contents;+}++.heartbeatBar[data-size="sm"] {+ gap: rem(2px);+ height: rem(12px);+}++.beat {+ flex: 0 0 auto;+ width: rem(5px);+ border-radius: rem(1px);+ background-color: var(--status-color);+ transition: transform 120ms ease;+}++.heartbeatBar[data-size="sm"] .beat {+ width: rem(4px);+}++.beat[data-status="empty"] {+ opacity: 0.18;+}++.beat:not([data-status="empty"]):hover {+ transform: scaleY(1.2);+}++@media (prefers-reduced-motion: reduce) {+ .beat {+ transition: none;+ }}diff --git a/packages/widgets/src/uptime-kuma/component.tsx b/packages/widgets/src/uptime-kuma/component.tsxindex 9c4b2d9e5..b72d1c2d4 100644--- a/packages/widgets/src/uptime-kuma/component.tsx+++ b/packages/widgets/src/uptime-kuma/component.tsx@@ -1,83 +1,55 @@"use client";-import type { CSSProperties } from "react";-import { Badge, Box, Group, RingProgress, ScrollArea, SimpleGrid, Stack, Text } from "@mantine/core";-import { IconArrowDown, IconArrowUp, IconClockPause, IconServer } from "@tabler/icons-react";+import type { CSSProperties, ReactNode } from "react";+import { Anchor, Badge, OverflowList, ScrollArea, Text } from "@mantine/core";+import { clamp } from "@mantine/hooks";+import { IconCircleCheck, IconExternalLink, IconHeartbeat } from "@tabler/icons-react";import { clientApi } from "@homarr/api/client";-import { formatNumber } from "@homarr/common";+import { calculateBoardUiScale } from "@homarr/boards/scale";+import { getSafeApplicationUrl, SAFE_NEW_TAB_REL } from "@homarr/common";+import type { UptimeKumaSummary } from "@homarr/integrations/types";+import { summarizeUptimeKumaMonitors } from "@homarr/integrations/types";import { useI18n } from "@homarr/translation/client";-import { zoomCompensatedSize } from "@homarr/ui";+import { iconSizes } from "@homarr/ui";-import { WidgetEmptyState } from "../common/empty-state";import { IntegrationErrorIndicator } from "../common/integration-error-indicator";-import type { WidgetComponentProps } from "../definition";import { getUsableWidgetQueryData } from "../common/query-state";+import { WidgetQueryLoadingState } from "../common/query-state-indicator";+import { useWidgetNow } from "../common/use-widget-now";+import type { WidgetComponentProps } from "../definition";import { NoIntegrationDataError } from "../errors/no-data-integration";import classes from "./component.module.css";-import { aggregateUptimeKumaDashboards } from "./aggregate";--const statVisibilityByOption = {- showTotalMonitors: "totalMonitors",- showUpCount: "upCount",- showDownCount: "downCount",- showPausedCount: "pausedCount",-} as const;--const statIcons = {- totalMonitors: IconServer,- upCount: IconArrowUp,- downCount: IconArrowDown,- pausedCount: IconClockPause,-} as const;--const statColorByKey = {- totalMonitors: "gray",- upCount: "green",- downCount: "red",- pausedCount: "yellow",-} as const;--const uptimeTierByThreshold = [- [99, "excellent"],- [95, "good"],- [0, "poor"],-] as const;--const uptimeColorByTier = {- excellent: "green",- good: "yellow",- poor: "red",-} as const;--const gridColsByWidth = [- { minWidth: 380, cols: 4 },- { minWidth: 260, cols: 2 },- { minWidth: 0, cols: 2 },-] as const;--const ringSizeByWidth = [- { minWidth: 400, size: 88 },- { minWidth: 320, size: 72 },- { minWidth: 220, size: 56 },- { minWidth: 0, size: 44 },-] as const;--const iconSizeByWidth = [- { minWidth: 320, size: 22 },- { minWidth: 200, size: 18 },- { minWidth: 0, size: 16 },-] as const;--const heroLayoutBySecondaryStats = {- false: classes.heroExpanded,- true: "",-} as const;--const heroVariantByRing = {- true: "",- false: classes.heroTextOnly,-} as const;+import {+ estimateSmallTextWidth,+ fitsHeadline,+ getMonitorColumnCount,+ getUptimeKumaLayout,+ showsInlineTags,+ usesInlineRows,+} from "./layout";+import type { UptimeKumaLayout } from "./layout";+import { getMonitorRowTemplate, MonitorRow } from "./monitor-row";+import type { MonitorRowVisibility } from "./monitor-row";+import { getAllMonitors, getMonitorSections, needsAttention, sortMonitors } from "./monitors";+import type { LoadedStatusPage, MonitorEntry } from "./monitors";+import type { Notice } from "./notices";+import { getNotices, NoticeIndicator, NoticeList } from "./notices";+import { formatUptime, monitorStatusColors } from "./status";+import {+ AverageUptime,+ DistributionBar,+ getAverageUptimeText,+ getOverallStatusLabel,+ getShortStatusLabel,+ OverallStatus,+ StatusBreakdown,+ SummaryLine,+ SummaryRing,+ useBreakdownLayout,+} from "./summary";++type Options = WidgetComponentProps<"uptimeKuma">["options"];export default function UptimeKumaWidget({integrationIds,@@ -97,7 +69,7 @@ export default function UptimeKumaWidget({options={options}width={width}height={height}- displayMode={displayMode}+ isAdvanced={displayMode === "advanced"}displayScale={displayScale}/>);@@ -105,10 +77,10 @@ export default function UptimeKumaWidget({interface UptimeKumaContentProps {integrationIds: string[];- options: WidgetComponentProps<"uptimeKuma">["options"];+ options: Options;width: number;height: number;- displayMode: "compact" | "advanced";+ isAdvanced: boolean;displayScale: number;}@@ -117,203 +89,344 @@ function UptimeKumaContent({options,width,height,- displayMode,+ isAdvanced,displayScale,}: UptimeKumaContentProps) {const t = useI18n("widget.uptimeKuma");- const dashboardQuery = clientApi.widget.uptimeKuma.getDashboard.useQuery({ integrationIds });- const dashboardData = getUsableWidgetQueryData(dashboardQuery);+ const now = useWidgetNow("minute");+ const statusPagesQuery = clientApi.widget.uptimeKuma.getStatusPages.useQuery({ integrationIds });+ const results = getUsableWidgetQueryData(statusPagesQuery);- if (!dashboardData) return <WidgetEmptyState />;- const successfulDashboardData = dashboardData.flatMap((item) =>- item.dashboard === null ? [] : [{ ...item, dashboard: item.dashboard }],- );+ if (!results) return <WidgetQueryLoadingState />;- const combined = aggregateUptimeKumaDashboards(successfulDashboardData.map((item) => item.dashboard));- const monitors = successfulDashboardData.flatMap((result) =>- result.dashboard.monitors.map((monitor) => ({- ...monitor,- key: `${result.integrationId}:${monitor.id}`,- integrationName: result.integrationName,- })),+ const pages: LoadedStatusPage[] = results.flatMap(({ integrationId, statusPage }) =>+ statusPage === null ? [] : [{ integrationId, statusPage }],);- const uptimeValue = clampPercent(combined.averageUptimePercent);- const uptimeColor = getUptimeColor(uptimeValue);- const isAdvanced = displayMode === "advanced";- let responsiveWidth = width;- let responsiveHeight = height;- if (!isAdvanced) {- responsiveWidth *= displayScale;- responsiveHeight *= displayScale;+ const uiScale = isAdvanced ? 1 : calculateBoardUiScale(displayScale);+ const size = { width: width / uiScale, height: height / uiScale };+ const layout = getUptimeKumaLayout(size.width, size.height, isAdvanced);+ const summary = summarizeUptimeKumaMonitors(getAllMonitors(pages));+ const notices = isAdvanced || options.showIncidents ? getNotices(pages, t("notice.untitled")) : [];+ const errorIndicator = <IntegrationErrorIndicator results={results} />;++ if (summary.total === 0) {+ return (+ <Frame overlay={errorIndicator}>+ <CenteredState+ icon={<IconHeartbeat className={classes.stateIcon} aria-hidden />}+ title={t("empty.title")}+ description={layout !== "tile" && t("empty.description")}+ />+ </Frame>+ );}- const visualScale = Math.min(responsiveWidth, responsiveHeight);- const ringSize = getRingSize(visualScale);- const iconSize = getIconSize(Math.min(width, height));- const gridCols = getGridCols(responsiveWidth);-- const enabledStatKeys = Object.entries(statVisibilityByOption)- .filter(([optionKey]) => isAdvanced || options[optionKey as keyof typeof options])- .map(([, statKey]) => statKey);- const showHero = isAdvanced || options.showAverageUptime;- const showRing = isAdvanced || options.showUptimeRing;- const visibleStatKeys = enabledStatKeys;- const hasContent = showHero || visibleStatKeys.length > 0;-- const heroLayoutClass =- heroLayoutBySecondaryStats[String(visibleStatKeys.length > 0) as keyof typeof heroLayoutBySecondaryStats];- const heroRingClass = heroVariantByRing[String(showRing) as keyof typeof heroVariantByRing];-- const summaryContent = (- <div className={classes.root} data-short={responsiveHeight < 240 || undefined}>- {showHero && (- <div className={`${classes.hero} ${heroLayoutClass} ${heroRingClass}`}>- <div className={classes.heroText}>- <span className={classes.heroLabel}>{t("averageUptime")}</span>- <span className={classes.heroValue}>{formatNumber(uptimeValue, 1)}%</span>- </div>- {showRing && (- <RingProgress- className={classes.ring}- size={ringSize}- thickness={Math.max(4, Math.round(ringSize / 10))}- roundCaps- sections={[{ value: uptimeValue, color: uptimeColor }]}- label={- <Text ta="center" size="xs" fw={700}>- {formatNumber(uptimeValue, 0)}%- </Text>- }- />- )}- </div>- )}-- {!hasContent && (- <div className={classes.emptyState}>- <Text size="sm" c="dimmed">- —- </Text>- </div>- )}-- {visibleStatKeys.length > 0 && (- <div className={classes.statGrid} style={{ "--stat-cols": gridCols } as CSSProperties}>- {visibleStatKeys.map((statKey) => {- const Icon = statIcons[statKey];- const color = statColorByKey[statKey];- return (- <div key={statKey} className={classes.statTile}>- <Icon- className={classes.statIcon}- style={zoomCompensatedSize(iconSize)}- stroke={1.5}- color={`var(--mantine-color-${color}-6)`}- />- <span className={classes.statValue}>{formatNumber(combined[statKey], 0)}</span>- <span className={classes.statLabel} title={t(`stats.${statKey}`)}>- {t(`stats.${statKey}`)}- </span>- </div>- );- })}- </div>- )}- </div>- );-- if (displayMode === "compact") {+ if (layout === "tile") {return (- <Box h="100%" pos="relative">- <Group pos="absolute" top={4} right={8} gap={0} style={{ zIndex: 2 }}>- <IntegrationErrorIndicator results={dashboardData} />- </Group>- {summaryContent}- </Box>+ <Frame overlay={errorIndicator}>+ <TileLayout summary={summary} notices={notices} size={size} showUptime={options.showUptime} />+ </Frame>);}- const monitorList = (- <Stack gap="xs">- {monitors- .toSorted((left, right) => statusOrder[left.status] - statusOrder[right.status])- .map((monitor) => (- <Group key={monitor.key} justify="space-between" wrap="nowrap" p="xs">- <Stack gap={0} style={{ minWidth: 0 }}>- <Text size="sm" fw={600} truncate>- {monitor.name}- </Text>- {(isAdvanced || successfulDashboardData.length > 1) && (- <Text size="xs" c="dimmed">- {monitor.integrationName}- </Text>- )}- </Stack>- <Badge color={monitor.status === "up" ? "green" : monitor.status === "down" ? "red" : "yellow"}>- {t(`status.${monitor.status}`)} ·{" "}- {monitor.uptimePercent24h === null ? "—" : `${formatNumber(monitor.uptimePercent24h, 1)}%`}- </Badge>- </Group>- ))}- </Stack>- );-- if (width < 760) {+ if (layout === "strip") {return (- <Box h="100%" pos="relative">- <Group pos="absolute" top={4} right={8} gap={0} style={{ zIndex: 2 }}>- <IntegrationErrorIndicator results={dashboardData} />- </Group>- <ScrollArea h="100%">- <Stack gap="lg" p="md">- <Box h={Math.min(420, Math.max(180, Math.floor(height * 0.55)))}>{summaryContent}</Box>- {monitorList}- </Stack>- </ScrollArea>- </Box>+ <Frame overlay={errorIndicator}>+ <StripLayout pages={pages} summary={summary} notices={notices} size={size} options={options} />+ </Frame>);}return (- <Box h="100%" pos="relative">- <Group pos="absolute" top={4} right={8} gap={0} style={{ zIndex: 2 }}>- <IntegrationErrorIndicator results={dashboardData} />- </Group>- <SimpleGrid cols={2} spacing="lg" h="100%" p="md" style={{ gridTemplateRows: "minmax(0, 1fr)" }}>- {summaryContent}- <ScrollArea h="100%">{monitorList}</ScrollArea>- </SimpleGrid>- </Box>+ <ListLayout+ pages={pages}+ summary={summary}+ notices={notices}+ layout={layout}+ size={size}+ options={options}+ isAdvanced={isAdvanced}+ now={now}+ errorIndicator={errorIndicator}+ />);}-const statusOrder = { down: 0, paused: 1, up: 2 } as const;--function clampPercent(value: number): number {- return Math.min(100, Math.max(0, value));+interface Size {+ width: number;+ height: number;}-function getUptimeTier(uptime: number): keyof typeof uptimeColorByTier {- const match = uptimeTierByThreshold.find(([min]) => uptime >= min);- const tier = match?.[1] ?? "poor";- return tier;+const Frame = ({ children, overlay }: { children: ReactNode; overlay: ReactNode }) => (+ <div className={classes.frame}>+ <div className={classes.overlay}>{overlay}</div>+ {children}+ </div>+);++const CenteredState = ({+ icon,+ title,+ description,+}: {+ icon: ReactNode;+ title: string;+ description?: string | false;+}) => (+ <div className={classes.centeredState}>+ {icon}+ <Text fw={600} size="sm" ta="center">+ {title}+ </Text>+ {description && (+ <Text size="xs" c="dimmed" ta="center">+ {description}+ </Text>+ )}+ </div>+);++interface TileLayoutProps {+ summary: UptimeKumaSummary;+ notices: Notice[];+ size: Size;+ showUptime: boolean;}-function getUptimeColor(uptime: number): string {- return uptimeColorByTier[getUptimeTier(uptime)];-}+const TileLayout = ({ summary, notices, size, showUptime }: TileLayoutProps) => {+ const t = useI18n("widget.uptimeKuma");+ const showAverageUptime = showUptime && summary.averageUptime24h !== null;+ const textHeight = 26 + (showAverageUptime ? 18 : 0);+ const ringSize = clamp(Math.min(size.width - 16, size.height - 20 - textHeight), 48, 160);-function getGridCols(width: number): number {- const match = gridColsByWidth.find(({ minWidth }) => width >= minWidth);- return match?.cols ?? 2;+ return (+ <div className={classes.tile}>+ {notices.length > 0 && (+ <div className={classes.tileNotice}>+ <NoticeIndicator notices={notices} />+ </div>+ )}+ <SummaryRing summary={summary} size={ringSize} />+ <div className={classes.tileText}>+ <OverallStatus summary={summary} short size="sm" />+ {showAverageUptime && summary.averageUptime24h !== null && (+ <Text size="xs" c="dimmed" truncate>+ {t("summary.uptimeShort", { value: formatUptime(summary.averageUptime24h) })}+ </Text>+ )}+ </div>+ </div>+ );+};++interface StripLayoutProps {+ pages: LoadedStatusPage[];+ summary: UptimeKumaSummary;+ notices: Notice[];+ size: Size;+ options: Options;}-function getRingSize(width: number): number {- const match = ringSizeByWidth.find(({ minWidth }) => width >= minWidth);- return match?.size ?? 44;-}+const stripChromeHeight = 54;+const stripHeaderReservedWidth = 20;+const stripLineHeight = 22;+const chipRowHeight = 32;+const chipOverflowWidth = 56;+const noticeIndicatorWidth = 30;++const StripLayout = ({ pages, summary, notices, size, options }: StripLayoutProps) => {+ const t = useI18n("widget.uptimeKuma");+ const ringSize = clamp(Math.min(size.height - 24, size.width * 0.3), 56, 150);+ const bodyWidth = size.width - ringSize - 48;+ const breakdown = useBreakdownLayout(summary, bodyWidth);+ const breakdownHeight = breakdown.rows * stripLineHeight;+ const showBreakdown = stripChromeHeight + breakdownHeight <= size.height;+ const usedHeight = stripChromeHeight + (showBreakdown ? breakdownHeight : 0);+ const chipMonitors = sortMonitors(getAllMonitors(pages).filter(needsAttention), options.sortBy);+ const chipRows = chipMonitors.length > 0 ? clamp(Math.floor((size.height - usedHeight) / chipRowHeight), 0, 3) : 0;+ const uptime = options.showUptime ? getAverageUptimeText(summary) : null;+ const uptimeLine = usedHeight + chipRows * chipRowHeight + stripLineHeight <= size.height ? uptime : null;+ const headlineWidth = bodyWidth - stripHeaderReservedWidth;+ const chipMaxWidth = clamp(bodyWidth - chipOverflowWidth, 72, 180);++ return (+ <div className={classes.strip}>+ {notices.length > 0 && (+ <div className={classes.tileNotice}>+ <NoticeIndicator notices={notices} />+ </div>+ )}+ <SummaryRing summary={summary} size={ringSize} />+ <div className={classes.stripBody}>+ <div className={classes.stripHeader}>+ <OverallStatus summary={summary} short={!fitsHeadline(getOverallStatusLabel(summary, t), headlineWidth)} />+ </div>+ {showBreakdown && <StatusBreakdown summary={summary} layout={breakdown.kind} />}+ {uptimeLine && <AverageUptime value={uptimeLine} />}+ {chipRows > 0 && (+ <OverflowList+ data={chipMonitors}+ maxRows={chipRows}+ gap={6}+ getItemKey={(monitor) => monitor.key}+ renderItem={(monitor) => <MonitorChip monitor={monitor} maxWidth={chipMaxWidth} />}+ renderOverflow={(hidden) => (+ <Badge variant="light" color="gray" size="lg" radius="sm" tt="none" fw={500}>+ +{hidden.length}+ </Badge>+ )}+ />+ )}+ </div>+ </div>+ );+};-function getIconSize(width: number): number {- const match = iconSizeByWidth.find(({ minWidth }) => width >= minWidth);- return match?.size ?? 16;+const MonitorChip = ({ monitor, maxWidth }: { monitor: MonitorEntry; maxWidth: number }) => {+ const t = useI18n("widget.uptimeKuma");++ return (+ <Badge+ variant="light"+ color={monitorStatusColors[monitor.status]}+ size="lg"+ radius="sm"+ tt="none"+ fw={500}+ maw={maxWidth}+ title={`${monitor.name} · ${t(`status.${monitor.status}`)}`}+ leftSection={<span className={classes.dot} data-status={monitor.status} />}+ >+ {monitor.name}+ </Badge>+ );+};++interface ListLayoutProps {+ pages: LoadedStatusPage[];+ summary: UptimeKumaSummary;+ notices: Notice[];+ layout: Exclude<UptimeKumaLayout, "tile" | "strip">;+ size: Size;+ options: Options;+ isAdvanced: boolean;+ now: Date | null;+ errorIndicator: ReactNode;}++const ListLayout = ({+ pages,+ summary,+ notices,+ layout,+ size,+ options,+ isAdvanced,+ now,+ errorIndicator,+}: ListLayoutProps) => {+ const t = useI18n("widget.uptimeKuma");+ const columnCount = layout === "board" ? getMonitorColumnCount(size.width) : 1;+ const variant = layout === "board" && usesInlineRows(size.width, columnCount) ? "inline" : "stacked";+ const isColumn = layout === "column";+ const isNarrow = size.width < 180;+ const visibility: MonitorRowVisibility = {+ heartbeatBar: isAdvanced || options.showHeartbeatBar,+ uptime: isAdvanced || options.showUptime,+ responseTime: (isAdvanced || options.showResponseTime) && !isNarrow,+ certificateExpiry: isAdvanced || options.showCertificateExpiry,+ statusDetail: !isColumn,+ tags: isAdvanced || (variant === "inline" && showsInlineTags(size.width, columnCount)),+ };+ const sections = getMonitorSections(pages, {+ groupByStatusPageGroup: options.groupByStatusPageGroup,+ showOnlyProblems: !isAdvanced && options.showOnlyProblems,+ sortBy: options.sortBy,+ });+ const showSummary = isAdvanced || options.showSummary;+ const headerWidth = size.width - (isColumn ? 16 : 32);+ const singlePage = pages.length === 1 ? pages[0]?.statusPage : undefined;+ const statusPageHref = getSafeApplicationUrl(singlePage?.url);+ const statusPageLink = singlePage && statusPageHref && size.width >= 340 ? singlePage : null;+ const statusPageLinkWidth = statusPageLink ? estimateSmallTextWidth(statusPageLink.title) + 28 : 0;+ const shortHeadline = isColumn || !fitsHeadline(getOverallStatusLabel(summary, t), headerWidth - statusPageLinkWidth);+ const showNoticeIndicator =+ showSummary &&+ isColumn &&+ notices.length > 0 &&+ fitsHeadline(getShortStatusLabel(summary, t), headerWidth - noticeIndicatorWidth);+ const gridStyle = {+ "--monitor-columns": columnCount,+ "--monitor-row-template": getMonitorRowTemplate(variant, visibility),+ } as CSSProperties;++ return (+ <div className={classes.list} data-layout={layout}>+ {!showSummary && <div className={classes.overlay}>{errorIndicator}</div>}+ {showSummary && (+ <header className={classes.header}>+ <div className={classes.headerTop}>+ <OverallStatus summary={summary} short={shortHeadline} size={isColumn ? "sm" : "md"} />+ {showNoticeIndicator && <NoticeIndicator notices={notices} />}+ {statusPageLink && statusPageHref && (+ <Anchor+ href={statusPageHref}+ target="_blank"+ rel={SAFE_NEW_TAB_REL}+ size="xs"+ c="dimmed"+ className={classes.statusPageLink}+ >+ <span className={classes.statusPageTitle}>{statusPageLink.title}</span>+ <IconExternalLink style={iconSizes.xs} aria-hidden />+ </Anchor>+ )}+ {errorIndicator}+ </div>+ <DistributionBar summary={summary} />+ <SummaryLine summary={summary} showUptime={visibility.uptime && !isColumn} width={headerWidth} />+ </header>+ )}+ <ScrollArea+ className={classes.scroll}+ classNames={{ viewport: classes.scrollViewport }}+ type="hover"+ scrollbarSize={6}+ offsetScrollbars={!isColumn && "y"}+ >+ <div className={classes.scrollContent}>+ {notices.length > 0 && !showNoticeIndicator && (+ <NoticeList notices={notices} compact={isColumn || size.height < 400} showAge={!isNarrow} now={now} />+ )}+ {sections.length === 0 && (+ <CenteredState+ icon={<IconCircleCheck className={classes.stateIcon} data-tone="success" aria-hidden />}+ title={t("allClear", { count: summary.total })}+ />+ )}+ {sections.map((section) => (+ <section key={section.key} className={classes.section}>+ {section.title && (+ <Text component="h3" className={classes.sectionTitle} truncate>+ {section.title}+ </Text>+ )}+ <div className={classes.monitorGrid} style={gridStyle} data-columns={columnCount}>+ {section.monitors.map((monitor) => (+ <MonitorRow+ key={monitor.key}+ monitor={monitor}+ variant={variant}+ visibility={visibility}+ showDetails={isAdvanced}+ now={now}+ />+ ))}+ </div>+ </section>+ ))}+ </div>+ </ScrollArea>+ </div>+ );+};diff --git a/packages/widgets/src/uptime-kuma/heartbeat-bar.tsx b/packages/widgets/src/uptime-kuma/heartbeat-bar.tsxnew file mode 100644index 000000000..dea69b03a--- /dev/null+++ b/packages/widgets/src/uptime-kuma/heartbeat-bar.tsx@@ -0,0 +1,64 @@+"use client";++import type { PointerEvent } from "react";+import { useState } from "react";+import { Tooltip, VisuallyHidden } from "@mantine/core";+import { useFormatter } from "next-intl";++import type { UptimeKumaHeartbeat } from "@homarr/integrations/types";+import { uptimeKumaMaxHeartbeats } from "@homarr/integrations/types";+import { useI18n } from "@homarr/translation/client";++import classes from "./component.module.css";++interface HeartbeatBarProps {+ heartbeats: readonly UptimeKumaHeartbeat[];+ size?: "sm" | "md";+}++export const HeartbeatBar = ({ heartbeats, size = "md" }: HeartbeatBarProps) => {+ const t = useI18n("widget.uptimeKuma");+ const formatter = useFormatter();+ const [hoveredIndex, setHoveredIndex] = useState<number | null>(null);+ const hovered = hoveredIndex === null ? undefined : heartbeats[hoveredIndex];+ const placeholderCount = Math.max(0, uptimeKumaMaxHeartbeats - heartbeats.length);+ const downCount = heartbeats.filter((heartbeat) => heartbeat.status === "down").length;++ const handlePointerMove = (event: PointerEvent<HTMLDivElement>) => {+ const index = event.target instanceof HTMLElement ? event.target.dataset.index : undefined;+ setHoveredIndex(index === undefined ? null : Number(index));+ };++ return (+ <Tooltip.Floating+ disabled={!hovered}+ label={+ hovered &&+ [+ t(`status.${hovered.status}`),+ formatter.dateTime(hovered.time, { month: "short", day: "numeric", hour: "numeric", minute: "2-digit" }),+ hovered.ping === null ? null : t("unit.milliseconds", { value: Math.round(hovered.ping) }),+ ]+ .filter(Boolean)+ .join(" · ")+ }+ >+ <div+ className={classes.heartbeatBar}+ data-size={size}+ onPointerMove={handlePointerMove}+ onPointerLeave={() => setHoveredIndex(null)}+ >+ <VisuallyHidden>{t("heartbeatBar.label", { count: heartbeats.length, down: downCount })}</VisuallyHidden>+ <span className={classes.beats} aria-hidden>+ {Array.from({ length: placeholderCount }, (_, index) => (+ <span key={`placeholder-${index}`} className={classes.beat} data-status="empty" />+ ))}+ {heartbeats.map((heartbeat, index) => (+ <span key={index} className={classes.beat} data-status={heartbeat.status} data-index={index} />+ ))}+ </span>+ </div>+ </Tooltip.Floating>+ );+};diff --git a/packages/widgets/src/uptime-kuma/index.ts b/packages/widgets/src/uptime-kuma/index.tsindex ad67a4601..a0a9dbc71 100644--- a/packages/widgets/src/uptime-kuma/index.ts+++ b/packages/widgets/src/uptime-kuma/index.ts@@ -10,30 +10,23 @@ export const { definition, componentLoader } = createWidgetDefinition("uptimeKumsupportsAdvancedFocus: true,createOptions() {return optionsBuilder.from((factory) => ({- showAverageUptime: factory.switch({- defaultValue: true,- withDescription: true,- }),- showUptimeRing: factory.switch({- defaultValue: true,- withDescription: true,- }),- showTotalMonitors: factory.switch({- defaultValue: true,- withDescription: true,- }),- showUpCount: factory.switch({- defaultValue: true,- withDescription: true,- }),- showDownCount: factory.switch({- defaultValue: true,- withDescription: true,- }),- showPausedCount: factory.switch({- defaultValue: true,- withDescription: true,+ showSummary: factory.switch({ defaultValue: true, withDescription: true }),+ showIncidents: factory.switch({ defaultValue: true, withDescription: true }),+ groupByStatusPageGroup: factory.switch({ defaultValue: false, withDescription: true }),+ showOnlyProblems: factory.switch({ defaultValue: false, withDescription: true }),+ sortBy: factory.select({+ defaultValue: "status",+ options: [+ { value: "status", label: (t) => t("widget.uptimeKuma.option.sortBy.option.status") },+ { value: "statusPage", label: (t) => t("widget.uptimeKuma.option.sortBy.option.statusPage") },+ { value: "name", label: (t) => t("widget.uptimeKuma.option.sortBy.option.name") },+ { value: "uptime", label: (t) => t("widget.uptimeKuma.option.sortBy.option.uptime") },+ ],}),+ showHeartbeatBar: factory.switch({ defaultValue: true, withDescription: true }),+ showUptime: factory.switch({ defaultValue: true }),+ showResponseTime: factory.switch({ defaultValue: true }),+ showCertificateExpiry: factory.switch({ defaultValue: true, withDescription: true }),}));},...getWidgetIntegrationConfig("uptimeKuma"),diff --git a/packages/widgets/src/uptime-kuma/layout.ts b/packages/widgets/src/uptime-kuma/layout.tsnew file mode 100644index 000000000..beb621f5e--- /dev/null+++ b/packages/widgets/src/uptime-kuma/layout.ts@@ -0,0 +1,52 @@+export type UptimeKumaLayout = "tile" | "strip" | "column" | "board";++const compactBreakpoint = 230;+const minimumColumnWidth = 430;+const minimumInlineRowWidth = 430;+const minimumTaggedRowWidth = 600;+const maximumColumns = 3;++export const getUptimeKumaLayout = (width: number, height: number, isAdvanced: boolean): UptimeKumaLayout => {+ if (isAdvanced) return "board";+ const isNarrow = width < compactBreakpoint;+ const isShort = height < compactBreakpoint;+ if (isNarrow && isShort) return "tile";+ if (isShort) return "strip";+ if (isNarrow) return "column";+ return "board";+};++export const getMonitorColumnCount = (width: number) =>+ Math.min(maximumColumns, Math.max(1, Math.floor(width / minimumColumnWidth)));++export const usesInlineRows = (width: number, columnCount: number) => width / columnCount >= minimumInlineRowWidth;++export const showsInlineTags = (width: number, columnCount: number) => width / columnCount >= minimumTaggedRowWidth;++export interface BreakdownLayout {+ kind: "inline" | "grid" | "list";+ rows: number;+}++const smallCharacterWidth = 6.2;+const headlineCharacterWidth = 8.2;+const headlineIconWidth = 26;+const breakdownItemChrome = 18;+export const summaryGap = 12;++export const estimateSmallTextWidth = (text: string) => text.length * smallCharacterWidth;++export const fitsHeadline = (text: string, availableWidth: number) =>+ text.length * headlineCharacterWidth + headlineIconWidth <= availableWidth;++export const getBreakdownLayout = (items: readonly string[], availableWidth: number): BreakdownLayout => {+ const widths = items.map((item) => breakdownItemChrome + estimateSmallTextWidth(item));+ const inlineWidth = widths.reduce((total, width) => total + width, 0) + summaryGap * Math.max(0, widths.length - 1);+ if (inlineWidth <= availableWidth) return { kind: "inline", rows: 1 };++ const columnWidth = (column: number) => Math.max(0, ...widths.filter((_, index) => index % 2 === column));+ if (columnWidth(0) + summaryGap + columnWidth(1) <= availableWidth) {+ return { kind: "grid", rows: Math.ceil(widths.length / 2) };+ }+ return { kind: "list", rows: widths.length };+};diff --git a/packages/widgets/src/uptime-kuma/monitor-row.tsx b/packages/widgets/src/uptime-kuma/monitor-row.tsxnew file mode 100644index 000000000..6dc5a03df--- /dev/null+++ b/packages/widgets/src/uptime-kuma/monitor-row.tsx@@ -0,0 +1,158 @@+"use client";++import { Anchor, Badge, Text, VisuallyHidden } from "@mantine/core";+import { useFormatter } from "next-intl";++import { getSafeApplicationUrl, SAFE_NEW_TAB_REL } from "@homarr/common";+import type { UptimeKumaTag } from "@homarr/integrations/types";+import { useI18n } from "@homarr/translation/client";++import classes from "./component.module.css";+import { HeartbeatBar } from "./heartbeat-bar";+import type { MonitorEntry } from "./monitors";+import {+ certificateWarningDays,+ formatRelativeTime,+ formatUptime,+ getMonitorTypeTranslationKey,+ getUptimeTone,+} from "./status";++export interface MonitorRowVisibility {+ heartbeatBar: boolean;+ uptime: boolean;+ responseTime: boolean;+ certificateExpiry: boolean;+ statusDetail: boolean;+ tags: boolean;+}++type MonitorRowVariant = "inline" | "stacked";++interface MonitorRowProps {+ monitor: MonitorEntry;+ variant: MonitorRowVariant;+ visibility: MonitorRowVisibility;+ showDetails: boolean;+ now: Date | null;+}++type Translate = ReturnType<typeof useI18n<"widget.uptimeKuma">>;++export const getMonitorRowTemplate = (variant: MonitorRowVariant, visibility: MonitorRowVisibility) => {+ if (variant === "stacked") return "minmax(0, 1fr)";+ return [+ "minmax(0, 2fr)",+ visibility.heartbeatBar && "minmax(0, 1fr)",+ visibility.responseTime && "4.25em",+ visibility.uptime && "3.75em",+ ]+ .filter(Boolean)+ .join(" ");+};++export const MonitorRow = ({ monitor, variant, visibility, showDetails, now }: MonitorRowProps) => {+ const t = useI18n("widget.uptimeKuma");+ const formatter = useFormatter();+ const href = getSafeApplicationUrl(monitor.url);+ const isStacked = variant === "stacked";+ const relative = (time: number | null) => formatRelativeTime(formatter, time, now);++ const statusDetail = getStatusDetail(monitor, visibility.statusDetail, relative(monitor.statusSince), t);+ const certificate = getCertificateDetail(monitor.certificateDaysRemaining, visibility, showDetails, t);+ const extraDetails = showDetails ? getExtraDetails(monitor, relative(monitor.lastCheckAt), t) : [];+ const orderedDetails = certificate?.isWarning+ ? [certificate.text, ...extraDetails]+ : [...extraDetails, certificate?.text];+ const details = orderedDetails.filter(Boolean).join(" · ");+ const metrics = (+ <>+ {visibility.responseTime && !(isStacked && monitor.ping === null) && (+ <span className={classes.ping}>+ {monitor.ping !== null && t("unit.milliseconds", { value: Math.round(monitor.ping) })}+ </span>+ )}+ {visibility.uptime && (+ <span className={classes.uptime} data-tone={getUptimeTone(monitor.status, monitor.uptime24h)}>+ {monitor.uptime24h !== null && formatUptime(monitor.uptime24h)}+ </span>+ )}+ </>+ );++ return (+ <div className={classes.monitorRow} data-variant={variant} data-status={monitor.status}>+ <div className={classes.monitorMain}>+ <div className={classes.monitorTitle}>+ <span className={classes.dot} data-status={monitor.status} aria-hidden />+ {href ? (+ <Anchor href={href} target="_blank" rel={SAFE_NEW_TAB_REL} c="inherit" className={classes.monitorName}>+ {monitor.name}+ </Anchor>+ ) : (+ <Text component="span" className={classes.monitorName}>+ {monitor.name}+ </Text>+ )}+ {statusDetail ? (+ <span className={classes.monitorStatus}>{statusDetail}</span>+ ) : (+ <VisuallyHidden>{t(`status.${monitor.status}`)}</VisuallyHidden>+ )}+ {visibility.tags && monitor.tags.length > 0 && <MonitorTags tags={monitor.tags} />}+ </div>+ {details && (+ <span className={classes.monitorDetails} data-warning={certificate?.isWarning || undefined}>+ {details}+ </span>+ )}+ </div>+ {!isStacked && visibility.heartbeatBar && <HeartbeatBar heartbeats={monitor.heartbeats} />}+ {!isStacked && metrics}+ {isStacked && (visibility.heartbeatBar || visibility.responseTime || visibility.uptime) && (+ <div className={classes.stackedFooter}>+ {visibility.heartbeatBar && <HeartbeatBar heartbeats={monitor.heartbeats} size="sm" />}+ {metrics}+ </div>+ )}+ </div>+ );+};++const MonitorTags = ({ tags }: { tags: readonly UptimeKumaTag[] }) => (+ <span className={classes.tags}>+ {tags.map((tag) => {+ const label = [tag.name, tag.value].filter(Boolean).join(": ");+ return (+ <Badge key={label} size="xs" variant="light" radius="sm" color={tag.color ?? "gray"} tt="none">+ {label}+ </Badge>+ );+ })}+ </span>+);++const getStatusDetail = (monitor: MonitorEntry, visible: boolean, since: string | null, t: Translate) => {+ if (!visible || monitor.status === "up") return null;+ return [t(`status.${monitor.status}`), since].filter(Boolean).join(" · ");+};++const getExtraDetails = (monitor: MonitorEntry, lastChecked: string | null, t: Translate) => {+ const typeKey = monitor.type === null ? null : getMonitorTypeTranslationKey(monitor.type);+ return [+ typeKey ? t(`monitorType.${typeKey}`) : monitor.type,+ lastChecked && t("detail.checked", { time: lastChecked }),+ ];+};++const getCertificateDetail = (+ daysRemaining: number | null,+ visibility: MonitorRowVisibility,+ showDetails: boolean,+ t: Translate,+) => {+ if (daysRemaining === null) return null;+ const isWarning = daysRemaining <= certificateWarningDays;+ if (!showDetails && !(visibility.certificateExpiry && isWarning)) return null;+ return { text: t("detail.certificate", { count: daysRemaining }), isWarning };+};diff --git a/packages/widgets/src/uptime-kuma/monitors.ts b/packages/widgets/src/uptime-kuma/monitors.tsnew file mode 100644index 000000000..75593cea8--- /dev/null+++ b/packages/widgets/src/uptime-kuma/monitors.ts@@ -0,0 +1,90 @@+import type { UptimeKumaMonitor, UptimeKumaMonitorStatus, UptimeKumaStatusPage } from "@homarr/integrations/types";+import { getUniqueUptimeKumaMonitors, isInactiveUptimeKumaStatus } from "@homarr/integrations/types";++import type { WidgetComponentProps } from "../definition";++type UptimeKumaSortBy = WidgetComponentProps<"uptimeKuma">["options"]["sortBy"];++export interface LoadedStatusPage {+ integrationId: string;+ statusPage: UptimeKumaStatusPage;+}++export interface MonitorEntry extends UptimeKumaMonitor {+ key: string;+}++export interface MonitorSection {+ key: string;+ title: string | null;+ monitors: MonitorEntry[];+}++interface MonitorSectionOptions {+ groupByStatusPageGroup: boolean;+ showOnlyProblems: boolean;+ sortBy: UptimeKumaSortBy;+}++const statusRank: Record<UptimeKumaMonitorStatus, number> = {+ down: 0,+ pending: 1,+ maintenance: 2,+ stale: 3,+ unknown: 4,+ up: 5,+};++export const getAllMonitors = (pages: readonly LoadedStatusPage[]): MonitorEntry[] =>+ pages.flatMap((page) => toEntries(page, getUniqueUptimeKumaMonitors(page.statusPage.groups)));++export const getMonitorSections = (+ pages: readonly LoadedStatusPage[],+ { groupByStatusPageGroup, showOnlyProblems, sortBy }: MonitorSectionOptions,+): MonitorSection[] => {+ const prepare = (monitors: MonitorEntry[]) => sortMonitors(filterProblems(monitors, showOnlyProblems), sortBy);+ if (!groupByStatusPageGroup) {+ return [{ key: "all", title: null, monitors: prepare(getAllMonitors(pages)) }].filter(hasMonitors);+ }++ const sections = pages.flatMap((page) =>+ page.statusPage.groups.map((group) => ({+ key: `${page.integrationId}:${group.id}`,+ title: pages.length > 1 ? `${page.statusPage.title} · ${group.name}` : group.name,+ monitors: prepare(toEntries(page, group.monitors)),+ })),+ );+ return sections.filter(hasMonitors);+};++const hasMonitors = (section: MonitorSection) => section.monitors.length > 0;++const filterProblems = (monitors: readonly MonitorEntry[], showOnlyProblems: boolean) =>+ monitors.filter((monitor) => !showOnlyProblems || monitor.status !== "up");++export const needsAttention = (monitor: MonitorEntry) =>+ monitor.status !== "up" && !isInactiveUptimeKumaStatus(monitor.status);++export const sortMonitors = (monitors: readonly MonitorEntry[], sortBy: UptimeKumaSortBy): MonitorEntry[] =>+ monitors.toSorted((left, right) => compareMonitors(left, right, sortBy));++const compareMonitors = (left: MonitorEntry, right: MonitorEntry, sortBy: UptimeKumaSortBy) => {+ switch (sortBy) {+ case "status":+ return statusRank[left.status] - statusRank[right.status];+ case "name":+ return left.name.localeCompare(right.name, undefined, { sensitivity: "base", numeric: true });+ case "uptime":+ return compareNullsLast(left.uptime24h, right.uptime24h);+ case "statusPage":+ return 0;+ }+};++const compareNullsLast = (left: number | null, right: number | null) => {+ if (left === null || right === null) return Number(left === null) - Number(right === null);+ return left - right;+};++const toEntries = (page: LoadedStatusPage, monitors: readonly UptimeKumaMonitor[]): MonitorEntry[] =>+ monitors.map((monitor) => ({ ...monitor, key: `${page.integrationId}:${monitor.id}` }));diff --git a/packages/widgets/src/uptime-kuma/notices.tsx b/packages/widgets/src/uptime-kuma/notices.tsxnew file mode 100644index 000000000..67c313f89--- /dev/null+++ b/packages/widgets/src/uptime-kuma/notices.tsx@@ -0,0 +1,124 @@+"use client";++import type { CSSProperties } from "react";+import type { MantineColor } from "@mantine/core";+import { ActionIcon, Text, Tooltip } from "@mantine/core";+import { IconSpeakerphone, IconTool } from "@tabler/icons-react";+import { useFormatter } from "next-intl";++import { useI18n } from "@homarr/translation/client";+import { iconSizes } from "@homarr/ui";++import classes from "./component.module.css";+import type { LoadedStatusPage } from "./monitors";+import { formatRelativeTime, incidentStyleColors } from "./status";++export interface Notice {+ key: string;+ kind: "incident" | "maintenance";+ color: MantineColor;+ title: string;+ description: string | null;+ updatedAt: number | null;+}++export const getNotices = (pages: readonly LoadedStatusPage[], fallbackTitle: string): Notice[] =>+ pages.flatMap(({ integrationId, statusPage }) => [+ ...statusPage.incidents.map((incident) => ({+ key: `${integrationId}:incident:${incident.id}`,+ kind: "incident" as const,+ color: incidentStyleColors[incident.style],+ title: incident.title || fallbackTitle,+ description: incident.content,+ updatedAt: incident.updatedAt ?? incident.createdAt,+ })),+ ...statusPage.maintenances.map((maintenance) => ({+ key: `${integrationId}:maintenance:${maintenance.id}`,+ kind: "maintenance" as const,+ color: "blue",+ title: maintenance.title || fallbackTitle,+ description: maintenance.description,+ updatedAt: null,+ })),+ ]);++const noticeIcons = { incident: IconSpeakerphone, maintenance: IconTool } as const;++export const NoticeList = ({+ notices,+ compact,+ showAge,+ now,+}: {+ notices: readonly Notice[];+ compact: boolean;+ showAge: boolean;+ now: Date | null;+}) => {+ const formatter = useFormatter();++ return (+ <div className={classes.notices}>+ {notices.map((notice) => {+ const Icon = noticeIcons[notice.kind];+ const age = showAge && formatRelativeTime(formatter, notice.updatedAt, now);++ return (+ <div+ key={notice.key}+ className={classes.notice}+ style={{ "--notice-color": `var(--mantine-color-${notice.color}-6)` } as CSSProperties}+ title={compact && notice.description ? notice.description : undefined}+ >+ <Icon className={classes.noticeIcon} aria-hidden />+ <div className={classes.noticeBody}>+ <div className={classes.noticeHeading}>+ <Text size="sm" fw={600} lineClamp={compact ? 1 : 2}>+ {notice.title}+ </Text>+ {age && (+ <Text size="xs" c="dimmed" className={classes.noticeAge}>+ {age}+ </Text>+ )}+ </div>+ {!compact && notice.description && (+ <Text size="xs" c="dimmed" lineClamp={2}>+ {notice.description}+ </Text>+ )}+ </div>+ </div>+ );+ })}+ </div>+ );+};++export const NoticeIndicator = ({ notices }: { notices: readonly Notice[] }) => {+ const t = useI18n("widget.uptimeKuma");+ const first = notices[0];+ if (!first) return null;+ const Icon = noticeIcons[first.kind];++ return (+ <Tooltip+ label={notices.map((notice) => notice.title).join("\n")}+ multiline+ maw={280}+ withArrow+ style={{ whiteSpace: "pre-line" }}+ >+ <ActionIcon+ variant="light"+ color={first.color}+ size="sm"+ radius="xl"+ aria-label={t("notice.label", { count: notices.length })}+ style={{ cursor: "help" }}+ >+ <Icon style={iconSizes.xs} aria-hidden />+ </ActionIcon>+ </Tooltip>+ );+};diff --git a/packages/widgets/src/uptime-kuma/status.ts b/packages/widgets/src/uptime-kuma/status.tsnew file mode 100644index 000000000..dc02ce2aa--- /dev/null+++ b/packages/widgets/src/uptime-kuma/status.ts@@ -0,0 +1,104 @@+import type { MantineColor } from "@mantine/core";+import { IconAlertTriangle, IconCircleCheck, IconCircleX, IconHelpCircle, IconTool } from "@tabler/icons-react";+import type { useFormatter } from "next-intl";++import type {+ UptimeKumaIncidentStyle,+ UptimeKumaMonitorStatus,+ UptimeKumaOverallStatus,+ UptimeKumaSummary,+} from "@homarr/integrations/types";+import { isInactiveUptimeKumaStatus } from "@homarr/integrations/types";+import type { TablerIcon } from "@homarr/ui";++export const monitorStatusColors: Record<UptimeKumaMonitorStatus, MantineColor> = {+ up: "green",+ down: "red",+ pending: "orange",+ maintenance: "blue",+ stale: "gray",+ unknown: "gray",+};++export const overallStatusColors: Record<UptimeKumaOverallStatus, MantineColor> = {+ operational: "green",+ degraded: "orange",+ outage: "red",+ maintenance: "blue",+ unknown: "gray",+};++export const overallStatusIcons: Record<UptimeKumaOverallStatus, TablerIcon> = {+ operational: IconCircleCheck,+ degraded: IconAlertTriangle,+ outage: IconCircleX,+ maintenance: IconTool,+ unknown: IconHelpCircle,+};++export const incidentStyleColors: Record<UptimeKumaIncidentStyle, MantineColor> = {+ info: "cyan",+ warning: "yellow",+ danger: "red",+ primary: "green",+ light: "gray",+ dark: "dark",+};++type MonitorTypeTranslationKey =+ | "http"+ | "keyword"+ | "jsonQuery"+ | "port"+ | "ping"+ | "dns"+ | "docker"+ | "push"+ | "group"+ | "realBrowser";++const monitorTypeTranslationKeys = new Map<string, MonitorTypeTranslationKey>([+ ["http", "http"],+ ["keyword", "keyword"],+ ["json-query", "jsonQuery"],+ ["port", "port"],+ ["ping", "ping"],+ ["dns", "dns"],+ ["docker", "docker"],+ ["push", "push"],+ ["group", "group"],+ ["real-browser", "realBrowser"],+]);++export const getMonitorTypeTranslationKey = (type: string) => monitorTypeTranslationKeys.get(type) ?? null;++const displayedStatusOrder = ["up", "down", "pending", "maintenance", "stale", "unknown"] as const;++export const presentStatuses = (summary: UptimeKumaSummary) =>+ displayedStatusOrder.filter((status) => summary.counts[status] > 0);++type UptimeTone = "healthy" | "warning" | "critical" | "inactive";++export const getUptimeTone = (status: UptimeKumaMonitorStatus, uptime: number | null): UptimeTone => {+ if (uptime === null || isInactiveUptimeKumaStatus(status)) return "inactive";+ if (uptime >= 99) return "healthy";+ if (uptime >= 95) return "warning";+ return "critical";+};++export const formatUptime = (uptime: number) => {+ if (uptime >= 100) return "100%";+ if (uptime >= 99) return `${(Math.floor(uptime * 100) / 100).toFixed(2)}%`;+ return `${(Math.floor(uptime * 10) / 10).toFixed(1)}%`;+};++export const certificateWarningDays = 14;++export const formatRelativeTime = (+ formatter: ReturnType<typeof useFormatter>,+ time: number | null,+ now: Date | null,+) => {+ if (time === null || now === null) return null;+ return formatter.relativeTime(time, { now, style: "narrow" });+};diff --git a/packages/widgets/src/uptime-kuma/summary.tsx b/packages/widgets/src/uptime-kuma/summary.tsxnew file mode 100644index 000000000..be7a479fd--- /dev/null+++ b/packages/widgets/src/uptime-kuma/summary.tsx@@ -0,0 +1,160 @@+"use client";++import { Progress, rem, RingProgress, Text, Tooltip } from "@mantine/core";++import type { UptimeKumaSummary } from "@homarr/integrations/types";+import { useI18n } from "@homarr/translation/client";++import classes from "./component.module.css";+import type { BreakdownLayout } from "./layout";+import { estimateSmallTextWidth, getBreakdownLayout, summaryGap } from "./layout";+import { formatUptime, monitorStatusColors, overallStatusColors, overallStatusIcons, presentStatuses } from "./status";++interface SummaryProps {+ summary: UptimeKumaSummary;+}++export const SummaryRing = ({ summary, size }: SummaryProps & { size: number }) => {+ const t = useI18n("widget.uptimeKuma");+ const sections = presentStatuses(summary).map((status) => ({+ value: (summary.counts[status] / summary.total) * 100,+ color: `${monitorStatusColors[status]}.6`,+ tooltip: t("summary.statusCount", { count: summary.counts[status], status: t(`status.${status}`) }),+ }));++ return (+ <RingProgress+ size={size}+ thickness={Math.max(4, Math.round(size / 11))}+ rootColor="var(--mantine-color-default-border)"+ sections={sections}+ label={+ <div className={classes.ringLabel} style={{ fontSize: rem(Math.max(12, Math.round(size / 4.2))) }}>+ <span className={classes.ringValue}>{summary.counts.up}</span>+ <span className={classes.ringTotal}>/{summary.total}</span>+ </div>+ }+ aria-label={t("summary.upRatio", { up: summary.counts.up, total: summary.total })}+ />+ );+};++export const OverallStatus = ({+ summary,+ short = false,+ size = "md",+}: SummaryProps & { short?: boolean; size?: "sm" | "md" }) => {+ const t = useI18n("widget.uptimeKuma");+ const Icon = overallStatusIcons[summary.overallStatus];+ const color = overallStatusColors[summary.overallStatus];+ const label = short ? getShortStatusLabel(summary, t) : getOverallStatusLabel(summary, t);++ return (+ <div className={classes.overallStatus} data-size={size}>+ <Icon className={classes.overallStatusIcon} color={`var(--mantine-color-${color}-6)`} aria-hidden />+ <Text component="span" fw={700} size={size} truncate title={label}>+ {label}+ </Text>+ </div>+ );+};++export const useBreakdownLayout = (summary: UptimeKumaSummary, availableWidth: number) => {+ const t = useI18n("widget.uptimeKuma");+ const items = presentStatuses(summary).map((status) => `${summary.counts[status]} ${t(`status.${status}`)}`);+ return getBreakdownLayout(items, availableWidth);+};++export const StatusBreakdown = ({ summary, layout }: SummaryProps & { layout: BreakdownLayout["kind"] }) => {+ const t = useI18n("widget.uptimeKuma");++ return (+ <div className={classes.breakdown} data-layout={layout}>+ {presentStatuses(summary).map((status) => (+ <span key={status} className={classes.breakdownItem}>+ <span className={classes.dot} data-status={status} />+ <span className={classes.breakdownValue}>{summary.counts[status]}</span>+ <span className={classes.breakdownLabel}>{t(`status.${status}`)}</span>+ </span>+ ))}+ </div>+ );+};++export const SummaryLine = ({ summary, showUptime, width }: SummaryProps & { showUptime: boolean; width: number }) => {+ const t = useI18n("widget.uptimeKuma");+ const uptime = showUptime ? getAverageUptimeText(summary) : null;+ const uptimeWidth = uptime ? estimateSmallTextWidth(`${uptime} ${t("summary.averageUptime")}`) + summaryGap : 0;+ const breakdown = useBreakdownLayout(summary, width - uptimeWidth);+ const counts = { up: summary.counts.up, total: summary.total };+ const ratio = t("summary.upRatio", counts);+ const fittingRatio = estimateSmallTextWidth(ratio) + uptimeWidth <= width ? ratio : t("summary.upRatioShort", counts);++ return (+ <div className={classes.summaryLine}>+ {breakdown.kind === "inline" ? (+ <StatusBreakdown summary={summary} layout="inline" />+ ) : (+ <Text component="span" size="xs" c="dimmed" truncate title={ratio} className={classes.summaryRatio}>+ {fittingRatio}+ </Text>+ )}+ {uptime && <AverageUptime value={uptime} />}+ </div>+ );+};++export const AverageUptime = ({ value }: { value: string }) => {+ const t = useI18n("widget.uptimeKuma");++ return (+ <span className={classes.metric}>+ <span className={classes.metricValue}>{value}</span>+ <span className={classes.metricLabel}>{t("summary.averageUptime")}</span>+ </span>+ );+};++export const getAverageUptimeText = (summary: UptimeKumaSummary) =>+ summary.averageUptime24h === null ? null : formatUptime(summary.averageUptime24h);++export const DistributionBar = ({ summary }: SummaryProps) => {+ const t = useI18n("widget.uptimeKuma");++ return (+ <Progress.Root size="sm" radius="xs" className={classes.distribution}>+ {presentStatuses(summary).map((status) => (+ <Tooltip+ key={status}+ label={t("summary.statusCount", { count: summary.counts[status], status: t(`status.${status}`) })}+ withArrow+ >+ <Progress.Section+ value={(summary.counts[status] / summary.total) * 100}+ color={`${monitorStatusColors[status]}.6`}+ />+ </Tooltip>+ ))}+ </Progress.Root>+ );+};++export const getOverallStatusLabel = (+ summary: UptimeKumaSummary,+ t: ReturnType<typeof useI18n<"widget.uptimeKuma">>,+) => {+ if (summary.overallStatus !== "unknown") return t(`overall.${summary.overallStatus}`);+ if (summary.counts.up > 0) return t("summary.upRatio", { up: summary.counts.up, total: summary.total });+ if (summary.counts.stale > 0) return t("status.stale");+ return t("overall.unknown");+};++export const getShortStatusLabel = (summary: UptimeKumaSummary, t: ReturnType<typeof useI18n<"widget.uptimeKuma">>) => {+ if (summary.counts.down > 0) return t("short.down", { count: summary.counts.down });+ if (summary.counts.pending > 0) return t("short.pending", { count: summary.counts.pending });+ if (summary.overallStatus === "maintenance") return t("short.maintenance");+ if (summary.overallStatus === "operational") return t("short.operational");+ if (summary.counts.up > 0) return t("summary.upRatioShort", { up: summary.counts.up, total: summary.total });+ if (summary.counts.stale > 0) return t("status.stale");+ return t("short.unknown");+};