Skip to content

Open-source status page, incident response and uptime monitoring

Created calender component for status page (#2178)

Moulik Aggarwal80ff8e75a2bc
diff --git a/apps/dashboard/next-env.d.ts b/apps/dashboard/next-env.d.ts
index 9edff1c7c..c4b7818fb 100644
--- a/apps/dashboard/next-env.d.ts
+++ b/apps/dashboard/next-env.d.ts
@@ -1,6 +1,6 @@
/// <reference types="next" />
/// <reference types="next/image-types/global" />
-import "./.next/types/routes.d.ts";
+import "./.next/dev/types/routes.d.ts";
// NOTE: This file should not be edited
// see https://nextjs.org/docs/app/api-reference/config/typescript for more information.
diff --git a/apps/status-page/messages/de.json b/apps/status-page/messages/de.json
index 99c10ac9d..522b1c2b0 100644
--- a/apps/status-page/messages/de.json
+++ b/apps/status-page/messages/de.json
@@ -116,6 +116,7 @@
"3Vaz8F": "Status-Tracker",
"apbxET": "Tag {n} Status",
"GbVCQb": "Erneut klicken zum Lösen",
+ "Coy6SH": "Kalender",
"heezSZ": "(in {duration})",
"lKJjwW": "({timeFromLast} früher)",
"VaZnIX": "(für {duration})",
diff --git a/apps/status-page/messages/en.json b/apps/status-page/messages/en.json
index c08b931ed..d21680ade 100644
--- a/apps/status-page/messages/en.json
+++ b/apps/status-page/messages/en.json
@@ -116,6 +116,7 @@
"3Vaz8F": "Status tracker",
"apbxET": "Day {n} status",
"GbVCQb": "Click again to unpin",
+ "Coy6SH": "Calendar",
"heezSZ": "(in {duration})",
"lKJjwW": "({timeFromLast} earlier)",
"VaZnIX": "(for {duration})",
diff --git a/apps/status-page/messages/fr.json b/apps/status-page/messages/fr.json
index dbc67d8c9..883f8cecb 100644
--- a/apps/status-page/messages/fr.json
+++ b/apps/status-page/messages/fr.json
@@ -116,6 +116,7 @@
"3Vaz8F": "Suivi de statut",
"apbxET": "Statut du jour {n}",
"GbVCQb": "Cliquez à nouveau pour désépingler",
+ "Coy6SH": "Calendrier",
"heezSZ": "(en {duration})",
"lKJjwW": "({timeFromLast} plus tôt)",
"VaZnIX": "(pendant {duration})",
diff --git a/apps/status-page/messages/hi.json b/apps/status-page/messages/hi.json
index c0ac9ecfe..b456aa445 100644
--- a/apps/status-page/messages/hi.json
+++ b/apps/status-page/messages/hi.json
@@ -116,6 +116,7 @@
"3Vaz8F": "स्थिति ट्रैकर",
"apbxET": "दिन {n} की स्थिति",
"GbVCQb": "अनपिन करने के लिए फिर से क्लिक करें",
+ "Coy6SH": "",
"heezSZ": "({duration} में)",
"lKJjwW": "({timeFromLast} पहले)",
"VaZnIX": "({duration} के लिए)",
diff --git a/apps/status-page/messages/tr.json b/apps/status-page/messages/tr.json
index 1b0361fdc..30d1a6f1d 100644
--- a/apps/status-page/messages/tr.json
+++ b/apps/status-page/messages/tr.json
@@ -116,6 +116,7 @@
"3Vaz8F": "Durum izleyici",
"apbxET": "Gün {n} durumu",
"GbVCQb": "Sabitlemeyi kaldırmak için tekrar tıklayın",
+ "Coy6SH": "Takvim",
"heezSZ": "({duration} içinde)",
"lKJjwW": "({timeFromLast} önce)",
"VaZnIX": "({duration} boyunca)",
diff --git a/apps/status-page/src/components/i18n/status-blocks-provider.tsx b/apps/status-page/src/components/i18n/status-blocks-provider.tsx
index 6f795b629..4fab1c659 100644
--- a/apps/status-page/src/components/i18n/status-blocks-provider.tsx
+++ b/apps/status-page/src/components/i18n/status-blocks-provider.tsx
@@ -97,6 +97,8 @@ export function StatusBlocksProvider({
ariaDayStatus: (n: number) => t("Day {n} status", { n: String(n) }),
clickAgainToUnpin: t("Click again to unpin"),
+ calendarTitle: t("Calendar"),
+
durationIn: (duration: string) => t("(in {duration})", { duration }),
durationEarlier: (timeFromLast: string) =>
t("({timeFromLast} earlier)", { timeFromLast }),
diff --git a/apps/status-page/src/components/status-page/status-calendar.tsx b/apps/status-page/src/components/status-page/status-calendar.tsx
new file mode 100644
index 000000000..211254c7f
--- /dev/null
+++ b/apps/status-page/src/components/status-page/status-calendar.tsx
@@ -0,0 +1,189 @@
+"use client";
+
+import {
+ eachDayOfInterval,
+ max as maxDate,
+ min as minDate,
+ startOfDay,
+} from "date-fns";
+import { useLocale } from "next-intl";
+import { useCallback, useMemo } from "react";
+
+import { Link } from "@/components/common/link";
+import { usePathnamePrefix } from "@/hooks/use-pathname-prefix";
+import type { Locale as AppLocale } from "@/i18n/config";
+import type { RouterOutputs } from "@openstatus/api";
+import { dateFnsLocales } from "@openstatus/locales";
+import { StatusBarEvent } from "@openstatus/ui/components/blocks/status-bar";
+import {
+ StatusCalendar as BlockStatusCalendar,
+ StatusCalendarSkeleton as BlockStatusCalendarSkeleton,
+ type StatusCalendarMarker,
+ type StatusCalendarProps,
+ type StatusCalendarSkeletonProps,
+} from "@openstatus/ui/components/blocks/status-calendar";
+import { useStatusBlocksLabels } from "@openstatus/ui/components/blocks/status-i18n";
+
+type Page = NonNullable<RouterOutputs["statusPage"]["get"]>;
+type ReportInput = Page["statusReports"][number];
+type MaintenanceInput = Page["maintenances"][number];
+type PageComponentInput = Page["pageComponents"][number];
+
+type Props = Omit<StatusCalendarProps, "markers" | "renderMarkerRow"> & {
+ statusReports?: ReportInput[];
+ maintenances?: MaintenanceInput[];
+ pageComponents?: PageComponentInput[];
+ /**
+ * Mirrors the bar's loading pattern (`status-bar.tsx` consumer): when true,
+ * the wrapper renders `<StatusCalendarSkeleton>` instead of the calendar.
+ * Wire this to the parent's data-fetch loading state.
+ */
+ isLoading?: boolean;
+};
+
+// Marker color is keyed by event TYPE (not status) so resolved historical
+// outages still show as red/yellow rather than green. Mirrors StatusBarEvent.
+
+export function StatusCalendar({
+ statusReports = [],
+ maintenances = [],
+ pageComponents = [],
+ isLoading,
+ ...rest
+}: Props) {
+ const labels = useStatusBlocksLabels();
+ const locale = useLocale() as AppLocale;
+ const dateFnsLocale = dateFnsLocales[locale];
+ const prefix = usePathnamePrefix();
+ const base = prefix ? `/${prefix}` : "";
+ const downtimeLabel = labels.systemStatus.error.short;
+ const calendarTitle = labels.calendarTitle;
+
+ const markers = useMemo<StatusCalendarMarker[]>(() => {
+ const out: StatusCalendarMarker[] = [];
+
+ for (const report of statusReports) {
+ const updates = report.statusReportUpdates
+ .slice()
+ .sort((a, b) => a.date.getTime() - b.date.getTime());
+ const firstUpdate = updates[0];
+ const lastUpdate = updates[updates.length - 1];
+ const startedAt = firstUpdate?.date ?? report.createdAt;
+ if (!startedAt) continue;
+ // Null (ongoing) unless a resolved update gives a real end date.
+ const resolvedAt =
+ report.status === "resolved" && lastUpdate?.status === "resolved"
+ ? lastUpdate.date
+ : null;
+
+ out.push({
+ id: `report-${report.id}`,
+ date: startOfDay(startedAt),
+ status: "degraded",
+ type: "report",
+ name: report.title,
+ from: startedAt,
+ to: resolvedAt,
+ href: `${base}/events/report/${report.id}`,
+ });
+ }
+
+ for (const m of maintenances) {
+ const start = startOfDay(minDate([m.from, m.to]));
+ const end = startOfDay(maxDate([m.from, m.to]));
+ const href = `${base}/events/maintenance/${m.id}`;
+ for (const day of eachDayOfInterval({ start, end })) {
+ out.push({
+ id: `maintenance-${m.id}-${day.toISOString()}`,
+ date: day,
+ status: "info",
+ type: "maintenance",
+ name: m.title,
+ from: m.from,
+ to: m.to,
+ href,
+ });
+ }
+ }
+
+ const seenIncidents = new Set<number>();
+ for (const c of pageComponents) {
+ const incidents = c.monitor?.incidents ?? [];
+ for (const inc of incidents) {
+ if (seenIncidents.has(inc.id)) continue;
+ seenIncidents.add(inc.id);
+ const startedAt = inc.startedAt;
+ const end = startOfDay(inc.resolvedAt ?? new Date());
+ const start = startOfDay(startedAt);
+ for (const day of eachDayOfInterval({ start, end })) {
+ out.push({
+ id: `incident-${inc.id}-${day.toISOString()}`,
+ date: day,
+ status: "error",
+ type: "incident",
+ // `incident.title` is empty string on the DB row by default; use
+ // the localized "Downtime" label as a sensible fallback.
+ name: inc.title?.trim() ? inc.title : downtimeLabel,
+ from: startedAt,
+ to: inc.resolvedAt,
+ });
+ }
+ }
+ }
+
+ return out;
+ }, [statusReports, maintenances, pageComponents, downtimeLabel, base]);
+
+ const renderMarkerRow = useCallback((marker: StatusCalendarMarker) => {
+ const event = (
+ <StatusBarEvent
+ type={marker.type}
+ name={marker.name}
+ from={marker.from}
+ to={marker.to}
+ isAggregated={marker.isAggregated}
+ />
+ );
+ if (marker.href) {
+ return (
+ <Link
+ variant="unstyled"
+ href={marker.href}
+ className="block cursor-pointer rounded-sm hover:bg-accent/50"
+ >
+ {event}
+ </Link>
+ );
+ }
+ return event;
+ }, []);
+
+ if (isLoading) {
+ return <BlockStatusCalendarSkeleton title={calendarTitle} />;
+ }
+
+ return (
+ <BlockStatusCalendar
+ title={calendarTitle}
+ locale={dateFnsLocale}
+ markers={markers}
+ renderMarkerRow={renderMarkerRow}
+ eventTypes={["report", "maintenance"]}
+ disableFuture
+ {...rest}
+ />
+ );
+}
+
+/**
+ * App-side skeleton wrapper that injects the localized "Calendar" title.
+ * Use while the status-page data is in flight.
+ */
+export function StatusCalendarSkeleton(
+ props: Omit<StatusCalendarSkeletonProps, "title">,
+) {
+ const labels = useStatusBlocksLabels();
+ return (
+ <BlockStatusCalendarSkeleton title={labels.calendarTitle} {...props} />
+ );
+}
diff --git a/packages/api/src/router/statusPage.e2e.test.ts b/packages/api/src/router/statusPage.e2e.test.ts
index 0074729b2..c53b237e8 100644
--- a/packages/api/src/router/statusPage.e2e.test.ts
+++ b/packages/api/src/router/statusPage.e2e.test.ts
@@ -1,6 +1,13 @@
import { afterAll, beforeAll, describe, expect, test } from "bun:test";
import { and, db, eq, isNotNull, isNull } from "@openstatus/db";
-import { page, pageSubscriber, workspace } from "@openstatus/db/src/schema";
+import {
+ incidentTable,
+ monitor,
+ page,
+ pageComponent,
+ pageSubscriber,
+ workspace,
+} from "@openstatus/db/src/schema";
/**
* End-to-end integration tests for the full unsubscribe flow.
@@ -924,3 +931,127 @@ describe("statusPage.get endpoint validation", () => {
}
});
});
+
+describe("statusPage.get gates incidents by barType (calendar manual mode)", () => {
+ const barTypeSlug = "bar-type-incident-gating-test-page";
+ let barTypePageId: number;
+ let barTypeMonitorId: number;
+ let barTypeIncidentId: number;
+ let barTypeComponentId: number;
+
+ async function getPage(barType?: "absolute" | "manual") {
+ const { edgeRouter } = await import("../edge");
+ const { createInnerTRPCContext } = await import("../trpc");
+ const ctx = createInnerTRPCContext({
+ req: undefined,
+ // @ts-expect-error - auth not required for public procedure
+ auth: undefined,
+ });
+ const caller = edgeRouter.createCaller(ctx);
+ return caller.statusPage.get({ slug: barTypeSlug, barType });
+ }
+
+ function monitorIncidents(result: Awaited<ReturnType<typeof getPage>>) {
+ const component = result?.pageComponents.find(
+ (c) => c.monitorId === barTypeMonitorId,
+ );
+ return component?.monitor?.incidents ?? [];
+ }
+
+ beforeAll(async () => {
+ await db.delete(page).where(eq(page.slug, barTypeSlug));
+
+ // Page is stored as "manual" so we can also assert the default (no explicit
+ // barType arg) resolves from the page configuration.
+ const testPage = await db
+ .insert(page)
+ .values({
+ workspaceId: 1,
+ title: "Bar Type Incident Gating Page",
+ description: "Verifies incident gating in statusPage.get",
+ slug: barTypeSlug,
+ customDomain: "",
+ configuration: {
+ type: "manual",
+ value: "requests",
+ uptime: true,
+ theme: "default",
+ },
+ })
+ .returning()
+ .get();
+ barTypePageId = testPage.id;
+
+ const testMonitor = await db
+ .insert(monitor)
+ .values({
+ workspaceId: 1,
+ name: "Bar Type Test Monitor",
+ periodicity: "1m",
+ url: "https://example.com",
+ active: true,
+ })
+ .returning()
+ .get();
+ barTypeMonitorId = testMonitor.id;
+
+ const testIncident = await db
+ .insert(incidentTable)
+ .values({
+ monitorId: barTypeMonitorId,
+ workspaceId: 1,
+ title: "Bar Type Test Incident",
+ startedAt: new Date(),
+ })
+ .returning()
+ .get();
+ barTypeIncidentId = testIncident.id;
+
+ const testComponent = await db
+ .insert(pageComponent)
+ .values({
+ workspaceId: 1,
+ pageId: barTypePageId,
+ type: "monitor",
+ monitorId: barTypeMonitorId,
+ name: "Bar Type Test Component",
+ order: 0,
+ })
+ .returning()
+ .get();
+ barTypeComponentId = testComponent.id;
+ });
+
+ afterAll(async () => {
+ await db
+ .delete(pageComponent)
+ .where(eq(pageComponent.id, barTypeComponentId));
+ await db
+ .delete(incidentTable)
+ .where(eq(incidentTable.id, barTypeIncidentId));
+ await db.delete(monitor).where(eq(monitor.id, barTypeMonitorId));
+ await db.delete(page).where(eq(page.id, barTypePageId));
+ });
+
+ test("barType 'absolute' keeps monitor incidents", async () => {
+ const result = await getPage("absolute");
+ const incidents = monitorIncidents(result);
+
+ expect(incidents.length).toBe(1);
+ expect(incidents[0].id).toBe(barTypeIncidentId);
+ });
+
+ test("barType 'manual' strips monitor incidents", async () => {
+ const result = await getPage("manual");
+
+ expect(monitorIncidents(result)).toEqual([]);
+ });
+
+ test("defaults to the page configuration when barType is omitted", async () => {
+ // Stored configuration is "manual", so incidents must be stripped without
+ // an explicit barType — this is the initial-load path the calendar uses.
+ const result = await getPage();
+
+ expect(monitorIncidents(result)).toEqual([]);
+ });
+});
diff --git a/packages/api/src/router/statusPage.ts b/packages/api/src/router/statusPage.ts
index e92f0f1fe..77a64545e 100644
--- a/packages/api/src/router/statusPage.ts
+++ b/packages/api/src/router/statusPage.ts
@@ -382,6 +382,18 @@ export const statusPageRouter = createTRPCRouter({
(a, b) => b.from.getTime() - a.from.getTime(),
);
+ // In "manual" mode the page only surfaces user-authored events, so drop
+ // monitor-derived incidents from the components consumers read (e.g. the
+ // calendar). Mirrors the bar/uptime gating in statusPage.utils.ts.
+ const publicPageComponents =
+ barType === "manual"
+ ? pageComponents.map((c) =>
+ c.monitor
+ ? { ...c, monitor: { ...c.monitor, incidents: [] } }
+ : c,
+ )
+ : pageComponents;
+
return selectPublicPageSchemaWithRelation.parse({
..._page,
monitors,
@@ -394,7 +406,7 @@ export const statusPageRouter = createTRPCRouter({
status,
lastEvents,
openEvents,
- pageComponents,
+ pageComponents: publicPageComponents,
pageComponentGroups: _page.pageComponentGroups,
whiteLabel,
});
diff --git a/packages/ui/registry.json b/packages/ui/registry.json
index e0788363c..c005d2d8b 100644
--- a/packages/ui/registry.json
+++ b/packages/ui/registry.json
@@ -283,6 +283,30 @@
}
]
},
+ {
+ "name": "status-calendar",
+ "type": "registry:block",
+ "title": "Status Calendar",
+ "description": "Monthly calendar view of status history with per-day markers and event hover cards",
+ "registryDependencies": [
+ "status-types",
+ "status-i18n",
+ "status-bar",
+ "button",
+ "hover-card",
+ "separator",
+ "skeleton",
+ "use-media-query"
+ ],
+ "dependencies": ["date-fns", "lucide-react", "react-day-picker"],
+ "files": [
+ {
+ "path": "src/components/blocks/status-calendar.tsx",
+ "type": "registry:ui",
+ "target": "components/blocks/status-calendar.tsx"
+ }
+ ]
+ },
{
"name": "status-feed",
"type": "registry:block",
@@ -447,6 +471,7 @@
"status-component-group",
"status-events",
"status-bar",
+ "status-calendar",
"status-feed",
"status-page-shell",
"status-page-header",
diff --git a/packages/ui/src/components/blocks/status-bar.tsx b/packages/ui/src/components/blocks/status-bar.tsx
index 7347bb33c..cbc14d50f 100644
--- a/packages/ui/src/components/blocks/status-bar.tsx
+++ b/packages/ui/src/components/blocks/status-bar.tsx
@@ -1,5 +1,12 @@
"use client";
+import { useStatusBlocksLabels } from "@openstatus/ui/components/blocks/status-i18n";
+import type {
+ StatusBarData,
+ StatusEventType,
+ StatusType,
+} from "@openstatus/ui/components/blocks/status.types";
+import { statusColors } from "@openstatus/ui/components/blocks/status.utils";
import {
HoverCard,
HoverCardContent,
@@ -10,14 +17,7 @@ import { Skeleton } from "@openstatus/ui/components/ui/skeleton";
import { useMediaQuery } from "@openstatus/ui/hooks/use-media-query";
import { cn } from "@openstatus/ui/lib/utils";
import { formatDistanceStrict } from "date-fns";
-import { useCallback, useEffect, useRef, useState, forwardRef } from "react";
-import { statusColors } from "@openstatus/ui/components/blocks/status.utils";
-import type {
- StatusBarData,
- StatusEventType,
- StatusType,
-} from "@openstatus/ui/components/blocks/status.types";
-import { useStatusBlocksLabels } from "@openstatus/ui/components/blocks/status-i18n";
+import { forwardRef, useCallback, useEffect, useRef, useState } from "react";
interface StatusBarProps {
data: StatusBarData[];
@@ -578,10 +578,10 @@ const StatusBarItem = forwardRef<HTMLDivElement, StatusBarItemProps>(
);
StatusBarItem.displayName = "StatusBarItem";
-interface StatusBarCardProps {
+export interface StatusBarCardProps {
item: StatusBarData;
- isPinned: boolean;
- isTouch: boolean;
+ isPinned?: boolean;
+ isTouch?: boolean;
renderCard?: StatusBarProps["renderCard"];
renderEvent?: StatusBarProps["renderEvent"];
}
@@ -604,10 +604,10 @@ interface StatusBarCardProps {
* @param renderCard - Optional custom renderer for status items
* @param renderEvent - Optional custom renderer for events
*/
-function StatusBarCard({
+export function StatusBarCard({
item,
- isPinned,
- isTouch,
+ isPinned = false,
+ isTouch = false,
renderCard,
renderEvent,
}: StatusBarCardProps) {
@@ -617,21 +617,25 @@ function StatusBarCard({
<div className="p-2 text-xs">
{labels.formatDateShort(new Date(item.day))}
</div>
- <Separator />
- <div className="space-y-1 p-2 text-sm">
- {item.card.map((cardItem, cardIndex) => {
- if (renderCard) {
- return renderCard(cardItem, cardIndex);
- }
- return (
- <StatusBarContent
- key={`${item.day}-card-${cardIndex}`}
- status={cardItem.status}
- value={cardItem.value}
- />
- );
- })}
- </div>
+ {item.card.length > 0 && (
+ <>
+ <Separator />
+ <div className="space-y-1 p-2 text-sm">
+ {item.card.map((cardItem, cardIndex) => {
+ if (renderCard) {
+ return renderCard(cardItem, cardIndex);
+ }
+ return (
+ <StatusBarContent
+ key={`${item.day}-card-${cardIndex}`}
+ status={cardItem.status}
+ value={cardItem.value}
+ />
+ );
+ })}
+ </div>
+ </>
+ )}
{item.events.length > 0 && (
<>
<Separator />
diff --git a/packages/ui/src/components/blocks/status-calendar.tsx b/packages/ui/src/components/blocks/status-calendar.tsx
new file mode 100644
index 000000000..e7046022d
--- /dev/null
+++ b/packages/ui/src/components/blocks/status-calendar.tsx
@@ -0,0 +1,656 @@
+"use client";
+
+import {
+ type Locale,
+ addMonths,
+ format,
+ isSameDay,
+ startOfDay,
+ startOfMonth,
+ subMonths,
+} from "date-fns";
+import { ChevronLeft, ChevronRight } from "lucide-react";
+import {
+ type FocusEvent,
+ type ReactNode,
+ type RefObject,
+ forwardRef,
+ useCallback,
+ useEffect,
+ useMemo,
+ useRef,
+ useState,
+} from "react";
+import { DayPicker, type DayProps } from "react-day-picker";
+
+import { StatusBarCard } from "@openstatus/ui/components/blocks/status-bar";
+import { useStatusBlocksLabels } from "@openstatus/ui/components/blocks/status-i18n";
+import type {
+ StatusBarData,
+ StatusEventType,
+ StatusType,
+} from "@openstatus/ui/components/blocks/status.types";
+import { Button } from "@openstatus/ui/components/ui/button";
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from "@openstatus/ui/components/ui/hover-card";
+import { Separator } from "@openstatus/ui/components/ui/separator";
+import { Skeleton } from "@openstatus/ui/components/ui/skeleton";
+import { useMediaQuery } from "@openstatus/ui/hooks/use-media-query";
+import { cn } from "@openstatus/ui/lib/utils";
+
+type BarEvent = StatusBarData["events"][number];
+
+export interface StatusCalendarMarker {
+ id: string | number;
+ /** Day this marker belongs to, in the viewer's local timezone. */
+ date: Date;
+ /** Drives the day cell's tinted-fill color (worst-severity wins per day). */
+ status: Exclude<StatusType, "empty">;
+ /** Event shape mirrors StatusBarEvent so the popover can render the same row. */
+ type: StatusEventType;
+ name: string;
+ /** Full event range (use the event's true start/end, not the per-day instance). */
+ from?: Date | null;
+ to?: Date | null;
+ isAggregated?: boolean;
+ href?: string;
+}
+
+export interface StatusCalendarProps {
+ markers: StatusCalendarMarker[];
+ /** Controlled month. Defaults to the first of the current month. */
+ month?: Date;
+ defaultMonth?: Date;
+ onMonthChange?: (month: Date) => void;
+ /** 0 = Sunday, 1 = Monday. Mockup shows Monday. */
+ weekStartsOn?: 0 | 1;
+ /**
+ * Treat the calendar as status history: render days after the latest event
+ * (or today, whichever is later) as disabled. Days up to and including that
+ * boundary — including scheduled future events — stay interactive. Forward
+ * navigation is still capped at the latest event's month. Defaults to false.
+ */
+ disableFuture?: boolean;
+ className?: string;
+ /** Calendar header label on the left side of the chrome. */
+ title?: ReactNode;
+ /**
+ * date-fns Locale used by DayPicker for weekday/month names. Callers should
+ * pass the locale resolved from their i18n layer; defaults to en-US.
+ */
+ locale?: Locale;
+ /** Override how a single marker row renders inside the hover card. */
+ renderMarkerRow?: (marker: StatusCalendarMarker) => ReactNode;
+ /**
+ * Restrict which event types drive the calendar (day fills, hover cards, and
+ * the forward-navigation cap). Markers of any other type are ignored. When
+ * omitted, all event types are shown.
+ */
+ eventTypes?: StatusEventType[];
+}
+
+const SEVERITY_RANK: Record<StatusCalendarMarker["status"], number> = {
+ error: 3,
+ degraded: 2,
+ info: 1,
+ success: 0,
+};
+
+// Hover deepens the same tint rather than swapping to the neutral accent, so
+// the severity signal survives the hover state.
+const SEVERITY_FILL: Record<StatusCalendarMarker["status"], string> = {
+ error: "bg-destructive/10 hover:bg-destructive/20 text-destructive",
+ degraded: "bg-warning/10 hover:bg-warning/20 text-warning",
+ info: "bg-info/10 hover:bg-info/20 text-info",
+ success: "bg-success/10 hover:bg-success/20 text-success",
+};
+
+function dayKey(date: Date): string {
+ return format(date, "yyyy-MM-dd");
+}
+
+function worstSeverity(
+ markers: StatusCalendarMarker[],
+): StatusCalendarMarker["status"] {
+ return markers.reduce<StatusCalendarMarker["status"]>((worst, m) => {
+ return SEVERITY_RANK[m.status] > SEVERITY_RANK[worst] ? m.status : worst;
+ }, "success");
+}
+
+export function StatusCalendar({
+ markers,
+ month,
+ defaultMonth,
+ onMonthChange,
+ weekStartsOn = 1,
+ disableFuture = false,
+ className,
+ title,
+ locale,
+ renderMarkerRow,
+ eventTypes,
+}: StatusCalendarProps) {
+ const labels = useStatusBlocksLabels();
+ const resolvedTitle = title ?? labels.calendarTitle;
+ const formatMonthYear = useCallback(
+ (d: Date) => {
+ // date-fns format reads its global locale (set by DateFnsProvider via
+ // setDefaultOptions), so this picks up the active language without us
+ // having to pass it explicitly here.
+ return format(d, "MMM yyyy", locale ? { locale } : undefined);
+ },
+ [locale],
+ );
+ const [internalMonth, setInternalMonth] = useState<Date>(() =>
+ startOfMonth(month ?? defaultMonth ?? new Date()),
+ );
+ const currentMonth = month ? startOfMonth(month) : internalMonth;
+
+ const setMonth = (next: Date) => {
+ const normalized = startOfMonth(next);
+ if (month === undefined) setInternalMonth(normalized);
+ onMonthChange?.(normalized);
+ };
+
+ // Drop markers whose type the caller opted out of before anything else reads
+ // them, so excluded types affect neither the fills, the cards, nor nav.
+ const visibleMarkers = useMemo(() => {
+ if (!eventTypes) return markers;
+ const allowed = new Set(eventTypes);
+ return markers.filter((m) => allowed.has(m.type));
+ }, [markers, eventTypes]);
+
+ const markersByDay = useMemo(() => {
+ const map = new Map<string, StatusCalendarMarker[]>();
+ for (const marker of visibleMarkers) {
+ const key = dayKey(marker.date);
+ const bucket = map.get(key);
+ if (bucket) bucket.push(marker);
+ else map.set(key, [marker]);
+ }
+ return map;
+ }, [visibleMarkers]);
+
+ // Cap forward navigation at the latest month that has a marker (or the
+ // current month, whichever is later). Prevents browsing into empty future
+ // months when no maintenance/event is scheduled.
+ const maxMonth = useMemo(() => {
+ const today = startOfMonth(new Date());
+ return visibleMarkers.reduce((acc, m) => {
+ const mm = startOfMonth(m.date);
+ return mm.getTime() > acc.getTime() ? mm : acc;
+ }, today);
+ }, [visibleMarkers]);
+ const canGoNext = currentMonth.getTime() < maxMonth.getTime();
+
+ // Status-history cutoff: disable days strictly after the latest event (or
+ // today, whichever is later) so the empty trailing future is blocked while
+ // scheduled future events stay reachable. Null = no blocking.
+ const maxDay = useMemo(() => {
+ if (!disableFuture) return null;
+ const today = startOfDay(new Date());
+ return visibleMarkers.reduce((acc, m) => {
+ const d = startOfDay(m.date);
+ return d.getTime() > acc.getTime() ? d : acc;
+ }, today);
+ }, [visibleMarkers, disableFuture]);
+
+ // Open state lives at the parent so the popover survives DayPicker remounts.
+ // Interaction model mirrors `status-bar.tsx` (hover on non-touch, tap pins).
+ const isTouch = useMediaQuery("(hover: none)");
+ const containerRef = useRef<HTMLDivElement>(null);
+ const [activeDayKey, setActiveDayKey] = useState<string | null>(null);
+ // Via ref, not a `Day` dep: keeps `Day` identity stable so cells don't remount
+ // every hover. CalendarDay re-renders top-down on setActiveDayKey regardless.
+ const activeDayKeyRef = useRef(activeDayKey);
+ useEffect(() => {
+ activeDayKeyRef.current = activeDayKey;
+ }, [activeDayKey]);
+ const [interaction, setInteraction] = useState<
+ "hover" | "pin" | "focus" | null
+ >(null);
+ const interactionRef = useRef(interaction);
+ useEffect(() => {
+ interactionRef.current = interaction;
+ }, [interaction]);
+
+ const closeTimerRef = useRef<number | null>(null);
+ const cancelClose = useCallback(() => {
+ if (closeTimerRef.current !== null) {
+ window.clearTimeout(closeTimerRef.current);
+ closeTimerRef.current = null;
+ }
+ }, []);
+ const close = useCallback(() => {
+ cancelClose();
+ setActiveDayKey(null);
+ setInteraction(null);
+ }, [cancelClose]);
+
+ // Tap/click pins the card; tapping the pinned day again closes it. This is
+ // the only open path on touch — Radix HoverCard ignores touch pointers. The
+ // `interactionRef` lags a tap's focus event, so a focus-then-click on the
+ // same day still reads "pin" and toggles closed.
+ const handleClick = useCallback(
+ (key: string) => {
+ cancelClose();
+ setActiveDayKey((prev) => {
+ if (prev === key && interactionRef.current === "pin") {
+ setInteraction(null);
+ return null;
+ }
+ setInteraction("pin");
+ return key;
+ });
+ },
+ [cancelClose],
+ );
+ const handleHoverStart = useCallback(
+ (key: string) => {
+ if (isTouch) return;
+ cancelClose();
+ setActiveDayKey(key);
+ setInteraction("hover");
+ },
+ [isTouch, cancelClose],
+ );
+ const handleHoverEnd = useCallback(() => {
+ if (interactionRef.current !== "hover") return;
+ closeTimerRef.current = window.setTimeout(() => {
+ setActiveDayKey(null);
+ setInteraction(null);
+ }, 100);
+ }, []);
+ const handleFocus = useCallback((key: string) => {
+ setActiveDayKey(key);
+ setInteraction("focus");
+ }, []);
+ const handleBlur = useCallback(
+ (e: FocusEvent) => {
+ const next = e.relatedTarget as Element | null;
+ // Focus moving into the card (e.g. an event link) shouldn't close it.
+ if (next?.closest('[data-slot="status-bar-card"]')) return;
+ close();
+ },
+ [close],
+ );
+
+ // Outside pointerdown closes the pinned card. Radix's own dismiss is
+ // suppressed on touch (see HoverCardContent) and the card is portaled out of
+ // `containerRef`, so we also keep clicks that land inside the card itself.
+ useEffect(() => {
+ if (activeDayKey === null) return;
+ const onDown = (e: MouseEvent) => {
+ const target = e.target as Element | null;
+ if (containerRef.current?.contains(target)) return;
+ if (target?.closest('[data-slot="status-bar-card"]')) return;
+ close();
+ };
+ document.addEventListener("mousedown", onDown);
+ return () => document.removeEventListener("mousedown", onDown);
+ }, [activeDayKey, close]);
+
+ const renderMarkerRowRef = useRef(renderMarkerRow);
+ useEffect(() => {
+ renderMarkerRowRef.current = renderMarkerRow;
+ }, [renderMarkerRow]);
+
+ const Day = useCallback(
+ (dayProps: DayProps) => (
+ <CalendarDay
+ {...dayProps}
+ markersByDay={markersByDay}
+ activeDayKeyRef={activeDayKeyRef}
+ isTouch={isTouch}
+ onClickDay={handleClick}
+ onHoverStart={handleHoverStart}
+ onHoverEnd={handleHoverEnd}
+ onHoverCardEnter={cancelClose}
+ onHoverCardLeave={close}
+ onFocusDay={handleFocus}
+ onBlurDay={handleBlur}
+ onClose={close}
+ renderMarkerRowRef={renderMarkerRowRef}
+ maxDay={maxDay}
+ />
+ ),
+ [
+ markersByDay,
+ isTouch,
+ handleClick,
+ handleHoverStart,
+ handleHoverEnd,
+ cancelClose,
+ close,
+ handleFocus,
+ handleBlur,
+ maxDay,
+ ],
+ );
+
+ const dayPickerComponents = useMemo(() => ({ Day }), [Day]);
+
+ return (
+ <div
+ ref={containerRef}
+ data-slot="status-calendar"
+ className={cn(
+ "flex flex-col rounded-lg border bg-card text-card-foreground",
+ className,
+ )}
+ >
+ <header className="flex items-center gap-3 px-4 py-3">
+ <div className="font-medium text-sm">{resolvedTitle}</div>
+ <div className="ml-auto flex items-center gap-1 text-muted-foreground text-sm">
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7"
+ aria-label="Previous month"
+ onClick={() => setMonth(subMonths(currentMonth, 1))}
+ >
+ <ChevronLeft className="size-4" />
+ </Button>
+ <span className="text-center font-medium font-mono text-foreground tabular-nums">
+ {formatMonthYear(currentMonth)}
+ </span>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="size-7"
+ aria-label="Next month"
+ disabled={!canGoNext}
+ onClick={() => setMonth(addMonths(currentMonth, 1))}
+ >
+ <ChevronRight className="size-4" />
+ </Button>
+ </div>
+ </header>
+ <div className="border-t">
+ <DayPicker
+ mode="default"
+ month={currentMonth}
+ weekStartsOn={weekStartsOn}
+ showOutsideDays={false}
+ locale={locale}
+ className="w-full"
+ classNames={{
+ months: "flex flex-col",
+ month: "flex flex-col w-full",
+ caption: "hidden",
+ table: "w-full border-collapse",
+ head_row: "flex w-full border-b",
+ head_cell:
+ "flex-1 text-muted-foreground font-mono font-normal text-[0.7rem] uppercase tracking-wide py-1.5 border-r last:border-r-0",
+ row: "flex w-full border-b last:border-b-0",
+ cell: "flex-1 relative p-0 text-center text-sm border-r last:border-r-0 focus-within:relative focus-within:z-20",
+ day: cn(
+ "inline-flex h-12 w-full items-center justify-center text-sm font-normal text-foreground/80 transition-colors",
+ "hover:bg-accent hover:text-accent-foreground",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
+ ),
+ day_today: "text-foreground font-semibold",
+ day_outside: "text-muted-foreground/50",
+ day_disabled: "text-muted-foreground/40 cursor-not-allowed",
+ day_hidden: "invisible",
+ }}
+ components={dayPickerComponents}
+ />
+ </div>
+ </div>
+ );
+}
+
+interface CalendarDayProps extends DayProps {
+ markersByDay: Map<string, StatusCalendarMarker[]>;
+ activeDayKeyRef: RefObject<string | null>;
+ isTouch: boolean;
+ onClickDay: (key: string) => void;
+ onHoverStart: (key: string) => void;
+ onHoverEnd: () => void;
+ onHoverCardEnter: () => void;
+ onHoverCardLeave: () => void;
+ onFocusDay: (key: string) => void;
+ onBlurDay: (e: FocusEvent) => void;
+ onClose: () => void;
+ renderMarkerRowRef: RefObject<
+ ((marker: StatusCalendarMarker) => ReactNode) | undefined
+ >;
+ /** Days strictly after this are disabled; null disables blocking entirely. */
+ maxDay: Date | null;
+}
+
+const CalendarDay = forwardRef<HTMLElement, CalendarDayProps>(
+ function CalendarDay(
+ {
+ date,
+ displayMonth,
+ markersByDay,
+ activeDayKeyRef,
+ isTouch,
+ onClickDay,
+ onHoverStart,
+ onHoverEnd,
+ onHoverCardEnter,
+ onHoverCardLeave,
+ onFocusDay,
+ onBlurDay,
+ onClose,
+ renderMarkerRowRef,
+ maxDay,
+ },
+ forwardedRef,
+ ) {
+ // With `mode="default"`, useDayRender returns `isButton: false` for every
+ // day — DayPicker only generates click handlers under a selection mode.
+ // We don't need DayPicker's interactivity (we drive our own hover popover),
+ // so we skip useDayRender entirely and render our own trigger.
+ const thisDayKey = dayKey(startOfDay(date));
+ const isOutside =
+ startOfMonth(date).getTime() !== startOfMonth(displayMonth).getTime();
+
+ // Overriding `components.Day` bypasses DayPicker's own hide-outside-days
+ // logic — we have to drop these cells ourselves so the grid only shows the
+ // current month.
+ if (isOutside) {
+ return (
+ <div data-day-state="outside" className="h-12 w-full bg-muted/30" />
+ );
+ }
+
+ // Past the status-history cutoff: render a dimmed, non-interactive cell.
+ const isBlocked =
+ maxDay !== null && startOfDay(date).getTime() > maxDay.getTime();
+ if (isBlocked) {
+ return (
+ <div
+ ref={forwardedRef as RefObject<HTMLDivElement>}
+ data-day={thisDayKey}
+ data-day-state="disabled"
+ aria-disabled
+ tabIndex={-1}
+ className="inline-flex h-12 w-full items-center justify-center font-mono text-muted-foreground/40 text-sm"
+ >
+ {format(date, "d")}
+ </div>
+ );
+ }
+
+ const isToday = isSameDay(date, new Date());
+ const dayMarkers = markersByDay.get(thisDayKey) ?? [];
+ const severity =
+ dayMarkers.length > 0 ? worstSeverity(dayMarkers) : undefined;
+ const open = activeDayKeyRef.current === thisDayKey;
+
+ const hasMarkers = dayMarkers.length > 0;
+ // Tinted-field: severity days get a soft fill that owns the hover state,
+ // empty days fall back to the neutral accent hover.
+ const dayClass = cn(
+ "inline-flex h-12 w-full items-center justify-center font-mono text-sm font-normal text-foreground/80 transition-colors",
+ "focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-inset focus-visible:ring-ring",
+ isToday && "text-foreground font-semibold",
+ severity
+ ? SEVERITY_FILL[severity]
+ : "hover:bg-accent hover:text-accent-foreground",
+ hasMarkers && "cursor-pointer",
+ );
+
+ // Days without events render a plain trigger — no HoverCard, no popover.
+ if (!hasMarkers) {
+ return (
+ <div
+ ref={forwardedRef as RefObject<HTMLDivElement>}
+ data-day={thisDayKey}
+ data-day-state="empty"
+ tabIndex={-1}
+ className={dayClass}
+ >
+ {format(date, "d")}
+ </div>
+ );
+ }
+
+ const barItem: StatusBarData = {
+ day: format(date, "yyyy-MM-dd"),
+ bar: [],
+ card: [],
+ events: dayMarkers.map(markerToBarEvent),
+ };
+ const indexByEventId = new Map<BarEvent["id"], number>(
+ barItem.events.map((e, i) => [e.id, i]),
+ );
+
+ return (
+ // No `onOpenChange`: open state is fully controlled by our handlers (see
+ // parent), matching `status-bar.tsx`. Radix's hover/dismiss listeners fire
+ // into a no-op, so they can't fight the pin/toggle model.
+ <HoverCard openDelay={0} closeDelay={0} open={open}>
+ <HoverCardTrigger asChild>
+ <button
+ type="button"
+ ref={forwardedRef as RefObject<HTMLButtonElement>}
+ data-day={thisDayKey}
+ data-day-state="interactive"
+ aria-pressed={open}
+ className={dayClass}
+ onClick={() => onClickDay(thisDayKey)}
+ onMouseEnter={() => onHoverStart(thisDayKey)}
+ onMouseLeave={onHoverEnd}
+ onFocus={() => onFocusDay(thisDayKey)}
+ onBlur={onBlurDay}
+ onKeyDown={(e) => {
+ if (e.key === "Escape") onClose();
+ }}
+ >
+ {format(date, "d")}
+ </button>
+ </HoverCardTrigger>
+ <HoverCardContent
+ side="top"
+ align="center"
+ className="w-auto min-w-40 p-0"
+ onMouseEnter={onHoverCardEnter}
+ onMouseLeave={onHoverCardLeave}
+ // On touch, the opening tap's emulated pointer sequence would trip
+ // Radix's dismiss-on-outside and close the card immediately. Suppress
+ // it here; the parent's document listener handles real outside taps.
+ onPointerDownOutside={(e) => {
+ if (isTouch) e.preventDefault();
+ }}
+ >
+ <StatusBarCard
+ item={barItem}
+ renderEvent={(event, eventIndex) => {
+ const fn = renderMarkerRowRef.current;
+ if (!fn) return undefined;
+ const idx = indexByEventId.get(event.id) ?? 0;
+ return (
+ <div key={`${event.id}-${event.type}`}>
+ {eventIndex > 0 && (
+ <Separator className="-mx-2 my-2 data-[orientation=horizontal]:w-auto" />
+ )}
+ {fn(dayMarkers[idx])}
+ </div>
+ );
+ }}
+ />
+ </HoverCardContent>
+ </HoverCard>
+ );
+ },
+);
+
+function markerToBarEvent(m: StatusCalendarMarker): BarEvent {
+ return {
+ id: m.id,
+ name: m.name,
+ type: m.type,
+ from: m.from ?? null,
+ to: m.to ?? null,
+ isAggregated: m.isAggregated,
+ };
+}
+
+export interface StatusCalendarSkeletonProps {
+ /** Title shown in the header chrome; falls back to "Calendar" if omitted. */
+ title?: ReactNode;
+ className?: string;
+}
+
+/** Loading placeholder mirroring `<StatusCalendar>`'s chrome (header + 6×7 grid). */
+export function StatusCalendarSkeleton({
+ title,
+ className,
+}: StatusCalendarSkeletonProps) {
+ const labels = useStatusBlocksLabels();
+ return (
+ <div
+ data-slot="status-calendar-skeleton"
+ className={cn(
+ "flex flex-col rounded-lg border bg-card text-card-foreground",
+ className,
+ )}
+ >
+ <header className="flex items-center gap-3 px-4 py-3">
+ <div className="font-medium text-sm">
+ {title ?? labels.calendarTitle}
+ </div>
+ <div className="ml-auto flex items-center gap-1">
+ <Skeleton className="size-7 rounded-md" />
+ <Skeleton className="h-4 w-20" />
+ <Skeleton className="size-7 rounded-md" />
+ </div>
+ </header>
+ <div className="border-t">
+ <div className="flex w-full border-b">
+ {Array.from({ length: 7 }).map((_, i) => (
+ <div
+ key={`weekday-${i}`}
+ className="flex flex-1 justify-center border-r py-1.5 last:border-r-0"
+ >
+ <Skeleton className="h-3 w-4" />
+ </div>
+ ))}
+ </div>
+ {Array.from({ length: 6 }).map((_, row) => (
+ <div
+ key={`row-${row}`}
+ className="flex w-full border-b last:border-b-0"
+ >
+ {Array.from({ length: 7 }).map((_, col) => (
+ <div
+ key={`cell-${row}-${col}`}
+ className="flex h-12 flex-1 items-center justify-center border-r last:border-r-0"
+ >
+ <Skeleton className="h-4 w-6" />
+ </div>
+ ))}
+ </div>
+ ))}
+ </div>
+ </div>
+ );
+}
diff --git a/packages/ui/src/components/blocks/status-i18n.tsx b/packages/ui/src/components/blocks/status-i18n.tsx
index 5cf82a6b9..d64936c28 100644
--- a/packages/ui/src/components/blocks/status-i18n.tsx
+++ b/packages/ui/src/components/blocks/status-i18n.tsx
@@ -1,12 +1,12 @@
"use client";
-import { createContext, useContext } from "react";
-import { defaultStatusBlocksLabels } from "@openstatus/ui/components/blocks/status.utils";
import type {
- StatusReportUpdateType,
- StatusType,
- ThemeValue,
+ StatusReportUpdateType,
+ StatusType,
+ ThemeValue,
} from "@openstatus/ui/components/blocks/status.types";
+import { defaultStatusBlocksLabels } from "@openstatus/ui/components/blocks/status.utils";
+import { createContext, useContext } from "react";
/**
* Labels and locale-aware formatters consumed by block components.
@@ -17,78 +17,83 @@ import type {
* supply translated strings + locale-aware formatters.
*/
export type StatusBlocksLabels = {
- systemStatus: Record<StatusType, { long: string; short: string }>;
- incidentStatus: Record<StatusReportUpdateType, string>;
- requestStatus: Record<StatusType, string>;
+ systemStatus: Record<StatusType, { long: string; short: string }>;
+ incidentStatus: Record<StatusReportUpdateType, string>;
+ requestStatus: Record<StatusType, string>;
+
+ today: string;
+ ongoing: string;
+ reportResolved: string;
+ noRecentNotifications: string;
+ noRecentNotificationsDescription: string;
+ noReports: string;
+ noReportsDescription: string;
+ noPublicMonitors: string;
+ noPublicMonitorsDescription: string;
- today: string;
- ongoing: string;
- reportResolved: string;
- noRecentNotifications: string;
- noRecentNotificationsDescription: string;
- noReports: string;
- noReportsDescription: string;
- noPublicMonitors: string;
- noPublicMonitorsDescription: string;
+ themeNames: Record<ThemeValue, string>;
+ ariaToggleTheme: string;
- themeNames: Record<ThemeValue, string>;
- ariaToggleTheme: string;
+ subscribe: string;
+ subscribeRssDescription: string;
+ subscribeAtomDescription: string;
+ subscribeJsonDescription: string;
+ subscribeSlackDescription: string;
+ subscribeSshDescription: string;
+ linkCopiedToClipboard: string;
+ ariaCopyLink: string;
- subscribe: string;
- subscribeRssDescription: string;
- subscribeAtomDescription: string;
- subscribeJsonDescription: string;
- subscribeSlackDescription: string;
- subscribeSshDescription: string;
- linkCopiedToClipboard: string;
- ariaCopyLink: string;
+ poweredBy: string;
+ getInTouch: string;
- poweredBy: string;
- getInTouch: string;
+ ariaStatusTracker: string;
+ ariaDayStatus: (n: number) => string;
+ clickAgainToUnpin: string;
- ariaStatusTracker: string;
- ariaDayStatus: (n: number) => string;
- clickAgainToUnpin: string;
+ /** Heading shown on the status-calendar block. */
+ calendarTitle: string;
- durationIn: (s: string) => string;
- durationEarlier: (s: string) => string;
- durationFor: (s: string) => string;
- durationAcross: (s: string) => string;
+ durationIn: (s: string) => string;
+ durationEarlier: (s: string) => string;
+ durationFor: (s: string) => string;
+ durationAcross: (s: string) => string;
- formatDate: (d: Date) => string;
- formatDateShort: (d: Date) => string;
- formatDateTime: (d: Date) => string;
- formatDateRange: (from?: Date, to?: Date) => string;
- /**
- * Returns the start/end of a closed range as separate strings, so callers
- * can render each side independently (e.g. wrap each in a hovercard)
- * without re-parsing the joined output of `formatDateRange`.
- *
- * Implementations should collapse same-day ranges (date on `from`, time
- * only on `to`) the same way `formatDateRange` does.
- *
- * Closed ranges only — both `from` and `to` are required. For open-ended
- * cases (`Since …` / `Until …` / `All time`) use `formatDateRange`.
- */
- formatDateRangeParts: (from: Date, to: Date) => { from: string; to: string };
+ formatDate: (d: Date) => string;
+ formatDateShort: (d: Date) => string;
+ formatDateTime: (d: Date) => string;
+ formatDateRange: (from?: Date, to?: Date) => string;
+ /**
+ * Returns the start/end of a closed range as separate strings, so callers
+ * can render each side independently (e.g. wrap each in a hovercard)
+ * without re-parsing the joined output of `formatDateRange`.
+ *
+ * Implementations should collapse same-day ranges (date on `from`, time
+ * only on `to`) the same way `formatDateRange` does.
+ *
+ * Closed ranges only — both `from` and `to` are required. For open-ended
+ * cases (`Since …` / `Until …` / `All time`) use `formatDateRange`.
+ */
+ formatDateRangeParts: (from: Date, to: Date) => { from: string; to: string };
};
-const StatusBlocksLabelsContext = createContext<StatusBlocksLabels | null>(null);
+const StatusBlocksLabelsContext = createContext<StatusBlocksLabels | null>(
+ null,
+);
export function StatusBlocksI18nProvider({
- value,
- children,
+ value,
+ children,
}: {
- value: StatusBlocksLabels;
- children: React.ReactNode;
+ value: StatusBlocksLabels;
+ children: React.ReactNode;
}) {
- return (
- <StatusBlocksLabelsContext.Provider value={value}>
- {children}
- </StatusBlocksLabelsContext.Provider>
- );
+ return (
+ <StatusBlocksLabelsContext.Provider value={value}>
+ {children}
+ </StatusBlocksLabelsContext.Provider>
+ );
}
export function useStatusBlocksLabels(): StatusBlocksLabels {
- return useContext(StatusBlocksLabelsContext) ?? defaultStatusBlocksLabels;
+ return useContext(StatusBlocksLabelsContext) ?? defaultStatusBlocksLabels;
}
diff --git a/packages/ui/src/components/blocks/status.types.ts b/packages/ui/src/components/blocks/status.types.ts
index 54a11d8c5..c4baff58c 100644
--- a/packages/ui/src/components/blocks/status.types.ts
+++ b/packages/ui/src/components/blocks/status.types.ts
@@ -1,6 +1,10 @@
export type StatusType = "success" | "degraded" | "error" | "info" | "empty";
export type StatusEventType = "incident" | "report" | "maintenance";
-export type StatusReportUpdateType = "investigating" | "identified" | "monitoring" | "resolved"
+export type StatusReportUpdateType =
+ | "investigating"
+ | "identified"
+ | "monitoring"
+ | "resolved";
export const THEME_VALUES = ["light", "dark", "system"] as const;
export type ThemeValue = (typeof THEME_VALUES)[number];
@@ -33,22 +37,22 @@ export type StatusEventData =
| { type: "maintenance"; data: Maintenance };
export type StatusBarData = {
- day: string;
- bar: {
- status: StatusType;
- // NOTE: is in percentage! should sum up to 100%
- height: number;
- }[];
- card: {
- status: StatusType;
- value: string;
- }[];
- events: {
- id: number;
- name: string;
- type: StatusEventType;
- from: Date | null;
- to: Date | null;
- isAggregated?: boolean;
- }[];
-}
\ No newline at end of file
+ day: string;
+ bar: {
+ status: StatusType;
+ // NOTE: is in percentage! should sum up to 100%
+ height: number;
+ }[];
+ card: {
+ status: StatusType;
+ value: string;
+ }[];
+ events: {
+ id: number | string;
+ name: string;
+ type: StatusEventType;
+ from: Date | null;
+ to: Date | null;
+ isAggregated?: boolean;
+ }[];
+};
diff --git a/packages/ui/src/components/blocks/status.utils.ts b/packages/ui/src/components/blocks/status.utils.ts
index e08a76519..b721b3d3c 100644
--- a/packages/ui/src/components/blocks/status.utils.ts
+++ b/packages/ui/src/components/blocks/status.utils.ts
@@ -1,5 +1,5 @@
-import { endOfDay, isSameDay, startOfDay } from "date-fns";
import type { StatusBlocksLabels } from "@openstatus/ui/components/blocks/status-i18n";
+import { endOfDay, isSameDay, startOfDay } from "date-fns";
/**
* Formats a date range in a human-readable format.
@@ -23,35 +23,35 @@ import type { StatusBlocksLabels } from "@openstatus/ui/components/blocks/status
* // => "January 1, 10:00 AM - 3:00 PM"
*/
export function formatDateRange(from?: Date, to?: Date) {
- const sameDay = from && to && isSameDay(from, to);
- const isFromStartDay = from && startOfDay(from).getTime() === from.getTime();
- const isToEndDay = to && endOfDay(to).getTime() === to.getTime();
+ const sameDay = from && to && isSameDay(from, to);
+ const isFromStartDay = from && startOfDay(from).getTime() === from.getTime();
+ const isToEndDay = to && endOfDay(to).getTime() === to.getTime();
- if (sameDay) {
- if (from && to && from.getTime() === to.getTime()) {
- return formatDateTime(from);
- }
- if (from && to) {
- return `${formatDateTime(from)} - ${formatTime(to)}`;
- }
- }
+ if (sameDay) {
+ if (from && to && from.getTime() === to.getTime()) {
+ return formatDateTime(from);
+ }
+ if (from && to) {
+ return `${formatDateTime(from)} - ${formatTime(to)}`;
+ }
+ }
- if (from && to) {
- if (isFromStartDay && isToEndDay) {
- return `${formatDate(from)} - ${formatDate(to)}`;
- }
- return `${formatDateTime(from)} - ${formatDateTime(to)}`;
- }
+ if (from && to) {
+ if (isFromStartDay && isToEndDay) {
+ return `${formatDate(from)} - ${formatDate(to)}`;
+ }
+ return `${formatDateTime(from)} - ${formatDateTime(to)}`;
+ }
- if (to) {
- return `Until ${formatDateTime(to)}`;
- }
+ if (to) {
+ return `Until ${formatDateTime(to)}`;
+ }
- if (from) {
- return `Since ${formatDateTime(from)}`;
- }
+ if (from) {
+ return `Since ${formatDateTime(from)}`;
+ }
- return "All time";
+ return "All time";
}
/**
@@ -63,16 +63,16 @@ export function formatDateRange(from?: Date, to?: Date) {
* @returns A formatted date string
*/
export function formatDate(
- date: Date,
- options?: Intl.DateTimeFormatOptions,
- locale = "en-US",
+ date: Date,
+ options?: Intl.DateTimeFormatOptions,
+ locale = "en-US",
) {
- return date.toLocaleDateString(locale, {
- year: "numeric",
- month: "long",
- day: "numeric",
- ...options,
- });
+ return date.toLocaleDateString(locale, {
+ year: "numeric",
+ month: "long",
+ day: "numeric",
+ ...options,
+ });
}
/**
@@ -83,11 +83,11 @@ export function formatDate(
* @returns A formatted date string with abbreviated month
*/
export function formatDateShort(date: Date, locale = "en-US") {
- return date.toLocaleDateString(locale, {
- year: "numeric",
- month: "short",
- day: "numeric",
- });
+ return date.toLocaleDateString(locale, {
+ year: "numeric",
+ month: "short",
+ day: "numeric",
+ });
}
/**
@@ -98,12 +98,12 @@ export function formatDateShort(date: Date, locale = "en-US") {
* @returns A formatted date and time string
*/
export function formatDateTime(date: Date, locale = "en-US") {
- return date.toLocaleDateString(locale, {
- month: "long",
- day: "numeric",
- hour: "numeric",
- minute: "numeric",
- });
+ return date.toLocaleDateString(locale, {
+ month: "long",
+ day: "numeric",
+ hour: "numeric",
+ minute: "numeric",
+ });
}
/**
@@ -114,15 +114,15 @@ export function formatDateTime(date: Date, locale = "en-US") {
* @returns A formatted time string
*/
export function formatTime(date: Date, locale = "en-US") {
- return date.toLocaleTimeString(locale, {
- hour: "numeric",
- minute: "numeric",
- });
+ return date.toLocaleTimeString(locale, {
+ hour: "numeric",
+ minute: "numeric",
+ });
}
import type {
- StatusReportUpdateType,
- StatusType,
+ StatusReportUpdateType,
+ StatusType,
} from "@openstatus/ui/components/blocks/status.types";
/**
@@ -130,29 +130,29 @@ import type {
* Used for displaying status banner and component statuses
*/
export const systemStatusLabels: Record<
- StatusType,
- { long: string; short: string }
+ StatusType,
+ { long: string; short: string }
> = {
- success: {
- long: "All Systems Operational",
- short: "Operational",
- },
- degraded: {
- long: "Degraded Performance",
- short: "Degraded",
- },
- error: {
- long: "Partial Outage",
- short: "Outage",
- },
- info: {
- long: "Maintenance",
- short: "Maintenance",
- },
- empty: {
- long: "No Data",
- short: "No Data",
- },
+ success: {
+ long: "All Systems Operational",
+ short: "Operational",
+ },
+ degraded: {
+ long: "Degraded Performance",
+ short: "Degraded",
+ },
+ error: {
+ long: "Partial Outage",
+ short: "Outage",
+ },
+ info: {
+ long: "Maintenance",
+ short: "Maintenance",
+ },
+ empty: {
+ long: "No Data",
+ short: "No Data",
+ },
} as const;
/**
@@ -160,20 +160,20 @@ export const systemStatusLabels: Record<
* @deprecated Use systemStatusLabels instead
*/
export const messages = {
- long: {
- success: systemStatusLabels.success.long,
- degraded: systemStatusLabels.degraded.long,
- error: systemStatusLabels.error.long,
- info: systemStatusLabels.info.long,
- empty: systemStatusLabels.empty.long,
- },
- short: {
- success: systemStatusLabels.success.short,
- degraded: systemStatusLabels.degraded.short,
- error: systemStatusLabels.error.short,
- info: systemStatusLabels.info.short,
- empty: systemStatusLabels.empty.short,
- },
+ long: {
+ success: systemStatusLabels.success.long,
+ degraded: systemStatusLabels.degraded.long,
+ error: systemStatusLabels.error.long,
+ info: systemStatusLabels.info.long,
+ empty: systemStatusLabels.empty.long,
+ },
+ short: {
+ success: systemStatusLabels.success.short,
+ degraded: systemStatusLabels.degraded.short,
+ error: systemStatusLabels.error.short,
+ info: systemStatusLabels.info.short,
+ empty: systemStatusLabels.empty.short,
+ },
} as const;
/**
@@ -181,11 +181,11 @@ export const messages = {
* Used for displaying individual request statuses
*/
export const requestStatusLabels: Record<StatusType, string> = {
- success: "Normal",
- degraded: "Degraded",
- error: "Error",
- info: "Maintenance",
- empty: "No Data",
+ success: "Normal",
+ degraded: "Degraded",
+ error: "Error",
+ info: "Maintenance",
+ empty: "No Data",
} as const;
/**
@@ -199,10 +199,10 @@ export const requests = requestStatusLabels;
* Used for displaying incident report update statuses
*/
export const incidentStatusLabels: Record<StatusReportUpdateType, string> = {
- resolved: "Resolved",
- monitoring: "Monitoring",
- identified: "Identified",
- investigating: "Investigating",
+ resolved: "Resolved",
+ monitoring: "Monitoring",
+ identified: "Identified",
+ investigating: "Investigating",
} as const;
/**
@@ -216,11 +216,11 @@ export const status = incidentStatusLabels;
* Maps StatusType to corresponding CSS custom properties
*/
export const statusColors: Record<StatusType, string> = {
- success: "var(--success)",
- degraded: "var(--warning)",
- error: "var(--destructive)",
- info: "var(--info)",
- empty: "var(--muted)",
+ success: "var(--success)",
+ degraded: "var(--warning)",
+ error: "var(--destructive)",
+ info: "var(--info)",
+ empty: "var(--muted)",
} as const;
/**
@@ -234,63 +234,65 @@ export const colors = statusColors;
* Registry/web preview render with this set; the status-page app overrides via the provider.
*/
export const defaultStatusBlocksLabels = {
- systemStatus: systemStatusLabels,
- incidentStatus: incidentStatusLabels,
- requestStatus: requestStatusLabels,
+ systemStatus: systemStatusLabels,
+ incidentStatus: incidentStatusLabels,
+ requestStatus: requestStatusLabels,
+
+ today: "Today",
+ ongoing: "Ongoing",
+ reportResolved: "Report resolved",
+ noRecentNotifications: "No recent notifications",
+ noRecentNotificationsDescription:
+ "There have been no reports within the last 7 days.",
+ noReports: "No reports",
+ noReportsDescription: "There are no reports to display.",
+ noPublicMonitors: "No public monitors",
+ noPublicMonitorsDescription: "There are no public monitors to display.",
- today: "Today",
- ongoing: "Ongoing",
- reportResolved: "Report resolved",
- noRecentNotifications: "No recent notifications",
- noRecentNotificationsDescription:
- "There have been no reports within the last 7 days.",
- noReports: "No reports",
- noReportsDescription: "There are no reports to display.",
- noPublicMonitors: "No public monitors",
- noPublicMonitorsDescription: "There are no public monitors to display.",
+ themeNames: {
+ light: "Light",
+ dark: "Dark",
+ system: "System",
+ },
+ ariaToggleTheme: "Toggle theme",
- themeNames: {
- light: "Light",
- dark: "Dark",
- system: "System",
- },
- ariaToggleTheme: "Toggle theme",
+ subscribe: "Get updates",
+ subscribeRssDescription: "Get the RSS feed",
+ subscribeAtomDescription: "Get the Atom feed",
+ subscribeJsonDescription: "Get the JSON updates",
+ subscribeSlackDescription:
+ "For status updates in Slack, paste the text below into any channel.",
+ subscribeSshDescription: "Get status via SSH",
+ linkCopiedToClipboard: "Link copied to clipboard",
+ ariaCopyLink: "Copy Link",
- subscribe: "Get updates",
- subscribeRssDescription: "Get the RSS feed",
- subscribeAtomDescription: "Get the Atom feed",
- subscribeJsonDescription: "Get the JSON updates",
- subscribeSlackDescription:
- "For status updates in Slack, paste the text below into any channel.",
- subscribeSshDescription: "Get status via SSH",
- linkCopiedToClipboard: "Link copied to clipboard",
- ariaCopyLink: "Copy Link",
+ poweredBy: "powered by",
+ getInTouch: "Get in touch",
- poweredBy: "powered by",
- getInTouch: "Get in touch",
+ ariaStatusTracker: "Status tracker",
+ ariaDayStatus: (n: number) => `Day ${n} status`,
+ clickAgainToUnpin: "Click again to unpin",
- ariaStatusTracker: "Status tracker",
- ariaDayStatus: (n: number) => `Day ${n} status`,
- clickAgainToUnpin: "Click again to unpin",
+ calendarTitle: "Calendar",
- durationIn: (s: string) => `(in ${s})`,
- durationEarlier: (s: string) => `(${s} earlier)`,
- durationFor: (s: string) => `(for ${s})`,
- durationAcross: (s: string) => `across ${s}`,
+ durationIn: (s: string) => `(in ${s})`,
+ durationEarlier: (s: string) => `(${s} earlier)`,
+ durationFor: (s: string) => `(for ${s})`,
+ durationAcross: (s: string) => `across ${s}`,
- formatDate: (d: Date) => formatDate(d),
- formatDateShort: (d: Date) => formatDateShort(d),
- formatDateTime: (d: Date) => formatDateTime(d),
- formatDateRange: (from?: Date, to?: Date) => formatDateRange(from, to),
- formatDateRangeParts: (from: Date, to: Date) => {
- if (isSameDay(from, to)) {
- return { from: formatDateTime(from), to: formatTime(to) };
- }
- const isFromStartDay = startOfDay(from).getTime() === from.getTime();
- const isToEndDay = endOfDay(to).getTime() === to.getTime();
- if (isFromStartDay && isToEndDay) {
- return { from: formatDate(from), to: formatDate(to) };
- }
- return { from: formatDateTime(from), to: formatDateTime(to) };
- },
+ formatDate: (d: Date) => formatDate(d),
+ formatDateShort: (d: Date) => formatDateShort(d),
+ formatDateTime: (d: Date) => formatDateTime(d),
+ formatDateRange: (from?: Date, to?: Date) => formatDateRange(from, to),
+ formatDateRangeParts: (from: Date, to: Date) => {
+ if (isSameDay(from, to)) {
+ return { from: formatDateTime(from), to: formatTime(to) };
+ }
+ const isFromStartDay = startOfDay(from).getTime() === from.getTime();
+ const isToEndDay = endOfDay(to).getTime() === to.getTime();
+ if (isFromStartDay && isToEndDay) {
+ return { from: formatDate(from), to: formatDate(to) };
+ }
+ return { from: formatDateTime(from), to: formatDateTime(to) };
+ },
} as const satisfies StatusBlocksLabels;