Skip to content

Open-source status page, incident response and uptime monitoring

feat: status-report/maintenance timeline (#2825)

Maximilian Kaskedec0730734ef
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
index a9f77fd43..e800b6b7b 100644
--- a/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
@@ -1,17 +1,10 @@
"use client";
import type { IncidentStatus } from "@openstatus/db/src/schema/incidents/constants";
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@openstatus/ui/components/ui/tabs";
import { useQuery } from "@tanstack/react-query";
import { formatDistanceStrict, formatDistanceToNow } from "date-fns";
import { useState } from "react";
-import { HoverCardTimestamp } from "@/components/common/hover-card-timestamp";
import { Link } from "@/components/common/link";
import {
DetailAside,
@@ -20,6 +13,7 @@ import {
DetailMain,
DetailMeta,
DetailMetaItem,
+ DetailMetaTime,
DetailSection,
DetailSectionTitle,
} from "@/components/content/detail";
@@ -100,8 +94,42 @@ export function Client({ id }: { id: number }) {
}
};
+ const resolved = incident.status === "resolved";
+ const timeline = (
+ <DetailSection>
+ <DetailSectionTitle variant="heading">
+ Timeline
+ {events ? (
+ <span className="text-muted-foreground ml-2 font-mono text-xs font-normal">
+ {events.length}
+ </span>
+ ) : null}
+ </DetailSectionTitle>
+ <Timeline>
+ {closed ? null : (
+ <IncidentComposer
+ incident={incident}
+ onStatusChanged={onStatusChanged}
+ />
+ )}
+ {events?.map((event) => (
+ <IncidentTimelineItem key={event.id} event={event} />
+ ))}
+ </Timeline>
+ </DetailSection>
+ );
+ const postmortem = (
+ <DetailSection>
+ <DetailSectionTitle variant="heading">Postmortem</DetailSectionTitle>
+ <IncidentPostmortem
+ incident={incident}
+ agentAllowed={workspace?.limits["slack-agent"] === true}
+ />
+ </DetailSection>
+ );
+
return (
- <SectionGroup className="max-w-6xl">
+ <SectionGroup>
<DetailHeader>
<IncidentHeading
incident={incident}
@@ -119,20 +147,16 @@ export function Client({ id }: { id: number }) {
</span>
</DetailMetaItem>
<DetailMetaItem>
- <HoverCardTimestamp date={incident.declaredAt} side="bottom">
- <time dateTime={incident.declaredAt.toISOString()}>
- {formatDistanceToNow(incident.declaredAt, { addSuffix: true })}
- </time>
- </HoverCardTimestamp>
+ <DetailMetaTime date={incident.declaredAt}>
+ {formatDistanceToNow(incident.declaredAt, { addSuffix: true })}
+ </DetailMetaTime>
</DetailMetaItem>
{incident.closedAt ? (
<DetailMetaItem>
Closed
- <HoverCardTimestamp date={incident.closedAt} side="bottom">
- <time dateTime={incident.closedAt.toISOString()}>
- {formatDistanceToNow(incident.closedAt, { addSuffix: true })}
- </time>
- </HoverCardTimestamp>
+ <DetailMetaTime date={incident.closedAt}>
+ {formatDistanceToNow(incident.closedAt, { addSuffix: true })}
+ </DetailMetaTime>
</DetailMetaItem>
) : (
<DetailMetaItem>
@@ -149,38 +173,9 @@ export function Client({ id }: { id: number }) {
</DetailHeader>
<DetailContent>
<DetailMain>
- <Tabs defaultValue="timeline" className="gap-4">
- <TabsList>
- <TabsTrigger value="timeline">
- Timeline
- {events ? (
- <span className="text-muted-foreground font-mono text-xs">
- {events.length}
- </span>
- ) : null}
- </TabsTrigger>
- <TabsTrigger value="postmortem">Postmortem</TabsTrigger>
- </TabsList>
- <TabsContent value="timeline">
- <Timeline>
- {closed ? null : (
- <IncidentComposer
- incident={incident}
- onStatusChanged={onStatusChanged}
- />
- )}
- {events?.map((event) => (
- <IncidentTimelineItem key={event.id} event={event} />
- ))}
- </Timeline>
- </TabsContent>
- <TabsContent value="postmortem">
- <IncidentPostmortem
- incident={incident}
- agentAllowed={workspace?.limits["slack-agent"] === true}
- />
- </TabsContent>
- </Tabs>
+ {/* Resolved incidents lead with the postmortem; open ones with the timeline. */}
+ {resolved ? postmortem : timeline}
+ {resolved ? timeline : postmortem}
</DetailMain>
<DetailAside>
<DetailSection>
@@ -218,7 +213,6 @@ export function Client({ id }: { id: number }) {
</DetailContent>
{report ? (
<ResolveReportDialog
- incidentId={incident.id}
report={report}
canNotify={canNotify}
defaultMessage={followUp?.note ?? ""}
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/[id]/page.tsx b/apps/dashboard/src/app/(dashboard)/incidents/[id]/page.tsx
index 5566255c3..089e47116 100644
--- a/apps/dashboard/src/app/(dashboard)/incidents/[id]/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/incidents/[id]/page.tsx
@@ -17,16 +17,25 @@ export default async function Page({
// Throws FORBIDDEN without the feature / NOT_FOUND for a foreign id;
// prefetchQuery swallows both and the client renders the empty state.
await Promise.all([
- queryClient.prefetchQuery(
- trpc.incident.get.queryOptions({ id: incidentId }),
- ),
+ queryClient
+ .prefetchQuery(trpc.incident.get.queryOptions({ id: incidentId }))
+ .then(() =>
+ queryClient.getQueryData(
+ trpc.incident.get.queryKey({ id: incidentId }),
+ ),
+ )
+ // the postmortem query is only enabled once resolved
+ .then((incident) =>
+ incident?.status === "resolved"
+ ? queryClient.prefetchQuery(
+ trpc.incident.getPostmortem.queryOptions({ id: incidentId }),
+ )
+ : undefined,
+ ),
queryClient.prefetchQuery(
trpc.incident.listEvents.queryOptions({ id: incidentId }),
),
queryClient.prefetchQuery(trpc.member.list.queryOptions()),
- queryClient.prefetchQuery(
- trpc.statusReport.list.queryOptions({ order: "desc" }),
- ),
]);
return (
diff --git a/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/client.tsx b/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/client.tsx
index b45bbec6e..8808a5fb3 100644
--- a/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/monitors/[id]/logs/client.tsx
@@ -74,7 +74,7 @@ export function Client({
if (!workspace || !monitor) return null;
- // No `SectionGroup` here: it centres content in a `max-w-4xl` column, and the
+ // No `SectionGroup` here: it centres content in a `max-w-6xl` column, and the
// table renders its own filter sidebar + toolbar shell that needs the full
// width of the content area. The box is pinned to the space left below the
// app header and the monitor tabs so the document never scrolls: the filter
diff --git a/apps/dashboard/src/app/(dashboard)/overview/create-event-button-group.tsx b/apps/dashboard/src/app/(dashboard)/overview/create-event-button-group.tsx
index 9194c419e..90e63c7b7 100644
--- a/apps/dashboard/src/app/(dashboard)/overview/create-event-button-group.tsx
+++ b/apps/dashboard/src/app/(dashboard)/overview/create-event-button-group.tsx
@@ -13,9 +13,13 @@ import { useState } from "react";
import { FormSheetMaintenanceCreate } from "@/components/forms/maintenance/sheet-create";
import { FormSheetStatusReportCreate } from "@/components/forms/status-report/sheet-create";
+import { DeclareIncidentButton } from "@/components/incidents/declare-incident-button";
+import { useFeature } from "@/hooks/use-feature";
export function CreateEventButtonGroup() {
const [maintenanceOpen, setMaintenanceOpen] = useState(false);
+ const [incidentOpen, setIncidentOpen] = useState(false);
+ const incidentsEnabled = useFeature("incident-management");
return (
<div>
@@ -42,6 +46,12 @@ export function CreateEventButtonGroup() {
<Add className="text-muted-foreground" />
Create Maintenance
</DropdownMenuItem>
+ {incidentsEnabled ? (
+ <DropdownMenuItem onSelect={() => setIncidentOpen(true)}>
+ <Add className="text-muted-foreground" />
+ Declare Incident
+ </DropdownMenuItem>
+ ) : null}
</DropdownMenuContent>
</DropdownMenu>
</ButtonGroup>
@@ -49,6 +59,10 @@ export function CreateEventButtonGroup() {
open={maintenanceOpen}
onOpenChange={setMaintenanceOpen}
/>
+ {/* Mounted on demand: the sheet fetches integrations as soon as it renders. */}
+ {incidentsEnabled && incidentOpen ? (
+ <DeclareIncidentButton open onOpenChange={setIncidentOpen} />
+ ) : null}
</div>
);
}
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/breadcrumb.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/breadcrumb.tsx
index 6ae97cfa4..f9deb367e 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/breadcrumb.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/breadcrumb.tsx
@@ -5,17 +5,33 @@ import { useQuery } from "@tanstack/react-query";
import { useParams, usePathname } from "next/navigation";
import { NavBreadcrumb } from "@/components/nav/nav-breadcrumb";
+import { useHydrated } from "@/hooks/use-hydrated";
import { useTRPC } from "@/lib/trpc/client";
import { STATUS_PAGE_TABS } from "./constants";
export function Breadcrumb() {
- const { id } = useParams<{ id: string }>();
+ // The entity crumb depends on data the page hydrates after this layout
+ // streamed, so it is only rendered on the client.
+ const hydrated = useHydrated();
+ const { id, reportId, maintenanceId } = useParams<{
+ id: string;
+ reportId?: string;
+ maintenanceId?: string;
+ }>();
const pathname = usePathname();
const trpc = useTRPC();
const { data: statusPage } = useQuery(
trpc.page.get.queryOptions({ id: Number.parseInt(id) }),
);
+ const { data: report } = useQuery({
+ ...trpc.statusReport.get.queryOptions({ id: Number(reportId) }),
+ enabled: reportId !== undefined,
+ });
+ const { data: maintenance } = useQuery({
+ ...trpc.maintenance.get.queryOptions({ id: Number(maintenanceId) }),
+ enabled: maintenanceId !== undefined,
+ });
if (!statusPage) return null;
@@ -23,6 +39,8 @@ export function Breadcrumb() {
const currentTab = STATUS_PAGE_TABS.find((tab) =>
segments.includes(tab.value),
);
+ const onDetail = reportId !== undefined || maintenanceId !== undefined;
+ const entity = hydrated ? (report?.title ?? maintenance?.title) : undefined;
return (
<NavBreadcrumb
@@ -36,16 +54,28 @@ export function Breadcrumb() {
{
type: "link",
label: statusPage.title,
- href: `/status-pages/${id}/status-reports`,
+ href: `/status-pages/${id}`,
},
+ // on a detail route the tab links back to its list even before the
+ // entity resolves
...(currentTab
- ? [
- {
- type: "page" as const,
- label: currentTab.label,
- icon: currentTab.icon,
- },
- ]
+ ? onDetail
+ ? [
+ {
+ type: "link" as const,
+ label: currentTab.label,
+ href: `/status-pages/${id}/${currentTab.value}`,
+ icon: currentTab.icon,
+ },
+ ...(entity ? [{ type: "page" as const, label: entity }] : []),
+ ]
+ : [
+ {
+ type: "page" as const,
+ label: currentTab.label,
+ icon: currentTab.icon,
+ },
+ ]
: []),
]}
/>
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/layout.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/(list)/layout.tsx
similarity index 96%
rename from apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/layout.tsx
rename to apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/(list)/layout.tsx
index 143aec60d..bbbb8f897 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/layout.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/(list)/layout.tsx
@@ -7,7 +7,7 @@ import {
} from "@/lib/sidebar-cookie";
import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";
-import { Sidebar } from "../sidebar";
+import { Sidebar } from "../../sidebar";
export default async function Layout({
children,
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/page.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/(list)/page.tsx
similarity index 100%
rename from apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/page.tsx
rename to apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/(list)/page.tsx
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/[maintenanceId]/client.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/[maintenanceId]/client.tsx
new file mode 100644
index 000000000..126e75141
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/[maintenanceId]/client.tsx
@@ -0,0 +1,114 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+import { formatDistanceStrict } from "date-fns";
+
+import {
+ DetailActions,
+ DetailAside,
+ DetailContent,
+ DetailHeader,
+ DetailInput,
+ DetailMain,
+ DetailMeta,
+ DetailMetaItem,
+ DetailMetaTime,
+ DetailSection,
+ DetailSectionTitle,
+ DetailTitle,
+ DetailTitleRow,
+} from "@/components/content/detail";
+import { SectionGroup } from "@/components/content/section";
+import { MaintenanceActions } from "@/components/maintenances/maintenance-actions";
+import { MaintenanceComponents } from "@/components/maintenances/maintenance-components";
+import { MaintenanceComposer } from "@/components/maintenances/maintenance-composer";
+import { MaintenanceProperties } from "@/components/maintenances/maintenance-properties";
+import { useMaintenanceStatus } from "@/components/maintenances/use-maintenance-status";
+import { useUpdateMaintenance } from "@/components/maintenances/use-update-maintenance";
+import { Notifications } from "@/components/status-pages/notifications";
+import { getPageUrl } from "@/data/status-pages.client";
+import { useTRPC } from "@/lib/trpc/client";
+
+export function Client({ id, pageId }: { id: number; pageId: number }) {
+ const trpc = useTRPC();
+ const { data: maintenance } = useQuery(
+ trpc.maintenance.get.queryOptions({ id }),
+ );
+ const { data: page } = useQuery(trpc.page.get.queryOptions({ id: pageId }));
+ const rename = useUpdateMaintenance(id);
+ const status = useMaintenanceStatus(
+ maintenance ?? { from: new Date(0), to: new Date(0) },
+ );
+
+ if (!maintenance || !page) return null;
+
+ const publicUrl = `${getPageUrl(page)}/events/maintenance/${maintenance.id}`;
+
+ return (
+ <SectionGroup>
+ <DetailHeader>
+ <DetailTitleRow>
+ <DetailTitle>
+ <DetailInput
+ aria-label="Title"
+ required
+ maxLength={256}
+ disabled={rename.isPending}
+ value={maintenance.title}
+ onCommit={(title) => rename.update({ title })}
+ />
+ </DetailTitle>
+ <DetailActions>
+ <MaintenanceActions
+ maintenance={maintenance}
+ publicUrl={publicUrl}
+ />
+ </DetailActions>
+ </DetailTitleRow>
+ <DetailMeta>
+ <DetailMetaItem>
+ {status === "scheduled" ? "Starts" : "Started"}{" "}
+ <DetailMetaTime date={maintenance.from} />
+ </DetailMetaItem>
+ <DetailMetaItem>
+ {status === "completed" ? "Lasted" : "Lasts"}{" "}
+ <span className="text-foreground font-mono">
+ {formatDistanceStrict(maintenance.from, maintenance.to)}
+ </span>
+ </DetailMetaItem>
+ </DetailMeta>
+ </DetailHeader>
+ <DetailContent>
+ <DetailMain>
+ <DetailSection>
+ <DetailSectionTitle variant="heading">Message</DetailSectionTitle>
+ <MaintenanceComposer maintenance={maintenance} />
+ </DetailSection>
+ </DetailMain>
+ <DetailAside>
+ <DetailSection>
+ <DetailSectionTitle>Properties</DetailSectionTitle>
+ <MaintenanceProperties
+ maintenance={maintenance}
+ page={page}
+ status={status}
+ publicUrl={publicUrl}
+ />
+ </DetailSection>
+ <DetailSection>
+ <DetailSectionTitle>Affected components</DetailSectionTitle>
+ <MaintenanceComponents
+ maintenance={maintenance}
+ components={page.pageComponents}
+ groups={page.pageComponentGroups}
+ />
+ </DetailSection>
+ <DetailSection>
+ <DetailSectionTitle>Notifications</DetailSectionTitle>
+ <Notifications pageId={pageId} />
+ </DetailSection>
+ </DetailAside>
+ </DetailContent>
+ </SectionGroup>
+ );
+}
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/[maintenanceId]/page.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/[maintenanceId]/page.tsx
new file mode 100644
index 000000000..c4a052c0b
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/maintenances/[maintenanceId]/page.tsx
@@ -0,0 +1,39 @@
+import { notFound } from "next/navigation";
+
+import {
+ HydrateClient,
+ fetchQueryOrNotFound,
+ getQueryClient,
+ trpc,
+} from "@/lib/trpc/server";
+
+import { Client } from "./client";
+
+export default async function Page({
+ params,
+}: {
+ params: Promise<{ id: string; maintenanceId: string }>;
+}) {
+ const { id, maintenanceId } = await params;
+ const pageId = Number(id);
+ const maintenanceIdNumber = Number(maintenanceId);
+ if (!Number.isInteger(pageId) || !Number.isInteger(maintenanceIdNumber)) {
+ notFound();
+ }
+
+ const subscribers = getQueryClient().prefetchQuery(
+ trpc.pageSubscriber.list.queryOptions({ pageId }),
+ );
+ const maintenance = await fetchQueryOrNotFound(
+ trpc.maintenance.get.queryOptions({ id: maintenanceIdNumber }),
+ );
+ // the URL's page must own the maintenance
+ if (maintenance.pageId !== pageId) notFound();
+ await subscribers;
+
+ return (
+ <HydrateClient>
+ <Client id={maintenanceIdNumber} pageId={pageId} />
+ </HydrateClient>
+ );
+}
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/nav-actions.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/nav-actions.tsx
index 3979fdd38..c1a6167ee 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/nav-actions.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/nav-actions.tsx
@@ -14,7 +14,7 @@ import { toast } from "sonner";
import { QuickActions } from "@/components/dropdowns/quick-actions";
import { NavFeedback } from "@/components/nav/nav-feedback";
-import { getActions } from "@/data/status-pages.client";
+import { getActions, getPageUrl } from "@/data/status-pages.client";
import { useTRPC } from "@/lib/trpc/client";
export function NavActions() {
@@ -58,13 +58,7 @@ export function NavActions() {
<Tooltip>
<TooltipTrigger asChild>
<Button variant="ghost" size="sm" className="group h-7 w-7" asChild>
- <a
- href={`https://${
- statusPage.customDomain || `${statusPage.slug}.openstatus.dev`
- }`}
- target="_blank"
- rel="noreferrer"
- >
+ <a href={getPageUrl(statusPage)} target="_blank" rel="noreferrer">
<Globe className="text-muted-foreground group-hover:text-foreground h-4 w-4" />
</a>
</Button>
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx
index 2979cbfa2..a3c6635ea 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/sidebar.tsx
@@ -14,6 +14,7 @@ import { useParams } from "next/navigation";
import { Link } from "@/components/common/link";
import { TableCellLink } from "@/components/data-table/table-cell-link";
import { SidebarRight } from "@/components/nav/sidebar-right";
+import { getPageUrl } from "@/data/status-pages.client";
import { useTRPC } from "@/lib/trpc/client";
export function Sidebar() {
@@ -26,9 +27,7 @@ export function Sidebar() {
if (!statusPage) return null;
- const BADGE_URL = `https://${
- statusPage.customDomain || `${statusPage.slug}.openstatus.dev`
- }/badge/v2`;
+ const BADGE_URL = `${getPageUrl(statusPage)}/badge/v2`;
return (
<SidebarRight
@@ -40,13 +39,7 @@ export function Sidebar() {
{
label: "Slug",
value: (
- <Link
- href={`https://${
- statusPage.customDomain ||
- `${statusPage.slug}.openstatus.dev`
- }`}
- target="_blank"
- >
+ <Link href={getPageUrl(statusPage)} target="_blank">
{statusPage.slug}
</Link>
),
@@ -138,12 +131,7 @@ export function Sidebar() {
footerButton={{
onClick: () =>
typeof window !== "undefined" &&
- window.open(
- `https://${
- statusPage.customDomain || `${statusPage.slug}.openstatus.dev`
- }`,
- "_blank",
- ),
+ window.open(getPageUrl(statusPage), "_blank"),
children: (
<>
<ExternalLink />
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/layout.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/(list)/layout.tsx
similarity index 96%
rename from apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/layout.tsx
rename to apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/(list)/layout.tsx
index df7a4b6e8..e6750dedc 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/layout.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/(list)/layout.tsx
@@ -7,7 +7,7 @@ import {
} from "@/lib/sidebar-cookie";
import { HydrateClient, getQueryClient, trpc } from "@/lib/trpc/server";
-import { Sidebar } from "../sidebar";
+import { Sidebar } from "../../sidebar";
export default async function Layout({
children,
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/page.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/(list)/page.tsx
similarity index 88%
rename from apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/page.tsx
rename to apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/(list)/page.tsx
index 4aea477eb..5ef268c14 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/(list)/page.tsx
@@ -17,7 +17,6 @@ import {
SectionHeaderRow,
SectionTitle,
} from "@/components/content/section";
-import { DataTable as UpdatesDataTable } from "@/components/data-table/status-report-updates/data-table";
import { columns } from "@/components/data-table/status-reports/columns";
import { FormSheetStatusReport } from "@/components/forms/status-report/sheet";
import { toCheckboxTreeItems } from "@/components/ui/checkbox-tree";
@@ -136,23 +135,7 @@ export default function Page() {
</FormSheetStatusReport>
</div>
</SectionHeaderRow>
- <DataTable
- columns={columns}
- data={statusReports}
- onRowClick={(row) =>
- row.getCanExpand() ? row.toggleExpanded() : undefined
- }
- rowComponent={({ row }) => (
- <UpdatesDataTable
- updates={row.original.updates}
- reportId={row.original.id}
- components={row.original.pageComponents.map((c) => ({
- id: c.id,
- name: c.name,
- }))}
- />
- )}
- />
+ <DataTable columns={columns} data={statusReports} />
</Section>
</SectionGroup>
);
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/client.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/client.tsx
new file mode 100644
index 000000000..e40058b32
--- /dev/null
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/client.tsx
@@ -0,0 +1,164 @@
+"use client";
+
+import { currentImpactsFromUpdates } from "@openstatus/db/src/schema/page_components/constants";
+import { useMutation, useQuery } from "@tanstack/react-query";
+import { toast } from "sonner";
+
+import {
+ ComponentImpact,
+ ComponentList,
+ ComponentListActions,
+ ComponentListEmpty,
+ ComponentListItem,
+ ComponentListName,
+} from "@/components/content/component-list";
+import {
+ DetailActions,
+ DetailAside,
+ DetailContent,
+ DetailHeader,
+ DetailInput,
+ DetailMain,
+ DetailMeta,
+ DetailMetaItem,
+ DetailMetaTime,
+ DetailSection,
+ DetailSectionTitle,
+ DetailTitle,
+ DetailTitleRow,
+} from "@/components/content/detail";
+import { SectionGroup } from "@/components/content/section";
+import { Timeline } from "@/components/content/timeline";
+import { Notifications } from "@/components/status-pages/notifications";
+import { StatusReportActions } from "@/components/status-reports/status-report-actions";
+import { StatusReportComposer } from "@/components/status-reports/status-report-composer";
+import { StatusReportProperties } from "@/components/status-reports/status-report-properties";
+import { StatusReportTimelineItem } from "@/components/status-reports/status-report-timeline";
+import { useInvalidateStatusReport } from "@/components/status-reports/use-invalidate-status-report";
+import { toGroupNameLookup } from "@/data/page-components.client";
+import { getPageUrl } from "@/data/status-pages.client";
+import { reportStartedAt } from "@/data/status-reports.client";
+import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
+
+export function Client({ id, pageId }: { id: number; pageId: number }) {
+ const trpc = useTRPC();
+ const { data: report } = useQuery(trpc.statusReport.get.queryOptions({ id }));
+ const { data: page } = useQuery(trpc.page.get.queryOptions({ id: pageId }));
+ const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
+
+ const invalidate = useInvalidateStatusReport(id);
+ const update = useMutation(
+ trpc.statusReport.updateStatus.mutationOptions({
+ onSuccess: invalidate,
+ onError: (error) => {
+ toast.error(errorMessage(error, "Failed to save"));
+ },
+ }),
+ );
+
+ if (!report) return null;
+
+ const publicUrl = `${getPageUrl(report.page)}/events/report/${report.id}`;
+ const canNotify = workspace?.limits["status-subscribers"] === true;
+ const updates = [...report.updates].sort(
+ (a, b) => b.date.getTime() - a.date.getTime() || b.id - a.id,
+ );
+ const latest = updates[0];
+ const currentImpacts = currentImpactsFromUpdates(report.updates);
+ const groupOf = toGroupNameLookup(
+ page?.pageComponents ?? [],
+ page?.pageComponentGroups ?? [],
+ );
+
+ return (
+ <SectionGroup>
+ <DetailHeader>
+ <DetailTitleRow>
+ <DetailTitle>
+ <DetailInput
+ aria-label="Title"
+ required
+ maxLength={256}
+ disabled={update.isPending}
+ value={report.title}
+ onCommit={(title) => update.mutate({ id: report.id, title })}
+ />
+ </DetailTitle>
+ <DetailActions>
+ <StatusReportActions report={report} publicUrl={publicUrl} />
+ </DetailActions>
+ </DetailTitleRow>
+ <DetailMeta>
+ <DetailMetaItem>
+ Opened <DetailMetaTime date={reportStartedAt(report)} />
+ </DetailMetaItem>
+ <DetailMetaItem>
+ {updates.length} {updates.length === 1 ? "update" : "updates"}
+ </DetailMetaItem>
+ {latest ? (
+ <DetailMetaItem>
+ Last update <DetailMetaTime date={latest.date} />
+ </DetailMetaItem>
+ ) : null}
+ </DetailMeta>
+ </DetailHeader>
+ <DetailContent>
+ <DetailMain>
+ <Timeline>
+ <StatusReportComposer
+ report={report}
+ currentImpacts={currentImpacts}
+ pageComponents={page?.pageComponents ?? []}
+ groups={page?.pageComponentGroups ?? []}
+ canNotify={canNotify}
+ />
+ {updates.map((update, i) => (
+ <StatusReportTimelineItem
+ key={update.id}
+ report={report}
+ update={update}
+ index={updates.length - i}
+ groupOf={groupOf}
+ />
+ ))}
+ </Timeline>
+ </DetailMain>
+ <DetailAside>
+ <DetailSection>
+ <DetailSectionTitle>Properties</DetailSectionTitle>
+ <StatusReportProperties report={report} publicUrl={publicUrl} />
+ </DetailSection>
+ <DetailSection>
+ <DetailSectionTitle>Affected components</DetailSectionTitle>
+ {report.pageComponents.length ? (
+ <ComponentList>
+ {report.pageComponents.map((component) => (
+ <ComponentListItem key={component.id}>
+ <ComponentListName group={groupOf.get(component.id)}>
+ {component.name}
+ </ComponentListName>
+ <ComponentListActions>
+ <ComponentImpact
+ impact={currentImpacts.get(component.id)}
+ />
+ </ComponentListActions>
+ </ComponentListItem>
+ ))}
+ </ComponentList>
+ ) : (
+ <ComponentListEmpty />
+ )}
+ <p className="text-muted-foreground text-sm">
+ Change impact per component in the composer.
+ </p>
+ </DetailSection>
+ <DetailSection>
+ <DetailSectionTitle>Notifications</DetailSectionTitle>
+ <Notifications pageId={pageId} />
+ </DetailSection>
+ </DetailAside>
+ </DetailContent>
+ </SectionGroup>
+ );
+}
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/layout.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/layout.tsx
deleted file mode 100644
index 557874e90..000000000
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/layout.tsx
+++ /dev/null
@@ -1,19 +0,0 @@
-import { notFound } from "next/navigation";
-
-import { HydrateClient, fetchQueryOrNotFound, trpc } from "@/lib/trpc/server";
-
-export default async function Layout({
- children,
- params,
-}: {
- children: React.ReactNode;
- params: Promise<{ id: string; reportId: string }>;
-}) {
- const { reportId } = await params;
- const statusReportId = Number.parseInt(reportId);
- if (Number.isNaN(statusReportId)) notFound();
- await fetchQueryOrNotFound(
- trpc.statusReport.get.queryOptions({ id: statusReportId }),
- );
- return <HydrateClient>{children}</HydrateClient>;
-}
diff --git a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/page.tsx b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/page.tsx
index 697a294cc..d0ec20ad1 100644
--- a/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/page.tsx
+++ b/apps/dashboard/src/app/(dashboard)/status-pages/[id]/status-reports/[reportId]/page.tsx
@@ -1,200 +1,51 @@
-"use client";
+import { notFound } from "next/navigation";
-import { currentImpactsFromUpdates } from "@openstatus/db/src/schema/page_components/constants";
-import { Add } from "@openstatus/icons";
-import { Button } from "@openstatus/ui/components/ui/button";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { useParams } from "next/navigation";
-
-import { Link } from "@/components/common/link";
-import {
- EmptyStateContainer,
- EmptyStateDescription,
-} from "@/components/content/empty-state";
-import {
- Section,
- SectionDescription,
- SectionGroup,
- SectionHeader,
- SectionHeaderRow,
- SectionTitle,
-} from "@/components/content/section";
-import { FormCardGroup } from "@/components/forms/form-card";
-import { FormSheetWithDirtyProtection } from "@/components/forms/form-sheet";
-import type { FormValues } from "@/components/forms/status-report-update/form";
import {
- FormStatusReportUpdateCard,
- type FormValues as UpdateCardFormValues,
-} from "@/components/forms/status-report-update/form-status-report";
-import { FormSheetStatusReportUpdate } from "@/components/forms/status-report-update/sheet";
-import {
- defaultComponentImpacts,
- getNextStatus,
- impactsEqual,
- toCreateStatusReportUpdateInput,
-} from "@/data/status-report-updates.client";
-import { useFeature } from "@/hooks/use-feature";
-import { useTRPC } from "@/lib/trpc/client";
-
-export default function Page() {
- const { reportId } = useParams<{ id: string; reportId: string }>();
- const trpc = useTRPC();
- const queryClient = useQueryClient();
-
- const { data: statusReport, refetch } = useQuery(
- trpc.statusReport.get.queryOptions({ id: Number.parseInt(reportId) }),
- );
-
- const incidentsEnabled = useFeature("incident-management");
- const { data: linkedIncident } = useQuery({
- ...trpc.incident.forStatusReport.queryOptions({
- statusReportId: Number.parseInt(reportId),
- }),
- enabled: incidentsEnabled,
- });
-
- const sendStatusReportUpdateMutation = useMutation(
- trpc.subscriberNotification.statusReport.mutationOptions(),
- );
-
- const createStatusReportUpdateMutation = useMutation(
- trpc.statusReport.createStatusReportUpdate.mutationOptions({
- onSuccess: (update) => {
- if (update?.notifySubscribers) {
- sendStatusReportUpdateMutation.mutate({ id: update.id });
- }
- refetch();
- queryClient.invalidateQueries({
- queryKey: trpc.page.list.queryKey(),
- });
- },
- }),
- );
-
- const updateStatusReportUpdateMutation = useMutation(
- trpc.statusReport.updateStatusReportUpdate.mutationOptions({
- onSuccess: () => {
- refetch();
- },
- }),
- );
-
- if (!statusReport) return null;
-
- const updates = [...statusReport.updates].sort(
- (a, b) => b.date.getTime() - a.date.getTime(),
- );
-
- const affected = statusReport.pageComponents
- .map((component) => component.name)
- .join(", ");
-
- const reportHasImpacts = statusReport.updates.some(
- (u) => u.componentImpacts.length > 0,
- );
- const currentImpacts = currentImpactsFromUpdates(statusReport.updates);
- const nextStatus = getNextStatus(statusReport.status);
+ HydrateClient,
+ fetchQueryOrNotFound,
+ getQueryClient,
+ trpc,
+} from "@/lib/trpc/server";
+
+import { Client } from "./client";
+
+export default async function Page({
+ params,
+}: {
+ params: Promise<{ id: string; reportId: string }>;
+}) {
+ const { id, reportId } = await params;
+ const pageId = Number(id);
+ const statusReportId = Number(reportId);
+ if (!Number.isInteger(pageId) || !Number.isInteger(statusReportId)) {
+ notFound();
+ }
+
+ const queryClient = getQueryClient();
+ const [report] = await Promise.all([
+ fetchQueryOrNotFound(
+ trpc.statusReport.get.queryOptions({ id: statusReportId }),
+ ),
+ queryClient.prefetchQuery(
+ trpc.pageSubscriber.list.queryOptions({ pageId }),
+ ),
+ // forStatusReport throws FORBIDDEN without the feature; skip it then.
+ queryClient
+ .fetchQuery(trpc.workspace.get.queryOptions())
+ .then((workspace) =>
+ workspace.features.includes("incident-management")
+ ? queryClient.prefetchQuery(
+ trpc.incident.forStatusReport.queryOptions({ statusReportId }),
+ )
+ : undefined,
+ ),
+ ]);
+ // the URL's page must own the report
+ if (report.pageId !== pageId) notFound();
return (
- <SectionGroup>
- <Section>
- <SectionHeaderRow>
- <SectionHeader>
- <SectionTitle>{statusReport.title}</SectionTitle>
- <SectionDescription>
- Manage updates for this status report. Affects{" "}
- <span className="text-foreground">
- {affected ? affected : "zero"}
- </span>{" "}
- component(s).
- {linkedIncident ? (
- <>
- {" "}
- Communicates incident{" "}
- <Link href={`/incidents/${linkedIncident.id}`}>
- {linkedIncident.title}
- </Link>
- .
- </>
- ) : null}
- </SectionDescription>
- </SectionHeader>
- </SectionHeaderRow>
-
- <EmptyStateContainer className="my-8 border-dashed">
- <EmptyStateDescription>Status Page Report</EmptyStateDescription>
- <FormSheetStatusReportUpdate
- defaultValues={{
- status: nextStatus,
- componentImpacts: defaultComponentImpacts({
- components: statusReport.pageComponents,
- currentImpacts,
- nextStatus,
- }),
- }}
- components={statusReport.pageComponents.map((c) => ({
- id: c.id,
- name: c.name,
- }))}
- onSubmit={async (values: FormValues) => {
- await createStatusReportUpdateMutation.mutateAsync(
- toCreateStatusReportUpdateInput({
- statusReportId: statusReport.id,
- values,
- reportHasImpacts,
- }),
- );
- }}
- >
- <Button size="sm">
- <Add />
- Create Status Update
- </Button>
- </FormSheetStatusReportUpdate>
- </EmptyStateContainer>
-
- <FormCardGroup>
- {updates.map((update, index) => (
- <FormSheetWithDirtyProtection key={update.id}>
- <FormStatusReportUpdateCard
- id={`update-form-${update.id}`}
- index={index}
- update={update}
- components={statusReport.pageComponents.map((c) => ({
- id: c.id,
- name: c.name,
- }))}
- defaultValues={{
- status: update.status,
- message: update.message,
- date: update.date,
- componentImpacts: update.componentImpacts.map((ci) => ({
- pageComponentId: ci.pageComponentId,
- impact: ci.impact,
- })),
- }}
- onSubmit={async (values: UpdateCardFormValues) => {
- await updateStatusReportUpdateMutation.mutateAsync({
- id: update.id,
- statusReportId: statusReport.id,
- message: values.message,
- status: values.status,
- // replace-set semantics: only send when actually edited,
- // so untouched (incl. legacy) updates keep their rows
- componentImpacts: impactsEqual(
- values.componentImpacts ?? [],
- update.componentImpacts,
- )
- ? undefined
- : values.componentImpacts,
- date: values.date,
- });
- }}
- />
- </FormSheetWithDirtyProtection>
- ))}
- </FormCardGroup>
- </Section>
- </SectionGroup>
+ <HydrateClient>
+ <Client id={statusReportId} pageId={pageId} />
+ </HydrateClient>
);
}
diff --git a/apps/dashboard/src/components/content/component-list.tsx b/apps/dashboard/src/components/content/component-list.tsx
new file mode 100644
index 000000000..366a87ea4
--- /dev/null
+++ b/apps/dashboard/src/components/content/component-list.tsx
@@ -0,0 +1,219 @@
+import type { PageComponentImpact } from "@openstatus/db/src/schema/page_components/constants";
+import {
+ Select,
+ SelectContent,
+ SelectGroup,
+ SelectItem,
+ SelectLabel,
+ SelectSeparator,
+ SelectTrigger,
+ SelectValue,
+} from "@openstatus/ui/components/ui/select";
+import { cn } from "@openstatus/ui/lib/utils";
+import { Fragment } from "react";
+
+import { StatusDot } from "@/components/common/status-dot";
+import { toComponentSections } from "@/data/page-components.client";
+import { impactDisplay } from "@/data/status-report-updates.client";
+
+type Component = {
+ id: number;
+ name: string;
+ groupId?: number | null;
+ order?: number | null;
+ groupOrder?: number | null;
+};
+
+export function ComponentList({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"ul">) {
+ return (
+ <ul
+ data-slot="component-list"
+ className={cn("flex flex-col gap-1 text-sm", className)}
+ {...props}
+ >
+ {children}
+ </ul>
+ );
+}
+
+export function ComponentListItem({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="component-list-item"
+ className={cn("group flex min-h-7 items-center gap-2", className)}
+ {...props}
+ >
+ {children}
+ </li>
+ );
+}
+
+/** `group` renders muted after the name for components in a group. */
+export function ComponentListName({
+ children,
+ group,
+ className,
+ ...props
+}: React.ComponentProps<"span"> & { group?: string | null }) {
+ return (
+ <span
+ data-slot="component-list-name"
+ className={cn("truncate font-mono", className)}
+ {...props}
+ >
+ {children}
+ {group ? (
+ <span className="text-muted-foreground ml-1.5">{group}</span>
+ ) : null}
+ </span>
+ );
+}
+
+/** Dot + label for an impact; nullish reads as untriaged. */
+export function ComponentImpact({
+ impact,
+ className,
+ ...props
+}: React.ComponentProps<"span"> & {
+ impact: PageComponentImpact | null | undefined;
+}) {
+ const display = impactDisplay(impact);
+ return (
+ <span
+ data-slot="component-impact"
+ className={cn(
+ "inline-flex shrink-0 items-center gap-1.5 font-mono",
+ className,
+ )}
+ {...props}
+ >
+ <StatusDot variant={display.variant} />
+ {display.label}
+ </span>
+ );
+}
+
+/** Right-aligned controls on a row, like `DetailActions`. */
+export function ComponentListActions({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="component-list-actions"
+ className={cn("ml-auto flex shrink-0 items-center gap-1", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function ComponentListEmpty({
+ children = "No components affected.",
+ className,
+ ...props
+}: React.ComponentProps<"p">) {
+ return (
+ <p
+ data-slot="component-list-empty"
+ className={cn("text-muted-foreground text-sm", className)}
+ {...props}
+ >
+ {children}
+ </p>
+ );
+}
+
+// Borderless until hovered, like PropertySelectTrigger.
+export function ComponentListSelectTrigger({
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectTrigger>) {
+ return (
+ <SelectTrigger
+ size="sm"
+ className={cn(
+ "hover:bg-accent dark:hover:bg-accent/50 data-[state=open]:bg-accent border-transparent bg-transparent shadow-none dark:bg-transparent",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
+
+/**
+ * Picker for `components` not yet on the list, in page order: a group's
+ * members sit under its label, runs of ungrouped components in between,
+ * separated.
+ */
+export function ComponentListAdd({
+ components,
+ groups = [],
+ onAdd,
+ disabled = false,
+ placeholder,
+ className,
+}: {
+ components: Component[];
+ groups?: { id: number; name: string }[];
+ onAdd: (id: number) => void;
+ disabled?: boolean;
+ /** Replaces the "Add component" / "All components added" copy. */
+ placeholder?: string;
+ className?: string;
+}) {
+ const sections = toComponentSections(components, groups);
+ const option = (c: Component) => (
+ <SelectItem key={c.id} value={String(c.id)} className="font-mono">
+ {c.name}
+ </SelectItem>
+ );
+
+ return (
+ <Select
+ value=""
+ disabled={disabled || components.length === 0}
+ onValueChange={(value) => onAdd(Number(value))}
+ >
+ <ComponentListSelectTrigger
+ aria-label="Add component"
+ className={cn("text-muted-foreground", className)}
+ >
+ <SelectValue
+ placeholder={
+ placeholder ??
+ (components.length ? "Add component" : "All components added")
+ }
+ />
+ </ComponentListSelectTrigger>
+ <SelectContent>
+ {sections.map((section, i) => {
+ const key = section.group?.id ?? `ungrouped-${i}`;
+ return (
+ <Fragment key={key}>
+ {i > 0 ? <SelectSeparator /> : null}
+ {section.group ? (
+ <SelectGroup>
+ <SelectLabel>{section.group.name}</SelectLabel>
+ {section.items.map(option)}
+ </SelectGroup>
+ ) : (
+ section.items.map(option)
+ )}
+ </Fragment>
+ );
+ })}
+ </SelectContent>
+ </Select>
+ );
+}
diff --git a/apps/dashboard/src/components/content/composer.tsx b/apps/dashboard/src/components/content/composer.tsx
index 7f2754a7b..288c5534c 100644
--- a/apps/dashboard/src/components/content/composer.tsx
+++ b/apps/dashboard/src/components/content/composer.tsx
@@ -15,15 +15,20 @@ import { cn } from "@openstatus/ui/lib/utils";
import { ProcessMessage } from "@/components/content/process-message";
-/** Markdown composer: write/preview tabs around a textarea, with a footer for actions. */
+/**
+ * Markdown composer: write/preview tabs around a textarea, with a footer for
+ * actions. `size="lg"` is for long-form documents (message, postmortem).
+ */
export function Composer({
children,
className,
+ size = "default",
...props
-}: React.ComponentProps<typeof Tabs>) {
+}: React.ComponentProps<typeof Tabs> & { size?: "default" | "lg" }) {
return (
<Tabs
defaultValue="write"
+ data-size={size}
className={cn("min-w-0 flex-1", className)}
{...props}
>
@@ -34,6 +39,7 @@ export function Composer({
);
}
+/** Write/Preview tabs on the left; `children` replaces the "Markdown" hint on the right. */
export function ComposerHeader({
children,
className,
@@ -48,7 +54,8 @@ export function ComposerHeader({
)}
{...props}
>
- {children}
+ <ComposerTabs />
+ {children ?? <ComposerHint>Markdown</ComposerHint>}
</InputGroupAddon>
);
}
@@ -56,7 +63,7 @@ export function ComposerHeader({
const tabsTriggerClassName =
"text-muted-foreground hover:text-foreground data-[state=active]:text-foreground dark:data-[state=active]:bg-transparent h-7 flex-none data-[state=active]:bg-transparent data-[state=active]:shadow-none dark:data-[state=active]:border-transparent";
-export function ComposerTabs({
+function ComposerTabs({
className,
...props
}: Omit<React.ComponentProps<typeof TabsList>, "children">) {
@@ -94,13 +101,29 @@ export function ComposerHint({
);
}
+/** `onSubmit` fires on Cmd/Ctrl+Enter. */
export function ComposerTextarea({
className,
+ onSubmit,
+ onKeyDown,
...props
-}: React.ComponentProps<typeof InputGroupTextarea>) {
+}: React.ComponentProps<typeof InputGroupTextarea> & {
+ onSubmit?: () => void;
+}) {
return (
<TabsContent value="write">
- <InputGroupTextarea className={cn("min-h-24", className)} {...props} />
+ <InputGroupTextarea
+ className={cn("min-h-24 in-data-[size=lg]:min-h-96", className)}
+ onKeyDown={(e) => {
+ onKeyDown?.(e);
+ if (e.defaultPrevented || e.nativeEvent.isComposing) return;
+ if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && onSubmit) {
+ e.preventDefault();
+ onSubmit();
+ }
+ }}
+ {...props}
+ />
</TabsContent>
);
}
@@ -115,7 +138,7 @@ export function ComposerPreview({
<div
data-slot="composer-preview"
className={cn(
- "prose prose-sm dark:prose-invert min-h-24 max-w-none px-3 py-3",
+ "prose prose-sm dark:prose-invert min-h-24 max-w-none px-3 py-3 in-data-[size=lg]:min-h-96",
className,
)}
{...props}
@@ -130,6 +153,26 @@ export function ComposerPreview({
);
}
+/** Structured fields between the textarea and the footer. */
+export function ComposerSection({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<typeof InputGroupAddon>) {
+ return (
+ <InputGroupAddon
+ align="block-end"
+ className={cn(
+ "flex-col items-stretch gap-2 border-t px-3 py-3 font-normal [.border-t]:pt-3",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </InputGroupAddon>
+ );
+}
+
export function ComposerFooter({
children,
className,
diff --git a/apps/dashboard/src/components/content/detail.tsx b/apps/dashboard/src/components/content/detail.tsx
index 81511a8a5..374eead37 100644
--- a/apps/dashboard/src/components/content/detail.tsx
+++ b/apps/dashboard/src/components/content/detail.tsx
@@ -3,8 +3,12 @@
import { Textarea } from "@openstatus/ui/components/ui/textarea";
import { cn } from "@openstatus/ui/lib/utils";
import { type VariantProps, cva } from "class-variance-authority";
+import { format } from "date-fns";
import { useState } from "react";
+import { HoverCardTimestamp } from "@/components/common/hover-card-timestamp";
+import { useHydrated } from "@/hooks/use-hydrated";
+
export function DetailHeader({
children,
className,
@@ -213,6 +217,34 @@ export function DetailMetaItem({
);
}
+/** Absolute by default; pass children for a relative or custom label. */
+export function DetailMetaTime({
+ date,
+ children,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"time">, "dateTime"> & { date: Date }) {
+ // local-time text differs between server and browser
+ const hydrated = useHydrated();
+ return (
+ <HoverCardTimestamp date={date} side="bottom">
+ <time
+ data-slot="detail-meta-time"
+ dateTime={date.toISOString()}
+ // focusable so the hover card opens from the keyboard
+ tabIndex={0}
+ className={cn(
+ "text-foreground focus-visible:ring-ring/50 rounded-sm font-mono outline-none focus-visible:ring-[3px]",
+ className,
+ )}
+ {...props}
+ >
+ {hydrated ? (children ?? format(date, "LLL dd, HH:mm")) : null}
+ </time>
+ </HoverCardTimestamp>
+ );
+}
+
export function DetailContent({
children,
className,
diff --git a/apps/dashboard/src/components/content/property-list.tsx b/apps/dashboard/src/components/content/property-list.tsx
index 966177f27..7cc2ebdfc 100644
--- a/apps/dashboard/src/components/content/property-list.tsx
+++ b/apps/dashboard/src/components/content/property-list.tsx
@@ -1,7 +1,10 @@
+import { ArrowUpRight } from "@openstatus/icons";
import { Input } from "@openstatus/ui/components/ui/input";
import { SelectTrigger } from "@openstatus/ui/components/ui/select";
import { cn } from "@openstatus/ui/lib/utils";
+import { Link } from "@/components/common/link";
+
export function PropertyList({
children,
className,
@@ -72,6 +75,27 @@ export function PropertyValue({
);
}
+// pr-2 lines the arrow up with select chevrons on sibling rows.
+export function PropertyLink({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<typeof Link>) {
+ return (
+ <Link
+ data-slot="property-link"
+ className={cn(
+ "group flex min-w-0 flex-1 items-center justify-between gap-2 pr-2 font-normal",
+ className,
+ )}
+ {...props}
+ >
+ <span className="truncate">{children}</span>
+ <ArrowUpRight className="text-muted-foreground group-hover:text-foreground size-4 shrink-0 transition-colors" />
+ </Link>
+ );
+}
+
// Borderless until hovered; -ml-2 keeps the control's text on the value column's edge.
const propertyControlClassName =
"hover:bg-accent dark:hover:bg-accent/50 -ml-2 h-8 w-[calc(100%+0.5rem)] min-w-0 border-transparent bg-transparent px-2 shadow-none dark:bg-transparent";
diff --git a/apps/dashboard/src/components/content/section.tsx b/apps/dashboard/src/components/content/section.tsx
index 96530c592..bbf12c6b0 100644
--- a/apps/dashboard/src/components/content/section.tsx
+++ b/apps/dashboard/src/components/content/section.tsx
@@ -79,7 +79,7 @@ export function SectionGroup({
}: React.ComponentProps<"div">) {
return (
<div
- className={cn("mx-auto w-full max-w-4xl space-y-8 px-4 py-8", className)}
+ className={cn("mx-auto w-full max-w-6xl space-y-8 px-4 py-8", className)}
{...props}
>
{children}
diff --git a/apps/dashboard/src/components/content/timeline.tsx b/apps/dashboard/src/components/content/timeline.tsx
index 31f7130f0..2cc0b3210 100644
--- a/apps/dashboard/src/components/content/timeline.tsx
+++ b/apps/dashboard/src/components/content/timeline.tsx
@@ -1,8 +1,17 @@
+"use client";
+
+import {
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
+} from "@openstatus/ui/components/ui/tooltip";
import { cn } from "@openstatus/ui/lib/utils";
import { type VariantProps, cva } from "class-variance-authority";
import { formatDistanceToNowStrict } from "date-fns";
import { HoverCardTimestamp } from "@/components/common/hover-card-timestamp";
+import { UserAvatar } from "@/components/common/user-avatar";
+import { useHydrated } from "@/hooks/use-hydrated";
export function Timeline({
children,
@@ -78,6 +87,105 @@ export function TimelineIndicator({
);
}
+// Same size as the indicator so the rail starts below it; children render
+// outside the avatar's overflow clip (see `TimelineAvatarBadge`).
+export function TimelineAvatar({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<typeof UserAvatar> & { children?: React.ReactNode }) {
+ return (
+ <span data-slot="timeline-avatar" className="relative size-8 shrink-0">
+ <UserAvatar
+ className={cn("size-8 text-xs", className)}
+ {...props}
+ data-slot="avatar"
+ />
+ {children}
+ </span>
+ );
+}
+
+// Event icon pinned to the avatar's corner; the ring lifts it off the photo.
+export function TimelineAvatarBadge({
+ children,
+ className,
+ variant,
+ ...props
+}: React.ComponentProps<"span"> &
+ VariantProps<typeof timelineIndicatorVariants>) {
+ return (
+ <span
+ data-slot="timeline-avatar-badge"
+ aria-hidden="true"
+ className={cn(
+ timelineIndicatorVariants({ variant }),
+ "ring-background absolute -right-1 -bottom-1 size-4 ring-2 [&>svg]:size-2.5",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </span>
+ );
+}
+
+type Actor = {
+ name: string | null;
+ email: string | null;
+ photoUrl?: string | null;
+};
+
+// Name and email on hover; the avatar is the only place the actor is shown.
+export function TimelineActorTooltip({
+ actor,
+ children,
+}: {
+ actor: Actor;
+ children: React.ReactNode;
+}) {
+ if (!actor.name && !actor.email) return children;
+ return (
+ <Tooltip>
+ <TooltipTrigger
+ asChild
+ // focusable so the tooltip opens from the keyboard
+ tabIndex={0}
+ className="focus-visible:ring-ring/50 rounded-full outline-none focus-visible:ring-[3px]"
+ >
+ {children}
+ </TooltipTrigger>
+ <TooltipContent side="top" className="text-center">
+ {actor.name && actor.name !== actor.email ? (
+ <div>{actor.name}</div>
+ ) : null}
+ {actor.email ? <div className="opacity-80">{actor.email}</div> : null}
+ </TooltipContent>
+ </Tooltip>
+ );
+}
+
+// Inline actor avatar for rows whose rail shows the event indicator.
+export function TimelineActor({
+ actor,
+ className,
+ ...props
+}: Omit<React.ComponentProps<typeof UserAvatar>, "name" | "src"> & {
+ actor: Actor;
+}) {
+ return (
+ <TimelineActorTooltip actor={actor}>
+ <UserAvatar
+ data-slot="timeline-actor"
+ name={actor.name ?? actor.email}
+ src={actor.photoUrl}
+ className={className}
+ {...props}
+ />
+ </TimelineActorTooltip>
+ );
+}
+
// pt-1.5 centers the first text line on the indicator.
export function TimelineContent({
children,
@@ -156,18 +264,24 @@ export function TimelineTime({
className,
...props
}: Omit<React.ComponentProps<"time">, "dateTime"> & { date: Date }) {
+ // local-time text differs between server and browser
+ const hydrated = useHydrated();
return (
<HoverCardTimestamp date={date} side="left">
<time
data-slot="timeline-time"
dateTime={date.toISOString()}
+ // focusable so the hover card opens from the keyboard
+ tabIndex={0}
className={cn(
- "text-muted-foreground shrink-0 font-mono text-xs",
+ "text-muted-foreground focus-visible:ring-ring/50 shrink-0 rounded-sm font-mono text-xs outline-none focus-visible:ring-[3px]",
className,
)}
{...props}
>
- {children ?? formatDistanceToNowStrict(date, { addSuffix: true })}
+ {hydrated
+ ? (children ?? formatDistanceToNowStrict(date, { addSuffix: true }))
+ : null}
</time>
</HoverCardTimestamp>
);
diff --git a/apps/dashboard/src/components/data-table/maintenances/columns.tsx b/apps/dashboard/src/components/data-table/maintenances/columns.tsx
index 2de5d98d0..4b9a98e68 100644
--- a/apps/dashboard/src/components/data-table/maintenances/columns.tsx
+++ b/apps/dashboard/src/components/data-table/maintenances/columns.tsx
@@ -4,8 +4,10 @@ import type { RouterOutputs } from "@openstatus/api";
import type { ColumnDef } from "@tanstack/react-table";
import { formatDistanceStrict } from "date-fns";
-import { ProcessMessage } from "@/components/content/process-message";
+import { Link } from "@/components/common/link";
+import { TableCellBadge } from "@/components/data-table/table-cell-badge";
import { TableCellDate } from "@/components/data-table/table-cell-date";
+import { TableCellLink } from "@/components/data-table/table-cell-link";
import { TableCellNumber } from "@/components/data-table/table-cell-number";
import { DataTableColumnHeader } from "@/components/ui/data-table/data-table-column-header";
@@ -17,6 +19,15 @@ export const columns: ColumnDef<Maintenance>[] = [
{
accessorKey: "title",
header: "Title",
+ cell: ({ row }) => {
+ const { id, pageId } = row.original;
+ return (
+ <TableCellLink
+ href={`/status-pages/${pageId}/maintenances/${id}`}
+ value={row.getValue("title")}
+ />
+ );
+ },
enableSorting: false,
enableHiding: false,
meta: {
@@ -24,15 +35,26 @@ export const columns: ColumnDef<Maintenance>[] = [
},
},
{
- accessorKey: "message",
- header: "Message",
+ id: "pageComponents",
+ accessorFn: (row) => row.pageComponents,
+ header: "Affected",
enableSorting: false,
- enableHiding: false,
cell: ({ row }) => {
- const value = String(row.getValue("message"));
+ const value = row.original.pageComponents;
+ if (value.length === 0) {
+ return <div className="text-muted-foreground">-</div>;
+ }
return (
- <div className="prose dark:prose-invert prose-sm text-muted-foreground line-clamp-3 max-w-[200px] truncate">
- <ProcessMessage value={value} />
+ <div className="flex flex-wrap gap-1">
+ {value.map((c) =>
+ c.monitorId ? (
+ <Link href={`/monitors/${c.monitorId}/overview`} key={c.id}>
+ <TableCellBadge value={c.name} />
+ </Link>
+ ) : (
+ <TableCellBadge value={c.name} key={c.id} />
+ ),
+ )}
</div>
);
},
diff --git a/apps/dashboard/src/components/data-table/managed-incidents/columns.tsx b/apps/dashboard/src/components/data-table/managed-incidents/columns.tsx
index b5f4c34ed..95e4a6d23 100644
--- a/apps/dashboard/src/components/data-table/managed-incidents/columns.tsx
+++ b/apps/dashboard/src/components/data-table/managed-incidents/columns.tsx
@@ -16,14 +16,6 @@ import {
type ManagedIncident = NonNullable<RouterOutputs["incident"]["list"]>[number];
export const columns: ColumnDef<ManagedIncident>[] = [
- {
- accessorKey: "severity",
- header: "Severity",
- enableSorting: false,
- cell: ({ row }) => (
- <IncidentSeverityBadge severity={row.original.severity} />
- ),
- },
{
accessorKey: "title",
header: "Title",
@@ -36,6 +28,14 @@ export const columns: ColumnDef<ManagedIncident>[] = [
),
meta: { cellClassName: "max-w-[260px] truncate" },
},
+ {
+ accessorKey: "severity",
+ header: "Severity",
+ enableSorting: false,
+ cell: ({ row }) => (
+ <IncidentSeverityBadge severity={row.original.severity} />
+ ),
+ },
{
accessorKey: "status",
header: "Status",
diff --git a/apps/dashboard/src/components/data-table/overview-events/columns.tsx b/apps/dashboard/src/components/data-table/overview-events/columns.tsx
index 58279932d..f7f5ba142 100644
--- a/apps/dashboard/src/components/data-table/overview-events/columns.tsx
+++ b/apps/dashboard/src/components/data-table/overview-events/columns.tsx
@@ -59,7 +59,7 @@ function getTitle(event: OverviewEvent): { title: string; href: string } {
case "maintenance":
return {
title: event.maintenance.title,
- href: `/status-pages/${event.maintenance.pageId}/maintenances`,
+ href: `/status-pages/${event.maintenance.pageId}/maintenances/${event.maintenance.id}`,
};
}
}
diff --git a/apps/dashboard/src/components/data-table/status-report-updates/data-table-row-actions.tsx b/apps/dashboard/src/components/data-table/status-report-updates/data-table-row-actions.tsx
deleted file mode 100644
index 5d1033b8b..000000000
--- a/apps/dashboard/src/components/data-table/status-report-updates/data-table-row-actions.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-"use client";
-
-import type { RouterOutputs } from "@openstatus/api";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { useParams } from "next/navigation";
-import { useRef } from "react";
-
-import { QuickActions } from "@/components/dropdowns/quick-actions";
-import { FormSheetStatusReportUpdate } from "@/components/forms/status-report-update/sheet";
-import { getActions, impactsEqual } from "@/data/status-report-updates.client";
-import { useTRPC } from "@/lib/trpc/client";
-
-type StatusReportUpdate =
- RouterOutputs["statusReport"]["list"][number]["updates"][number];
-
-interface DataTableRowActionsProps {
- row: StatusReportUpdate;
- components?: { id: number; name: string }[];
-}
-
-export function DataTableRowActions({
- row,
- components,
-}: DataTableRowActionsProps) {
- const buttonRef = useRef<HTMLButtonElement>(null);
- const { id } = useParams<{ id: string }>();
- const trpc = useTRPC();
- const queryClient = useQueryClient();
- const updateStatusReportUpdateMutation = useMutation(
- trpc.statusReport.updateStatusReportUpdate.mutationOptions({
- onSuccess: () => {
- queryClient.invalidateQueries({
- queryKey: trpc.statusReport.list.queryKey({
- pageId: Number.parseInt(id),
- }),
- });
- queryClient.invalidateQueries({
- queryKey: trpc.page.list.queryKey(),
- });
- queryClient.invalidateQueries({
- queryKey: trpc.statusReport.list.queryKey({
- period: "7d",
- }),
- });
- },
- }),
- );
- const deleteStatusReportUpdateMutation = useMutation(
- trpc.statusReport.deleteUpdate.mutationOptions({
- onSuccess: () => {
- queryClient.invalidateQueries({
- queryKey: trpc.statusReport.list.queryKey({
- pageId: Number.parseInt(id),
- }),
- });
- queryClient.invalidateQueries({
- queryKey: trpc.statusReport.list.queryKey({
- period: "7d",
- }),
- });
- },
- }),
- );
- const actions = getActions({
- edit: () => buttonRef.current?.click(),
- });
-
- return (
- <>
- <QuickActions
- actions={actions}
- deleteAction={{
- confirmationValue: row.status ?? "status report update",
- submitAction: async () => {
- await deleteStatusReportUpdateMutation.mutateAsync({
- id: row.id,
- });
- },
- }}
- />
- <FormSheetStatusReportUpdate
- defaultValues={{
- message: row.message,
- date: row.date,
- status: row.status,
- componentImpacts: row.componentImpacts.map((ci) => ({
- pageComponentId: ci.pageComponentId,
- impact: ci.impact,
- })),
- }}
- components={components}
- allowUnsetImpacts
- onSubmit={async (values) => {
- await updateStatusReportUpdateMutation.mutateAsync({
- id: row.id,
- statusReportId: row.statusReportId,
- message: values.message,
- status: values.status,
- // replace-set semantics: only send when actually edited, so
- // untouched (incl. legacy) updates keep their rows
- componentImpacts: impactsEqual(
- values.componentImpacts ?? [],
- row.componentImpacts,
- )
- ? undefined
- : values.componentImpacts,
- date: values.date,
- });
- }}
- >
- <button ref={buttonRef} type="button" className="sr-only">
- Open sheet
- </button>
- </FormSheetStatusReportUpdate>
- </>
- );
-}
diff --git a/apps/dashboard/src/components/data-table/status-report-updates/data-table.tsx b/apps/dashboard/src/components/data-table/status-report-updates/data-table.tsx
deleted file mode 100644
index 583b929bf..000000000
--- a/apps/dashboard/src/components/data-table/status-report-updates/data-table.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-"use client";
-
-import type { RouterOutputs } from "@openstatus/api";
-import { currentImpactsFromUpdates } from "@openstatus/db/src/schema/page_components/constants";
-import { Add } from "@openstatus/icons";
-import { Button } from "@openstatus/ui/components/ui/button";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui/components/ui/table";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui/components/ui/tooltip";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-import { useParams } from "next/navigation";
-
-import { ProcessMessage } from "@/components/content/process-message";
-import { TableCellDate } from "@/components/data-table/table-cell-date";
-import { FormSheetStatusReportUpdate } from "@/components/forms/status-report-update/sheet";
-import { icons } from "@/data/icons";
-import {
- colors,
- defaultComponentImpacts,
- getNextStatus,
- toCreateStatusReportUpdateInput,
-} from "@/data/status-report-updates.client";
-import { useTRPC } from "@/lib/trpc/client";
-import { cn } from "@/lib/utils";
-
-import { DataTableRowActions } from "./data-table-row-actions";
-
-type StatusReportUpdates =
- RouterOutputs["statusReport"]["list"][number]["updates"];
-
-export function DataTable({
- updates,
- reportId,
- components = [],
-}: {
- updates: StatusReportUpdates;
- reportId: number;
- components?: { id: number; name: string }[];
-}) {
- const reportHasImpacts = updates.some((u) => u.componentImpacts.length > 0);
- const currentImpacts = currentImpactsFromUpdates(updates);
- const nextStatus = getNextStatus(
- updates[updates.length - 1]?.status ?? "investigating",
- );
- const trpc = useTRPC();
- const { id } = useParams<{ id: string }>();
- const queryClient = useQueryClient();
- const sendStatusReportUpdateMutation = useMutation(
- trpc.subscriberNotification.statusReport.mutationOptions(),
- );
- const createStatusReportUpdateMutation = useMutation(
- trpc.statusReport.createStatusReportUpdate.mutationOptions({
- onSuccess: (update) => {
- if (update?.notifySubscribers) {
- sendStatusReportUpdateMutation.mutate({ id: update.id });
- }
- queryClient.invalidateQueries({
- queryKey: trpc.statusReport.list.queryKey({
- pageId: Number.parseInt(id),
- }),
- });
- queryClient.invalidateQueries({
- queryKey: trpc.page.list.queryKey(),
- });
- queryClient.invalidateQueries({
- queryKey: trpc.statusReport.list.queryKey({
- period: "7d",
- }),
- });
- },
- }),
- );
-
- return (
- <Table className="w-full">
- <TableHeader>
- <TableRow>
- <TableHead className="w-7">
- <span className="sr-only">Status</span>
- </TableHead>
- <TableHead>Message</TableHead>
- <TableHead>Date</TableHead>
- <TableHead className="w-[px]">
- <TooltipProvider>
- <Tooltip>
- <FormSheetStatusReportUpdate
- defaultValues={{
- status: nextStatus,
- componentImpacts: defaultComponentImpacts({
- components,
- currentImpacts,
- nextStatus,
- }),
- }}
- components={components}
- onSubmit={async (values) => {
- await createStatusReportUpdateMutation.mutateAsync(
- toCreateStatusReportUpdateInput({
- statusReportId: reportId,
- values,
- reportHasImpacts,
- }),
- );
- }}
- >
- <TooltipTrigger asChild>
- <Button size="icon" className="ml-auto flex h-7 w-7 p-0">
- <Add />
- <span className="sr-only">Create Report Update</span>
- </Button>
- </TooltipTrigger>
- </FormSheetStatusReportUpdate>
- <TooltipContent side="left" align="center">
- Create Report Update
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </TableHead>
- </TableRow>
- </TableHeader>
- <TableBody>
- {updates.map((update) => {
- const Icon = icons.status[update.status];
- return (
- <TableRow key={update.id}>
- <TableCell>
- <div className="p-1">
- <Icon className={cn(colors[update.status])} size={20} />
- </div>
- </TableCell>
- <TableCell>
- <div className="prose dark:prose-invert prose-sm text-muted-foreground line-clamp-3 text-wrap">
- <ProcessMessage value={update.message} />
- </div>
- </TableCell>
- <TableCell className="text-muted-foreground w-[170px]">
- <TableCellDate value={update.date} />
- </TableCell>
- <TableCell className="w-8">
- <DataTableRowActions row={update} components={components} />
- </TableCell>
- </TableRow>
- );
- })}
- </TableBody>
- </Table>
- );
-}
diff --git a/apps/dashboard/src/components/data-table/status-reports/columns.tsx b/apps/dashboard/src/components/data-table/status-reports/columns.tsx
index c23fe6b63..386c2e0e0 100644
--- a/apps/dashboard/src/components/data-table/status-reports/columns.tsx
+++ b/apps/dashboard/src/components/data-table/status-reports/columns.tsx
@@ -5,9 +5,6 @@ import {
type PageComponentImpact,
worstImpact,
} from "@openstatus/db/src/schema/page_components/constants";
-import { ChevronDown, ChevronUp } from "@openstatus/icons";
-import { Button } from "@openstatus/ui/components/ui/button";
-import { cn } from "@openstatus/ui/lib/utils";
import type { ColumnDef } from "@tanstack/react-table";
import Link from "next/link";
@@ -15,12 +12,12 @@ import { TableCellBadge } from "@/components/data-table/table-cell-badge";
import { TableCellDate } from "@/components/data-table/table-cell-date";
import { TableCellLink } from "@/components/data-table/table-cell-link";
import { TableCellNumber } from "@/components/data-table/table-cell-number";
-import { DataTableColumnHeader } from "@/components/ui/data-table/data-table-column-header";
import {
- colors,
- impactConfig,
- untriagedImpact,
-} from "@/data/status-report-updates.client";
+ StatusReportImpactBadge,
+ StatusReportStatusBadge,
+} from "@/components/status-reports/status-report-badge";
+import { DataTableColumnHeader } from "@/components/ui/data-table/data-table-column-header";
+import { reportStartedAt } from "@/data/status-reports.client";
import { DataTableRowActions } from "./data-table-row-actions";
@@ -38,103 +35,45 @@ function worstReportImpact(report: StatusReport) {
}
export const columns: ColumnDef<StatusReport>[] = [
- {
- id: "expander",
- header: () => null,
- cell: ({ row }) => {
- return row.getCanExpand() ? (
- <Button
- {...{
- className: "size-7 shadow-none text-muted-foreground",
- onClick: (e) => {
- e.stopPropagation();
- row.toggleExpanded();
- },
- "aria-expanded": row.getIsExpanded(),
- "aria-label": row.getIsExpanded()
- ? `Collapse details for ${row.original.title}`
- : `Expand details for ${row.original.title}`,
- size: "icon",
- variant: "ghost",
- }}
- >
- {row.getIsExpanded() ? (
- <ChevronUp className="opacity-60" size={16} aria-hidden="true" />
- ) : (
- <ChevronDown className="opacity-60" size={16} aria-hidden="true" />
- )}
- </Button>
- ) : undefined;
- },
- meta: {
- headerClassName: "w-7",
- },
- },
{
accessorKey: "title",
header: "Title",
+ enableSorting: false,
+ enableHiding: false,
cell: ({ row }) => {
const { id, pageId } = row.original;
-
return (
<TableCellLink
href={`/status-pages/${pageId}/status-reports/${id}`}
- onClick={(e) => {
- // avoid expanding the row
- e.stopPropagation();
- }}
value={row.getValue("title")}
/>
);
},
- enableSorting: false,
- enableHiding: false,
- meta: {
- cellClassName: "max-w-[200px] truncate",
- },
- },
- {
- accessorKey: "status",
- header: "Current Status",
- cell: ({ row }) => {
- const value = String(row.getValue("status"));
- return (
- <div
- className={cn(
- "font-mono capitalize",
- colors[value as keyof typeof colors],
- )}
- >
- {value}
- </div>
- );
- },
- enableSorting: false,
- enableHiding: false,
+ meta: { cellClassName: "max-w-[200px] truncate" },
},
{
id: "impact",
accessorFn: (row) => worstReportImpact(row),
header: "Impact",
- cell: ({ row }) => {
- const impact = row.getValue<PageComponentImpact | null>("impact");
- const config = impact ? impactConfig[impact] : untriagedImpact;
- return (
- <div className={cn("max-w-[120px] truncate font-mono", config.color)}>
- {config.label}
- </div>
- );
- },
enableSorting: false,
+ cell: ({ row }) => (
+ <StatusReportImpactBadge
+ impact={row.getValue<PageComponentImpact | null>("impact")}
+ />
+ ),
+ },
+ {
+ accessorKey: "status",
+ header: "Status",
+ enableSorting: false,
+ enableHiding: false,
+ cell: ({ row }) => <StatusReportStatusBadge status={row.original.status} />,
},
{
id: "updates",
accessorFn: (row) => row.updates.length,
header: "Updates",
- cell: ({ row }) => {
- const value = row.getValue("updates");
- return <TableCellNumber value={value} />;
- },
+ cell: ({ row }) => <TableCellNumber value={row.getValue("updates")} />,
},
{
id: "pageComponents",
@@ -162,23 +101,17 @@ export const columns: ColumnDef<StatusReport>[] = [
},
{
id: "startedAt",
- accessorFn: (row) =>
- row.updates.sort((a, b) => a.date.getTime() - b.date.getTime())[0]
- ?.date ?? row.createdAt,
+ accessorFn: (row) => reportStartedAt(row),
header: ({ column }) => (
<DataTableColumnHeader column={column} title="Started At" />
),
cell: ({ row }) => <TableCellDate value={row.getValue("startedAt")} />,
enableHiding: false,
- meta: {
- cellClassName: "w-[170px]",
- },
+ meta: { cellClassName: "whitespace-nowrap" },
},
{
id: "actions",
cell: ({ row }) => <DataTableRowActions row={row} />,
- meta: {
- cellClassName: "w-8",
- },
+ meta: { cellClassName: "w-8" },
},
];
diff --git a/apps/dashboard/src/components/data-table/status-reports/data-table-row-actions.tsx b/apps/dashboard/src/components/data-table/status-reports/data-table-row-actions.tsx
index 1a6c9a5e6..ebdcff3f2 100644
--- a/apps/dashboard/src/components/data-table/status-reports/data-table-row-actions.tsx
+++ b/apps/dashboard/src/components/data-table/status-reports/data-table-row-actions.tsx
@@ -1,14 +1,11 @@
"use client";
import type { RouterOutputs } from "@openstatus/api";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
import type { Row } from "@tanstack/react-table";
-import { useRef } from "react";
import { QuickActions } from "@/components/dropdowns/quick-actions";
-import { FormSheetStatusReportUpdateCreate } from "@/components/forms/status-report-update/sheet-create";
-import { FormSheetStatusReport } from "@/components/forms/status-report/sheet";
-import { toCheckboxTreeItems } from "@/components/ui/checkbox-tree";
+import { getPageUrl } from "@/data/status-pages.client";
import { getActions } from "@/data/status-reports.client";
import { useTRPC } from "@/lib/trpc/client";
@@ -22,96 +19,41 @@ export function DataTableRowActions({ row }: { row: Row<StatusReport> }) {
}
export function StatusReportRowActions({ report }: { report: StatusReport }) {
- const buttonCreateRef = useRef<HTMLButtonElement>(null);
- const buttonUpdateRef = useRef<HTMLButtonElement>(null);
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
const actions = getActions({
- "create-update": () => buttonCreateRef.current?.click(),
- edit: () => buttonUpdateRef.current?.click(),
"view-report": () => {
- if (typeof window !== "undefined") {
- window.open(
- `https://${
- report.page.customDomain || `${report.page.slug}.openstatus.dev`
- }/events/report/${report.id}`,
- "_blank",
- );
- }
+ window.open(
+ `${getPageUrl(report.page)}/events/report/${report.id}`,
+ "_blank",
+ );
},
});
- const trpc = useTRPC();
- const queryClient = useQueryClient();
- const { data: page } = useQuery(
- trpc.page.get.queryOptions(
- { id: report.pageId ?? 0 },
- { enabled: report.pageId !== null },
- ),
- );
- // no-input prefix key — matches every statusReport.list query (overview, page detail)
- const invalidateLists = () => {
- queryClient.invalidateQueries({
- queryKey: trpc.statusReport.list.queryKey(),
- });
- queryClient.invalidateQueries({
- queryKey: trpc.page.list.queryKey(),
- });
- };
- const updateStatusReportMutation = useMutation(
- trpc.statusReport.updateStatus.mutationOptions({
- onSuccess: invalidateLists,
- }),
- );
const deleteStatusReportMutation = useMutation(
trpc.statusReport.delete.mutationOptions({
- onSuccess: invalidateLists,
+ // no-input prefix key — matches every statusReport.list query (overview, page detail)
+ onSuccess: () => {
+ queryClient.invalidateQueries({
+ queryKey: trpc.statusReport.list.queryKey(),
+ });
+ queryClient.invalidateQueries({
+ queryKey: trpc.page.list.queryKey(),
+ });
+ },
}),
);
if (!report.pageId) return null;
return (
- <>
- <QuickActions
- actions={actions}
- deleteAction={{
- confirmationValue: report.title ?? "status report",
- submitAction: async () => {
- await deleteStatusReportMutation.mutateAsync({
- id: report.id,
- });
- },
- }}
- />
- <FormSheetStatusReport
- items={toCheckboxTreeItems(
- page?.pageComponents ?? [],
- page?.pageComponentGroups ?? [],
- )}
- defaultValues={{
- title: report.title,
- status: report.status,
- pageComponents: report.pageComponents?.map((c) => c.id) ?? [],
- }}
- onSubmit={async (values) => {
- const hasComponents =
- (page?.pageComponents?.length ?? 0) > 0 ||
- (page?.pageComponentGroups?.length ?? 0) > 0;
- await updateStatusReportMutation.mutateAsync({
- id: report.id,
- pageComponents: hasComponents ? values.pageComponents : undefined,
- title: values.title,
- status: values.status,
- });
- }}
- >
- <button ref={buttonUpdateRef} type="button" className="sr-only">
- Open sheet
- </button>
- </FormSheetStatusReport>
- <FormSheetStatusReportUpdateCreate report={report}>
- <button ref={buttonCreateRef} type="button" className="sr-only">
- Open sheet
- </button>
- </FormSheetStatusReportUpdateCreate>
- </>
+ <QuickActions
+ actions={actions}
+ deleteAction={{
+ confirmationValue: report.title ?? "status report",
+ submitAction: async () => {
+ await deleteStatusReportMutation.mutateAsync({ id: report.id });
+ },
+ }}
+ />
);
}
diff --git a/apps/dashboard/src/components/forms/incident/form.tsx b/apps/dashboard/src/components/forms/incident/form.tsx
index 308931634..9e01685b8 100644
--- a/apps/dashboard/src/components/forms/incident/form.tsx
+++ b/apps/dashboard/src/components/forms/incident/form.tsx
@@ -23,8 +23,6 @@ import {
import { Textarea } from "@openstatus/ui/components/ui/textarea";
import { cn } from "@openstatus/ui/lib/utils";
import { useQuery } from "@tanstack/react-query";
-import { isTRPCClientError } from "@trpc/client";
-import { format } from "date-fns";
import React, { useTransition } from "react";
import { useForm } from "react-hook-form";
import { toast } from "sonner";
@@ -37,7 +35,9 @@ import {
} from "@/components/forms/form-card";
import { useFormSheetDirty } from "@/components/forms/form-sheet";
import { personName, severityConfig } from "@/data/managed-incidents.client";
+import { formatDateForInput } from "@/lib/formatter";
import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
const NONE = "none";
@@ -69,10 +69,6 @@ export type DeclareIncidentValues = {
openSlackChannel: boolean;
};
-export function toLocalInput(date: Date): string {
- return format(date, "yyyy-MM-dd'T'HH:mm");
-}
-
export function FormDeclareIncident({
defaultValues,
onSubmit,
@@ -100,7 +96,7 @@ export function FormDeclareIncident({
// user.get is prefetched in the dashboard layout, so it is hydrated
// before the sheet can mount and the default is never NONE for members.
commanderId: user ? String(user.id) : NONE,
- startedAt: toLocalInput(new Date()),
+ startedAt: formatDateForInput(new Date()),
statusReportId: NONE,
openSlackChannel: slack === "ready",
...defaultValues,
@@ -134,8 +130,7 @@ export function FormDeclareIncident({
toast.promise(promise, {
loading: "Declaring...",
success: () => "Incident declared",
- error: (error) =>
- isTRPCClientError(error) ? error.message : "Failed to declare",
+ error: (error) => errorMessage(error, "Failed to declare"),
});
await promise;
} catch (error) {
diff --git a/apps/dashboard/src/components/forms/status-report-update/form-status-report.tsx b/apps/dashboard/src/components/forms/status-report-update/form-status-report.tsx
deleted file mode 100644
index 7b57e3af2..000000000
--- a/apps/dashboard/src/components/forms/status-report-update/form-status-report.tsx
+++ /dev/null
@@ -1,459 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import type { StatusReportUpdate } from "@openstatus/db/src/schema";
-import { pageComponentImpact } from "@openstatus/db/src/schema/page_components/constants";
-import { statusReportStatus } from "@openstatus/db/src/schema/status_reports/constants";
-import { Calendar as CalendarIcon, Clock } from "@openstatus/icons";
-import { Button } from "@openstatus/ui/components/ui/button";
-import { Calendar } from "@openstatus/ui/components/ui/calendar";
-import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
-import {
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@openstatus/ui/components/ui/form";
-import { Input } from "@openstatus/ui/components/ui/input";
-import { Label } from "@openstatus/ui/components/ui/label";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@openstatus/ui/components/ui/popover";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@openstatus/ui/components/ui/select";
-import { TabsContent } from "@openstatus/ui/components/ui/tabs";
-import { TabsList, TabsTrigger } from "@openstatus/ui/components/ui/tabs";
-import { Tabs } from "@openstatus/ui/components/ui/tabs";
-import { Textarea } from "@openstatus/ui/components/ui/textarea";
-import { useIsMobile } from "@openstatus/ui/hooks/use-mobile";
-import { cn } from "@openstatus/ui/lib/utils";
-import { useMutation, useQuery } from "@tanstack/react-query";
-import { isTRPCClientError } from "@trpc/client";
-import { format } from "date-fns";
-import { useParams } from "next/navigation";
-import React, { useTransition } from "react";
-import { useForm } from "react-hook-form";
-import { toast } from "sonner";
-import { z } from "zod";
-
-import { ProcessMessage } from "@/components/content/process-message";
-import { FormAlertDialog } from "@/components/forms/form-alert-dialog";
-import {
- FormCardContent,
- FormCardSeparator,
-} from "@/components/forms/form-card";
-import {
- FormCard,
- FormCardFooter,
- FormCardHeader,
- FormCardTitle,
-} from "@/components/forms/form-card";
-import { useFormSheetDirty } from "@/components/forms/form-sheet";
-import { ComponentImpactList } from "@/components/forms/status-report/component-impact-field";
-import { colors } from "@/data/status-report-updates.client";
-import { useTRPC } from "@/lib/trpc/client";
-
-const schema = z.object({
- status: z.enum(statusReportStatus),
- message: z.string(),
- date: z.date(),
- componentImpacts: z
- .array(
- z.object({
- pageComponentId: z.number(),
- impact: z.enum(pageComponentImpact),
- }),
- )
- .optional(),
- notifySubscribers: z.boolean().optional(),
-});
-
-export type FormValues = z.infer<typeof schema>;
-
-export function FormStatusReportUpdateCard({
- defaultValues,
- onSubmit,
- className,
- index,
- update,
- components,
- ...props
-}: Omit<React.ComponentProps<"form">, "onSubmit"> & {
- defaultValues?: FormValues;
- onSubmit: (values: FormValues) => Promise<void>;
- index: number;
- update: StatusReportUpdate;
- /** The report's affected components; renders the per-component impact picker. */
- components?: { id: number; name: string }[];
-}) {
- const { reportId } = useParams<{ id: string; reportId: string }>();
- const trpc = useTRPC();
- const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
- const mobile = useIsMobile();
- const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
- const form = useForm<FormValues>({
- resolver: zodResolver(schema),
- defaultValues: defaultValues ?? {
- status: "identified",
- message: "",
- date: new Date(),
- componentImpacts: undefined,
- notifySubscribers: !!workspace?.limits["status-subscribers"],
- },
- });
-
- const watchMessage = form.watch("message");
- const [isPending, startTransition] = useTransition();
- const { setIsDirty } = useFormSheetDirty();
-
- const formIsDirty = form.formState.isDirty;
- React.useEffect(() => {
- setIsDirty(formIsDirty);
- }, [formIsDirty, setIsDirty]);
-
- const { data: statusReport, refetch } = useQuery(
- trpc.statusReport.get.queryOptions({ id: Number.parseInt(reportId) }),
- );
-
- function submitAction(values: FormValues) {
- if (isPending) return;
-
- startTransition(async () => {
- try {
- const promise = onSubmit(values);
- toast.promise(promise, {
- loading: "Saving...",
- success: () => "Saved",
- error: (error) => {
- if (isTRPCClientError(error)) {
- return error.message;
- }
- return "Failed to save";
- },
- });
- await promise;
- } catch (error) {
- console.error(error);
- }
- });
- }
-
- const deleteStatusReportUpdateMutation = useMutation(
- trpc.statusReport.deleteUpdate.mutationOptions({
- onSuccess: () => {
- refetch();
- },
- }),
- );
-
- const updates = [...(statusReport?.updates ?? [])].sort(
- (a, b) => b.date.getTime() - a.date.getTime(),
- );
-
- return (
- <FormCard>
- <FormCardHeader>
- <FormCardTitle>
- Status Report Update #{updates.length - index}
- </FormCardTitle>
- </FormCardHeader>
-
- <Form {...form}>
- <form
- className={cn("grid gap-4", className)}
- onSubmit={form.handleSubmit(submitAction)}
- {...props}
- >
- <FormCardContent className="grid gap-4 sm:grid-cols-3">
- <FormField
- control={form.control}
- name="status"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Status</FormLabel>
- <FormControl>
- <Select
- defaultValue={field.value}
- onValueChange={(value) => {
- field.onChange(value);
- // resolved implies components are back up — prefill, still editable
- if (value === "resolved" && components?.length) {
- form.setValue(
- "componentImpacts",
- components.map((c) => ({
- pageComponentId: c.id,
- impact: "operational" as const,
- })),
- { shouldDirty: true },
- );
- }
- }}
- >
- <SelectTrigger
- size="sm"
- className={cn(
- colors[field.value],
- "w-full font-mono capitalize",
- )}
- >
- <SelectValue placeholder="Select a status" />
- </SelectTrigger>
- <SelectContent>
- {statusReportStatus.map((status) => (
- <SelectItem
- key={status}
- value={status}
- className={cn(
- colors[status],
- "font-mono capitalize",
- )}
- >
- {status}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="date"
- render={({ field }) => (
- <FormItem className="flex flex-col">
- <FormLabel>Date</FormLabel>
- <Popover modal>
- <FormControl>
- <PopoverTrigger asChild>
- <Button
- type="button"
- variant="outline"
- size="sm"
- className={cn(
- "w-full pl-3 text-left font-normal sm:w-[240px]",
- !field.value && "text-muted-foreground",
- )}
- >
- {field.value ? (
- format(field.value, "PPP 'at' h:mm a")
- ) : (
- <span>Pick a date</span>
- )}
- <CalendarIcon className="ml-auto h-4 w-4 opacity-50" />
- </Button>
- </PopoverTrigger>
- </FormControl>
- <PopoverContent
- className="pointer-events-auto w-auto p-0"
- align="start"
- side={mobile ? "bottom" : "left"}
- >
- <Calendar
- mode="single"
- selected={field.value}
- onSelect={(selectedDate) => {
- if (!selectedDate) return;
- const newDate = new Date(selectedDate);
- newDate.setHours(
- field.value.getHours(),
- field.value.getMinutes(),
- field.value.getSeconds(),
- field.value.getMilliseconds(),
- );
- field.onChange(newDate);
- }}
- disabled={(date) =>
- date > new Date() || date < new Date("1900-01-01")
- }
- initialFocus
- />
- <div className="border-t p-3">
- <div className="flex items-center gap-3">
- <Label htmlFor="time" className="text-xs">
- Enter time
- </Label>
- <div className="relative grow">
- <Input
- id="time"
- type="time"
- step="1"
- defaultValue={new Date()
- .toTimeString()
- .slice(0, 8)}
- className="peer appearance-none ps-9 [&::-webkit-calendar-picker-indicator]:hidden [&::-webkit-calendar-picker-indicator]:appearance-none"
- onChange={(e) => {
- try {
- const timeValue = e.target.value;
- if (!timeValue || !field.value) return;
- const [hours, minutes, seconds] = timeValue
- .split(":")
- .map(Number);
- const newDate = new Date(field.value);
- newDate.setHours(
- hours,
- minutes,
- seconds || 0,
- 0,
- );
- field.onChange(newDate);
- } catch (error) {
- console.error(error);
- }
- }}
- />
- <div className="text-muted-foreground/80 pointer-events-none absolute inset-y-0 start-0 flex items-center justify-center ps-3 peer-disabled:opacity-50">
- <Clock size={16} aria-hidden="true" />
- </div>
- </div>
- </div>
- </div>
- </PopoverContent>
- </Popover>
- <FormMessage />
- </FormItem>
- )}
- />
- </FormCardContent>
- <FormCardContent>
- <FormDescription>
- When the status report was created. Shown in your timezone (
- <code className="font-commit-mono text-foreground/70">
- {timezone}
- </code>
- ) and saved as Unix time (
- <code className="font-commit-mono text-foreground/70">UTC</code>
- ).
- </FormDescription>
- </FormCardContent>
- {components && components.length > 0 ? (
- <>
- <FormCardSeparator />
- <FormCardContent>
- <FormField
- control={form.control}
- name="componentImpacts"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Component Impact</FormLabel>
- <FormDescription>
- The impact this update set per component. Components
- marked &quot;No change&quot; keep their prior impact.
- </FormDescription>
- <FormControl>
- <ComponentImpactList
- components={components}
- value={field.value ?? []}
- onValueChange={field.onChange}
- allowUnset
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </FormCardContent>
- </>
- ) : null}
- <FormCardSeparator />
- <FormCardContent>
- <Tabs defaultValue="tab-1">
- <TabsList>
- <TabsTrigger value="tab-1">Writing</TabsTrigger>
- <TabsTrigger value="tab-2">Preview</TabsTrigger>
- </TabsList>
- <TabsContent value="tab-1">
- <FormField
- control={form.control}
- name="message"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Message</FormLabel>
- <FormControl>
- <Textarea rows={6} {...field} />
- </FormControl>
- <FormMessage />
- <FormDescription>Markdown support</FormDescription>
- </FormItem>
- )}
- />
- </TabsContent>
- <TabsContent value="tab-2">
- <div className="grid gap-2">
- <Label>Preview</Label>
- <div className="prose prose-sm dark:prose-invert text-foreground rounded-md border px-3 py-2 text-sm">
- <ProcessMessage value={watchMessage} />
- </div>
- </div>
- </TabsContent>
- </Tabs>
- </FormCardContent>
- {!defaultValues && workspace?.limits["status-subscribers"] ? (
- <>
- <FormCardSeparator />
- <FormCardContent>
- <FormField
- control={form.control}
- name="notifySubscribers"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Notify Subscribers</FormLabel>
- <FormControl>
- <div className="flex items-center gap-2">
- <Checkbox
- id="notifySubscribers"
- checked={field.value}
- onCheckedChange={field.onChange}
- />
- <Label htmlFor="notifySubscribers">
- Send notification to subscribers
- </Label>
- </div>
- </FormControl>
- <FormMessage />
- <FormDescription>
- Subscribers will be notified when creating a status
- report.
- </FormDescription>
- </FormItem>
- )}
- />
- </FormCardContent>
- </>
- ) : null}
- </form>
- </Form>
- <FormCardFooter className="flex items-center justify-end gap-2 [&>:last-child]:ml-0">
- <FormAlertDialog
- confirmationValue={update.status}
- submitAction={async () => {
- await deleteStatusReportUpdateMutation.mutateAsync({
- id: update.id,
- });
- }}
- >
- <Button
- variant="outline"
- className="text-destructive hover:bg-destructive/10 hover:text-destructive"
- >
- Delete
- </Button>
- </FormAlertDialog>
- <Button type="submit" form={`update-form-${update.id}`}>
- {isPending ? "Submitting..." : "Submit"}
- </Button>
- </FormCardFooter>
- </FormCard>
- );
-}
diff --git a/apps/dashboard/src/components/forms/status-report/component-impact-field.tsx b/apps/dashboard/src/components/forms/status-report/component-impact-field.tsx
index 451021a3c..95f997b87 100644
--- a/apps/dashboard/src/components/forms/status-report/component-impact-field.tsx
+++ b/apps/dashboard/src/components/forms/status-report/component-impact-field.tsx
@@ -11,9 +11,14 @@ import {
SelectTrigger,
SelectValue,
} from "@openstatus/ui/components/ui/select";
-import { cn } from "@openstatus/ui/lib/utils";
-import { impactConfig } from "@/data/status-report-updates.client";
+import {
+ ComponentImpact,
+ ComponentList,
+ ComponentListActions,
+ ComponentListItem,
+ ComponentListName,
+} from "@/components/content/component-list";
export type ComponentImpactValue = {
pageComponentId: number;
@@ -51,45 +56,35 @@ export function ComponentImpactList({
if (components.length === 0) return null;
return (
- <div className="grid gap-2">
- {components.map((component) => {
- const impact = impactFor(component.id);
- return (
- <div
- key={component.id}
- className="flex items-center justify-between gap-2"
- >
- <span className="truncate text-sm">{component.name}</span>
+ <ComponentList>
+ {components.map((component) => (
+ <ComponentListItem key={component.id}>
+ <ComponentListName>{component.name}</ComponentListName>
+ <ComponentListActions>
<Select
- value={impact}
+ value={impactFor(component.id)}
onValueChange={(next) =>
setImpact(component.id, next as PageComponentImpact)
}
>
<SelectTrigger
size="sm"
- className={cn(
- impact ? impactConfig[impact].color : "text-muted-foreground",
- "w-[180px] font-mono",
- )}
+ aria-label={`${component.name} impact`}
+ className="w-[180px] font-mono"
>
<SelectValue placeholder={placeholder} />
</SelectTrigger>
<SelectContent>
{pageComponentImpact.map((option) => (
- <SelectItem
- key={option}
- value={option}
- className={cn(impactConfig[option].color, "font-mono")}
- >
- {impactConfig[option].label}
+ <SelectItem key={option} value={option}>
+ <ComponentImpact impact={option} />
</SelectItem>
))}
</SelectContent>
</Select>
- </div>
- );
- })}
- </div>
+ </ComponentListActions>
+ </ComponentListItem>
+ ))}
+ </ComponentList>
);
}
diff --git a/apps/dashboard/src/components/forms/status-report/sheet-create.tsx b/apps/dashboard/src/components/forms/status-report/sheet-create.tsx
index f23318cfe..993d9e4d5 100644
--- a/apps/dashboard/src/components/forms/status-report/sheet-create.tsx
+++ b/apps/dashboard/src/components/forms/status-report/sheet-create.tsx
@@ -40,12 +40,17 @@ export function FormSheetStatusReportCreate({
open: controlledOpen,
onOpenChange,
defaultPageId,
+ incidentId,
+ onCreated,
}: {
children?: React.ReactNode;
open?: boolean;
onOpenChange?: (open: boolean) => void;
/** Pre-scopes the sheet to a page and hides the selector. */
defaultPageId?: number;
+ /** Links the new report to an incident on create. */
+ incidentId?: number;
+ onCreated?: () => void;
}) {
const [internalOpen, setInternalOpen] = useState(false);
const open = controlledOpen ?? internalOpen;
@@ -85,6 +90,7 @@ export function FormSheetStatusReportCreate({
queryClient.invalidateQueries({
queryKey: trpc.page.list.queryKey(),
});
+ onCreated?.();
},
}),
);
@@ -177,6 +183,7 @@ export function FormSheetStatusReportCreate({
date: values.date,
message: values.message,
notifySubscribers: values.notifySubscribers,
+ incidentId,
});
setOpen(false);
}
diff --git a/apps/dashboard/src/components/incidents/confirm-close-dialog.tsx b/apps/dashboard/src/components/incidents/confirm-close-dialog.tsx
new file mode 100644
index 000000000..853c0dcc4
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/confirm-close-dialog.tsx
@@ -0,0 +1,80 @@
+"use client";
+
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@openstatus/ui/components/ui/alert-dialog";
+
+export type ConfirmCloseKind = "cancel" | "close";
+
+const COPY: Record<
+ ConfirmCloseKind,
+ { title: string; description: string; action: string }
+> = {
+ cancel: {
+ title: "Cancel this incident?",
+ description:
+ "Marks it as a false alarm and closes it. Status, severity, commander and notes can't be changed afterwards.",
+ action: "Cancel incident",
+ },
+ close: {
+ title: "Close this incident?",
+ description:
+ "Closing is final. Status, severity, commander and notes can't be changed afterwards.",
+ action: "Close incident",
+ },
+};
+
+/**
+ * Guards the two transitions that freeze an incident (cancel, close).
+ * Resolving is reversible and intentionally not guarded.
+ */
+export function ConfirmCloseDialog({
+ kind,
+ open,
+ onOpenChange,
+ onConfirm,
+ pending,
+}: {
+ kind: ConfirmCloseKind;
+ open: boolean;
+ onOpenChange: (open: boolean) => void;
+ onConfirm: () => void;
+ pending?: boolean;
+}) {
+ const copy = COPY[kind];
+ return (
+ <AlertDialog open={open} onOpenChange={onOpenChange}>
+ <AlertDialogContent
+ onCloseAutoFocus={(event) => {
+ // Opened from a Select; body stays unclickable without this.
+ event.preventDefault();
+ document.body.style.pointerEvents = "";
+ }}
+ >
+ <AlertDialogHeader>
+ <AlertDialogTitle>{copy.title}</AlertDialogTitle>
+ <AlertDialogDescription>{copy.description}</AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep editing</AlertDialogCancel>
+ <AlertDialogAction
+ disabled={pending}
+ onClick={(e) => {
+ e.preventDefault();
+ onConfirm();
+ }}
+ >
+ {copy.action}
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/declare-from-row.tsx b/apps/dashboard/src/components/incidents/declare-from-row.tsx
index 6f83f99b0..7ad624b9d 100644
--- a/apps/dashboard/src/components/incidents/declare-from-row.tsx
+++ b/apps/dashboard/src/components/incidents/declare-from-row.tsx
@@ -3,8 +3,8 @@
import { Button } from "@openstatus/ui/components/ui/button";
import { useQuery } from "@tanstack/react-query";
-import { toLocalInput } from "@/components/forms/incident/form";
import { useFeature } from "@/hooks/use-feature";
+import { formatDateForInput } from "@/lib/formatter";
import { useTRPC } from "@/lib/trpc/client";
import {
@@ -41,7 +41,7 @@ export function DeclareFromRow({
defaultValues={{
title,
// epoch = legacy report without dates; prefill now instead
- startedAt: toLocalInput(
+ startedAt: formatDateForInput(
startedAt.getTime() === 0 ? new Date() : startedAt,
),
...(statusReportId ? { statusReportId: String(statusReportId) } : {}),
diff --git a/apps/dashboard/src/components/incidents/incident-actions.tsx b/apps/dashboard/src/components/incidents/incident-actions.tsx
index a5ea3919f..9e5f61e4e 100644
--- a/apps/dashboard/src/components/incidents/incident-actions.tsx
+++ b/apps/dashboard/src/components/incidents/incident-actions.tsx
@@ -3,13 +3,15 @@
import type { RouterOutputs } from "@openstatus/api";
import { Button } from "@openstatus/ui/components/ui/button";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { isTRPCClientError } from "@trpc/client";
import { useRouter } from "next/navigation";
+import { useState } from "react";
import { toast } from "sonner";
import { QuickActions } from "@/components/dropdowns/quick-actions";
import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
+import { ConfirmCloseDialog } from "./confirm-close-dialog";
import { useInvalidateIncident } from "./use-invalidate-incident";
type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
@@ -27,18 +29,22 @@ export function IncidentActions({ incident }: { incident: Incident }) {
const router = useRouter();
const queryClient = useQueryClient();
const invalidate = useInvalidateIncident(incident.id);
- const { data: postmortem } = useQuery(
- trpc.incident.getPostmortem.queryOptions({ id: incident.id }),
- );
+ const closable = incident.status === "resolved" && incident.closedAt === null;
+ const { data: postmortem } = useQuery({
+ ...trpc.incident.getPostmortem.queryOptions({ id: incident.id }),
+ enabled: closable,
+ });
const approved = postmortem?.status === "approved";
+ const [confirmClose, setConfirmClose] = useState(false);
const close = useMutation(
trpc.incident.close.mutationOptions({
- onSuccess: invalidate,
+ onSuccess: async () => {
+ await invalidate();
+ setConfirmClose(false);
+ },
onError: (error) => {
- toast.error(
- isTRPCClientError(error) ? error.message : "Failed to close",
- );
+ toast.error(errorMessage(error, "Failed to close"));
},
}),
);
@@ -54,24 +60,32 @@ export function IncidentActions({ incident }: { incident: Incident }) {
);
if (!hasIncidentActions(incident)) return null;
- const closable = incident.status === "resolved" && incident.closedAt === null;
return (
<>
{closable ? (
- <Button
- size="sm"
- variant="outline"
- disabled={close.isPending}
- onClick={() =>
- close.mutate({
- id: incident.id,
- skipPostmortem: approved ? undefined : true,
- })
- }
- >
- {approved ? "Close incident" : "Close (skip postmortem)"}
- </Button>
+ <>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={close.isPending}
+ onClick={() => setConfirmClose(true)}
+ >
+ {approved ? "Close incident" : "Close (skip postmortem)"}
+ </Button>
+ <ConfirmCloseDialog
+ kind="close"
+ open={confirmClose}
+ onOpenChange={setConfirmClose}
+ pending={close.isPending}
+ onConfirm={() =>
+ close.mutate({
+ id: incident.id,
+ skipPostmortem: approved ? undefined : true,
+ })
+ }
+ />
+ </>
) : null}
{incident.deletable ? (
<QuickActions
diff --git a/apps/dashboard/src/components/incidents/incident-composer.tsx b/apps/dashboard/src/components/incidents/incident-composer.tsx
index 7ee4ccf2f..792e65037 100644
--- a/apps/dashboard/src/components/incidents/incident-composer.tsx
+++ b/apps/dashboard/src/components/incidents/incident-composer.tsx
@@ -10,25 +10,23 @@ import {
SelectValue,
} from "@openstatus/ui/components/ui/select";
import { useMutation, useQuery } from "@tanstack/react-query";
-import { isTRPCClientError } from "@trpc/client";
import { useState } from "react";
import { toast } from "sonner";
import { StatusDot } from "@/components/common/status-dot";
-import { UserAvatar } from "@/components/common/user-avatar";
import {
Composer,
ComposerFooter,
ComposerHeader,
- ComposerHint,
ComposerPreview,
- ComposerTabs,
ComposerTextarea,
} from "@/components/content/composer";
-import { TimelineItem } from "@/components/content/timeline";
+import { TimelineAvatar, TimelineItem } from "@/components/content/timeline";
import { personName, statusConfig } from "@/data/managed-incidents.client";
import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
+import { ConfirmCloseDialog } from "./confirm-close-dialog";
import { useInvalidateIncident } from "./use-invalidate-incident";
/**
@@ -53,6 +51,7 @@ export function IncidentComposer({
const { data: user } = useQuery(trpc.user.get.queryOptions());
const [selected, setSelected] = useState<string | null>(null);
const [message, setMessage] = useState("");
+ const [confirmCancel, setConfirmCancel] = useState(false);
const invalidate = useInvalidateIncident(incident.id);
const addNote = useMutation(
@@ -65,6 +64,13 @@ export function IncidentComposer({
const next = incident.allowedTransitions.find((s) => s === selected);
const disabled = pending || (!next && !message.trim());
+ // Canceling closes the incident for good; route through the dialog first.
+ function requestSubmit() {
+ if (disabled) return;
+ if (next === "canceled") setConfirmCancel(true);
+ else submit().catch(console.error);
+ }
+
async function submit() {
if (disabled) return;
const note = message.trim();
@@ -82,10 +88,10 @@ export function IncidentComposer({
toast.promise(promise, {
loading: "Posting...",
success: "Posted",
- error: (error) =>
- isTRPCClientError(error) ? error.message : "Failed to post",
+ error: (error) => errorMessage(error, "Failed to post"),
});
await promise;
+ setConfirmCancel(false);
setMessage("");
setSelected(null);
if (next) onStatusChanged(next, note);
@@ -93,26 +99,24 @@ export function IncidentComposer({
return (
<TimelineItem>
- <UserAvatar
+ <ConfirmCloseDialog
+ kind="cancel"
+ open={confirmCancel}
+ onOpenChange={setConfirmCancel}
+ pending={pending}
+ onConfirm={() => submit().catch(console.error)}
+ />
+ <TimelineAvatar
name={user ? personName(user) : null}
src={user?.photoUrl}
- className="size-8 text-xs"
/>
<Composer>
- <ComposerHeader>
- <ComposerTabs />
- <ComposerHint>Markdown</ComposerHint>
- </ComposerHeader>
+ <ComposerHeader />
<ComposerTextarea
placeholder="What's happening? Impact, what you've found, what's next."
value={message}
onChange={(e) => setMessage(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey)) {
- e.preventDefault();
- submit().catch(console.error);
- }
- }}
+ onSubmit={requestSubmit}
/>
<ComposerPreview value={message} />
<ComposerFooter>
@@ -145,11 +149,7 @@ export function IncidentComposer({
<span className="hidden text-xs sm:inline">
Only your team sees notes
</span>
- <Button
- size="sm"
- disabled={disabled}
- onClick={() => submit().catch(console.error)}
- >
+ <Button size="sm" disabled={disabled} onClick={requestSubmit}>
{next
? `Post and mark ${statusConfig[next].label.toLowerCase()}`
: "Post note"}
diff --git a/apps/dashboard/src/components/incidents/incident-heading.tsx b/apps/dashboard/src/components/incidents/incident-heading.tsx
index d311f2d0a..6b0a06b28 100644
--- a/apps/dashboard/src/components/incidents/incident-heading.tsx
+++ b/apps/dashboard/src/components/incidents/incident-heading.tsx
@@ -2,7 +2,6 @@
import type { RouterOutputs } from "@openstatus/api";
import { useMutation } from "@tanstack/react-query";
-import { isTRPCClientError } from "@trpc/client";
import { toast } from "sonner";
import {
@@ -13,6 +12,7 @@ import {
DetailTitleRow,
} from "@/components/content/detail";
import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
import { useInvalidateIncident } from "./use-invalidate-incident";
@@ -31,9 +31,7 @@ export function IncidentHeading({
trpc.incident.update.mutationOptions({
onSuccess: invalidate,
onError: (error) => {
- toast.error(
- isTRPCClientError(error) ? error.message : "Failed to save",
- );
+ toast.error(errorMessage(error, "Failed to save"));
},
}),
);
diff --git a/apps/dashboard/src/components/incidents/incident-postmortem.tsx b/apps/dashboard/src/components/incidents/incident-postmortem.tsx
index fccfb639c..cf1f3063b 100644
--- a/apps/dashboard/src/components/incidents/incident-postmortem.tsx
+++ b/apps/dashboard/src/components/incidents/incident-postmortem.tsx
@@ -5,7 +5,6 @@ import { AI } from "@openstatus/icons";
import { Button } from "@openstatus/ui/components/ui/button";
import { InputGroupButton } from "@openstatus/ui/components/ui/input-group";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { isTRPCClientError } from "@trpc/client";
import { useState } from "react";
import { toast } from "sonner";
@@ -14,9 +13,7 @@ import {
Composer,
ComposerFooter,
ComposerHeader,
- ComposerHint,
ComposerPreview,
- ComposerTabs,
ComposerTextarea,
} from "@/components/content/composer";
import {
@@ -25,7 +22,9 @@ import {
EmptyStateTitle,
} from "@/components/content/empty-state";
import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
+import { ConfirmCloseDialog } from "./confirm-close-dialog";
import { useInvalidateIncident } from "./use-invalidate-incident";
type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
@@ -45,10 +44,6 @@ const TEMPLATE = `## Summary
## Action items
- [ ] `;
-function errorText(error: { message: string }) {
- return isTRPCClientError(error) ? error.message : "Something went wrong";
-}
-
/** The postmortem editor: draft by hand or with the agent, then approve. */
export function IncidentPostmortem({
incident,
@@ -60,12 +55,14 @@ export function IncidentPostmortem({
const trpc = useTRPC();
const queryClient = useQueryClient();
const invalidate = useInvalidateIncident(incident.id);
- const { data: postmortem } = useQuery(
- trpc.incident.getPostmortem.queryOptions({ id: incident.id }),
- );
+ const { data: postmortem } = useQuery({
+ ...trpc.incident.getPostmortem.queryOptions({ id: incident.id }),
+ enabled: incident.status === "resolved",
+ });
// null = pristine: the editor follows the server copy, so a background
// refetch never clobbers unsaved edits.
const [draft, setDraft] = useState<string | null>(null);
+ const [confirmClose, setConfirmClose] = useState(false);
const server = postmortem?.content ?? TEMPLATE;
const content = draft ?? server;
@@ -77,7 +74,7 @@ export function IncidentPostmortem({
invalidate(),
]);
const onError = (error: { message: string }) => {
- toast.error(errorText(error));
+ toast.error(errorMessage(error));
};
const save = useMutation(
@@ -102,6 +99,7 @@ export function IncidentPostmortem({
trpc.incident.approvePostmortem.mutationOptions({
onSuccess: () => {
toast.success("Postmortem approved");
+ setConfirmClose(false);
return refresh();
},
onError,
@@ -138,9 +136,8 @@ export function IncidentPostmortem({
: "No postmortem yet";
return (
- <Composer defaultValue={approved ? "preview" : "write"}>
+ <Composer size="lg" defaultValue={approved ? "preview" : "write"}>
<ComposerHeader>
- <ComposerTabs />
{agentAllowed && !approved ? (
<InputGroupButton
variant="outline"
@@ -150,23 +147,19 @@ export function IncidentPostmortem({
<AI />
{draftWithAgent.isPending ? "Drafting..." : "Draft with agent"}
</InputGroupButton>
- ) : (
- <ComposerHint>Markdown</ComposerHint>
- )}
+ ) : null}
</ComposerHeader>
<ComposerTextarea
aria-label="Postmortem"
- className="min-h-96"
value={content}
onChange={(e) => setDraft(e.target.value)}
- onKeyDown={(e) => {
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey) && canSave) {
- e.preventDefault();
- save.mutate({ id: incident.id, content, draftedBy: "user" });
- }
- }}
+ onSubmit={
+ canSave
+ ? () => save.mutate({ id: incident.id, content, draftedBy: "user" })
+ : undefined
+ }
/>
- <ComposerPreview value={content} className="min-h-96" />
+ <ComposerPreview value={content} />
<ComposerFooter>
<div className="flex items-center gap-2">
{postmortem ? (
@@ -204,10 +197,19 @@ export function IncidentPostmortem({
<Button
size="sm"
disabled={busy || dirty || incident.closedAt !== null}
- onClick={() => approve.mutate({ id: incident.id, close: true })}
+ onClick={() => setConfirmClose(true)}
>
Approve & close
</Button>
+ <ConfirmCloseDialog
+ kind="close"
+ open={confirmClose}
+ onOpenChange={setConfirmClose}
+ pending={approve.isPending}
+ onConfirm={() =>
+ approve.mutate({ id: incident.id, close: true })
+ }
+ />
</>
) : null}
</div>
diff --git a/apps/dashboard/src/components/incidents/incident-properties.tsx b/apps/dashboard/src/components/incidents/incident-properties.tsx
index d824d763a..589cc178d 100644
--- a/apps/dashboard/src/components/incidents/incident-properties.tsx
+++ b/apps/dashboard/src/components/incidents/incident-properties.tsx
@@ -5,7 +5,6 @@ import {
type IncidentStatus,
incidentSeverity,
} from "@openstatus/db/src/schema/incidents/constants";
-import { Button } from "@openstatus/ui/components/ui/button";
import {
Select,
SelectContent,
@@ -13,7 +12,6 @@ import {
SelectValue,
} from "@openstatus/ui/components/ui/select";
import { useMutation, useQuery } from "@tanstack/react-query";
-import { isTRPCClientError } from "@trpc/client";
import {
format,
formatDistanceStrict,
@@ -27,13 +25,11 @@ import { StatusDot } from "@/components/common/status-dot";
import { UserAvatar } from "@/components/common/user-avatar";
import {
Property,
- PropertyInput,
PropertyLabel,
PropertyList,
PropertySelectTrigger,
PropertyValue,
} from "@/components/content/property-list";
-import { toLocalInput } from "@/components/forms/incident/form";
import {
incidentEndedAt,
personName,
@@ -41,7 +37,9 @@ import {
statusConfig,
} from "@/data/managed-incidents.client";
import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
+import { ConfirmCloseDialog } from "./confirm-close-dialog";
import { useInvalidateIncident } from "./use-invalidate-incident";
type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
@@ -59,20 +57,24 @@ export function IncidentProperties({
}) {
const trpc = useTRPC();
const { data: members } = useQuery(trpc.member.list.queryOptions());
- const [startedAt, setStartedAt] = useState(toLocalInput(incident.startedAt));
+ const [confirmCancel, setConfirmCancel] = useState(false);
const closed = incident.closedAt !== null;
const invalidate = useInvalidateIncident(incident.id);
const onError = (error: { message: string }) => {
- toast.error(isTRPCClientError(error) ? error.message : "Failed to save");
+ toast.error(errorMessage(error, "Failed to save"));
};
const update = useMutation(
- trpc.incident.update.mutationOptions({ onSuccess: invalidate, onError }),
+ trpc.incident.update.mutationOptions({
+ onSuccess: invalidate,
+ onError,
+ }),
);
const setStatus = useMutation(
trpc.incident.setStatus.mutationOptions({
onSuccess: async (row) => {
await invalidate();
+ setConfirmCancel(false);
if (row) onStatusChanged(row.status, "");
},
onError,
@@ -86,6 +88,15 @@ export function IncidentProperties({
return (
<PropertyList>
+ <ConfirmCloseDialog
+ kind="cancel"
+ open={confirmCancel}
+ onOpenChange={setConfirmCancel}
+ pending={setStatus.isPending}
+ onConfirm={() =>
+ setStatus.mutate({ id: incident.id, status: "canceled" })
+ }
+ />
<Property>
<PropertyLabel>Severity</PropertyLabel>
<PropertyValue>
@@ -136,7 +147,10 @@ export function IncidentProperties({
const next = incident.allowedTransitions.find(
(s) => s === value,
);
- if (next) setStatus.mutate({ id: incident.id, status: next });
+ if (!next) return;
+ // Canceling closes the incident for good; ask first.
+ if (next === "canceled") setConfirmCancel(true);
+ else setStatus.mutate({ id: incident.id, status: next });
}}
>
<PropertySelectTrigger aria-label="Status">
@@ -207,49 +221,10 @@ export function IncidentProperties({
</Property>
<Property>
<PropertyLabel>Started at</PropertyLabel>
- <PropertyValue className="flex-wrap">
- {closed ? (
- <HoverCardTimestamp date={incident.startedAt} side="left">
- <span>{format(incident.startedAt, "LLL dd, y HH:mm")}</span>
- </HoverCardTimestamp>
- ) : (
- <>
- <PropertyInput
- type="datetime-local"
- aria-label="Started at"
- value={startedAt}
- onChange={(e) => setStartedAt(e.target.value)}
- />
- {startedAt !== toLocalInput(incident.startedAt) ? (
- <div className="flex gap-1 font-sans">
- <Button
- size="sm"
- className="h-7"
- disabled={!startedAt || update.isPending}
- onClick={() =>
- update.mutate({
- id: incident.id,
- startedAt: new Date(startedAt),
- })
- }
- >
- Save
- </Button>
- <Button
- size="sm"
- variant="ghost"
- className="h-7"
- disabled={update.isPending}
- onClick={() =>
- setStartedAt(toLocalInput(incident.startedAt))
- }
- >
- Reset
- </Button>
- </div>
- ) : null}
- </>
- )}
+ <PropertyValue>
+ <HoverCardTimestamp date={incident.startedAt} side="left">
+ <span>{format(incident.startedAt, "LLL dd, y HH:mm")}</span>
+ </HoverCardTimestamp>
</PropertyValue>
</Property>
<Property>
diff --git a/apps/dashboard/src/components/incidents/incident-status-report.tsx b/apps/dashboard/src/components/incidents/incident-status-report.tsx
index 737a13eb0..bb130ad15 100644
--- a/apps/dashboard/src/components/incidents/incident-status-report.tsx
+++ b/apps/dashboard/src/components/incidents/incident-status-report.tsx
@@ -4,7 +4,6 @@ import type { RouterOutputs } from "@openstatus/api";
import { statusReportStatus } from "@openstatus/db/src/schema/status_reports/constants";
import { Button } from "@openstatus/ui/components/ui/button";
import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
-import { Input } from "@openstatus/ui/components/ui/input";
import { Label } from "@openstatus/ui/components/ui/label";
import {
Select,
@@ -15,7 +14,6 @@ import {
} from "@openstatus/ui/components/ui/select";
import { Textarea } from "@openstatus/ui/components/ui/textarea";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-import { isTRPCClientError } from "@trpc/client";
import { useState } from "react";
import { toast } from "sonner";
@@ -29,17 +27,14 @@ import {
ActionCardHeader,
ActionCardTitle,
} from "@/components/content/action-card";
+import { FormSheetStatusReportCreate } from "@/components/forms/status-report/sheet-create";
+import { usePublishUpdate } from "@/components/status-reports/use-publish-update";
import { statusVariants } from "@/data/status-report-updates.client";
import { useTRPC } from "@/lib/trpc/client";
-
-import { usePublicUpdate } from "./use-public-update";
+import { errorMessage } from "@/lib/trpc/error";
type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
-function toastError(error: Error) {
- return isTRPCClientError(error) ? error.message : "Something went wrong";
-}
-
export function IncidentStatusReport({
incident,
canNotify,
@@ -56,7 +51,7 @@ export function IncidentStatusReport({
/>
);
}
- return <UnlinkedReport incident={incident} canNotify={canNotify} />;
+ return <UnlinkedReport incident={incident} />;
}
function NotifySubscribers({
@@ -97,7 +92,7 @@ function LinkedReport({
);
const [message, setMessage] = useState("");
const [notifySubscribers, setNotifySubscribers] = useState(canNotify);
- const update = usePublicUpdate(incident.id);
+ const update = usePublishUpdate(report.id);
const unlink = useMutation(
trpc.incident.unlinkStatusReport.mutationOptions({
onSuccess: () =>
@@ -111,16 +106,17 @@ function LinkedReport({
async function post() {
const parsed = statusReportStatus.find((s) => s === status);
if (!parsed) return;
- const promise = update.post({
+ const promise = update.publish({
statusReportId: report.id,
status: parsed,
message,
+ date: new Date(),
notifySubscribers,
});
toast.promise(promise, {
loading: "Posting public update...",
success: "Public update posted",
- error: toastError,
+ error: (error) => errorMessage(error),
});
await promise;
setMessage("");
@@ -220,25 +216,13 @@ function LinkedReport({
);
}
-function UnlinkedReport({
- incident,
- canNotify,
-}: {
- incident: Incident;
- canNotify: boolean;
-}) {
+function UnlinkedReport({ incident }: { incident: Incident }) {
const trpc = useTRPC();
const queryClient = useQueryClient();
- const { data: reports } = useQuery(
- trpc.statusReport.list.queryOptions({ order: "desc" }),
- );
- const { data: pages } = useQuery(trpc.page.list.queryOptions());
- const [draftMode, setMode] = useState<"link" | "create" | null>(null);
+ const [createOpen, setCreateOpen] = useState(false);
+ const [linking, setLinking] = useState(false);
const [reportId, setReportId] = useState<string>("");
- const [pageId, setPageId] = useState<string>("");
- const [title, setTitle] = useState(incident.title);
- const [message, setMessage] = useState("");
- const [notifySubscribers, setNotifySubscribers] = useState(canNotify);
+ const closed = incident.closedAt !== null;
const refresh = () =>
Promise.all([
@@ -252,42 +236,13 @@ function UnlinkedReport({
const link = useMutation(
trpc.incident.linkStatusReport.mutationOptions({ onSuccess: refresh }),
);
- const create = useMutation(
- trpc.statusReport.create.mutationOptions({ onSuccess: refresh }),
- );
- const notify = useMutation(
- trpc.subscriberNotification.statusReport.mutationOptions(),
- );
- const closed = incident.closedAt !== null;
- // Closing mid-edit would otherwise strand a form whose footer is gone.
- const mode = closed ? null : draftMode;
-
- async function createReport() {
- const promise = (async () => {
- const created = await create.mutateAsync({
- title,
- status: "investigating",
- pageId: Number(pageId),
- pageComponents: [],
- date: new Date(),
- message,
- notifySubscribers,
- incidentId: incident.id,
- });
- if (created && notifySubscribers) {
- await notify.mutateAsync({ id: created.id });
- }
- })();
- toast.promise(promise, {
- loading: "Creating status report...",
- success: "Status report created",
- error: toastError,
- });
- await promise;
- setMode(null);
- }
-
+ const { data: reports } = useQuery({
+ ...trpc.statusReport.list.queryOptions({ order: "desc" }),
+ enabled: !closed,
+ });
const openReports = (reports ?? []).filter((r) => r.status !== "resolved");
+ // Closing mid-edit would otherwise strand a form whose footer is gone.
+ const showLink = !closed && linking && openReports.length > 0;
return (
<ActionCard className="border-dashed">
@@ -305,7 +260,7 @@ function UnlinkedReport({
: "Nothing here is public. Customers only see what you publish on your status page."}
</ActionCardDescription>
</ActionCardHeader>
- {mode === "link" ? (
+ {showLink ? (
<ActionCardContent className="grid gap-2">
<Select value={reportId} onValueChange={setReportId}>
<SelectTrigger size="sm" className="w-full">
@@ -314,6 +269,7 @@ function UnlinkedReport({
<SelectContent>
{openReports.map((r) => (
<SelectItem key={r.id} value={String(r.id)}>
+ <StatusDot variant={statusVariants[r.status]} />
{r.title}
</SelectItem>
))}
@@ -321,98 +277,64 @@ function UnlinkedReport({
</Select>
</ActionCardContent>
) : null}
- {mode === "create" ? (
- <ActionCardContent className="grid gap-2">
- <Select value={pageId} onValueChange={setPageId}>
- <SelectTrigger size="sm" className="w-full">
- <SelectValue placeholder="Select a status page" />
- </SelectTrigger>
- <SelectContent>
- {(pages ?? []).map((p) => (
- <SelectItem key={p.id} value={String(p.id)}>
- {p.title}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <Input
- aria-label="Title"
- value={title}
- onChange={(e) => setTitle(e.target.value)}
- />
- <Textarea
- rows={3}
- placeholder="First public message"
- value={message}
- onChange={(e) => setMessage(e.target.value)}
- />
- {canNotify ? (
- <NotifySubscribers
- id="incident-create-notify"
- checked={notifySubscribers}
- onCheckedChange={setNotifySubscribers}
- />
- ) : null}
- </ActionCardContent>
- ) : null}
{closed ? null : (
<ActionCardFooter className="flex-wrap gap-2">
- {mode === null ? (
+ {showLink ? (
<>
- <Button size="sm" onClick={() => setMode("create")}>
- Create status report
+ <Button
+ size="sm"
+ disabled={!reportId || link.isPending}
+ onClick={() =>
+ toast.promise(
+ link.mutateAsync({
+ id: incident.id,
+ statusReportId: Number(reportId),
+ }),
+ {
+ loading: "Linking...",
+ success: "Status report linked",
+ error: (error) => errorMessage(error),
+ },
+ )
+ }
+ >
+ Link
</Button>
<Button
size="sm"
- variant="outline"
- onClick={() => setMode("link")}
+ variant="ghost"
+ onClick={() => setLinking(false)}
>
- Link existing
+ Cancel
</Button>
</>
) : (
<>
- {mode === "create" ? (
- <Button
- size="sm"
- disabled={
- !pageId ||
- !title.trim() ||
- !message.trim() ||
- create.isPending
- }
- onClick={() => createReport().catch(console.error)}
- >
- Create and link
- </Button>
- ) : (
+ <Button size="sm" onClick={() => setCreateOpen(true)}>
+ Create status report
+ </Button>
+ {openReports.length > 0 ? (
<Button
size="sm"
- disabled={!reportId || link.isPending}
- onClick={() =>
- toast.promise(
- link.mutateAsync({
- id: incident.id,
- statusReportId: Number(reportId),
- }),
- {
- loading: "Linking...",
- success: "Status report linked",
- error: toastError,
- },
- )
- }
+ variant="outline"
+ onClick={() => setLinking(true)}
>
- Link
+ Link existing
</Button>
- )}
- <Button size="sm" variant="ghost" onClick={() => setMode(null)}>
- Cancel
- </Button>
+ ) : null}
</>
)}
</ActionCardFooter>
)}
+ {/* Mounted on demand: the sheet fetches pages as soon as it renders. */}
+ {createOpen ? (
+ <FormSheetStatusReportCreate
+ open
+ onOpenChange={setCreateOpen}
+ incidentId={incident.id}
+ onCreated={() => refresh().catch(console.error)}
+ />
+ ) : null}
</ActionCard>
);
}
diff --git a/apps/dashboard/src/components/incidents/incident-timeline.tsx b/apps/dashboard/src/components/incidents/incident-timeline.tsx
index 921fd739a..be903cf22 100644
--- a/apps/dashboard/src/components/incidents/incident-timeline.tsx
+++ b/apps/dashboard/src/components/incidents/incident-timeline.tsx
@@ -29,6 +29,10 @@ import { SlackIcon } from "@openstatus/icons/brand";
import type { StatusVariant } from "@/components/common/status-dot";
import { ProcessMessage } from "@/components/content/process-message";
import {
+ TimelineActor,
+ TimelineActorTooltip,
+ TimelineAvatar,
+ TimelineAvatarBadge,
TimelineBody,
TimelineContent,
TimelineHeader,
@@ -133,20 +137,39 @@ export function IncidentTimelineItem({ event }: { event: Event }) {
: event.type === "declared" && severity
? severityConfig[severity].variant
: config.variant;
+ const user = event.createdByUser;
+ const actor = user
+ ? { name: personName(user), email: user.email, photoUrl: user.photoUrl }
+ : null;
+ // Notes are authored, so the author leads the row; state changes keep the
+ // colored indicator and show the actor inline.
+ const authored = event.type === "note" && actor;
return (
<TimelineItem>
- <TimelineIndicator variant={variant}>
- <config.icon />
- </TimelineIndicator>
+ {authored ? (
+ <TimelineActorTooltip actor={actor}>
+ <TimelineAvatar name={actor.name ?? actor.email} src={actor.photoUrl}>
+ <TimelineAvatarBadge variant={variant}>
+ <config.icon />
+ </TimelineAvatarBadge>
+ </TimelineAvatar>
+ </TimelineActorTooltip>
+ ) : (
+ <TimelineIndicator variant={variant}>
+ <config.icon />
+ </TimelineIndicator>
+ )}
<TimelineContent>
<TimelineHeader>
<TimelineTitle>
{config.label}
{status ? <IncidentStatusBadge status={status} /> : null}
{severity ? <IncidentSeverityBadge severity={severity} /> : null}
- <TimelineMeta>
- {personName(event.createdByUser) ?? "System"}
- </TimelineMeta>
+ {authored ? null : actor ? (
+ <TimelineActor actor={actor} />
+ ) : (
+ <TimelineMeta>System</TimelineMeta>
+ )}
{slackUrl ? (
<TimelineMeta>
<a
diff --git a/apps/dashboard/src/components/incidents/resolve-report-dialog.tsx b/apps/dashboard/src/components/incidents/resolve-report-dialog.tsx
index 73c1b69f0..63557a727 100644
--- a/apps/dashboard/src/components/incidents/resolve-report-dialog.tsx
+++ b/apps/dashboard/src/components/incidents/resolve-report-dialog.tsx
@@ -13,25 +13,23 @@ import {
import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
import { Label } from "@openstatus/ui/components/ui/label";
import { Textarea } from "@openstatus/ui/components/ui/textarea";
-import { isTRPCClientError } from "@trpc/client";
import { useEffect, useState } from "react";
import { toast } from "sonner";
-import { usePublicUpdate } from "./use-public-update";
+import { usePublishUpdate } from "@/components/status-reports/use-publish-update";
+import { errorMessage } from "@/lib/trpc/error";
/**
* Offered after an incident is resolved or canceled while its status report
* is still open. Nothing is posted unless the user confirms the text.
*/
export function ResolveReportDialog({
- incidentId,
report,
defaultMessage,
canNotify,
open,
onOpenChange,
}: {
- incidentId: number;
report: { id: number; title: string };
defaultMessage: string;
canNotify: boolean;
@@ -40,24 +38,24 @@ export function ResolveReportDialog({
}) {
const [message, setMessage] = useState(defaultMessage);
const [notifySubscribers, setNotifySubscribers] = useState(canNotify);
- const update = usePublicUpdate(incidentId);
+ const update = usePublishUpdate(report.id);
useEffect(() => {
if (open) setMessage(defaultMessage);
}, [open, defaultMessage]);
async function submit() {
- const promise = update.post({
+ const promise = update.publish({
statusReportId: report.id,
status: "resolved",
message,
+ date: new Date(),
notifySubscribers,
});
toast.promise(promise, {
loading: "Resolving status report...",
success: "Status report resolved",
- error: (error) =>
- isTRPCClientError(error) ? error.message : "Failed to resolve",
+ error: (error) => errorMessage(error, "Failed to resolve"),
});
await promise;
onOpenChange(false);
diff --git a/apps/dashboard/src/components/incidents/use-public-update.ts b/apps/dashboard/src/components/incidents/use-public-update.ts
deleted file mode 100644
index 8fc69c371..000000000
--- a/apps/dashboard/src/components/incidents/use-public-update.ts
+++ /dev/null
@@ -1,42 +0,0 @@
-"use client";
-
-import type { statusReportStatus } from "@openstatus/db/src/schema/status_reports/constants";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
-
-import { useTRPC } from "@/lib/trpc/client";
-
-/** Posts a status-report update and, when asked, notifies subscribers. */
-export function usePublicUpdate(incidentId: number) {
- const trpc = useTRPC();
- const queryClient = useQueryClient();
- const createUpdate = useMutation(
- trpc.statusReport.createStatusReportUpdate.mutationOptions(),
- );
- const notify = useMutation(
- trpc.subscriberNotification.statusReport.mutationOptions(),
- );
-
- return {
- isPending: createUpdate.isPending || notify.isPending,
- async post(args: {
- statusReportId: number;
- status: (typeof statusReportStatus)[number];
- message: string;
- notifySubscribers: boolean;
- }) {
- const update = await createUpdate.mutateAsync({
- statusReportId: args.statusReportId,
- status: args.status,
- message: args.message,
- date: new Date(),
- notifySubscribers: args.notifySubscribers,
- });
- if (update && args.notifySubscribers) {
- await notify.mutateAsync({ id: update.id });
- }
- await queryClient.invalidateQueries({
- queryKey: trpc.incident.get.queryKey({ id: incidentId }),
- });
- },
- };
-}
diff --git a/apps/dashboard/src/components/maintenances/maintenance-actions.tsx b/apps/dashboard/src/components/maintenances/maintenance-actions.tsx
new file mode 100644
index 000000000..b0e48cd0f
--- /dev/null
+++ b/apps/dashboard/src/components/maintenances/maintenance-actions.tsx
@@ -0,0 +1,60 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { Show } from "@openstatus/icons";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+
+import { QuickActions } from "@/components/dropdowns/quick-actions";
+import { useTRPC } from "@/lib/trpc/client";
+
+type Maintenance = NonNullable<RouterOutputs["maintenance"]["get"]>;
+
+export function MaintenanceActions({
+ maintenance,
+ publicUrl,
+}: {
+ maintenance: Maintenance;
+ publicUrl: string;
+}) {
+ const trpc = useTRPC();
+ const router = useRouter();
+ const queryClient = useQueryClient();
+ const remove = useMutation(
+ trpc.maintenance.delete.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.maintenance.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.page.list.queryKey(),
+ }),
+ ]);
+ router.push(`/status-pages/${maintenance.pageId}/maintenances`);
+ },
+ }),
+ );
+
+ return (
+ <QuickActions
+ actions={[
+ {
+ id: "view",
+ label: "View Page",
+ icon: Show,
+ variant: "default",
+ onClick: () => {
+ window.open(publicUrl, "_blank", "noopener,noreferrer");
+ },
+ },
+ ]}
+ deleteAction={{
+ confirmationValue: maintenance.title || "maintenance",
+ submitAction: async () => {
+ await remove.mutateAsync({ id: maintenance.id });
+ },
+ }}
+ />
+ );
+}
diff --git a/apps/dashboard/src/components/maintenances/maintenance-components.tsx b/apps/dashboard/src/components/maintenances/maintenance-components.tsx
new file mode 100644
index 000000000..28b67bc87
--- /dev/null
+++ b/apps/dashboard/src/components/maintenances/maintenance-components.tsx
@@ -0,0 +1,87 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { Close } from "@openstatus/icons";
+import { Button } from "@openstatus/ui/components/ui/button";
+
+import { StatusDot } from "@/components/common/status-dot";
+import {
+ ComponentList,
+ ComponentListActions,
+ ComponentListAdd,
+ ComponentListEmpty,
+ ComponentListItem,
+ ComponentListName,
+} from "@/components/content/component-list";
+import { toGroupNameLookup } from "@/data/page-components.client";
+
+import { useUpdateMaintenance } from "./use-update-maintenance";
+
+type Maintenance = NonNullable<RouterOutputs["maintenance"]["get"]>;
+
+/** Affected components as an inline list: remove per row, add via the picker below. */
+export function MaintenanceComponents({
+ maintenance,
+ components,
+ groups,
+}: {
+ maintenance: Maintenance;
+ components: { id: number; name: string; groupId?: number | null }[];
+ groups: { id: number; name: string }[];
+}) {
+ const { update, isPending } = useUpdateMaintenance(maintenance.id);
+ const selected = maintenance.pageComponents;
+ const addable = components.filter(
+ (c) => !maintenance.pageComponentIds.includes(c.id),
+ );
+ const groupOf = toGroupNameLookup(components, groups);
+
+ return (
+ <div className="flex flex-col gap-1">
+ {selected.length ? (
+ <ComponentList>
+ {selected.map((component) => (
+ <ComponentListItem key={component.id}>
+ <StatusDot variant="info" />
+ <ComponentListName group={groupOf.get(component.id)}>
+ {component.name}
+ </ComponentListName>
+ <ComponentListActions>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="text-muted-foreground invisible size-7 group-hover:visible focus-visible:visible"
+ aria-label={`Remove ${component.name}`}
+ disabled={isPending}
+ onClick={() =>
+ update({
+ pageComponents: maintenance.pageComponentIds.filter(
+ (id) => id !== component.id,
+ ),
+ })
+ }
+ >
+ <Close />
+ </Button>
+ </ComponentListActions>
+ </ComponentListItem>
+ ))}
+ </ComponentList>
+ ) : (
+ <ComponentListEmpty />
+ )}
+ <ComponentListAdd
+ className="-ml-2"
+ components={addable}
+ groups={groups}
+ disabled={isPending}
+ placeholder={
+ components.length === 0 ? "No page components yet" : undefined
+ }
+ onAdd={(id) =>
+ update({ pageComponents: [...maintenance.pageComponentIds, id] })
+ }
+ />
+ </div>
+ );
+}
diff --git a/apps/dashboard/src/components/maintenances/maintenance-composer.tsx b/apps/dashboard/src/components/maintenances/maintenance-composer.tsx
new file mode 100644
index 000000000..39d1baf60
--- /dev/null
+++ b/apps/dashboard/src/components/maintenances/maintenance-composer.tsx
@@ -0,0 +1,79 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import {
+ Composer,
+ ComposerFooter,
+ ComposerHeader,
+ ComposerPreview,
+ ComposerTextarea,
+} from "@/components/content/composer";
+
+import { useUpdateMaintenance } from "./use-update-maintenance";
+
+type Maintenance = NonNullable<RouterOutputs["maintenance"]["get"]>;
+
+/** The single maintenance message: edit in place, save explicitly, no matter the status. */
+export function MaintenanceComposer({
+ maintenance,
+}: {
+ maintenance: Maintenance;
+}) {
+ // null = pristine: the editor follows the server copy, so a background
+ // refetch never clobbers unsaved edits.
+ const [draft, setDraft] = useState<string | null>(null);
+ const server = maintenance.message;
+ const content = draft ?? server;
+ const { update, isPending } = useUpdateMaintenance(maintenance.id, {
+ onSuccess: () => {
+ toast.success("Message saved");
+ setDraft(null);
+ },
+ });
+
+ const dirty = draft !== null && draft !== server;
+ // the service rejects an empty message
+ const canSave = dirty && content.trim().length > 0 && !isPending;
+ const submit = () => update({ message: content });
+
+ return (
+ <Composer size="lg">
+ <ComposerHeader />
+ <ComposerTextarea
+ aria-label="Message"
+ placeholder="What is being maintained and what customers can expect."
+ disabled={isPending}
+ value={content}
+ onChange={(e) => setDraft(e.target.value)}
+ onSubmit={canSave ? submit : undefined}
+ />
+ <ComposerPreview value={content} />
+ <ComposerFooter>
+ <span className="text-xs">
+ {dirty
+ ? "Unsaved changes"
+ : "Visible to everyone on your status page"}
+ </span>
+ <div className="ml-auto flex items-center gap-2">
+ {dirty ? (
+ <Button
+ size="sm"
+ variant="ghost"
+ disabled={isPending}
+ onClick={() => setDraft(null)}
+ >
+ Reset
+ </Button>
+ ) : null}
+ <Button size="sm" disabled={!canSave} onClick={submit}>
+ Save
+ </Button>
+ </div>
+ </ComposerFooter>
+ </Composer>
+ );
+}
diff --git a/apps/dashboard/src/components/maintenances/maintenance-properties.tsx b/apps/dashboard/src/components/maintenances/maintenance-properties.tsx
new file mode 100644
index 000000000..2a7577533
--- /dev/null
+++ b/apps/dashboard/src/components/maintenances/maintenance-properties.tsx
@@ -0,0 +1,149 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { formatDistanceStrict } from "date-fns";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { StatusDot } from "@/components/common/status-dot";
+import {
+ Property,
+ PropertyInput,
+ PropertyLabel,
+ PropertyLink,
+ PropertyList,
+ PropertyValue,
+} from "@/components/content/property-list";
+import {
+ type MaintenanceStatus,
+ maintenanceStatusConfig,
+} from "@/data/overview-events.client";
+import { useHydrated } from "@/hooks/use-hydrated";
+import { formatDateForInput } from "@/lib/formatter";
+
+import { useUpdateMaintenance } from "./use-update-maintenance";
+
+type Maintenance = NonNullable<RouterOutputs["maintenance"]["get"]>;
+
+export function MaintenanceProperties({
+ maintenance,
+ page,
+ status,
+ publicUrl,
+}: {
+ maintenance: Maintenance;
+ page: { id: number; title: string };
+ status: MaintenanceStatus;
+ publicUrl: string;
+}) {
+ // datetime-local values and the timezone are browser-local
+ const hydrated = useHydrated();
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+ // null = pristine: the inputs follow the server copy until edited.
+ const [draft, setDraft] = useState<{ from: string; to: string } | null>(null);
+ const serverFrom = formatDateForInput(maintenance.from);
+ const serverTo = formatDateForInput(maintenance.to);
+ const from = draft?.from ?? serverFrom;
+ const to = draft?.to ?? serverTo;
+ const { update, isPending } = useUpdateMaintenance(maintenance.id, {
+ onSuccess: () => {
+ toast.success("Schedule saved");
+ setDraft(null);
+ },
+ });
+
+ const dirty = draft !== null && (from !== serverFrom || to !== serverTo);
+ const invalid = !from || !to || new Date(to) <= new Date(from);
+
+ return (
+ <PropertyList>
+ <Property>
+ <PropertyLabel>Status</PropertyLabel>
+ <PropertyValue>
+ <StatusDot variant={maintenanceStatusConfig[status].variant} />
+ {maintenanceStatusConfig[status].label}
+ </PropertyValue>
+ </Property>
+ <Property>
+ <PropertyLabel>Status page</PropertyLabel>
+ <PropertyValue>
+ <PropertyLink href={publicUrl}>{page.title}</PropertyLink>
+ </PropertyValue>
+ </Property>
+ <Property>
+ <PropertyLabel>From</PropertyLabel>
+ <PropertyValue>
+ <PropertyInput
+ type="datetime-local"
+ aria-label="From"
+ value={hydrated ? from : ""}
+ onChange={(e) => setDraft({ from: e.target.value, to })}
+ />
+ </PropertyValue>
+ </Property>
+ <Property>
+ <PropertyLabel>To</PropertyLabel>
+ <PropertyValue className="flex-wrap">
+ <PropertyInput
+ type="datetime-local"
+ aria-label="To"
+ value={hydrated ? to : ""}
+ onChange={(e) => setDraft({ from, to: e.target.value })}
+ />
+ {dirty ? (
+ <div className="grid w-full grid-cols-2 gap-1 font-sans">
+ <Button
+ size="sm"
+ className="h-7"
+ disabled={invalid || isPending}
+ // an untouched field keeps its Date: the input drops seconds
+ onClick={() =>
+ update({
+ startDate:
+ from === serverFrom ? maintenance.from : new Date(from),
+ endDate: to === serverTo ? maintenance.to : new Date(to),
+ })
+ }
+ >
+ Save
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ className="h-7"
+ disabled={isPending}
+ onClick={() => setDraft(null)}
+ >
+ Reset
+ </Button>
+ {from && to && invalid ? (
+ <span className="text-destructive col-span-full text-xs">
+ End must be after start
+ </span>
+ ) : null}
+ </div>
+ ) : null}
+ </PropertyValue>
+ </Property>
+ <Property>
+ <PropertyLabel>Duration</PropertyLabel>
+ <PropertyValue>
+ {formatDistanceStrict(maintenance.from, maintenance.to)}
+ {status === "in-progress" ? (
+ <>
+ <StatusDot variant="warning" className="size-1.5" />
+ <span className="sr-only">in progress</span>
+ </>
+ ) : null}
+ </PropertyValue>
+ </Property>
+ <Property>
+ <PropertyLabel>Timezone</PropertyLabel>
+ <PropertyValue>
+ <span className="truncate">{hydrated ? timezone : null}</span>
+ </PropertyValue>
+ </Property>
+ </PropertyList>
+ );
+}
diff --git a/apps/dashboard/src/components/maintenances/use-invalidate-maintenance.ts b/apps/dashboard/src/components/maintenances/use-invalidate-maintenance.ts
new file mode 100644
index 000000000..91617796e
--- /dev/null
+++ b/apps/dashboard/src/components/maintenances/use-invalidate-maintenance.ts
@@ -0,0 +1,21 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+
+import { useTRPC } from "@/lib/trpc/client";
+
+/** Refetches the maintenance and every maintenance list. */
+export function useInvalidateMaintenance(id: number) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ return () =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.maintenance.get.queryKey({ id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.maintenance.list.queryKey(),
+ }),
+ ]);
+}
diff --git a/apps/dashboard/src/components/maintenances/use-maintenance-status.ts b/apps/dashboard/src/components/maintenances/use-maintenance-status.ts
new file mode 100644
index 000000000..650b5b8e2
--- /dev/null
+++ b/apps/dashboard/src/components/maintenances/use-maintenance-status.ts
@@ -0,0 +1,33 @@
+"use client";
+
+import { useEffect, useState } from "react";
+
+import {
+ type MaintenanceStatus,
+ getMaintenanceStatus,
+} from "@/data/overview-events.client";
+
+// setTimeout overflows past 2^31-1 ms and would fire immediately.
+const MAX_DELAY = 2 ** 31 - 1;
+
+/** `getMaintenanceStatus`, re-evaluated when `from` or `to` passes. */
+export function useMaintenanceStatus(maintenance: {
+ from: Date;
+ to: Date;
+}): MaintenanceStatus {
+ const [now, setNow] = useState(() => new Date());
+ const from = maintenance.from.getTime();
+ const to = maintenance.to.getTime();
+
+ useEffect(() => {
+ const next = [from, to].find((t) => t > now.getTime());
+ if (next === undefined) return;
+ const timer = setTimeout(
+ () => setNow(new Date()),
+ Math.min(next - now.getTime(), MAX_DELAY),
+ );
+ return () => clearTimeout(timer);
+ }, [from, to, now]);
+
+ return getMaintenanceStatus(maintenance, now);
+}
diff --git a/apps/dashboard/src/components/maintenances/use-update-maintenance.ts b/apps/dashboard/src/components/maintenances/use-update-maintenance.ts
new file mode 100644
index 000000000..93baf4772
--- /dev/null
+++ b/apps/dashboard/src/components/maintenances/use-update-maintenance.ts
@@ -0,0 +1,58 @@
+"use client";
+
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+
+import { toUpdateInput } from "@/data/maintenances.client";
+import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
+
+import { useInvalidateMaintenance } from "./use-invalidate-maintenance";
+
+type Patch = Partial<ReturnType<typeof toUpdateInput>>;
+
+/**
+ * `maintenance.update` takes the whole row, so the patch is spread over the
+ * cached row, which is patched right away: a second save that lands before
+ * the first one's refetch then carries the first one's values instead of
+ * reverting them. `onSuccess` runs after the refetch.
+ */
+export function useUpdateMaintenance(
+ id: number,
+ { onSuccess }: { onSuccess?: () => void } = {},
+) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const invalidate = useInvalidateMaintenance(id);
+ const queryKey = trpc.maintenance.get.queryKey({ id });
+ const mutation = useMutation(
+ trpc.maintenance.update.mutationOptions({
+ onSuccess: async () => {
+ await invalidate();
+ onSuccess?.();
+ },
+ onError: async (error) => {
+ toast.error(errorMessage(error, "Failed to save"));
+ await invalidate();
+ },
+ }),
+ );
+
+ return {
+ isPending: mutation.isPending,
+ update: (patch: Patch) => {
+ const maintenance = queryClient.getQueryData(queryKey);
+ if (!maintenance) return;
+ const input = { ...toUpdateInput(maintenance), ...patch };
+ queryClient.setQueryData(queryKey, {
+ ...maintenance,
+ title: input.title,
+ message: input.message,
+ from: input.startDate,
+ to: input.endDate,
+ pageComponentIds: input.pageComponents ?? maintenance.pageComponentIds,
+ });
+ mutation.mutate(input);
+ },
+ };
+}
diff --git a/apps/dashboard/src/components/status-pages/notifications.tsx b/apps/dashboard/src/components/status-pages/notifications.tsx
new file mode 100644
index 000000000..ab03d2505
--- /dev/null
+++ b/apps/dashboard/src/components/status-pages/notifications.tsx
@@ -0,0 +1,43 @@
+"use client";
+
+import { useQuery } from "@tanstack/react-query";
+
+import { Link } from "@/components/common/link";
+import {
+ Property,
+ PropertyLabel,
+ PropertyList,
+ PropertyValue,
+} from "@/components/content/property-list";
+import { useTRPC } from "@/lib/trpc/client";
+
+/** Who gets told when something is published on the page. */
+export function Notifications({ pageId }: { pageId: number }) {
+ const trpc = useTRPC();
+ const { data: subscribers } = useQuery(
+ trpc.pageSubscriber.list.queryOptions({ pageId }),
+ );
+ const active = subscribers?.filter(
+ (s) => s.acceptedAt !== null && s.unsubscribedAt === null,
+ );
+
+ return (
+ <PropertyList>
+ <Property>
+ <PropertyLabel>Subscribers</PropertyLabel>
+ <PropertyValue>
+ {active ? (
+ <Link
+ href={`/status-pages/${pageId}/subscribers`}
+ className="font-normal"
+ >
+ {active.length.toLocaleString()}
+ </Link>
+ ) : (
+ <span className="text-muted-foreground">–</span>
+ )}
+ </PropertyValue>
+ </Property>
+ </PropertyList>
+ );
+}
diff --git a/apps/dashboard/src/components/status-reports/status-report-actions.tsx b/apps/dashboard/src/components/status-reports/status-report-actions.tsx
new file mode 100644
index 000000000..e9cc91090
--- /dev/null
+++ b/apps/dashboard/src/components/status-reports/status-report-actions.tsx
@@ -0,0 +1,55 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useRouter } from "next/navigation";
+
+import { QuickActions } from "@/components/dropdowns/quick-actions";
+import { getActions } from "@/data/status-reports.client";
+import { useTRPC } from "@/lib/trpc/client";
+
+type StatusReport = NonNullable<RouterOutputs["statusReport"]["get"]>;
+
+export function StatusReportActions({
+ report,
+ publicUrl,
+}: {
+ report: StatusReport;
+ publicUrl: string;
+}) {
+ const trpc = useTRPC();
+ const router = useRouter();
+ const queryClient = useQueryClient();
+ const remove = useMutation(
+ trpc.statusReport.delete.mutationOptions({
+ onSuccess: async () => {
+ await Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.statusReport.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.page.list.queryKey(),
+ }),
+ ]);
+ router.push(`/status-pages/${report.pageId}/status-reports`);
+ },
+ }),
+ );
+ const actions = getActions({
+ "view-report": () => {
+ window.open(publicUrl, "_blank", "noopener,noreferrer");
+ },
+ });
+
+ return (
+ <QuickActions
+ actions={actions}
+ deleteAction={{
+ confirmationValue: report.title || "status report",
+ submitAction: async () => {
+ await remove.mutateAsync({ id: report.id });
+ },
+ }}
+ />
+ );
+}
diff --git a/apps/dashboard/src/components/status-reports/status-report-badge.tsx b/apps/dashboard/src/components/status-reports/status-report-badge.tsx
new file mode 100644
index 000000000..d45a3471b
--- /dev/null
+++ b/apps/dashboard/src/components/status-reports/status-report-badge.tsx
@@ -0,0 +1,37 @@
+import type { StatusReportStatus } from "@openstatus/db/src/schema";
+import type { PageComponentImpact } from "@openstatus/db/src/schema/page_components/constants";
+
+import { StatusBadge } from "@/components/common/status-badge";
+import {
+ impactDisplay,
+ statusVariants,
+} from "@/data/status-report-updates.client";
+
+type BadgeProps = Omit<
+ React.ComponentProps<typeof StatusBadge>,
+ "children" | "variant" | "dot"
+>;
+
+export function StatusReportStatusBadge({
+ status,
+ ...props
+}: BadgeProps & { status: StatusReportStatus }) {
+ return (
+ <StatusBadge variant={statusVariants[status]} dot {...props}>
+ <span className="capitalize">{status}</span>
+ </StatusBadge>
+ );
+}
+
+/** `null` is a legacy report without impact rows. */
+export function StatusReportImpactBadge({
+ impact,
+ ...props
+}: BadgeProps & { impact: PageComponentImpact | null }) {
+ const display = impactDisplay(impact);
+ return (
+ <StatusBadge variant={display.variant} {...props}>
+ {display.label}
+ </StatusBadge>
+ );
+}
diff --git a/apps/dashboard/src/components/status-reports/status-report-composer.tsx b/apps/dashboard/src/components/status-reports/status-report-composer.tsx
new file mode 100644
index 000000000..7fd807c51
--- /dev/null
+++ b/apps/dashboard/src/components/status-reports/status-report-composer.tsx
@@ -0,0 +1,354 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import type { StatusReportStatus } from "@openstatus/db/src/schema";
+import {
+ type PageComponentImpact,
+ pageComponentImpact,
+} from "@openstatus/db/src/schema/page_components/constants";
+import { statusReportStatus } from "@openstatus/db/src/schema/status_reports/constants";
+import { Close } from "@openstatus/icons";
+import { Button } from "@openstatus/ui/components/ui/button";
+import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
+import { Input } from "@openstatus/ui/components/ui/input";
+import { Label } from "@openstatus/ui/components/ui/label";
+import {
+ Select,
+ SelectContent,
+ SelectItem,
+ SelectTrigger,
+ SelectValue,
+} from "@openstatus/ui/components/ui/select";
+import { useQuery } from "@tanstack/react-query";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { StatusDot } from "@/components/common/status-dot";
+import {
+ ComponentImpact,
+ ComponentList,
+ ComponentListActions,
+ ComponentListAdd,
+ ComponentListItem,
+ ComponentListName,
+ ComponentListSelectTrigger,
+} from "@/components/content/component-list";
+import {
+ Composer,
+ ComposerFooter,
+ ComposerHeader,
+ ComposerPreview,
+ ComposerSection,
+ ComposerTextarea,
+} from "@/components/content/composer";
+import { TimelineAvatar, TimelineItem } from "@/components/content/timeline";
+import { personName } from "@/data/managed-incidents.client";
+import { toGroupNameLookup } from "@/data/page-components.client";
+import {
+ getNextStatus,
+ statusVariants,
+ toCreateStatusReportUpdateInput,
+} from "@/data/status-report-updates.client";
+import { formatDateForInput } from "@/lib/formatter";
+import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
+
+import { usePublishUpdate } from "./use-publish-update";
+
+type StatusReport = NonNullable<RouterOutputs["statusReport"]["get"]>;
+type Component = {
+ id: number;
+ name: string;
+ groupId?: number | null;
+ order?: number | null;
+ groupOrder?: number | null;
+};
+
+/**
+ * Publishes a status report update. Impact rows default to "No change"
+ * (carry the current impact; all operational once resolved); switching
+ * status resets the overrides.
+ */
+export function StatusReportComposer({
+ report,
+ currentImpacts,
+ pageComponents,
+ groups,
+ canNotify,
+}: {
+ report: StatusReport;
+ currentImpacts: Map<number, PageComponentImpact>;
+ /** Every component on the page; the ones not on the report can be added. */
+ pageComponents: Component[];
+ groups: { id: number; name: string }[];
+ /** Whether the plan includes subscriber notifications. */
+ canNotify: boolean;
+}) {
+ const trpc = useTRPC();
+ const { data: user } = useQuery(trpc.user.get.queryOptions());
+ const [message, setMessage] = useState("");
+ const [notifyChecked, setNotifyChecked] = useState(true);
+ const [selected, setSelected] = useState<StatusReportStatus | null>(null);
+ // null = now, resolved at publish time so an open composer never backdates.
+ const [date, setDate] = useState<string | null>(null);
+ const [overrides, setOverrides] = useState<Map<number, PageComponentImpact>>(
+ () => new Map(),
+ );
+ // null = the report's own components; an edit replaces the set for this update.
+ const [ids, setIds] = useState<number[] | null>(null);
+
+ const publish = usePublishUpdate(report.id);
+ const notify = canNotify && notifyChecked;
+ const status = selected ?? getNextStatus(report.status);
+ const now = formatDateForInput(new Date());
+ // the input's `max` is not enforced on the button handler
+ const invalidDate =
+ date !== null &&
+ (date === "" ||
+ Number.isNaN(new Date(date).getTime()) ||
+ new Date(date) > new Date());
+ const disabled = publish.isPending || !message.trim() || invalidDate;
+
+ const byId = new Map<number, Component>(
+ [...report.pageComponents, ...pageComponents].map((c) => [c.id, c]),
+ );
+ const componentIds = ids ?? report.pageComponents.map((c) => c.id);
+ const components = componentIds.flatMap((id) => byId.get(id) ?? []);
+ const addable = pageComponents.filter((c) => !componentIds.includes(c.id));
+ const groupOf = toGroupNameLookup(pageComponents, groups);
+ const reportHasImpacts = report.updates.some(
+ (u) => u.componentImpacts.length > 0,
+ );
+ const impactFor = (id: number): PageComponentImpact =>
+ overrides.get(id) ??
+ (status === "resolved"
+ ? "operational"
+ : (currentImpacts.get(id) ?? "operational"));
+
+ function reset() {
+ setMessage("");
+ setSelected(null);
+ setDate(null);
+ setOverrides(new Map());
+ setIds(null);
+ }
+
+ async function submit() {
+ if (disabled) return;
+ const promise = publish.publish(
+ toCreateStatusReportUpdateInput({
+ statusReportId: report.id,
+ values: {
+ status,
+ message: message.trim(),
+ date: date ? new Date(date) : new Date(),
+ componentImpacts: components.map((c) => ({
+ pageComponentId: c.id,
+ impact: impactFor(c.id),
+ })),
+ notifySubscribers: notify,
+ },
+ reportHasImpacts,
+ }),
+ );
+ toast.promise(promise, {
+ loading: "Publishing...",
+ success: "Update published",
+ error: (error) => errorMessage(error, "Failed to publish"),
+ });
+ await promise;
+ reset();
+ }
+
+ return (
+ <TimelineItem>
+ <TimelineAvatar
+ name={user ? personName(user) : null}
+ src={user?.photoUrl}
+ />
+ <Composer>
+ <ComposerHeader />
+ <ComposerTextarea
+ placeholder="What changed? Customers will read this on the status page."
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ onSubmit={() => submit().catch(console.error)}
+ />
+ <ComposerPreview value={message} />
+ {pageComponents.length ? (
+ <ComposerSection>
+ <div className="flex items-center justify-between gap-2">
+ <span className="text-muted-foreground text-xs font-light tracking-wide uppercase">
+ Affected components
+ </span>
+ <Button
+ variant="ghost"
+ size="sm"
+ className="text-muted-foreground -my-1 h-7 font-normal"
+ disabled={components.length === 0}
+ onClick={() =>
+ setOverrides(
+ new Map(components.map((c) => [c.id, "operational"])),
+ )
+ }
+ >
+ Mark all operational
+ </Button>
+ </div>
+ <ComponentList>
+ {components.map((component) => {
+ const override = overrides.get(component.id);
+ return (
+ <ComponentListItem key={component.id}>
+ <ComponentListName group={groupOf.get(component.id)}>
+ {component.name}
+ </ComponentListName>
+ <ComponentImpact
+ impact={currentImpacts.get(component.id)}
+ />
+ <ComponentListActions>
+ <Select
+ value={override ?? ""}
+ onValueChange={(value) => {
+ const impact = pageComponentImpact.find(
+ (i) => i === value,
+ );
+ if (!impact) return;
+ setOverrides((prev) =>
+ new Map(prev).set(component.id, impact),
+ );
+ }}
+ >
+ <ComponentListSelectTrigger
+ aria-label={`${component.name} impact`}
+ // fixed width keeps chevrons and close buttons in a column
+ className="text-foreground w-52 font-mono"
+ >
+ <SelectValue
+ placeholder={
+ status === "resolved" ? (
+ <ComponentImpact
+ impact="operational"
+ className="text-muted-foreground"
+ />
+ ) : (
+ <span className="text-muted-foreground inline-flex items-center gap-1.5">
+ <StatusDot />
+ No change
+ </span>
+ )
+ }
+ />
+ </ComponentListSelectTrigger>
+ <SelectContent>
+ {pageComponentImpact.map((impact) => (
+ <SelectItem key={impact} value={impact}>
+ <ComponentImpact impact={impact} />
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Button
+ variant="ghost"
+ size="icon"
+ className="text-muted-foreground size-7"
+ aria-label={`Leave ${component.name} out of this update`}
+ onClick={() =>
+ setIds(
+ componentIds.filter((id) => id !== component.id),
+ )
+ }
+ >
+ <Close />
+ </Button>
+ </ComponentListActions>
+ </ComponentListItem>
+ );
+ })}
+ </ComponentList>
+ <ComponentListAdd
+ components={addable}
+ groups={groups}
+ onAdd={(id) => {
+ setIds([...componentIds, id]);
+ // a component joins the report with a concrete impact
+ if (!report.pageComponents.some((c) => c.id === id)) {
+ setOverrides((prev) =>
+ new Map(prev).set(id, "degraded_performance"),
+ );
+ }
+ }}
+ />
+ </ComposerSection>
+ ) : null}
+ <ComposerFooter>
+ <div className="flex flex-wrap items-center gap-2">
+ <span>Status</span>
+ <Select
+ value={status}
+ onValueChange={(value) => {
+ const next = statusReportStatus.find((s) => s === value);
+ if (!next) return;
+ setSelected(next);
+ setOverrides(new Map());
+ }}
+ >
+ <SelectTrigger
+ size="sm"
+ aria-label="Status"
+ className="bg-background text-foreground font-mono"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {statusReportStatus.map((s) => (
+ <SelectItem key={s} value={s} className="font-mono">
+ <StatusDot variant={statusVariants[s]} />
+ <span className="capitalize">{s}</span>
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <span>at</span>
+ <Input
+ type="datetime-local"
+ aria-label="Date"
+ value={date ?? now}
+ max={now}
+ onChange={(e) => setDate(e.target.value)}
+ className="bg-background text-foreground h-8 w-auto font-mono md:text-sm"
+ />
+ </div>
+ <div className="ml-auto flex items-center gap-3">
+ <div className="flex items-center gap-2">
+ <Checkbox
+ id="notify-subscribers"
+ checked={notify}
+ disabled={!canNotify}
+ onCheckedChange={(value) => setNotifyChecked(value === true)}
+ />
+ <Label
+ htmlFor="notify-subscribers"
+ className="text-xs font-normal"
+ title={
+ canNotify
+ ? undefined
+ : "Subscriber notifications are not included in your plan."
+ }
+ >
+ Notify subscribers
+ </Label>
+ </div>
+ <Button
+ size="sm"
+ disabled={disabled}
+ onClick={() => submit().catch(console.error)}
+ >
+ Publish update
+ </Button>
+ </div>
+ </ComposerFooter>
+ </Composer>
+ </TimelineItem>
+ );
+}
diff --git a/apps/dashboard/src/components/status-reports/status-report-properties.tsx b/apps/dashboard/src/components/status-reports/status-report-properties.tsx
new file mode 100644
index 000000000..2caa9082a
--- /dev/null
+++ b/apps/dashboard/src/components/status-reports/status-report-properties.tsx
@@ -0,0 +1,80 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { useQuery } from "@tanstack/react-query";
+
+import { Link } from "@/components/common/link";
+import { StatusDot } from "@/components/common/status-dot";
+import {
+ Property,
+ PropertyLabel,
+ PropertyLink,
+ PropertyList,
+ PropertyValue,
+} from "@/components/content/property-list";
+import { statusVariants } from "@/data/status-report-updates.client";
+import { useFeature } from "@/hooks/use-feature";
+import { useTRPC } from "@/lib/trpc/client";
+
+type StatusReport = NonNullable<RouterOutputs["statusReport"]["get"]>;
+
+export function StatusReportProperties({
+ report,
+ publicUrl,
+}: {
+ report: StatusReport;
+ publicUrl: string;
+}) {
+ const trpc = useTRPC();
+ const incidentsEnabled = useFeature("incident-management");
+ const { data: incident } = useQuery({
+ ...trpc.incident.forStatusReport.queryOptions({
+ statusReportId: report.id,
+ }),
+ enabled: incidentsEnabled,
+ });
+ const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone;
+
+ return (
+ <PropertyList>
+ <Property>
+ <PropertyLabel>Status</PropertyLabel>
+ <PropertyValue>
+ <StatusDot variant={statusVariants[report.status]} />
+ <span className="capitalize">{report.status}</span>
+ </PropertyValue>
+ </Property>
+ <Property>
+ <PropertyLabel>Status page</PropertyLabel>
+ <PropertyValue>
+ <PropertyLink href={publicUrl}>{report.page.title}</PropertyLink>
+ </PropertyValue>
+ </Property>
+ {incidentsEnabled ? (
+ <Property>
+ <PropertyLabel>Incident</PropertyLabel>
+ <PropertyValue>
+ {incident ? (
+ <Link
+ href={`/incidents/${incident.id}`}
+ className="truncate font-normal"
+ >
+ {incident.title}
+ </Link>
+ ) : (
+ <span className="text-muted-foreground">None</span>
+ )}
+ </PropertyValue>
+ </Property>
+ ) : null}
+ <Property>
+ <PropertyLabel>Timezone</PropertyLabel>
+ <PropertyValue>
+ <span className="truncate" suppressHydrationWarning>
+ {timezone}
+ </span>
+ </PropertyValue>
+ </Property>
+ </PropertyList>
+ );
+}
diff --git a/apps/dashboard/src/components/status-reports/status-report-timeline.tsx b/apps/dashboard/src/components/status-reports/status-report-timeline.tsx
new file mode 100644
index 000000000..6daedc8c1
--- /dev/null
+++ b/apps/dashboard/src/components/status-reports/status-report-timeline.tsx
@@ -0,0 +1,188 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import {
+ type PageComponentImpact,
+ worstImpact,
+} from "@openstatus/db/src/schema/page_components/constants";
+import {
+ HoverCard,
+ HoverCardContent,
+ HoverCardTrigger,
+} from "@openstatus/ui/components/ui/hover-card";
+import { useMutation } from "@tanstack/react-query";
+import { useState } from "react";
+
+import {
+ ComponentImpact,
+ ComponentListName,
+} from "@/components/content/component-list";
+import { ProcessMessage } from "@/components/content/process-message";
+import {
+ TimelineBody,
+ TimelineContent,
+ TimelineHeader,
+ TimelineIndicator,
+ TimelineItem,
+ TimelineTime,
+ TimelineTitle,
+} from "@/components/content/timeline";
+import { QuickActions } from "@/components/dropdowns/quick-actions";
+import { FormSheetStatusReportUpdate } from "@/components/forms/status-report-update/sheet";
+import { icons } from "@/data/icons";
+import {
+ getActions,
+ impactsEqual,
+ statusVariants,
+} from "@/data/status-report-updates.client";
+import { useTRPC } from "@/lib/trpc/client";
+
+import { StatusReportImpactBadge } from "./status-report-badge";
+import { useInvalidateStatusReport } from "./use-invalidate-status-report";
+
+type StatusReport = NonNullable<RouterOutputs["statusReport"]["get"]>;
+type StatusReportUpdate = StatusReport["updates"][number];
+
+/** Worst impact of the update; hover lists each component's own impact. */
+function TimelineImpact({
+ impacts,
+}: {
+ impacts: {
+ id: number;
+ name: string;
+ group?: string;
+ impact: PageComponentImpact;
+ }[];
+}) {
+ const worst = worstImpact(impacts.map((i) => i.impact));
+ return (
+ <HoverCard openDelay={100} closeDelay={100}>
+ <HoverCardTrigger asChild>
+ <StatusReportImpactBadge
+ impact={worst}
+ tabIndex={0}
+ className="focus-visible:ring-ring/50 cursor-default outline-none focus-visible:ring-[3px]"
+ />
+ </HoverCardTrigger>
+ <HoverCardContent align="start" className="w-auto min-w-56 p-3">
+ <ul className="flex flex-col gap-1.5 text-xs">
+ {impacts.map((ci) => (
+ <li key={ci.id} className="flex items-center justify-between gap-4">
+ <ComponentListName group={ci.group}>{ci.name}</ComponentListName>
+ <ComponentImpact impact={ci.impact} />
+ </li>
+ ))}
+ </ul>
+ </HoverCardContent>
+ </HoverCard>
+ );
+}
+
+export function StatusReportTimelineItem({
+ report,
+ update,
+ index,
+ groupOf,
+}: {
+ report: StatusReport;
+ update: StatusReportUpdate;
+ /** 1-based, counted from the oldest update. */
+ index: number;
+ /** component id → group name, for disambiguating same-named components */
+ groupOf?: Map<number, string>;
+}) {
+ const trpc = useTRPC();
+ const [editing, setEditing] = useState(false);
+ const invalidate = useInvalidateStatusReport(report.id);
+ const edit = useMutation(
+ trpc.statusReport.updateStatusReportUpdate.mutationOptions({
+ onSuccess: invalidate,
+ }),
+ );
+ const remove = useMutation(
+ trpc.statusReport.deleteUpdate.mutationOptions({ onSuccess: invalidate }),
+ );
+ const components = report.pageComponents.map((c) => ({
+ id: c.id,
+ name: c.name,
+ }));
+ const Icon = icons.status[update.status];
+ const impacts = update.componentImpacts.flatMap((ci) => {
+ const component = components.find((c) => c.id === ci.pageComponentId);
+ return component
+ ? [
+ {
+ id: component.id,
+ name: component.name,
+ group: groupOf?.get(component.id),
+ impact: ci.impact,
+ },
+ ]
+ : [];
+ });
+
+ return (
+ <TimelineItem>
+ <TimelineIndicator variant={statusVariants[update.status]}>
+ <Icon />
+ </TimelineIndicator>
+ <TimelineContent>
+ <TimelineHeader>
+ <TimelineTitle>
+ <span className="capitalize">{update.status}</span>
+ {impacts.length ? <TimelineImpact impacts={impacts} /> : null}
+ </TimelineTitle>
+ <TimelineTime date={update.date} />
+ </TimelineHeader>
+ {update.message ? (
+ <TimelineBody className="prose prose-sm dark:prose-invert max-w-none">
+ <ProcessMessage value={update.message} />
+ </TimelineBody>
+ ) : null}
+ <div className="text-muted-foreground flex items-center justify-between gap-2 font-mono text-xs">
+ <span>#{index}</span>
+ <QuickActions
+ actions={getActions({ edit: () => setEditing(true) })}
+ deleteAction={{
+ description: `Permanently remove update #${index}. The report status is recomputed from the remaining updates.`,
+ submitAction: async () => {
+ await remove.mutateAsync({ id: update.id });
+ },
+ }}
+ />
+ </div>
+ </TimelineContent>
+ <FormSheetStatusReportUpdate
+ open={editing}
+ onOpenChange={setEditing}
+ defaultValues={{
+ message: update.message,
+ date: update.date,
+ status: update.status,
+ componentImpacts: update.componentImpacts.map((ci) => ({
+ pageComponentId: ci.pageComponentId,
+ impact: ci.impact,
+ })),
+ }}
+ components={components}
+ allowUnsetImpacts
+ onSubmit={async (values) => {
+ await edit.mutateAsync({
+ id: update.id,
+ statusReportId: report.id,
+ message: values.message,
+ status: values.status,
+ // replace-set semantics: untouched (incl. legacy) rows keep their set
+ componentImpacts: impactsEqual(
+ values.componentImpacts ?? [],
+ update.componentImpacts,
+ )
+ ? undefined
+ : values.componentImpacts,
+ date: values.date,
+ });
+ }}
+ />
+ </TimelineItem>
+ );
+}
diff --git a/apps/dashboard/src/components/status-reports/use-invalidate-status-report.ts b/apps/dashboard/src/components/status-reports/use-invalidate-status-report.ts
new file mode 100644
index 000000000..2e0f8d33e
--- /dev/null
+++ b/apps/dashboard/src/components/status-reports/use-invalidate-status-report.ts
@@ -0,0 +1,24 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+
+import { useTRPC } from "@/lib/trpc/client";
+
+/** Refetches the report, every report list and the page list. */
+export function useInvalidateStatusReport(id: number) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ return () =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.statusReport.get.queryKey({ id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.statusReport.list.queryKey(),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.page.list.queryKey(),
+ }),
+ ]);
+}
diff --git a/apps/dashboard/src/components/status-reports/use-publish-update.ts b/apps/dashboard/src/components/status-reports/use-publish-update.ts
new file mode 100644
index 000000000..95c9f97e5
--- /dev/null
+++ b/apps/dashboard/src/components/status-reports/use-publish-update.ts
@@ -0,0 +1,50 @@
+"use client";
+
+import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { toast } from "sonner";
+
+import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
+
+import { useInvalidateStatusReport } from "./use-invalidate-status-report";
+
+/**
+ * Posts a status-report update, notifies subscribers when asked, then
+ * refetches the report and any incident that embeds it. The update is
+ * persisted before notifying, so a notification failure is reported on its
+ * own and never rejects the publish (a retry would duplicate the update).
+ */
+export function usePublishUpdate(statusReportId: number) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const invalidate = useInvalidateStatusReport(statusReportId);
+ const create = useMutation(
+ trpc.statusReport.createStatusReportUpdate.mutationOptions(),
+ );
+ const notify = useMutation(
+ trpc.subscriberNotification.statusReport.mutationOptions(),
+ );
+
+ return {
+ isPending: create.isPending || notify.isPending,
+ async publish(input: Parameters<typeof create.mutateAsync>[0]) {
+ const update = await create.mutateAsync(input);
+ if (update && input.notifySubscribers) {
+ const fallback = "Update published, but subscribers were not notified";
+ try {
+ // resolves with success=false when the plan lacks subscribers
+ const result = await notify.mutateAsync({ id: update.id });
+ if (!result.success) toast.error(fallback);
+ } catch (error) {
+ toast.error(errorMessage(error, fallback));
+ }
+ }
+ await Promise.all([
+ invalidate(),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.get.queryKey(),
+ }),
+ ]);
+ },
+ };
+}
diff --git a/apps/dashboard/src/components/ui/checkbox-tree.tsx b/apps/dashboard/src/components/ui/checkbox-tree.tsx
index 736a664d9..d91049a39 100644
--- a/apps/dashboard/src/components/ui/checkbox-tree.tsx
+++ b/apps/dashboard/src/components/ui/checkbox-tree.tsx
@@ -5,6 +5,8 @@ import { Label } from "@openstatus/ui/components/ui/label";
import { cn } from "@openstatus/ui/lib/utils";
import { useId } from "react";
+import { toComponentSections } from "@/data/page-components.client";
+
export type CheckboxTreeItem = {
id: number;
label: string;
@@ -13,38 +15,31 @@ export type CheckboxTreeItem = {
/**
* Build a CheckboxTree shape from a flat list of page components plus their
- * optional groups. Components with a `groupId` nest under the matching group;
- * ungrouped components render as top-level leaves.
+ * optional groups, in page order. Components with a `groupId` nest under the
+ * matching group; ungrouped components render as top-level leaves. Group ids
+ * may collide with component ids, so callers treat tree ids as opaque.
*/
export function toCheckboxTreeItems(
- components: { id: number; name: string; groupId?: number | null }[],
+ components: {
+ id: number;
+ name: string;
+ groupId?: number | null;
+ order?: number | null;
+ groupOrder?: number | null;
+ }[],
groups: { id: number; name: string }[] = [],
): CheckboxTreeItem[] {
- const groupIds = new Set(groups.map((g) => g.id));
- const byGroup = new Map<number, { id: number; label: string }[]>();
- const ungrouped: CheckboxTreeItem[] = [];
-
- for (const c of components) {
- if (c.groupId != null && groupIds.has(c.groupId)) {
- const bucket = byGroup.get(c.groupId) ?? [];
- bucket.push({ id: c.id, label: c.name });
- byGroup.set(c.groupId, bucket);
- } else {
- ungrouped.push({ id: c.id, label: c.name });
- }
- }
-
- const groupItems: CheckboxTreeItem[] = groups
- .filter((g) => (byGroup.get(g.id)?.length ?? 0) > 0)
- .map((g) => ({
- id: g.id,
- label: g.name,
- children: byGroup.get(g.id),
- }));
-
- // Group the group IDs first (synthetic group ids may collide with component
- // ids in rare cases — callers should treat tree ids as opaque). Then leaves.
- return [...groupItems, ...ungrouped];
+ return toComponentSections(components, groups).flatMap((section) =>
+ section.group
+ ? [
+ {
+ id: section.group.id,
+ label: section.group.name,
+ children: section.items.map((c) => ({ id: c.id, label: c.name })),
+ },
+ ]
+ : section.items.map((c) => ({ id: c.id, label: c.name })),
+ );
}
export type CheckboxTreeProps = {
diff --git a/apps/dashboard/src/data/maintenances.client.ts b/apps/dashboard/src/data/maintenances.client.ts
index 4ca23e6a6..82ee52518 100644
--- a/apps/dashboard/src/data/maintenances.client.ts
+++ b/apps/dashboard/src/data/maintenances.client.ts
@@ -1,3 +1,4 @@
+import type { RouterOutputs } from "@openstatus/api";
import { Settings, Delete } from "@openstatus/icons";
export const actions = [
@@ -25,3 +26,17 @@ export const getActions = (
onClick: props[action.id as keyof typeof props],
}));
};
+
+type Maintenance = NonNullable<RouterOutputs["maintenance"]["get"]>;
+
+/** `maintenance.update` requires every field: start from the current row. */
+export function toUpdateInput(maintenance: Maintenance) {
+ return {
+ id: maintenance.id,
+ title: maintenance.title,
+ message: maintenance.message,
+ startDate: maintenance.from,
+ endDate: maintenance.to,
+ pageComponents: maintenance.pageComponentIds,
+ };
+}
diff --git a/apps/dashboard/src/data/overview-events.client.ts b/apps/dashboard/src/data/overview-events.client.ts
index 1f77612e4..a4c896148 100644
--- a/apps/dashboard/src/data/overview-events.client.ts
+++ b/apps/dashboard/src/data/overview-events.client.ts
@@ -8,6 +8,12 @@ import {
Maintenance as MaintenanceIcon,
} from "@openstatus/icons";
+import type { StatusVariant } from "@/components/common/status-dot";
+import {
+ reportResolvedAt,
+ reportStartedAt,
+} from "@/data/status-reports.client";
+
type Incident = RouterOutputs["monitorIncident"]["list"][number];
type StatusReport = RouterOutputs["statusReport"]["list"][number];
type Maintenance = RouterOutputs["maintenance"]["list"][number];
@@ -34,10 +40,21 @@ export const incidentStatusConfig = {
export type IncidentStatus = keyof typeof incidentStatusConfig;
export const maintenanceStatusConfig = {
- scheduled: { label: "Scheduled", color: "text-info/80" },
- "in-progress": { label: "In Progress", color: "text-info/80" },
- completed: { label: "Completed", color: "text-info/80" },
-} as const;
+ scheduled: { label: "Scheduled", color: "text-info/80", variant: "info" },
+ "in-progress": {
+ label: "In Progress",
+ color: "text-info/80",
+ variant: "warning",
+ },
+ completed: {
+ label: "Completed",
+ color: "text-info/80",
+ variant: "success",
+ },
+} as const satisfies Record<
+ string,
+ { label: string; color: string; variant: StatusVariant }
+>;
export type MaintenanceStatus = keyof typeof maintenanceStatusConfig;
@@ -59,20 +76,6 @@ export function getMaintenanceStatus(
return "in-progress";
}
-function reportStartedAt(report: StatusReport): Date {
- const dates = report.updates.map((u) => u.date.getTime());
- if (dates.length) return new Date(Math.min(...dates));
- return report.createdAt ?? new Date(0);
-}
-
-function reportResolvedAt(report: StatusReport): Date | null {
- if (report.status !== "resolved") return null;
- const dates = report.updates.map((u) => u.date.getTime());
- // legacy resolved report without updates: fall back to updatedAt
- if (!dates.length) return report.updatedAt ?? report.createdAt;
- return new Date(Math.max(...dates));
-}
-
export function getStartedAt(event: OverviewEvent): Date {
switch (event.type) {
case "incident":
diff --git a/apps/dashboard/src/data/page-components.client.ts b/apps/dashboard/src/data/page-components.client.ts
index 9aba51217..3beeb7bad 100644
--- a/apps/dashboard/src/data/page-components.client.ts
+++ b/apps/dashboard/src/data/page-components.client.ts
@@ -19,3 +19,80 @@ export const getActions = (
onClick: props[action.id as keyof typeof props],
}));
};
+
+type OrderedComponent = {
+ id: number;
+ name: string;
+ groupId?: number | null;
+ order?: number | null;
+ groupOrder?: number | null;
+};
+
+export type ComponentSection<C extends OrderedComponent> = {
+ /** null for a run of ungrouped components */
+ group: { id: number; name: string } | null;
+ items: C[];
+};
+
+/**
+ * Splits components into sections in page order, as the components config
+ * and the public page show them: ungrouped components by `order`, a group
+ * placed at its first member's `order`, members by `groupOrder`. Consecutive
+ * ungrouped components share one section; empty groups are dropped.
+ */
+export function toComponentSections<C extends OrderedComponent>(
+ components: C[],
+ groups: { id: number; name: string }[] = [],
+): ComponentSection<C>[] {
+ const groupById = new Map(groups.map((g) => [g.id, g]));
+ const members = new Map<number, C[]>();
+ const ungrouped: C[] = [];
+ for (const c of components) {
+ if (c.groupId != null && groupById.has(c.groupId)) {
+ members.set(c.groupId, [...(members.get(c.groupId) ?? []), c]);
+ } else {
+ ungrouped.push(c);
+ }
+ }
+
+ const entries: { order: number; section: ComponentSection<C> }[] = [];
+ for (const c of ungrouped) {
+ entries.push({ order: c.order ?? 0, section: { group: null, items: [c] } });
+ }
+ for (const [groupId, items] of members) {
+ const group = groupById.get(groupId);
+ if (!group) continue;
+ items.sort((a, b) => (a.groupOrder ?? 0) - (b.groupOrder ?? 0));
+ entries.push({
+ order: Math.min(...items.map((c) => c.order ?? 0)),
+ section: { group: { id: group.id, name: group.name }, items },
+ });
+ }
+ entries.sort((a, b) => a.order - b.order);
+
+ // merge adjacent ungrouped singletons into one run
+ const sections: ComponentSection<C>[] = [];
+ for (const { section } of entries) {
+ const last = sections.at(-1);
+ if (section.group === null && last?.group === null) {
+ last.items.push(...section.items);
+ } else {
+ sections.push(section);
+ }
+ }
+ return sections;
+}
+
+/** componentId -> group name, for components in a known group. */
+export function toGroupNameLookup(
+ components: { id: number; groupId?: number | null }[],
+ groups: { id: number; name: string }[],
+): Map<number, string> {
+ const groupName = new Map(groups.map((g) => [g.id, g.name]));
+ const lookup = new Map<number, string>();
+ for (const c of components) {
+ const name = c.groupId != null ? groupName.get(c.groupId) : undefined;
+ if (name) lookup.set(c.id, name);
+ }
+ return lookup;
+}
diff --git a/apps/dashboard/src/data/status-pages.client.ts b/apps/dashboard/src/data/status-pages.client.ts
index 25b1b9a08..14eaca43f 100644
--- a/apps/dashboard/src/data/status-pages.client.ts
+++ b/apps/dashboard/src/data/status-pages.client.ts
@@ -1,5 +1,12 @@
import { Settings, Copy, Delete } from "@openstatus/icons";
+export function getPageUrl(page: {
+ slug: string;
+ customDomain: string | null;
+}): string {
+ return `https://${page.customDomain || `${page.slug}.openstatus.dev`}`;
+}
+
export const actions = [
{
id: "edit",
diff --git a/apps/dashboard/src/data/status-report-updates.client.ts b/apps/dashboard/src/data/status-report-updates.client.ts
index 1cde9fcd0..9d21ea24d 100644
--- a/apps/dashboard/src/data/status-report-updates.client.ts
+++ b/apps/dashboard/src/data/status-report-updates.client.ts
@@ -8,27 +8,23 @@ import type { FormValues as StatusReportUpdateFormValues } from "@/components/fo
export const impactConfig = {
operational: {
label: "Operational",
- color:
- "text-success/80 data-[state=selected]:bg-success/10 data-[state=selected]:text-success",
+ variant: "success",
},
degraded_performance: {
label: "Degraded performance",
- color:
- "text-warning/80 data-[state=selected]:bg-warning/10 data-[state=selected]:text-warning",
+ variant: "warning",
},
partial_outage: {
label: "Partial outage",
- color:
- "text-warning/80 data-[state=selected]:bg-warning/10 data-[state=selected]:text-warning",
+ variant: "warning",
},
major_outage: {
label: "Major outage",
- color:
- "text-destructive/80 data-[state=selected]:bg-destructive/10 data-[state=selected]:text-destructive",
+ variant: "destructive",
},
} as const satisfies Record<
PageComponentImpact,
- { label: string; color: string }
+ { label: string; variant: StatusVariant }
>;
/** Set equality regardless of order — used to skip no-op impact writes. */
@@ -47,8 +43,13 @@ export function impactsEqual(
// legacy report (created before impact tracking): no impact rows
export const untriagedImpact = {
label: "Untriaged",
- color: "text-muted-foreground/80",
-} as const;
+ variant: "default",
+} as const satisfies { label: string; variant: StatusVariant };
+
+/** Label + dot variant for an impact; nullish reads as untriaged. */
+export function impactDisplay(impact: PageComponentImpact | null | undefined) {
+ return impact ? impactConfig[impact] : untriagedImpact;
+}
export const actions = [
{
@@ -116,24 +117,6 @@ export function getNextStatus(currentStatus: string): StatusReportStatus {
);
}
-export function defaultComponentImpacts({
- components,
- currentImpacts,
- nextStatus,
-}: {
- components: { id: number }[];
- currentImpacts: Map<number, PageComponentImpact>;
- nextStatus: StatusReportStatus;
-}): NonNullable<StatusReportUpdateFormValues["componentImpacts"]> {
- return components.map((c) => ({
- pageComponentId: c.id,
- impact:
- nextStatus === "resolved"
- ? "operational"
- : (currentImpacts.get(c.id) ?? "operational"),
- }));
-}
-
// a legacy report stays legacy unless the operator actively sets a
// non-operational impact — never silently flip it green
export function toCreateStatusReportUpdateInput({
diff --git a/apps/dashboard/src/data/status-reports.client.ts b/apps/dashboard/src/data/status-reports.client.ts
index 6eb21c60e..710d7a556 100644
--- a/apps/dashboard/src/data/status-reports.client.ts
+++ b/apps/dashboard/src/data/status-reports.client.ts
@@ -1,18 +1,29 @@
-import { Settings, Show, Add, Delete } from "@openstatus/icons";
+import { Show, Delete } from "@openstatus/icons";
+
+type StatusReportWithUpdates = {
+ status: string;
+ createdAt: Date | null;
+ updatedAt: Date | null;
+ updates: { date: Date }[];
+};
+
+/** Earliest update, else the row's creation. */
+export function reportStartedAt(report: StatusReportWithUpdates): Date {
+ const dates = report.updates.map((u) => u.date.getTime());
+ if (dates.length) return new Date(Math.min(...dates));
+ return report.createdAt ?? new Date(0);
+}
+
+/** Latest update once resolved; `null` while the report is open. */
+export function reportResolvedAt(report: StatusReportWithUpdates): Date | null {
+ if (report.status !== "resolved") return null;
+ const dates = report.updates.map((u) => u.date.getTime());
+ // legacy resolved report without updates: fall back to updatedAt
+ if (!dates.length) return report.updatedAt ?? report.createdAt;
+ return new Date(Math.max(...dates));
+}
export const actions = [
- {
- id: "edit",
- label: "Settings",
- icon: Settings,
- variant: "default" as const,
- },
- {
- id: "create-update",
- label: "Create Update",
- icon: Add,
- variant: "default" as const,
- },
{
id: "view-report",
label: "View Report",
diff --git a/apps/dashboard/src/hooks/use-hydrated.ts b/apps/dashboard/src/hooks/use-hydrated.ts
new file mode 100644
index 000000000..2f4cab85c
--- /dev/null
+++ b/apps/dashboard/src/hooks/use-hydrated.ts
@@ -0,0 +1,16 @@
+import { useSyncExternalStore } from "react";
+
+const subscribe = () => () => {};
+
+/**
+ * false on the server and during hydration, true afterwards. Gate output that
+ * depends on the browser (timezone, locale) so SSR and the first client
+ * render match; `suppressHydrationWarning` would keep the server text.
+ */
+export function useHydrated() {
+ return useSyncExternalStore(
+ subscribe,
+ () => true,
+ () => false,
+ );
+}
diff --git a/apps/dashboard/src/lib/trpc/error.ts b/apps/dashboard/src/lib/trpc/error.ts
new file mode 100644
index 000000000..3074b978c
--- /dev/null
+++ b/apps/dashboard/src/lib/trpc/error.ts
@@ -0,0 +1,9 @@
+import { isTRPCClientError } from "@trpc/client";
+
+/** What to show for a failed call: the server's message, else `fallback`. */
+export function errorMessage(
+ error: unknown,
+ fallback = "Something went wrong",
+): string {
+ return isTRPCClientError(error) ? error.message : fallback;
+}
diff --git a/packages/api/src/router/maintenance.ts b/packages/api/src/router/maintenance.ts
index 12b46da7c..d04e9424c 100644
--- a/packages/api/src/router/maintenance.ts
+++ b/packages/api/src/router/maintenance.ts
@@ -3,6 +3,7 @@ import { NotFoundError } from "@openstatus/services";
import {
createMaintenance,
deleteMaintenance,
+ getMaintenance,
listMaintenances,
updateMaintenance,
} from "@openstatus/services/maintenance";
@@ -35,6 +36,19 @@ export const maintenanceRouter = createTRPCRouter({
}
}),
+ get: protectedProcedure
+ .input(z.object({ id: z.number() }))
+ .query(async ({ ctx, input }) => {
+ try {
+ return await getMaintenance({
+ ctx: toServiceCtx(ctx),
+ input: { id: input.id },
+ });
+ } catch (err) {
+ toTRPCError(err);
+ }
+ }),
+
list: protectedProcedure
.input(
z
diff --git a/packages/api/src/router/statusReport.ts b/packages/api/src/router/statusReport.ts
index aa8734be4..b682b5008 100644
--- a/packages/api/src/router/statusReport.ts
+++ b/packages/api/src/router/statusReport.ts
@@ -58,7 +58,8 @@ const updateStatusTRPCInput = z.object({
id: z.number(),
pageComponents: z.array(z.number()).optional(),
title: z.string(),
- status: CreateStatusReportInput.shape.status,
+ // A defined status rewrites the latest update, so title-only edits omit it.
+ status: CreateStatusReportInput.shape.status.optional(),
});
export const statusReportRouter = createTRPCRouter({
diff --git a/packages/services/src/incident/list-events.ts b/packages/services/src/incident/list-events.ts
index 048ce7f81..2ce56a56d 100644
--- a/packages/services/src/incident/list-events.ts
+++ b/packages/services/src/incident/list-events.ts
@@ -27,6 +27,7 @@ export async function listIncidentEvents(args: {
firstName: true,
lastName: true,
email: true,
+ photoUrl: true,
},
},
},