Skip to content

Open-source status page, incident response and uptime monitoring

feat: dashboard incident details pages (#2821)

Maximilian Kaske246d9bd50ed7
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
index 31791ccae..3aa26f6e1 100644
--- a/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
@@ -1,7 +1,6 @@
"use client";
import type { IncidentStatus } from "@openstatus/db/src/schema/incidents/constants";
-import { Badge } from "@openstatus/ui/components/ui/badge";
import {
Tabs,
TabsContent,
@@ -9,29 +8,50 @@ import {
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,
+ DetailContent,
+ DetailHeader,
+ DetailMain,
+ DetailMeta,
+ DetailMetaItem,
+ DetailSection,
+ DetailSectionTitle,
+} from "@/components/content/detail";
import {
EmptyStateContainer,
EmptyStateTitle,
} from "@/components/content/empty-state";
import {
- Section,
- SectionDescription,
- SectionGroup,
- SectionHeader,
- SectionTitle,
-} from "@/components/content/section";
+ Property,
+ PropertyLabel,
+ PropertyList,
+ PropertyValue,
+} from "@/components/content/property-list";
+import { SectionGroup } from "@/components/content/section";
+import {
+ IncidentActions,
+ hasIncidentActions,
+} from "@/components/incidents/incident-actions";
import { IncidentComposer } from "@/components/incidents/incident-composer";
+import { IncidentHeading } from "@/components/incidents/incident-heading";
import { IncidentPostmortem } from "@/components/incidents/incident-postmortem";
import { IncidentProperties } from "@/components/incidents/incident-properties";
import { IncidentStatusReport } from "@/components/incidents/incident-status-report";
import { IncidentTimeline } from "@/components/incidents/incident-timeline";
import { ResolveReportDialog } from "@/components/incidents/resolve-report-dialog";
-import { severityConfig } from "@/data/managed-incidents.client";
+import { incidentEndedAt, personName } from "@/data/managed-incidents.client";
import { useFeature } from "@/hooks/use-feature";
import { useTRPC } from "@/lib/trpc/client";
-import { cn } from "@/lib/utils";
+
+function slackChannelUrl(teamId: string, channelId: string): string {
+ return `https://slack.com/app_redirect?team=${teamId}&channel=${channelId}`;
+}
export function Client({ id }: { id: number }) {
const trpc = useTRPC();
@@ -61,6 +81,8 @@ export function Client({ id }: { id: number }) {
const canNotify = workspace?.limits["status-subscribers"] === true;
const report = incident.statusReport;
+ const closed = incident.closedAt !== null;
+ const endedAt = incidentEndedAt(incident);
const onStatusChanged = (status: IncidentStatus, note: string) => {
if (
(status === "resolved" || status === "canceled") &&
@@ -78,38 +100,73 @@ export function Client({ id }: { id: number }) {
};
return (
- <SectionGroup>
- <Section>
- <SectionHeader>
- <SectionTitle className="flex items-center gap-2">
- {incident.title}
- <Badge
- variant="outline"
- className={cn(
- "font-mono",
- severityConfig[incident.severity].className,
- )}
- >
- {severityConfig[incident.severity].label}
- </Badge>
- </SectionTitle>
- {incident.summary ? (
- <SectionDescription>{incident.summary}</SectionDescription>
- ) : null}
- </SectionHeader>
- <div className="grid gap-6 lg:grid-cols-[minmax(0,1fr)_320px]">
- <Tabs defaultValue="timeline" className="min-w-0">
+ <SectionGroup className="max-w-6xl">
+ <DetailHeader>
+ <IncidentHeading
+ incident={incident}
+ actions={
+ hasIncidentActions(incident) ? (
+ <IncidentActions incident={incident} />
+ ) : null
+ }
+ />
+ <DetailMeta>
+ <DetailMetaItem>
+ Declared by
+ <span className="text-foreground">
+ {personName(incident.declaredByUser) ?? "System"}
+ </span>
+ </DetailMetaItem>
+ <DetailMetaItem>
+ <HoverCardTimestamp date={incident.declaredAt} side="bottom">
+ <time dateTime={incident.declaredAt.toISOString()}>
+ {formatDistanceToNow(incident.declaredAt, { addSuffix: true })}
+ </time>
+ </HoverCardTimestamp>
+ </DetailMetaItem>
+ {incident.closedAt ? (
+ <DetailMetaItem>
+ Closed
+ <HoverCardTimestamp date={incident.closedAt} side="bottom">
+ <time dateTime={incident.closedAt.toISOString()}>
+ {formatDistanceToNow(incident.closedAt, { addSuffix: true })}
+ </time>
+ </HoverCardTimestamp>
+ </DetailMetaItem>
+ ) : (
+ <DetailMetaItem>
+ {endedAt ? "Lasted" : "Ongoing for"}
+ <span className="text-foreground font-mono">
+ {formatDistanceStrict(
+ incident.startedAt,
+ endedAt ?? new Date(),
+ )}
+ </span>
+ </DetailMetaItem>
+ )}
+ </DetailMeta>
+ </DetailHeader>
+ <DetailContent>
+ <DetailMain>
+ <Tabs defaultValue="timeline" className="gap-4">
<TabsList>
- <TabsTrigger value="timeline">Timeline</TabsTrigger>
+ <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" className="grid gap-6">
- {incident.closedAt === null ? (
+ <TabsContent value="timeline" className="flex flex-col gap-8">
+ {closed ? null : (
<IncidentComposer
incident={incident}
onStatusChanged={onStatusChanged}
/>
- ) : null}
+ )}
<IncidentTimeline events={events ?? []} />
</TabsContent>
<TabsContent value="postmortem">
@@ -119,15 +176,41 @@ export function Client({ id }: { id: number }) {
/>
</TabsContent>
</Tabs>
- <aside className="grid content-start gap-6">
- <IncidentProperties incident={incident} />
- <div className="grid gap-2 border-t pt-4">
- <h3 className="text-sm font-medium">Status report</h3>
- <IncidentStatusReport incident={incident} canNotify={canNotify} />
- </div>
- </aside>
- </div>
- </Section>
+ </DetailMain>
+ <DetailAside>
+ <DetailSection>
+ <DetailSectionTitle>Properties</DetailSectionTitle>
+ <IncidentProperties
+ incident={incident}
+ lastUpdateAt={events?.[0]?.createdAt}
+ onStatusChanged={onStatusChanged}
+ />
+ </DetailSection>
+ <DetailSection>
+ <DetailSectionTitle>Communication</DetailSectionTitle>
+ <IncidentStatusReport incident={incident} canNotify={canNotify} />
+ <PropertyList>
+ <Property>
+ <PropertyLabel>Slack</PropertyLabel>
+ <PropertyValue>
+ {incident.slackTeamId && incident.slackChannelId ? (
+ <Link
+ href={slackChannelUrl(
+ incident.slackTeamId,
+ incident.slackChannelId,
+ )}
+ >
+ Open channel
+ </Link>
+ ) : (
+ <span className="text-muted-foreground">No channel</span>
+ )}
+ </PropertyValue>
+ </Property>
+ </PropertyList>
+ </DetailSection>
+ </DetailAside>
+ </DetailContent>
{report ? (
<ResolveReportDialog
incidentId={incident.id}
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/client.tsx b/apps/dashboard/src/app/(dashboard)/incidents/client.tsx
index b67b56094..9b5e39e1a 100644
--- a/apps/dashboard/src/app/(dashboard)/incidents/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/incidents/client.tsx
@@ -1,6 +1,5 @@
"use client";
-import { Button } from "@openstatus/ui/components/ui/button";
import { useQuery } from "@tanstack/react-query";
import {
@@ -13,12 +12,11 @@ import {
SectionDescription,
SectionGroup,
SectionHeader,
- SectionHeaderRow,
SectionTitle,
} from "@/components/content/section";
import { columns } from "@/components/data-table/managed-incidents/columns";
-import { DeclareIncidentButton } from "@/components/incidents/declare-incident-button";
import { DataTable } from "@/components/ui/data-table/data-table";
+import { DataTablePaginationSimple } from "@/components/ui/data-table/data-table-pagination";
import { useFeature } from "@/hooks/use-feature";
import { useTRPC } from "@/lib/trpc/client";
@@ -46,20 +44,12 @@ export function Client() {
return (
<SectionGroup>
<Section>
- <SectionHeaderRow>
- <SectionHeader>
- <SectionTitle>Incidents</SectionTitle>
- <SectionDescription>
- Declare an incident when the team is responding to an outage: a
- severity, a commander and a timeline, resolved and closed with a
- postmortem. Monitor downtime is detected automatically and lives
- on each monitor.
- </SectionDescription>
- </SectionHeader>
- <DeclareIncidentButton>
- <Button size="sm">Declare incident</Button>
- </DeclareIncidentButton>
- </SectionHeaderRow>
+ <SectionHeader>
+ <SectionTitle>Incidents</SectionTitle>
+ <SectionDescription>
+ Declare and track the incidents your team is responding to.
+ </SectionDescription>
+ </SectionHeader>
{!incidents ? null : incidents.length === 0 ? (
<EmptyStateContainer>
<EmptyStateTitle>No incidents declared</EmptyStateTitle>
@@ -71,7 +61,11 @@ export function Client() {
</EmptyStateContainer>
) : (
// incident.list already sorts open first, then newest declared.
- <DataTable columns={columns} data={incidents} />
+ <DataTable
+ columns={columns}
+ data={incidents}
+ paginationComponent={DataTablePaginationSimple}
+ />
)}
</Section>
</SectionGroup>
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/nav-actions.tsx b/apps/dashboard/src/app/(dashboard)/incidents/nav-actions.tsx
index 768c5c97f..24b6954b4 100644
--- a/apps/dashboard/src/app/(dashboard)/incidents/nav-actions.tsx
+++ b/apps/dashboard/src/app/(dashboard)/incidents/nav-actions.tsx
@@ -1,9 +1,26 @@
+"use client";
+
+import { Button } from "@openstatus/ui/components/ui/button";
+import { useParams } from "next/navigation";
+
+import { DeclareIncidentButton } from "@/components/incidents/declare-incident-button";
import { NavFeedback } from "@/components/nav/nav-feedback";
+import { useFeature } from "@/hooks/use-feature";
export function NavActions() {
+ const params = useParams<{ id?: string }>();
+ const enabled = useFeature("incident-management");
+ // The layout also wraps /incidents/[id]; the detail page has its own actions.
+ const isList = !params.id;
+
return (
<div className="flex items-center gap-2 text-sm">
<NavFeedback />
+ {enabled && isList ? (
+ <DeclareIncidentButton>
+ <Button size="sm">Declare incident</Button>
+ </DeclareIncidentButton>
+ ) : null}
</div>
);
}
diff --git a/apps/dashboard/src/app/(dashboard)/overview/layout.tsx b/apps/dashboard/src/app/(dashboard)/overview/layout.tsx
index afea19169..ee1ac8185 100644
--- a/apps/dashboard/src/app/(dashboard)/overview/layout.tsx
+++ b/apps/dashboard/src/app/(dashboard)/overview/layout.tsx
@@ -20,6 +20,10 @@ export default async function Layout({
queryClient.prefetchQuery(trpc.monitorIncident.list.queryOptions()),
queryClient.prefetchQuery(trpc.statusReport.list.queryOptions({})),
queryClient.prefetchQuery(trpc.maintenance.list.queryOptions()),
+ // Throws FORBIDDEN without the feature; prefetchQuery swallows it.
+ queryClient.prefetchQuery(
+ trpc.incident.list.queryOptions({ status: ["open", "mitigated"] }),
+ ),
]);
return (
diff --git a/apps/dashboard/src/components/command-menu/command-menu.tsx b/apps/dashboard/src/components/command-menu/command-menu.tsx
index bd544cf72..d717ac273 100644
--- a/apps/dashboard/src/components/command-menu/command-menu.tsx
+++ b/apps/dashboard/src/components/command-menu/command-menu.tsx
@@ -21,11 +21,13 @@ import { FormSheetMaintenanceCreate } from "@/components/forms/maintenance/sheet
import { FormSheetStatusReportUpdateCreate } from "@/components/forms/status-report-update/sheet-create";
import { FormSheetStatusReportCreate } from "@/components/forms/status-report/sheet-create";
import { FormDialogSupportContact } from "@/components/forms/support-contact/dialog";
+import { DeclareIncidentButton } from "@/components/incidents/declare-incident-button";
import { scrollToHash, useScrollToHash } from "@/hooks/use-scroll-to-hash";
import { switchWorkspace } from "@/lib/workspace-cookie";
import { GroupView } from "./group-view";
import {
+ incidentsGroup,
maintenancesGroup,
monitorsGroup,
statusPagesGroup,
@@ -146,12 +148,13 @@ export function CommandMenu() {
maintenances: data.sortedMaintenances,
})
: [
+ incidentsGroup(data.incidents),
monitorsGroup(data.monitors),
statusPagesGroup(data.statusPages),
statusReportsGroup(data.sortedStatusReports),
maintenancesGroup(data.sortedMaintenances, data.pageTitleById),
- navigationGroup(),
- createGroup(),
+ navigationGroup({ incidents: data.incidentsEnabled }),
+ createGroup({ incidents: data.incidentsEnabled }),
settingsGroup(),
workspacesGroup(data.otherWorkspaces, switchWorkspace),
helpGroup(),
@@ -255,6 +258,15 @@ export function CommandMenu() {
open={activeSheet?.sheet === "support"}
onOpenChange={(o) => setActiveSheet(o ? { sheet: "support" } : null)}
/>
+ {/* Mounted on demand: the sheet fetches integrations as soon as it renders. */}
+ {data.incidentsEnabled && activeSheet?.sheet === "declare-incident" ? (
+ <DeclareIncidentButton
+ open
+ onOpenChange={(o) => {
+ if (!o) setActiveSheet(null);
+ }}
+ />
+ ) : null}
{reportForUpdate ? (
<FormSheetStatusReportUpdateCreate
report={reportForUpdate}
diff --git a/apps/dashboard/src/components/command-menu/groups/entities.ts b/apps/dashboard/src/components/command-menu/groups/entities.ts
index 54decf185..99c7c4a45 100644
--- a/apps/dashboard/src/components/command-menu/groups/entities.ts
+++ b/apps/dashboard/src/components/command-menu/groups/entities.ts
@@ -7,6 +7,26 @@ type StatusPage = RouterOutputs["page"]["list"][number];
type StatusReport = RouterOutputs["statusReport"]["list"][number];
type Maintenance = RouterOutputs["maintenance"]["list"][number];
type Workspace = RouterOutputs["workspace"]["list"][number];
+type Incident = RouterOutputs["incident"]["list"][number];
+
+export function incidentsGroup(
+ incidents: Incident[] | undefined,
+): CommandMenuGroup | null {
+ if (!incidents || incidents.length === 0) return null;
+ return {
+ heading: "Incidents",
+ idleLimit: 5,
+ items: incidents.map((i) => ({
+ value: `incident-${i.id}`,
+ label: i.title,
+ description: `${i.status} · ${i.severity}`,
+ keywords: [i.title, i.status, i.severity, i.commander?.name].filter(
+ Boolean,
+ ) as string[],
+ action: { type: "navigate", href: `/incidents/${i.id}` },
+ })),
+ };
+}
export function monitorsGroup(
monitors: Monitor[] | undefined,
diff --git a/apps/dashboard/src/components/command-menu/groups/static.ts b/apps/dashboard/src/components/command-menu/groups/static.ts
index a8c8e36cf..66fcc069f 100644
--- a/apps/dashboard/src/components/command-menu/groups/static.ts
+++ b/apps/dashboard/src/components/command-menu/groups/static.ts
@@ -2,15 +2,24 @@ import { Dark, Light } from "@openstatus/icons";
import { AtSign, KeyRound, Palette, Pencil, Plus, Users } from "lucide-react";
import { HELP_LINKS, HELP_SUPPORT } from "@/config/help";
-import { NAV_MENU_ITEMS } from "@/config/nav";
+import { NAV, NAV_MENU_ITEMS } from "@/config/nav";
import { SETTINGS_TABS } from "@/config/settings";
import type { CommandMenuGroup, CommandMenuItem } from "../types";
-export function navigationGroup(): CommandMenuGroup {
+// Incident entries are feature-flagged. Unlike the sidebar, Incidents sits
+// right below Overview: the palette is for reaching the urgent thing fast.
+export function navigationGroup({
+ incidents,
+}: {
+ incidents: boolean;
+}): CommandMenuGroup {
+ const items = incidents
+ ? [...NAV_MENU_ITEMS.slice(0, 1), NAV.incidents, ...NAV_MENU_ITEMS.slice(1)]
+ : NAV_MENU_ITEMS;
return {
heading: "Navigation",
- items: NAV_MENU_ITEMS.map((item) => ({
+ items: items.map((item) => ({
value: item.label,
label: item.label,
icon: item.icon,
@@ -20,6 +29,16 @@ export function navigationGroup(): CommandMenuGroup {
};
}
+export function declareIncidentItem(): CommandMenuItem {
+ return {
+ value: "Declare Incident",
+ label: "Declare Incident",
+ icon: Plus,
+ keywords: ["new incident", "outage", "commander", "severity"],
+ action: { type: "sheet", sheet: { sheet: "declare-incident" } },
+ };
+}
+
export function createStatusReportItem(pageId?: number): CommandMenuItem {
return {
value: pageId ? "create-status-report" : "Create Status Report",
@@ -40,10 +59,15 @@ export function createMaintenanceItem(pageId?: number): CommandMenuItem {
};
}
-export function createGroup(): CommandMenuGroup {
+export function createGroup({
+ incidents,
+}: {
+ incidents: boolean;
+}): CommandMenuGroup {
return {
heading: "Create",
items: [
+ ...(incidents ? [declareIncidentItem()] : []),
{
value: "Create Monitor",
label: "Create Monitor",
diff --git a/apps/dashboard/src/components/command-menu/types.ts b/apps/dashboard/src/components/command-menu/types.ts
index df779a496..859f82772 100644
--- a/apps/dashboard/src/components/command-menu/types.ts
+++ b/apps/dashboard/src/components/command-menu/types.ts
@@ -10,6 +10,7 @@ type CommandSheetContext = {
maintenance: { pageId?: number };
support: Record<never, never>;
"status-report-update": { reportId: number };
+ "declare-incident": Record<never, never>;
};
export type CommandSheet = {
diff --git a/apps/dashboard/src/components/command-menu/use-command-menu-data.ts b/apps/dashboard/src/components/command-menu/use-command-menu-data.ts
index 7296f31ef..dea8196df 100644
--- a/apps/dashboard/src/components/command-menu/use-command-menu-data.ts
+++ b/apps/dashboard/src/components/command-menu/use-command-menu-data.ts
@@ -2,10 +2,12 @@
import { useQuery } from "@tanstack/react-query";
+import { useFeature } from "@/hooks/use-feature";
import { useTRPC } from "@/lib/trpc/client";
export function useCommandMenuData({ open }: { open: boolean }) {
const trpc = useTRPC();
+ const incidentsEnabled = useFeature("incident-management");
// `enabled: open` keeps the always-mounted palette from fetching on every
// dashboard load; data stays cached once fetched.
@@ -29,6 +31,13 @@ export function useCommandMenuData({ open }: { open: boolean }) {
const { data: maintenances } = useQuery(
trpc.maintenance.list.queryOptions(undefined, { enabled: open }),
);
+ // Server rejects the query without the feature — never fire it unflagged.
+ // Server order is already open → mitigated → newest declared.
+ const { data: incidents } = useQuery(
+ trpc.incident.list.queryOptions(undefined, {
+ enabled: open && incidentsEnabled,
+ }),
+ );
const otherWorkspaces =
workspaces?.filter((w) => w.slug !== workspace?.slug) ?? [];
@@ -55,6 +64,8 @@ export function useCommandMenuData({ open }: { open: boolean }) {
const pageTitleById = new Map(statusPages?.map((p) => [p.id, p.title]) ?? []);
return {
+ incidentsEnabled,
+ incidents: incidentsEnabled ? incidents : undefined,
monitors,
statusPages,
statusReports,
diff --git a/apps/dashboard/src/components/common/status-badge.tsx b/apps/dashboard/src/components/common/status-badge.tsx
new file mode 100644
index 000000000..b215ee5e9
--- /dev/null
+++ b/apps/dashboard/src/components/common/status-badge.tsx
@@ -0,0 +1,45 @@
+import { Badge } from "@openstatus/ui/components/ui/badge";
+import { cn } from "@openstatus/ui/lib/utils";
+import { type VariantProps, cva } from "class-variance-authority";
+
+import { StatusDot, type StatusVariant } from "./status-dot";
+
+const statusBadgeVariants = cva("", {
+ variants: {
+ variant: {
+ default: "bg-muted/50",
+ success: "border-success/20 bg-success/10 text-success",
+ warning: "border-warning/20 bg-warning/10 text-warning",
+ destructive: "border-destructive/20 bg-destructive/10 text-destructive",
+ info: "border-info/20 bg-info/10 text-info",
+ } satisfies Record<StatusVariant, string>,
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+});
+
+/** Tinted by `variant`; with `dot` it stays neutral and the dot carries the color. */
+export function StatusBadge({
+ children,
+ className,
+ variant,
+ dot = false,
+ ...props
+}: Omit<React.ComponentProps<typeof Badge>, "variant"> &
+ VariantProps<typeof statusBadgeVariants> & { dot?: boolean }) {
+ return (
+ <Badge
+ variant="outline"
+ className={cn(
+ "font-mono",
+ dot ? "gap-1.5" : statusBadgeVariants({ variant }),
+ className,
+ )}
+ {...props}
+ >
+ {dot ? <StatusDot variant={variant} /> : null}
+ {children}
+ </Badge>
+ );
+}
diff --git a/apps/dashboard/src/components/common/status-dot.tsx b/apps/dashboard/src/components/common/status-dot.tsx
new file mode 100644
index 000000000..c7c173cdb
--- /dev/null
+++ b/apps/dashboard/src/components/common/status-dot.tsx
@@ -0,0 +1,36 @@
+import { cn } from "@openstatus/ui/lib/utils";
+import { type VariantProps, cva } from "class-variance-authority";
+
+const statusDotVariants = cva("inline-block size-2 shrink-0 rounded-full", {
+ variants: {
+ variant: {
+ default: "bg-muted-foreground",
+ success: "bg-success",
+ warning: "bg-warning",
+ destructive: "bg-destructive",
+ info: "bg-info",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+});
+
+export type StatusVariant = NonNullable<
+ VariantProps<typeof statusDotVariants>["variant"]
+>;
+
+export function StatusDot({
+ className,
+ variant,
+ ...props
+}: React.ComponentProps<"span"> & VariantProps<typeof statusDotVariants>) {
+ return (
+ <span
+ data-slot="status-dot"
+ aria-hidden="true"
+ className={cn(statusDotVariants({ variant }), className)}
+ {...props}
+ />
+ );
+}
diff --git a/apps/dashboard/src/components/common/user-avatar.tsx b/apps/dashboard/src/components/common/user-avatar.tsx
new file mode 100644
index 000000000..9ef10e0c9
--- /dev/null
+++ b/apps/dashboard/src/components/common/user-avatar.tsx
@@ -0,0 +1,25 @@
+import {
+ Avatar,
+ AvatarFallback,
+ AvatarImage,
+} from "@openstatus/ui/components/ui/avatar";
+import { cn } from "@openstatus/ui/lib/utils";
+
+export function UserAvatar({
+ name,
+ src,
+ className,
+ ...props
+}: Omit<React.ComponentProps<typeof Avatar>, "children"> & {
+ name: string | null;
+ src?: string | null;
+}) {
+ return (
+ <Avatar className={cn("size-5 text-[10px]", className)} {...props}>
+ {src ? <AvatarImage src={src} alt={name ?? ""} /> : null}
+ <AvatarFallback className="bg-foreground text-background font-sans font-medium uppercase">
+ {Array.from(name ?? "")[0] ?? "?"}
+ </AvatarFallback>
+ </Avatar>
+ );
+}
diff --git a/apps/dashboard/src/components/content/composer.tsx b/apps/dashboard/src/components/content/composer.tsx
new file mode 100644
index 000000000..7f2754a7b
--- /dev/null
+++ b/apps/dashboard/src/components/content/composer.tsx
@@ -0,0 +1,150 @@
+"use client";
+
+import {
+ InputGroup,
+ InputGroupAddon,
+ InputGroupTextarea,
+} from "@openstatus/ui/components/ui/input-group";
+import {
+ Tabs,
+ TabsContent,
+ TabsList,
+ TabsTrigger,
+} from "@openstatus/ui/components/ui/tabs";
+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. */
+export function Composer({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<typeof Tabs>) {
+ return (
+ <Tabs
+ defaultValue="write"
+ className={cn("min-w-0 flex-1", className)}
+ {...props}
+ >
+ <InputGroup className="bg-background items-stretch overflow-hidden">
+ {children}
+ </InputGroup>
+ </Tabs>
+ );
+}
+
+export function ComposerHeader({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<typeof InputGroupAddon>) {
+ return (
+ <InputGroupAddon
+ align="block-start"
+ className={cn(
+ "justify-between border-b px-2 py-1.5 [.border-b]:pb-1.5",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </InputGroupAddon>
+ );
+}
+
+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({
+ className,
+ ...props
+}: Omit<React.ComponentProps<typeof TabsList>, "children">) {
+ return (
+ <TabsList
+ className={cn("h-auto rounded-none bg-transparent p-0", className)}
+ {...props}
+ >
+ <TabsTrigger value="write" className={tabsTriggerClassName}>
+ Write
+ </TabsTrigger>
+ <TabsTrigger value="preview" className={tabsTriggerClassName}>
+ Preview
+ </TabsTrigger>
+ </TabsList>
+ );
+}
+
+export function ComposerHint({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="composer-hint"
+ className={cn(
+ "text-muted-foreground px-1 text-xs font-normal",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </span>
+ );
+}
+
+export function ComposerTextarea({
+ className,
+ ...props
+}: React.ComponentProps<typeof InputGroupTextarea>) {
+ return (
+ <TabsContent value="write">
+ <InputGroupTextarea className={cn("min-h-24", className)} {...props} />
+ </TabsContent>
+ );
+}
+
+export function ComposerPreview({
+ value,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"div">, "children"> & { value: string }) {
+ return (
+ <TabsContent value="preview">
+ <div
+ data-slot="composer-preview"
+ className={cn(
+ "prose prose-sm dark:prose-invert min-h-24 max-w-none px-3 py-3",
+ className,
+ )}
+ {...props}
+ >
+ {value.trim() ? (
+ <ProcessMessage value={value} />
+ ) : (
+ <p className="text-muted-foreground">Nothing to preview.</p>
+ )}
+ </div>
+ </TabsContent>
+ );
+}
+
+export function ComposerFooter({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<typeof InputGroupAddon>) {
+ return (
+ <InputGroupAddon
+ align="block-end"
+ className={cn(
+ "bg-muted/50 flex-wrap justify-between border-t px-2 py-2 font-normal [.border-t]:pt-2",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </InputGroupAddon>
+ );
+}
diff --git a/apps/dashboard/src/components/content/detail.tsx b/apps/dashboard/src/components/content/detail.tsx
new file mode 100644
index 000000000..aa74c7fc6
--- /dev/null
+++ b/apps/dashboard/src/components/content/detail.tsx
@@ -0,0 +1,328 @@
+"use client";
+
+import { Textarea } from "@openstatus/ui/components/ui/textarea";
+import { cn } from "@openstatus/ui/lib/utils";
+import { type VariantProps, cva } from "class-variance-authority";
+import { useState } from "react";
+
+export function DetailHeader({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"header">) {
+ return (
+ <header
+ data-slot="detail-header"
+ className={cn("flex flex-col gap-3 border-b pb-6", className)}
+ {...props}
+ >
+ {children}
+ </header>
+ );
+}
+
+export function DetailEyebrow({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="detail-eyebrow"
+ className={cn("flex min-h-8 flex-wrap items-center gap-2", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function DetailActions({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="detail-actions"
+ className={cn("ml-auto flex items-center gap-2", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+/** Title on the left, `DetailActions` on the right, on one line. */
+export function DetailTitleRow({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="detail-title-row"
+ className={cn("flex items-start justify-between gap-4", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function DetailTitle({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"h1">) {
+ return (
+ <h1
+ data-slot="detail-title"
+ className={cn(
+ "min-w-0 flex-1 text-2xl font-semibold tracking-tight text-balance",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </h1>
+ );
+}
+
+export function DetailDescription({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"p">) {
+ return (
+ <p
+ data-slot="detail-description"
+ className={cn("text-muted-foreground text-pretty", className)}
+ {...props}
+ >
+ {children}
+ </p>
+ );
+}
+
+/** Edit-in-place field for `DetailTitle` / `DetailDescription`; commits on blur. */
+export function DetailInput({
+ value,
+ onCommit,
+ multiline = false,
+ className,
+ ...props
+}: Omit<
+ React.ComponentProps<typeof Textarea>,
+ "value" | "defaultValue" | "onBlur" | "onKeyDown" | "onInput"
+> & {
+ value: string;
+ onCommit: (value: string) => void;
+ multiline?: boolean;
+}) {
+ // Keyed by the server value: a new one resets the draft as it remounts.
+ const [draft, setDraft] = useState({ base: value, text: value });
+ const text = draft.base === value ? draft.text : value;
+
+ return (
+ <span
+ data-slot="detail-input"
+ className={cn(
+ "-mx-2 -my-1 grid w-[calc(100%+1rem)] text-wrap",
+ className,
+ )}
+ >
+ {/* Invisible mirror in the same cell sizes the textarea in every browser. */}
+ <span
+ aria-hidden="true"
+ className="invisible col-start-1 row-start-1 border border-transparent px-2 py-1 break-words whitespace-pre-wrap"
+ >
+ {text}{" "}
+ </span>
+ <Textarea
+ // Uncontrolled: remounting on a new server value drops the stale draft.
+ key={value}
+ defaultValue={value}
+ rows={1}
+ onInput={(e) => setDraft({ base: value, text: e.currentTarget.value })}
+ className="hover:bg-accent dark:hover:bg-accent/50 placeholder:text-muted-foreground/60 col-start-1 row-start-1 min-h-0 resize-none overflow-hidden border-transparent bg-transparent px-2 py-1 text-[length:inherit] shadow-none md:text-[length:inherit] dark:bg-transparent"
+ onBlur={(e) => {
+ const next = multiline
+ ? e.currentTarget.value.trim()
+ : e.currentTarget.value.replace(/\s+/g, " ").trim();
+ if (!next && props.required) {
+ e.currentTarget.value = value;
+ setDraft({ base: value, text: value });
+ } else if (next !== value) onCommit(next);
+ }}
+ onKeyDown={(e) => {
+ if (e.nativeEvent.isComposing) return;
+ if (e.key === "Escape") {
+ e.currentTarget.value = value;
+ setDraft({ base: value, text: value });
+ e.currentTarget.blur();
+ } else if (
+ e.key === "Enter" &&
+ (!multiline || e.metaKey || e.ctrlKey)
+ ) {
+ e.preventDefault();
+ e.currentTarget.blur();
+ }
+ }}
+ {...props}
+ />
+ </span>
+ );
+}
+
+export function DetailMeta({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="detail-meta"
+ className={cn(
+ "text-muted-foreground flex flex-wrap items-center gap-x-2 gap-y-1 text-sm",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function DetailMetaItem({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="detail-meta-item"
+ className={cn(
+ "not-first:before:text-muted-foreground/50 inline-flex items-center gap-1.5 not-first:before:mr-0.5 not-first:before:content-['·']",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </span>
+ );
+}
+
+export function DetailContent({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="detail-content"
+ className={cn(
+ "grid gap-x-12 gap-y-8 lg:grid-cols-[minmax(0,1fr)_22rem]",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function DetailMain({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="detail-main"
+ className={cn("flex min-w-0 flex-col gap-8", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function DetailAside({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"aside">) {
+ return (
+ <aside
+ data-slot="detail-aside"
+ className={cn("flex min-w-0 flex-col gap-8", className)}
+ {...props}
+ >
+ {children}
+ </aside>
+ );
+}
+
+export function DetailSection({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"section">) {
+ return (
+ <section
+ data-slot="detail-section"
+ className={cn("flex flex-col gap-3", className)}
+ {...props}
+ >
+ {children}
+ </section>
+ );
+}
+
+export function DetailSectionHeader({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="detail-section-header"
+ className={cn("flex items-baseline justify-between gap-2", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+const detailSectionTitleVariants = cva("", {
+ variants: {
+ variant: {
+ label:
+ "text-muted-foreground text-xs font-medium tracking-wide uppercase",
+ heading: "text-base font-medium",
+ },
+ },
+ defaultVariants: {
+ variant: "label",
+ },
+});
+
+export function DetailSectionTitle({
+ children,
+ className,
+ variant,
+ ...props
+}: React.ComponentProps<"h2"> &
+ VariantProps<typeof detailSectionTitleVariants>) {
+ return (
+ <h2
+ data-slot="detail-section-title"
+ className={cn(detailSectionTitleVariants({ variant }), className)}
+ {...props}
+ >
+ {children}
+ </h2>
+ );
+}
diff --git a/apps/dashboard/src/components/content/property-list.tsx b/apps/dashboard/src/components/content/property-list.tsx
new file mode 100644
index 000000000..966177f27
--- /dev/null
+++ b/apps/dashboard/src/components/content/property-list.tsx
@@ -0,0 +1,114 @@
+import { Input } from "@openstatus/ui/components/ui/input";
+import { SelectTrigger } from "@openstatus/ui/components/ui/select";
+import { cn } from "@openstatus/ui/lib/utils";
+
+export function PropertyList({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"dl">) {
+ return (
+ <dl
+ data-slot="property-list"
+ className={cn("flex flex-col gap-1", className)}
+ {...props}
+ >
+ {children}
+ </dl>
+ );
+}
+
+export function Property({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="property"
+ className={cn(
+ "grid grid-cols-[6rem_minmax(0,1fr)] items-start gap-x-3 text-sm",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function PropertyLabel({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"dt">) {
+ return (
+ <dt
+ data-slot="property-label"
+ className={cn("text-muted-foreground truncate leading-8", className)}
+ {...props}
+ >
+ {children}
+ </dt>
+ );
+}
+
+export function PropertyValue({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"dd">) {
+ return (
+ <dd
+ data-slot="property-value"
+ className={cn(
+ "flex min-h-8 min-w-0 items-center gap-2 font-mono",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </dd>
+ );
+}
+
+// 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";
+
+export function PropertySelectTrigger({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<typeof SelectTrigger>) {
+ return (
+ <SelectTrigger
+ size="sm"
+ className={cn(
+ propertyControlClassName,
+ "data-[state=open]:bg-accent",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </SelectTrigger>
+ );
+}
+
+// The native date picker icon is pinned right to line up with select chevrons.
+export function PropertyInput({
+ className,
+ ...props
+}: React.ComponentProps<typeof Input>) {
+ return (
+ <Input
+ className={cn(
+ propertyControlClassName,
+ "relative md:text-sm [&::-webkit-calendar-picker-indicator]:absolute [&::-webkit-calendar-picker-indicator]:right-2 [&::-webkit-calendar-picker-indicator]:cursor-pointer [&::-webkit-calendar-picker-indicator]:opacity-50",
+ className,
+ )}
+ {...props}
+ />
+ );
+}
diff --git a/apps/dashboard/src/components/content/timeline.tsx b/apps/dashboard/src/components/content/timeline.tsx
new file mode 100644
index 000000000..31f7130f0
--- /dev/null
+++ b/apps/dashboard/src/components/content/timeline.tsx
@@ -0,0 +1,190 @@
+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";
+
+export function Timeline({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"ol">) {
+ return (
+ <ol
+ data-slot="timeline"
+ className={cn("flex flex-col", className)}
+ {...props}
+ >
+ {children}
+ </ol>
+ );
+}
+
+// The rail is drawn per item, from below its indicator down to the next one.
+export function TimelineItem({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"li">) {
+ return (
+ <li
+ data-slot="timeline-item"
+ className={cn(
+ "relative grid grid-cols-[auto_minmax(0,1fr)] gap-x-3 pb-6 last:pb-0",
+ "before:bg-border before:absolute before:top-9 before:bottom-1 before:left-4 before:w-px before:-translate-x-1/2 last:before:hidden",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </li>
+ );
+}
+
+const timelineIndicatorVariants = cva(
+ "flex size-8 shrink-0 items-center justify-center rounded-full border [&>svg]:size-3.5",
+ {
+ variants: {
+ variant: {
+ default: "border-border bg-background text-muted-foreground",
+ success: "border-success/20 bg-success/10 text-success",
+ warning: "border-warning/20 bg-warning/10 text-warning",
+ destructive: "border-destructive/20 bg-destructive/10 text-destructive",
+ info: "border-info/20 bg-info/10 text-info",
+ },
+ },
+ defaultVariants: {
+ variant: "default",
+ },
+ },
+);
+
+export function TimelineIndicator({
+ children,
+ className,
+ variant,
+ ...props
+}: React.ComponentProps<"div"> &
+ VariantProps<typeof timelineIndicatorVariants>) {
+ return (
+ <div
+ data-slot="timeline-indicator"
+ aria-hidden="true"
+ className={cn(timelineIndicatorVariants({ variant }), className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+// pt-1.5 centers the first text line on the indicator.
+export function TimelineContent({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="timeline-content"
+ className={cn("flex min-w-0 flex-col gap-1.5 pt-1.5", className)}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+// The time stays top-right; the title group wraps underneath itself.
+export function TimelineHeader({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="timeline-header"
+ className={cn(
+ "flex min-h-5 items-baseline justify-between gap-3 text-sm",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function TimelineTitle({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="timeline-title"
+ className={cn(
+ "flex min-w-0 flex-wrap items-center gap-x-2 gap-y-1 font-medium",
+ className,
+ )}
+ {...props}
+ >
+ {children}
+ </div>
+ );
+}
+
+export function TimelineMeta({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"span">) {
+ return (
+ <span
+ data-slot="timeline-meta"
+ className={cn("text-muted-foreground truncate font-normal", className)}
+ {...props}
+ >
+ {children}
+ </span>
+ );
+}
+
+export function TimelineTime({
+ date,
+ children,
+ className,
+ ...props
+}: Omit<React.ComponentProps<"time">, "dateTime"> & { date: Date }) {
+ return (
+ <HoverCardTimestamp date={date} side="left">
+ <time
+ data-slot="timeline-time"
+ dateTime={date.toISOString()}
+ className={cn(
+ "text-muted-foreground shrink-0 font-mono text-xs",
+ className,
+ )}
+ {...props}
+ >
+ {children ?? formatDistanceToNowStrict(date, { addSuffix: true })}
+ </time>
+ </HoverCardTimestamp>
+ );
+}
+
+export function TimelineBody({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"div">) {
+ return (
+ <div
+ data-slot="timeline-body"
+ className={cn("text-sm", className)}
+ {...props}
+ >
+ {children}
+ </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 138712dc2..b5f4c34ed 100644
--- a/apps/dashboard/src/components/data-table/managed-incidents/columns.tsx
+++ b/apps/dashboard/src/components/data-table/managed-incidents/columns.tsx
@@ -1,21 +1,17 @@
"use client";
import type { RouterOutputs } from "@openstatus/api";
-import { Badge } from "@openstatus/ui/components/ui/badge";
import type { ColumnDef } from "@tanstack/react-table";
import { formatDistanceStrict } from "date-fns";
-import { Link } from "@/components/common/link";
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 { TableCellText } from "@/components/data-table/table-cell-text";
import {
- personName,
- severityConfig,
- statusConfig,
-} from "@/data/managed-incidents.client";
-import { cn } from "@/lib/utils";
+ IncidentSeverityBadge,
+ IncidentStatusBadge,
+} from "@/components/incidents/incident-badge";
type ManagedIncident = NonNullable<RouterOutputs["incident"]["list"]>[number];
@@ -24,23 +20,19 @@ export const columns: ColumnDef<ManagedIncident>[] = [
accessorKey: "severity",
header: "Severity",
enableSorting: false,
- cell: ({ row }) => {
- const config = severityConfig[row.original.severity];
- return (
- <Badge variant="outline" className={cn("font-mono", config.className)}>
- {config.label}
- </Badge>
- );
- },
+ cell: ({ row }) => (
+ <IncidentSeverityBadge severity={row.original.severity} />
+ ),
},
{
accessorKey: "title",
header: "Title",
enableSorting: false,
cell: ({ row }) => (
- <Link href={`/incidents/${row.original.id}`} className="font-medium">
- {row.original.title}
- </Link>
+ <TableCellLink
+ href={`/incidents/${row.original.id}`}
+ value={row.original.title}
+ />
),
meta: { cellClassName: "max-w-[260px] truncate" },
},
@@ -48,23 +40,11 @@ export const columns: ColumnDef<ManagedIncident>[] = [
accessorKey: "status",
header: "Status",
enableSorting: false,
- cell: ({ row }) => {
- const config = statusConfig[row.original.status];
- return (
- <span className={cn("font-mono text-sm", config.className)}>
- {config.label}
- {row.original.closedAt && row.original.status !== "canceled"
- ? " · closed"
- : null}
- </span>
- );
- },
- },
- {
- id: "commander",
- header: "Commander",
cell: ({ row }) => (
- <TableCellText value={personName(row.original.commander)} />
+ <IncidentStatusBadge
+ status={row.original.status}
+ closed={row.original.closedAt !== null}
+ />
),
},
{
@@ -90,26 +70,4 @@ export const columns: ColumnDef<ManagedIncident>[] = [
return <TableCellNumber value={amount} unit={unit} />;
},
},
- {
- id: "statusReport",
- header: "Status report",
- cell: ({ row }) => (
- <TableCellText value={row.original.statusReport?.title ?? null} />
- ),
- meta: { cellClassName: "max-w-[200px] truncate" },
- },
- {
- id: "slack",
- header: "Slack",
- cell: ({ row }) => {
- const { slackTeamId, slackChannelId } = row.original;
- const bound = slackTeamId && slackChannelId;
- return (
- <TableCellLink
- value={bound ? "Open channel" : null}
- href={`https://app.slack.com/client/${slackTeamId}/${slackChannelId}`}
- />
- );
- },
- },
];
diff --git a/apps/dashboard/src/components/dropdowns/quick-actions.tsx b/apps/dashboard/src/components/dropdowns/quick-actions.tsx
index 74da943b4..27ae9596a 100644
--- a/apps/dashboard/src/components/dropdowns/quick-actions.tsx
+++ b/apps/dashboard/src/components/dropdowns/quick-actions.tsx
@@ -107,6 +107,7 @@ export function QuickActions({
{...props}
>
<More />
+ <span className="sr-only">Actions</span>
</Button>
)}
</DropdownMenuTrigger>
diff --git a/apps/dashboard/src/components/forms/incident/sheet.tsx b/apps/dashboard/src/components/forms/incident/sheet.tsx
index 972dce170..a1fede2e1 100644
--- a/apps/dashboard/src/components/forms/incident/sheet.tsx
+++ b/apps/dashboard/src/components/forms/incident/sheet.tsx
@@ -22,22 +22,30 @@ import {
export function FormSheetDeclareIncident({
children,
+ open: controlledOpen,
+ onOpenChange,
defaultValues,
onSubmit,
footer,
slack,
}: {
- children: React.ReactNode;
+ children?: React.ReactNode;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
defaultValues?: Partial<FormValues>;
onSubmit: (values: DeclareIncidentValues) => Promise<void>;
footer?: React.ReactNode;
slack: "ready" | "reconnect" | "disconnected";
}) {
- const [open, setOpen] = useState(false);
+ const [internalOpen, setInternalOpen] = useState(false);
+ const open = controlledOpen ?? internalOpen;
+ const setOpen = onOpenChange ?? setInternalOpen;
return (
<FormSheetWithDirtyProtection open={open} onOpenChange={setOpen}>
- <FormSheetTrigger asChild>{children}</FormSheetTrigger>
+ {children ? (
+ <FormSheetTrigger asChild>{children}</FormSheetTrigger>
+ ) : null}
<FormSheetContent className="sm:max-w-lg">
<FormSheetHeader>
<FormSheetTitle>Declare incident</FormSheetTitle>
diff --git a/apps/dashboard/src/components/incidents/declare-incident-button.tsx b/apps/dashboard/src/components/incidents/declare-incident-button.tsx
index 3f5912324..ccd913948 100644
--- a/apps/dashboard/src/components/incidents/declare-incident-button.tsx
+++ b/apps/dashboard/src/components/incidents/declare-incident-button.tsx
@@ -15,11 +15,15 @@ export type DeclareSource = {
/** Opens the declare sheet and lands on the new incident once declared. */
export function DeclareIncidentButton({
children,
+ open,
+ onOpenChange,
defaultValues,
source,
footer,
}: {
- children: React.ReactNode;
+ children?: React.ReactNode;
+ open?: boolean;
+ onOpenChange?: (open: boolean) => void;
defaultValues?: Partial<FormValues>;
source?: DeclareSource;
footer?: React.ReactNode;
@@ -51,6 +55,8 @@ export function DeclareIncidentButton({
return (
<FormSheetDeclareIncident
+ open={open}
+ onOpenChange={onOpenChange}
defaultValues={defaultValues}
footer={footer}
slack={slack}
diff --git a/apps/dashboard/src/components/incidents/incident-actions.tsx b/apps/dashboard/src/components/incidents/incident-actions.tsx
new file mode 100644
index 000000000..a5ea3919f
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/incident-actions.tsx
@@ -0,0 +1,88 @@
+"use client";
+
+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 { toast } from "sonner";
+
+import { QuickActions } from "@/components/dropdowns/quick-actions";
+import { useTRPC } from "@/lib/trpc/client";
+
+import { useInvalidateIncident } from "./use-invalidate-incident";
+
+type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
+
+/** Whether `IncidentActions` renders anything; lets the page skip the row. */
+export function hasIncidentActions(incident: Incident): boolean {
+ return (
+ (incident.status === "resolved" && incident.closedAt === null) ||
+ incident.deletable
+ );
+}
+
+export function IncidentActions({ incident }: { incident: Incident }) {
+ const trpc = useTRPC();
+ const router = useRouter();
+ const queryClient = useQueryClient();
+ const invalidate = useInvalidateIncident(incident.id);
+ const { data: postmortem } = useQuery(
+ trpc.incident.getPostmortem.queryOptions({ id: incident.id }),
+ );
+ const approved = postmortem?.status === "approved";
+
+ const close = useMutation(
+ trpc.incident.close.mutationOptions({
+ onSuccess: invalidate,
+ onError: (error) => {
+ toast.error(
+ isTRPCClientError(error) ? error.message : "Failed to close",
+ );
+ },
+ }),
+ );
+ const remove = useMutation(
+ trpc.incident.delete.mutationOptions({
+ onSuccess: async () => {
+ await queryClient.invalidateQueries({
+ queryKey: trpc.incident.list.queryKey(),
+ });
+ router.push("/incidents");
+ },
+ }),
+ );
+
+ 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>
+ ) : null}
+ {incident.deletable ? (
+ <QuickActions
+ deleteAction={{
+ confirmationValue: incident.title,
+ submitAction: async () => {
+ await remove.mutateAsync({ id: incident.id });
+ },
+ }}
+ />
+ ) : null}
+ </>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/incident-badge.tsx b/apps/dashboard/src/components/incidents/incident-badge.tsx
new file mode 100644
index 000000000..8042ebe19
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/incident-badge.tsx
@@ -0,0 +1,38 @@
+import type {
+ IncidentSeverity,
+ IncidentStatus,
+} from "@openstatus/db/src/schema/incidents/constants";
+
+import { StatusBadge } from "@/components/common/status-badge";
+import { severityConfig, statusConfig } from "@/data/managed-incidents.client";
+
+type StatusBadgeProps = Omit<
+ React.ComponentProps<typeof StatusBadge>,
+ "children" | "variant" | "dot"
+>;
+
+export function IncidentStatusBadge({
+ status,
+ closed = false,
+ ...props
+}: StatusBadgeProps & { status: IncidentStatus; closed?: boolean }) {
+ const config = statusConfig[status];
+ return (
+ <StatusBadge variant={config.variant} dot {...props}>
+ {config.label}
+ {closed && status !== "canceled" ? " · closed" : null}
+ </StatusBadge>
+ );
+}
+
+export function IncidentSeverityBadge({
+ severity,
+ ...props
+}: StatusBadgeProps & { severity: IncidentSeverity }) {
+ const config = severityConfig[severity];
+ return (
+ <StatusBadge variant={config.variant} {...props}>
+ {config.label}
+ </StatusBadge>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/incident-composer.tsx b/apps/dashboard/src/components/incidents/incident-composer.tsx
index fde76f1e7..c8994b901 100644
--- a/apps/dashboard/src/components/incidents/incident-composer.tsx
+++ b/apps/dashboard/src/components/incidents/incident-composer.tsx
@@ -9,23 +9,26 @@ import {
SelectTrigger,
SelectValue,
} from "@openstatus/ui/components/ui/select";
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@openstatus/ui/components/ui/tabs";
-import { Textarea } from "@openstatus/ui/components/ui/textarea";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
+import { useMutation, useQuery } from "@tanstack/react-query";
import { isTRPCClientError } from "@trpc/client";
import { useState } from "react";
import { toast } from "sonner";
-import { ProcessMessage } from "@/components/content/process-message";
-import { statusConfig } from "@/data/managed-incidents.client";
+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 { personName, statusConfig } from "@/data/managed-incidents.client";
import { useTRPC } from "@/lib/trpc/client";
-const UNCHANGED = "unchanged";
+import { useInvalidateIncident } from "./use-invalidate-incident";
/**
* Posting with the status unchanged adds a note; picking a new status moves
@@ -43,23 +46,11 @@ export function IncidentComposer({
onStatusChanged: (status: IncidentStatus, note: string) => void;
}) {
const trpc = useTRPC();
- const queryClient = useQueryClient();
- const [status, setStatus] = useState<string>(UNCHANGED);
+ const { data: user } = useQuery(trpc.user.get.queryOptions());
+ const [selected, setSelected] = useState<string | null>(null);
const [message, setMessage] = useState("");
- const invalidate = () =>
- Promise.all([
- queryClient.invalidateQueries({
- queryKey: trpc.incident.get.queryKey({ id: incident.id }),
- }),
- queryClient.invalidateQueries({
- queryKey: trpc.incident.listEvents.queryKey({ id: incident.id }),
- }),
- queryClient.invalidateQueries({
- queryKey: trpc.incident.list.queryKey(),
- }),
- ]);
-
+ const invalidate = useInvalidateIncident(incident.id);
const addNote = useMutation(
trpc.incident.addNote.mutationOptions({ onSuccess: invalidate }),
);
@@ -67,9 +58,11 @@ export function IncidentComposer({
trpc.incident.setStatus.mutationOptions({ onSuccess: invalidate }),
);
const pending = addNote.isPending || setIncidentStatus.isPending;
- const next = incident.allowedTransitions.find((s) => s === status);
+ const next = incident.allowedTransitions.find((s) => s === selected);
+ const disabled = pending || (!next && !message.trim());
async function submit() {
+ if (disabled) return;
const note = message.trim();
const promise: Promise<void> = next
? setIncidentStatus
@@ -90,57 +83,76 @@ export function IncidentComposer({
});
await promise;
setMessage("");
- setStatus(UNCHANGED);
+ setSelected(null);
if (next) onStatusChanged(next, note);
}
- const disabled = pending || (!next && !message.trim());
-
return (
- <div className="bg-background grid gap-2 rounded-lg border p-3">
- <Tabs defaultValue="write">
- <div className="flex items-center justify-between gap-2">
- <TabsList>
- <TabsTrigger value="write">Write</TabsTrigger>
- <TabsTrigger value="preview">Preview</TabsTrigger>
- </TabsList>
- <Select value={status} onValueChange={setStatus}>
- <SelectTrigger size="sm" className="w-[180px] font-mono">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value={UNCHANGED}>
- {statusConfig[incident.status].label} (unchanged)
- </SelectItem>
- {incident.allowedTransitions.map((s) => (
- <SelectItem key={s} value={s}>
- Mark {statusConfig[s].label.toLowerCase()}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- <TabsContent value="write">
- <Textarea
- rows={4}
- placeholder="What's happening? Markdown supported."
- value={message}
- onChange={(e) => setMessage(e.target.value)}
- />
- </TabsContent>
- <TabsContent value="preview">
- <div className="prose dark:prose-invert prose-sm min-h-24 rounded-md border px-3 py-2">
- <ProcessMessage value={message || "_Nothing to preview._"} />
+ <div className="flex gap-3">
+ <UserAvatar
+ name={user ? personName(user) : null}
+ src={user?.photoUrl}
+ className="size-8 text-xs"
+ />
+ <Composer>
+ <ComposerHeader>
+ <ComposerTabs />
+ <ComposerHint>Markdown</ComposerHint>
+ </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);
+ }
+ }}
+ />
+ <ComposerPreview value={message} />
+ <ComposerFooter>
+ <div className="flex items-center gap-2">
+ <span>Set status to</span>
+ <Select
+ value={next ?? incident.status}
+ onValueChange={(value) =>
+ setSelected(value === incident.status ? null : value)
+ }
+ >
+ <SelectTrigger
+ size="sm"
+ aria-label="Set status to"
+ className="bg-background text-foreground font-mono"
+ >
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {[incident.status, ...incident.allowedTransitions].map((s) => (
+ <SelectItem key={s} value={s} className="font-mono">
+ <StatusDot variant={statusConfig[s].variant} />
+ {statusConfig[s].label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ </div>
+ <div className="ml-auto flex items-center gap-3">
+ <span className="hidden text-xs sm:inline">
+ Only your team sees notes
+ </span>
+ <Button
+ size="sm"
+ disabled={disabled}
+ onClick={() => submit().catch(console.error)}
+ >
+ {next
+ ? `Post and mark ${statusConfig[next].label.toLowerCase()}`
+ : "Post note"}
+ </Button>
</div>
- </TabsContent>
- </Tabs>
- <div className="flex justify-end">
- <Button size="sm" disabled={disabled} onClick={() => submit()}>
- {next
- ? `Post and mark ${statusConfig[next].label.toLowerCase()}`
- : "Post note"}
- </Button>
- </div>
+ </ComposerFooter>
+ </Composer>
</div>
);
}
diff --git a/apps/dashboard/src/components/incidents/incident-heading.tsx b/apps/dashboard/src/components/incidents/incident-heading.tsx
new file mode 100644
index 000000000..d311f2d0a
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/incident-heading.tsx
@@ -0,0 +1,87 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { useMutation } from "@tanstack/react-query";
+import { isTRPCClientError } from "@trpc/client";
+import { toast } from "sonner";
+
+import {
+ DetailActions,
+ DetailDescription,
+ DetailInput,
+ DetailTitle,
+ DetailTitleRow,
+} from "@/components/content/detail";
+import { useTRPC } from "@/lib/trpc/client";
+
+import { useInvalidateIncident } from "./use-invalidate-incident";
+
+type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
+
+export function IncidentHeading({
+ incident,
+ actions,
+}: {
+ incident: Incident;
+ actions?: React.ReactNode;
+}) {
+ const trpc = useTRPC();
+ const invalidate = useInvalidateIncident(incident.id);
+ const update = useMutation(
+ trpc.incident.update.mutationOptions({
+ onSuccess: invalidate,
+ onError: (error) => {
+ toast.error(
+ isTRPCClientError(error) ? error.message : "Failed to save",
+ );
+ },
+ }),
+ );
+
+ if (incident.closedAt !== null) {
+ return (
+ <>
+ <DetailTitleRow>
+ <DetailTitle>{incident.title}</DetailTitle>
+ {actions ? <DetailActions>{actions}</DetailActions> : null}
+ </DetailTitleRow>
+ {incident.summary ? (
+ <DetailDescription className="whitespace-pre-wrap">
+ {incident.summary}
+ </DetailDescription>
+ ) : null}
+ </>
+ );
+ }
+
+ return (
+ <>
+ <DetailTitleRow>
+ <DetailTitle>
+ <DetailInput
+ aria-label="Title"
+ required
+ maxLength={256}
+ disabled={update.isPending}
+ value={incident.title}
+ onCommit={(title) => update.mutate({ id: incident.id, title })}
+ />
+ </DetailTitle>
+ {actions ? <DetailActions>{actions}</DetailActions> : null}
+ </DetailTitleRow>
+ <DetailDescription>
+ <DetailInput
+ multiline
+ aria-label="Summary"
+ placeholder="Add a summary…"
+ maxLength={4000}
+ disabled={update.isPending}
+ value={incident.summary ?? ""}
+ onCommit={(summary) =>
+ update.mutate({ id: incident.id, summary: summary || null })
+ }
+ />
+ </DetailDescription>
+ </>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/incident-postmortem.tsx b/apps/dashboard/src/components/incidents/incident-postmortem.tsx
index 1000e2dfe..fccfb639c 100644
--- a/apps/dashboard/src/components/incidents/incident-postmortem.tsx
+++ b/apps/dashboard/src/components/incidents/incident-postmortem.tsx
@@ -1,23 +1,33 @@
"use client";
import type { RouterOutputs } from "@openstatus/api";
-import { Badge } from "@openstatus/ui/components/ui/badge";
+import { AI } from "@openstatus/icons";
import { Button } from "@openstatus/ui/components/ui/button";
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@openstatus/ui/components/ui/tabs";
-import { Textarea } from "@openstatus/ui/components/ui/textarea";
+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";
-import { ProcessMessage } from "@/components/content/process-message";
+import { StatusBadge } from "@/components/common/status-badge";
+import {
+ Composer,
+ ComposerFooter,
+ ComposerHeader,
+ ComposerHint,
+ ComposerPreview,
+ ComposerTabs,
+ ComposerTextarea,
+} from "@/components/content/composer";
+import {
+ EmptyStateContainer,
+ EmptyStateDescription,
+ EmptyStateTitle,
+} from "@/components/content/empty-state";
import { useTRPC } from "@/lib/trpc/client";
+import { useInvalidateIncident } from "./use-invalidate-incident";
+
type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
const TEMPLATE = `## Summary
@@ -49,6 +59,7 @@ 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 }),
);
@@ -63,15 +74,7 @@ export function IncidentPostmortem({
queryClient.invalidateQueries({
queryKey: trpc.incident.getPostmortem.queryKey({ id: incident.id }),
}),
- queryClient.invalidateQueries({
- queryKey: trpc.incident.get.queryKey({ id: incident.id }),
- }),
- queryClient.invalidateQueries({
- queryKey: trpc.incident.listEvents.queryKey({ id: incident.id }),
- }),
- queryClient.invalidateQueries({
- queryKey: trpc.incident.list.queryKey(),
- }),
+ invalidate(),
]);
const onError = (error: { message: string }) => {
toast.error(errorText(error));
@@ -107,97 +110,108 @@ export function IncidentPostmortem({
if (incident.status !== "resolved") {
return (
- <p className="text-muted-foreground text-sm">
- The postmortem opens once the incident is resolved.
- </p>
+ <EmptyStateContainer>
+ <EmptyStateTitle>No postmortem yet</EmptyStateTitle>
+ <EmptyStateDescription>
+ The postmortem opens once the incident is resolved.
+ </EmptyStateDescription>
+ </EmptyStateContainer>
);
}
+ // The default tab depends on the server copy; mounting earlier would pin it.
+ if (postmortem === undefined) return null;
const approved = postmortem?.status === "approved";
const dirty = draft !== null && draft !== server;
const busy = save.isPending || draftWithAgent.isPending || approve.isPending;
+ const canSave = !busy && dirty && content.trim().length > 0;
+ const canApprove = postmortem !== null && !approved;
+
+ const hint = dirty
+ ? "Unsaved changes"
+ : approved && incident.closedAt === null
+ ? "Close the incident from the header"
+ : postmortem?.draftedBy === "agent"
+ ? "Drafted by the agent"
+ : postmortem
+ ? null
+ : "No postmortem yet";
return (
- <div className="grid gap-3">
- <div className="flex flex-wrap items-center justify-between gap-2">
- <div className="flex items-center gap-2 text-sm">
- {postmortem ? (
- <Badge variant="outline" className="font-mono capitalize">
- {postmortem.status}
- </Badge>
- ) : (
- <span className="text-muted-foreground">No postmortem yet</span>
- )}
- {postmortem?.draftedBy === "agent" ? (
- <span className="text-muted-foreground">Drafted by the agent</span>
- ) : null}
- </div>
+ <Composer defaultValue={approved ? "preview" : "write"}>
+ <ComposerHeader>
+ <ComposerTabs />
{agentAllowed && !approved ? (
- <Button
- size="sm"
+ <InputGroupButton
variant="outline"
disabled={busy}
onClick={() => draftWithAgent.mutate({ id: incident.id })}
>
+ <AI />
{draftWithAgent.isPending ? "Drafting..." : "Draft with agent"}
- </Button>
- ) : null}
- </div>
- <Tabs defaultValue="write">
- <TabsList>
- <TabsTrigger value="write">Write</TabsTrigger>
- <TabsTrigger value="preview">Preview</TabsTrigger>
- </TabsList>
- <TabsContent value="write">
- <Textarea
- rows={18}
- className="font-mono text-sm"
- value={content}
- onChange={(e) => setDraft(e.target.value)}
- />
- </TabsContent>
- <TabsContent value="preview">
- <div className="prose dark:prose-invert prose-sm max-w-none rounded-md border px-3 py-2">
- <ProcessMessage value={content} />
- </div>
- </TabsContent>
- </Tabs>
- <div className="flex flex-wrap justify-end gap-2">
- <Button
- size="sm"
- variant="outline"
- disabled={busy || !dirty || !content.trim()}
- onClick={() =>
- save.mutate({ id: incident.id, content, draftedBy: "user" })
+ </InputGroupButton>
+ ) : (
+ <ComposerHint>Markdown</ComposerHint>
+ )}
+ </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" });
}
- >
- Save
- </Button>
- {postmortem && !approved ? (
- <>
- <Button
- size="sm"
- variant="outline"
- disabled={busy || dirty}
- onClick={() => approve.mutate({ id: incident.id })}
- >
- Approve
- </Button>
- <Button
- size="sm"
- disabled={busy || dirty || incident.closedAt !== null}
- onClick={() => approve.mutate({ id: incident.id, close: true })}
+ }}
+ />
+ <ComposerPreview value={content} className="min-h-96" />
+ <ComposerFooter>
+ <div className="flex items-center gap-2">
+ {postmortem ? (
+ <StatusBadge
+ dot
+ variant={approved ? "success" : "default"}
+ className="bg-background"
>
- Approve & close
- </Button>
- </>
- ) : null}
- </div>
- {approved && incident.closedAt === null ? (
- <p className="text-muted-foreground text-right text-xs">
- Approved. Close the incident from the panel on the right.
- </p>
- ) : null}
- </div>
+ {approved ? "Approved" : "Draft"}
+ </StatusBadge>
+ ) : null}
+ {hint ? <span className="text-xs">{hint}</span> : null}
+ </div>
+ <div className="ml-auto flex items-center gap-2">
+ <Button
+ size="sm"
+ variant={canApprove ? "outline" : "default"}
+ disabled={!canSave}
+ onClick={() =>
+ save.mutate({ id: incident.id, content, draftedBy: "user" })
+ }
+ >
+ Save
+ </Button>
+ {canApprove ? (
+ <>
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={busy || dirty}
+ onClick={() => approve.mutate({ id: incident.id })}
+ >
+ Approve
+ </Button>
+ <Button
+ size="sm"
+ disabled={busy || dirty || incident.closedAt !== null}
+ onClick={() => approve.mutate({ id: incident.id, close: true })}
+ >
+ Approve & close
+ </Button>
+ </>
+ ) : null}
+ </div>
+ </ComposerFooter>
+ </Composer>
);
}
diff --git a/apps/dashboard/src/components/incidents/incident-properties.tsx b/apps/dashboard/src/components/incidents/incident-properties.tsx
index 335acaae5..b08ec7316 100644
--- a/apps/dashboard/src/components/incidents/incident-properties.tsx
+++ b/apps/dashboard/src/components/incidents/incident-properties.tsx
@@ -1,245 +1,286 @@
"use client";
import type { RouterOutputs } from "@openstatus/api";
-import { incidentSeverity } from "@openstatus/db/src/schema/incidents/constants";
+import {
+ type IncidentStatus,
+ incidentSeverity,
+} from "@openstatus/db/src/schema/incidents/constants";
import { Button } from "@openstatus/ui/components/ui/button";
-import { Input } from "@openstatus/ui/components/ui/input";
import {
Select,
SelectContent,
SelectItem,
- SelectTrigger,
SelectValue,
} from "@openstatus/ui/components/ui/select";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import { useMutation, useQuery } from "@tanstack/react-query";
import { isTRPCClientError } from "@trpc/client";
-import { formatDistanceStrict } from "date-fns";
-import { useRouter } from "next/navigation";
+import {
+ format,
+ formatDistanceStrict,
+ formatDistanceToNowStrict,
+} from "date-fns";
import { useState } from "react";
import { toast } from "sonner";
-import { Link } from "@/components/common/link";
-import { FormAlertDialog } from "@/components/forms/form-alert-dialog";
+import { HoverCardTimestamp } from "@/components/common/hover-card-timestamp";
+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,
severityConfig,
statusConfig,
} from "@/data/managed-incidents.client";
import { useTRPC } from "@/lib/trpc/client";
+import { useInvalidateIncident } from "./use-invalidate-incident";
+
type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
const NONE = "none";
-function Row({
- label,
- children,
+export function IncidentProperties({
+ incident,
+ lastUpdateAt,
+ onStatusChanged,
}: {
- label: string;
- children: React.ReactNode;
+ incident: Incident;
+ lastUpdateAt?: Date;
+ onStatusChanged: (status: IncidentStatus, note: string) => void;
}) {
- return (
- <div className="grid grid-cols-[110px_1fr] items-center gap-2 text-sm">
- <span className="text-muted-foreground">{label}</span>
- <div className="min-w-0">{children}</div>
- </div>
- );
-}
-
-export function slackChannelUrl(teamId: string, channelId: string): string {
- return `https://slack.com/app_redirect?team=${teamId}&channel=${channelId}`;
-}
-
-export function IncidentProperties({ incident }: { incident: Incident }) {
const trpc = useTRPC();
- const router = useRouter();
- const queryClient = useQueryClient();
const { data: members } = useQuery(trpc.member.list.queryOptions());
- const { data: postmortem } = useQuery(
- trpc.incident.getPostmortem.queryOptions({ id: incident.id }),
- );
const [startedAt, setStartedAt] = useState(toLocalInput(incident.startedAt));
const closed = incident.closedAt !== null;
- const refresh = () =>
- Promise.all([
- queryClient.invalidateQueries({
- queryKey: trpc.incident.get.queryKey({ id: incident.id }),
- }),
- queryClient.invalidateQueries({
- queryKey: trpc.incident.listEvents.queryKey({ id: incident.id }),
- }),
- queryClient.invalidateQueries({
- queryKey: trpc.incident.list.queryKey(),
- }),
- ]);
+ const invalidate = useInvalidateIncident(incident.id);
const onError = (error: { message: string }) => {
toast.error(isTRPCClientError(error) ? error.message : "Failed to save");
};
-
const update = useMutation(
- trpc.incident.update.mutationOptions({ onSuccess: refresh, onError }),
- );
- const close = useMutation(
- trpc.incident.close.mutationOptions({ onSuccess: refresh, onError }),
+ trpc.incident.update.mutationOptions({ onSuccess: invalidate, onError }),
);
- const remove = useMutation(
- trpc.incident.delete.mutationOptions({
- onSuccess: async () => {
- await queryClient.invalidateQueries({
- queryKey: trpc.incident.list.queryKey(),
- });
- router.push("/incidents");
+ const setStatus = useMutation(
+ trpc.incident.setStatus.mutationOptions({
+ onSuccess: async (row) => {
+ await invalidate();
+ if (row) onStatusChanged(row.status, "");
},
+ onError,
}),
);
- const end =
- incident.status === "resolved" && incident.resolvedAt
- ? incident.resolvedAt
- : (incident.closedAt ?? new Date());
+ const severity = severityConfig[incident.severity];
+ const status = statusConfig[incident.status];
+ const commander = personName(incident.commander);
+ const endedAt = incidentEndedAt(incident);
return (
- <div className="grid gap-3">
- <Row label="Severity">
- <Select
- disabled={closed}
- value={incident.severity}
- onValueChange={(value) => {
- const severity = incidentSeverity.find((s) => s === value);
- if (severity) update.mutate({ id: incident.id, severity });
- }}
- >
- <SelectTrigger size="sm" className="w-full font-mono">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {incidentSeverity.map((severity) => (
- <SelectItem key={severity} value={severity}>
- {severityConfig[severity].label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </Row>
- <Row label="Status">
- <span
- className={`font-mono ${statusConfig[incident.status].className}`}
- >
- {statusConfig[incident.status].label}
- {closed && incident.status !== "canceled" ? " · closed" : null}
- </span>
- </Row>
- <Row label="Commander">
- <Select
- disabled={closed}
- value={incident.commanderId ? String(incident.commanderId) : NONE}
- onValueChange={(value) =>
- update.mutate({
- id: incident.id,
- commanderId: value === NONE ? null : Number(value),
- })
- }
- >
- <SelectTrigger size="sm" className="w-full">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- <SelectItem value={NONE}>No commander</SelectItem>
- {(members ?? []).map((member) => (
- <SelectItem key={member.user.id} value={String(member.user.id)}>
- {personName(member.user) ?? `User ${member.user.id}`}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </Row>
- <Row label="Started at">
- <div className="flex gap-1">
- <Input
- type="datetime-local"
- disabled={closed}
- value={startedAt}
- onChange={(e) => setStartedAt(e.target.value)}
- />
- {startedAt !== toLocalInput(incident.startedAt) ? (
- <Button
- size="sm"
- variant="outline"
- onClick={() =>
+ <PropertyList>
+ <Property>
+ <PropertyLabel>Severity</PropertyLabel>
+ <PropertyValue>
+ {closed ? (
+ <>
+ <StatusDot variant={severity.variant} className="rounded-xs" />
+ {severity.label}
+ </>
+ ) : (
+ <Select
+ value={incident.severity}
+ onValueChange={(value) => {
+ const next = incidentSeverity.find((s) => s === value);
+ if (next) update.mutate({ id: incident.id, severity: next });
+ }}
+ >
+ <PropertySelectTrigger aria-label="Severity">
+ <SelectValue />
+ </PropertySelectTrigger>
+ <SelectContent>
+ {incidentSeverity.map((s) => (
+ <SelectItem key={s} value={s} className="font-mono">
+ <StatusDot
+ variant={severityConfig[s].variant}
+ className="rounded-xs"
+ />
+ {severityConfig[s].label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </PropertyValue>
+ </Property>
+ <Property>
+ <PropertyLabel>Status</PropertyLabel>
+ <PropertyValue>
+ {incident.allowedTransitions.length === 0 ? (
+ <>
+ <StatusDot variant={status.variant} />
+ {status.label}
+ {closed && incident.status !== "canceled" ? " · closed" : null}
+ </>
+ ) : (
+ <Select
+ value={incident.status}
+ onValueChange={(value) => {
+ const next = incident.allowedTransitions.find(
+ (s) => s === value,
+ );
+ if (next) setStatus.mutate({ id: incident.id, status: next });
+ }}
+ >
+ <PropertySelectTrigger aria-label="Status">
+ <SelectValue />
+ </PropertySelectTrigger>
+ <SelectContent>
+ {[incident.status, ...incident.allowedTransitions].map((s) => (
+ <SelectItem key={s} value={s} className="font-mono">
+ <StatusDot variant={statusConfig[s].variant} />
+ {statusConfig[s].label}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ )}
+ </PropertyValue>
+ </Property>
+ <Property>
+ <PropertyLabel>Commander</PropertyLabel>
+ <PropertyValue>
+ {closed ? (
+ commander ? (
+ <>
+ <UserAvatar name={commander} />
+ <span className="truncate">{commander}</span>
+ </>
+ ) : (
+ <span className="text-muted-foreground">No commander</span>
+ )
+ ) : (
+ <Select
+ value={incident.commanderId ? String(incident.commanderId) : NONE}
+ onValueChange={(value) =>
update.mutate({
id: incident.id,
- startedAt: new Date(startedAt),
+ commanderId: value === NONE ? null : Number(value),
})
}
>
- Save
- </Button>
- ) : null}
- </div>
- </Row>
- <Row label="Duration">
- <span className="font-mono">
- {formatDistanceStrict(incident.startedAt, end)}
- </span>
- </Row>
- <Row label="Declared by">
- {personName(incident.declaredByUser) ?? "System"}
- </Row>
- <Row label="Slack">
- {incident.slackTeamId && incident.slackChannelId ? (
- <Link
- href={slackChannelUrl(
- incident.slackTeamId,
- incident.slackChannelId,
- )}
- target="_blank"
- rel="noreferrer"
- >
- Open channel
- </Link>
- ) : (
- <span className="text-muted-foreground">No channel</span>
- )}
- </Row>
- <div className="flex flex-wrap gap-2 pt-2">
- {incident.status === "resolved" && !closed ? (
- postmortem?.status === "approved" ? (
- <Button
- size="sm"
- variant="outline"
- disabled={close.isPending}
- onClick={() => close.mutate({ id: incident.id })}
- >
- Close incident
- </Button>
+ <PropertySelectTrigger aria-label="Commander">
+ <SelectValue />
+ </PropertySelectTrigger>
+ <SelectContent>
+ <SelectItem value={NONE} className="font-mono">
+ <span className="text-muted-foreground">No commander</span>
+ </SelectItem>
+ {(members ?? []).map((member) => {
+ const name =
+ personName(member.user) ?? `User ${member.user.id}`;
+ return (
+ <SelectItem
+ key={member.user.id}
+ value={String(member.user.id)}
+ className="font-mono"
+ >
+ <UserAvatar name={name} />
+ <span className="truncate">{name}</span>
+ </SelectItem>
+ );
+ })}
+ </SelectContent>
+ </Select>
+ )}
+ </PropertyValue>
+ </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>
) : (
- <Button
- size="sm"
- variant="outline"
- disabled={close.isPending}
- onClick={() =>
- close.mutate({ id: incident.id, skipPostmortem: true })
- }
- >
- Close (skip postmortem)
- </Button>
- )
- ) : null}
- {incident.deletable ? (
- <FormAlertDialog
- confirmationValue={incident.title}
- submitAction={async () => {
- await remove.mutateAsync({ id: incident.id });
- }}
- >
- <Button size="sm" variant="destructive">
- Delete
- </Button>
- </FormAlertDialog>
- ) : null}
- </div>
- </div>
+ <>
+ <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>
+ </Property>
+ <Property>
+ <PropertyLabel>Duration</PropertyLabel>
+ <PropertyValue>
+ {formatDistanceStrict(incident.startedAt, endedAt ?? new Date())}
+ {endedAt ? null : (
+ <>
+ <StatusDot variant="destructive" className="size-1.5" />
+ <span className="sr-only">ongoing</span>
+ </>
+ )}
+ </PropertyValue>
+ </Property>
+ {lastUpdateAt ? (
+ <Property>
+ <PropertyLabel>Last update</PropertyLabel>
+ <PropertyValue>
+ <HoverCardTimestamp date={lastUpdateAt} side="left">
+ <span>
+ {formatDistanceToNowStrict(lastUpdateAt, { addSuffix: true })}
+ </span>
+ </HoverCardTimestamp>
+ </PropertyValue>
+ </Property>
+ ) : null}
+ <Property>
+ <PropertyLabel>Declared by</PropertyLabel>
+ <PropertyValue>
+ <span className="truncate">
+ {personName(incident.declaredByUser) ?? "System"}
+ </span>
+ </PropertyValue>
+ </Property>
+ </PropertyList>
);
}
diff --git a/apps/dashboard/src/components/incidents/incident-status-report.tsx b/apps/dashboard/src/components/incidents/incident-status-report.tsx
index 661ebc06e..737a13eb0 100644
--- a/apps/dashboard/src/components/incidents/incident-status-report.tsx
+++ b/apps/dashboard/src/components/incidents/incident-status-report.tsx
@@ -20,6 +20,16 @@ import { useState } from "react";
import { toast } from "sonner";
import { Link } from "@/components/common/link";
+import { StatusDot } from "@/components/common/status-dot";
+import {
+ ActionCard,
+ ActionCardContent,
+ ActionCardDescription,
+ ActionCardFooter,
+ ActionCardHeader,
+ ActionCardTitle,
+} from "@/components/content/action-card";
+import { statusVariants } from "@/data/status-report-updates.client";
import { useTRPC } from "@/lib/trpc/client";
import { usePublicUpdate } from "./use-public-update";
@@ -49,6 +59,27 @@ export function IncidentStatusReport({
return <UnlinkedReport incident={incident} canNotify={canNotify} />;
}
+function NotifySubscribers({
+ id,
+ checked,
+ onCheckedChange,
+}: {
+ id: string;
+ checked: boolean;
+ onCheckedChange: (checked: boolean) => void;
+}) {
+ return (
+ <div className="flex items-center gap-2">
+ <Checkbox
+ id={id}
+ checked={checked}
+ onCheckedChange={(value) => onCheckedChange(value === true)}
+ />
+ <Label htmlFor={id}>Notify subscribers</Label>
+ </div>
+ );
+}
+
function LinkedReport({
incident,
report,
@@ -60,6 +91,7 @@ function LinkedReport({
}) {
const trpc = useTRPC();
const queryClient = useQueryClient();
+ const [composing, setComposing] = useState(false);
const [status, setStatus] = useState<string>(
report.status === "resolved" ? "monitoring" : report.status,
);
@@ -92,78 +124,99 @@ function LinkedReport({
});
await promise;
setMessage("");
+ setComposing(false);
}
return (
- <div className="grid gap-3">
- <div className="flex items-start justify-between gap-2">
- <div className="grid gap-0.5">
+ <ActionCard>
+ <ActionCardHeader>
+ <ActionCardTitle className="flex items-center gap-2 text-sm">
+ <StatusDot variant={statusVariants[report.status]} />
+ Published
+ <span className="text-muted-foreground ml-auto font-mono text-xs font-normal capitalize">
+ {report.status}
+ </span>
+ </ActionCardTitle>
+ <ActionCardDescription>
{report.pageId ? (
<Link
href={`/status-pages/${report.pageId}/status-reports/${report.id}`}
- className="font-medium"
>
{report.title}
</Link>
) : (
- <span className="font-medium">{report.title}</span>
- )}
- <span className="text-muted-foreground font-mono text-xs capitalize">
- {report.status}
- </span>
- </div>
- {closed ? null : (
- <Button
- variant="ghost"
- size="sm"
- disabled={unlink.isPending}
- onClick={() => unlink.mutate({ id: incident.id })}
- >
- Unlink
- </Button>
- )}
- </div>
- <div className="grid gap-2">
- <Label>Post public update</Label>
- <Select value={status} onValueChange={setStatus}>
- <SelectTrigger size="sm" className="font-mono capitalize">
- <SelectValue />
- </SelectTrigger>
- <SelectContent>
- {statusReportStatus.map((s) => (
- <SelectItem key={s} value={s} className="capitalize">
- {s}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <Textarea
- rows={3}
- placeholder="Message shown on your status page"
- value={message}
- onChange={(e) => setMessage(e.target.value)}
- />
- {canNotify ? (
- <div className="flex items-center gap-2">
- <Checkbox
+ <span className="text-foreground font-medium">{report.title}</span>
+ )}{" "}
+ is what customers see on your status page.
+ </ActionCardDescription>
+ </ActionCardHeader>
+ {composing ? (
+ <ActionCardContent className="grid gap-2">
+ <Select value={status} onValueChange={setStatus}>
+ <SelectTrigger size="sm" className="w-full font-mono capitalize">
+ <SelectValue />
+ </SelectTrigger>
+ <SelectContent>
+ {statusReportStatus.map((s) => (
+ <SelectItem key={s} value={s} className="font-mono capitalize">
+ <StatusDot variant={statusVariants[s]} />
+ {s}
+ </SelectItem>
+ ))}
+ </SelectContent>
+ </Select>
+ <Textarea
+ rows={3}
+ placeholder="Message shown on your status page"
+ value={message}
+ onChange={(e) => setMessage(e.target.value)}
+ />
+ {canNotify ? (
+ <NotifySubscribers
id="incident-report-notify"
checked={notifySubscribers}
- onCheckedChange={(checked) =>
- setNotifySubscribers(checked === true)
- }
+ onCheckedChange={setNotifySubscribers}
/>
- <Label htmlFor="incident-report-notify">Notify subscribers</Label>
- </div>
- ) : null}
- <Button
- size="sm"
- disabled={!message.trim() || update.isPending}
- onClick={() => post().catch(console.error)}
- >
- Post public update
- </Button>
- </div>
- </div>
+ ) : null}
+ </ActionCardContent>
+ ) : null}
+ <ActionCardFooter className="flex-wrap gap-2">
+ {composing ? (
+ <>
+ <Button
+ size="sm"
+ disabled={!message.trim() || update.isPending}
+ onClick={() => post().catch(console.error)}
+ >
+ Post public update
+ </Button>
+ <Button
+ size="sm"
+ variant="ghost"
+ onClick={() => setComposing(false)}
+ >
+ Cancel
+ </Button>
+ </>
+ ) : (
+ <>
+ <Button size="sm" onClick={() => setComposing(true)}>
+ Post public update
+ </Button>
+ {closed ? null : (
+ <Button
+ size="sm"
+ variant="outline"
+ disabled={unlink.isPending}
+ onClick={() => unlink.mutate({ id: incident.id })}
+ >
+ Unlink
+ </Button>
+ )}
+ </>
+ )}
+ </ActionCardFooter>
+ </ActionCard>
);
}
@@ -180,7 +233,7 @@ function UnlinkedReport({
trpc.statusReport.list.queryOptions({ order: "desc" }),
);
const { data: pages } = useQuery(trpc.page.list.queryOptions());
- const [mode, setMode] = useState<"link" | "create" | null>(null);
+ const [draftMode, setMode] = useState<"link" | "create" | null>(null);
const [reportId, setReportId] = useState<string>("");
const [pageId, setPageId] = useState<string>("");
const [title, setTitle] = useState(incident.title);
@@ -205,12 +258,9 @@ function UnlinkedReport({
const notify = useMutation(
trpc.subscriberNotification.statusReport.mutationOptions(),
);
-
- if (incident.closedAt !== null) {
- return (
- <p className="text-muted-foreground text-sm">No status report linked.</p>
- );
- }
+ 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 () => {
@@ -240,30 +290,25 @@ function UnlinkedReport({
const openReports = (reports ?? []).filter((r) => r.status !== "resolved");
return (
- <div className="grid gap-3">
- <p className="text-muted-foreground text-sm">
- No status report yet. Your users only see what you publish there.
- </p>
- <div className="flex gap-2">
- <Button
- size="sm"
- variant={mode === "create" ? "default" : "outline"}
- onClick={() => setMode("create")}
- >
- Create status report
- </Button>
- <Button
- size="sm"
- variant={mode === "link" ? "default" : "outline"}
- onClick={() => setMode("link")}
- >
- Link existing
- </Button>
- </div>
+ <ActionCard className="border-dashed">
+ <ActionCardHeader>
+ <ActionCardTitle className="flex items-center gap-2 text-sm">
+ <span
+ aria-hidden="true"
+ className="border-muted-foreground size-2 shrink-0 rounded-full border"
+ />
+ Not published
+ </ActionCardTitle>
+ <ActionCardDescription>
+ {closed
+ ? "This incident was never linked to a status report."
+ : "Nothing here is public. Customers only see what you publish on your status page."}
+ </ActionCardDescription>
+ </ActionCardHeader>
{mode === "link" ? (
- <div className="grid gap-2">
+ <ActionCardContent className="grid gap-2">
<Select value={reportId} onValueChange={setReportId}>
- <SelectTrigger size="sm">
+ <SelectTrigger size="sm" className="w-full">
<SelectValue placeholder="Select an open report" />
</SelectTrigger>
<SelectContent>
@@ -274,31 +319,12 @@ function UnlinkedReport({
))}
</SelectContent>
</Select>
- <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,
- },
- )
- }
- >
- Link
- </Button>
- </div>
+ </ActionCardContent>
) : null}
{mode === "create" ? (
- <div className="grid gap-2">
+ <ActionCardContent className="grid gap-2">
<Select value={pageId} onValueChange={setPageId}>
- <SelectTrigger size="sm">
+ <SelectTrigger size="sm" className="w-full">
<SelectValue placeholder="Select a status page" />
</SelectTrigger>
<SelectContent>
@@ -309,7 +335,11 @@ function UnlinkedReport({
))}
</SelectContent>
</Select>
- <Input value={title} onChange={(e) => setTitle(e.target.value)} />
+ <Input
+ aria-label="Title"
+ value={title}
+ onChange={(e) => setTitle(e.target.value)}
+ />
<Textarea
rows={3}
placeholder="First public message"
@@ -317,28 +347,72 @@ function UnlinkedReport({
onChange={(e) => setMessage(e.target.value)}
/>
{canNotify ? (
- <div className="flex items-center gap-2">
- <Checkbox
- id="incident-create-notify"
- checked={notifySubscribers}
- onCheckedChange={(checked) =>
- setNotifySubscribers(checked === true)
- }
- />
- <Label htmlFor="incident-create-notify">Notify subscribers</Label>
- </div>
+ <NotifySubscribers
+ id="incident-create-notify"
+ checked={notifySubscribers}
+ onCheckedChange={setNotifySubscribers}
+ />
) : null}
- <Button
- size="sm"
- disabled={
- !pageId || !title.trim() || !message.trim() || create.isPending
- }
- onClick={() => createReport().catch(console.error)}
- >
- Create and link
- </Button>
- </div>
+ </ActionCardContent>
) : null}
- </div>
+ {closed ? null : (
+ <ActionCardFooter className="flex-wrap gap-2">
+ {mode === null ? (
+ <>
+ <Button size="sm" onClick={() => setMode("create")}>
+ Create status report
+ </Button>
+ <Button
+ size="sm"
+ variant="outline"
+ onClick={() => setMode("link")}
+ >
+ Link existing
+ </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"
+ disabled={!reportId || link.isPending}
+ onClick={() =>
+ toast.promise(
+ link.mutateAsync({
+ id: incident.id,
+ statusReportId: Number(reportId),
+ }),
+ {
+ loading: "Linking...",
+ success: "Status report linked",
+ error: toastError,
+ },
+ )
+ }
+ >
+ Link
+ </Button>
+ )}
+ <Button size="sm" variant="ghost" onClick={() => setMode(null)}>
+ Cancel
+ </Button>
+ </>
+ )}
+ </ActionCardFooter>
+ )}
+ </ActionCard>
);
}
diff --git a/apps/dashboard/src/components/incidents/incident-timeline.tsx b/apps/dashboard/src/components/incidents/incident-timeline.tsx
index d25cb86b9..c1e3c7c1b 100644
--- a/apps/dashboard/src/components/incidents/incident-timeline.tsx
+++ b/apps/dashboard/src/components/incidents/incident-timeline.tsx
@@ -1,61 +1,159 @@
"use client";
import type { RouterOutputs } from "@openstatus/api";
-import type { IncidentEventType } from "@openstatus/db/src/schema/incidents/constants";
-import { formatDistanceToNow } from "date-fns";
+import {
+ type IncidentEventType,
+ type IncidentSeverity,
+ type IncidentStatus,
+ incidentSeverity,
+ incidentStatus,
+} from "@openstatus/db/src/schema/incidents/constants";
+import {
+ Account,
+ Chat,
+ Check,
+ Clock,
+ Close,
+ Compare,
+ FileText,
+ type IconType,
+ Impact,
+ Linked,
+ Lock,
+ Plug,
+ Unlinked,
+ Warning,
+} from "@openstatus/icons";
+import type { StatusVariant } from "@/components/common/status-dot";
import { ProcessMessage } from "@/components/content/process-message";
-import { personName } from "@/data/managed-incidents.client";
+import {
+ Timeline,
+ TimelineBody,
+ TimelineContent,
+ TimelineHeader,
+ TimelineIndicator,
+ TimelineItem,
+ TimelineMeta,
+ TimelineTime,
+ TimelineTitle,
+} from "@/components/content/timeline";
+import {
+ personName,
+ severityConfig,
+ statusConfig,
+} from "@/data/managed-incidents.client";
+
+import { IncidentSeverityBadge, IncidentStatusBadge } from "./incident-badge";
type Event = NonNullable<RouterOutputs["incident"]["listEvents"]>[number];
-const labels: Record<IncidentEventType, string> = {
- declared: "Declared",
- severity_changed: "Severity changed",
- status_changed: "Status changed",
- commander_changed: "Commander changed",
- started_at_changed: "Start time changed",
- note: "Note",
- status_report_linked: "Status report linked",
- status_report_unlinked: "Status report unlinked",
- slack_channel_bound: "Slack channel bound",
- slack_channel_unbound: "Slack channel unbound",
- mitigated: "Mitigated",
- resolved: "Resolved",
- canceled: "Canceled",
- postmortem_drafted: "Postmortem drafted",
- postmortem_updated: "Postmortem updated",
- postmortem_approved: "Postmortem approved",
- closed: "Closed",
+const eventConfig: Record<
+ IncidentEventType,
+ { label: string; icon: IconType; variant?: StatusVariant }
+> = {
+ declared: { label: "Declared", icon: Warning, variant: "warning" },
+ severity_changed: { label: "Severity changed", icon: Impact },
+ status_changed: { label: "Status changed", icon: Compare },
+ commander_changed: { label: "Commander changed", icon: Account },
+ started_at_changed: { label: "Start time changed", icon: Clock },
+ note: { label: "Note", icon: Chat },
+ status_report_linked: { label: "Status report linked", icon: Linked },
+ status_report_unlinked: { label: "Status report unlinked", icon: Unlinked },
+ slack_channel_bound: { label: "Slack channel bound", icon: Plug },
+ slack_channel_unbound: { label: "Slack channel unbound", icon: Plug },
+ mitigated: { label: "Mitigated", icon: Check, variant: "warning" },
+ resolved: { label: "Resolved", icon: Check, variant: "success" },
+ canceled: { label: "Canceled", icon: Close },
+ postmortem_drafted: { label: "Postmortem drafted", icon: FileText },
+ postmortem_updated: { label: "Postmortem updated", icon: FileText },
+ postmortem_approved: {
+ label: "Postmortem approved",
+ icon: FileText,
+ variant: "success",
+ },
+ closed: { label: "Closed", icon: Lock },
};
+const TRANSITION = /^\w+ changed from \w+ to (\w+)(?:\n\n([\s\S]+))?$/;
+const DECLARED = /^Declared as (\w+): /;
+
+// Events carry no structured payload, so the target of a transition is read
+// from the service's own message. An unknown shape falls back to the raw text.
+function parseEvent(event: Event): {
+ status?: IncidentStatus;
+ severity?: IncidentSeverity;
+ message: string | null;
+} {
+ const message = event.message;
+ if (!message) return { message: null };
+
+ // The message only repeats the label around a raw Slack channel id.
+ if (
+ event.type === "slack_channel_bound" ||
+ event.type === "slack_channel_unbound"
+ ) {
+ return { message: null };
+ }
+ if (event.type === "status_changed") {
+ const match = TRANSITION.exec(message);
+ const status = incidentStatus.find((s) => s === match?.[1]);
+ if (status) return { status, message: match?.[2] ?? null };
+ }
+ if (event.type === "severity_changed") {
+ const match = TRANSITION.exec(message);
+ const severity = incidentSeverity.find((s) => s === match?.[1]);
+ if (severity) return { severity, message: match?.[2] ?? null };
+ }
+ if (event.type === "declared") {
+ const severity = incidentSeverity.find(
+ (s) => s === DECLARED.exec(message)?.[1],
+ );
+ if (severity) return { severity, message: null };
+ }
+ return { message };
+}
+
export function IncidentTimeline({ events }: { events: Event[] }) {
if (events.length === 0) return null;
return (
- <ol className="grid gap-4">
- {events.map((event) => (
- <li key={event.id} className="grid gap-1 border-l-2 pl-3">
- <div className="text-muted-foreground flex flex-wrap items-center gap-x-2 text-xs">
- <span className="text-foreground font-medium">
- {labels[event.type]}
- </span>
- <span>·</span>
- <span>{personName(event.createdByUser) ?? "System"}</span>
- <span>·</span>
- <time
- dateTime={event.createdAt.toISOString()}
- title={event.createdAt.toLocaleString()}
- >
- {formatDistanceToNow(event.createdAt, { addSuffix: true })}
- </time>
- </div>
- {event.message ? (
- <div className="prose dark:prose-invert prose-sm max-w-none">
- <ProcessMessage value={event.message} />
- </div>
- ) : null}
- </li>
- ))}
- </ol>
+ <Timeline>
+ {events.map((event) => {
+ const config = eventConfig[event.type];
+ const { status, severity, message } = parseEvent(event);
+ const variant = status
+ ? statusConfig[status].variant
+ : event.type === "declared" && severity
+ ? severityConfig[severity].variant
+ : config.variant;
+ return (
+ <TimelineItem key={event.id}>
+ <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>
+ </TimelineTitle>
+ <TimelineTime date={event.createdAt} />
+ </TimelineHeader>
+ {message ? (
+ <TimelineBody className="prose prose-sm dark:prose-invert max-w-none">
+ <ProcessMessage value={message} />
+ </TimelineBody>
+ ) : null}
+ </TimelineContent>
+ </TimelineItem>
+ );
+ })}
+ </Timeline>
);
}
diff --git a/apps/dashboard/src/components/incidents/use-invalidate-incident.ts b/apps/dashboard/src/components/incidents/use-invalidate-incident.ts
new file mode 100644
index 000000000..e5fdb4c42
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/use-invalidate-incident.ts
@@ -0,0 +1,24 @@
+"use client";
+
+import { useQueryClient } from "@tanstack/react-query";
+
+import { useTRPC } from "@/lib/trpc/client";
+
+/** Refetches the incident, its timeline and the incident list. */
+export function useInvalidateIncident(id: number) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+
+ return () =>
+ Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.get.queryKey({ id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.listEvents.queryKey({ id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.list.queryKey(),
+ }),
+ ]);
+}
diff --git a/apps/dashboard/src/components/nav/app-sidebar.tsx b/apps/dashboard/src/components/nav/app-sidebar.tsx
index b330dc7da..afe87d160 100644
--- a/apps/dashboard/src/components/nav/app-sidebar.tsx
+++ b/apps/dashboard/src/components/nav/app-sidebar.tsx
@@ -62,13 +62,14 @@ export function AppSidebar({ ...props }: React.ComponentProps<typeof Sidebar>) {
const incidents = useFeature("incident-management");
const overview = incidents
? [
- data.overview[0],
+ ...data.overview.slice(0, 3),
{
name: NAV.incidents.label,
url: NAV.incidents.href,
icon: NAV.incidents.icon,
+ badge: "New",
},
- ...data.overview.slice(1),
+ ...data.overview.slice(3),
]
: data.overview;
diff --git a/apps/dashboard/src/components/nav/nav-overview.tsx b/apps/dashboard/src/components/nav/nav-overview.tsx
index c2c980471..147fc9cae 100644
--- a/apps/dashboard/src/components/nav/nav-overview.tsx
+++ b/apps/dashboard/src/components/nav/nav-overview.tsx
@@ -5,6 +5,7 @@ import {
SidebarGroup,
SidebarGroupLabel,
SidebarMenu,
+ SidebarMenuBadge,
SidebarMenuButton,
SidebarMenuItem,
useSidebar,
@@ -25,6 +26,7 @@ export function NavOverview({
name: string;
url: string;
icon: IconType;
+ badge?: string;
}[];
}) {
const pathname = usePathname();
@@ -53,6 +55,11 @@ export function NavOverview({
<span>{item.name}</span>
</Link>
</SidebarMenuButton>
+ {item.badge ? (
+ <SidebarMenuBadge className="font-commit-mono text-muted-foreground">
+ {item.badge}
+ </SidebarMenuBadge>
+ ) : null}
</SidebarMenuItem>
))}
</SidebarMenu>
diff --git a/apps/dashboard/src/data/managed-incidents.client.ts b/apps/dashboard/src/data/managed-incidents.client.ts
index e29a1e389..3302b0d5e 100644
--- a/apps/dashboard/src/data/managed-incidents.client.ts
+++ b/apps/dashboard/src/data/managed-incidents.client.ts
@@ -3,28 +3,39 @@ import type {
IncidentStatus,
} from "@openstatus/db/src/schema/incidents/constants";
+import type { StatusVariant } from "@/components/common/status-dot";
+
export const severityConfig = {
- critical: {
- label: "Critical",
- className: "text-destructive border-destructive/40",
- },
- major: { label: "Major", className: "text-warning border-warning/40" },
- minor: { label: "Minor", className: "text-info border-info/40" },
+ critical: { label: "Critical", variant: "destructive" },
+ major: { label: "Major", variant: "warning" },
+ minor: { label: "Minor", variant: "info" },
} as const satisfies Record<
IncidentSeverity,
- { label: string; className: string }
+ { label: string; variant: StatusVariant }
>;
export const statusConfig = {
- open: { label: "Open", className: "text-destructive" },
- mitigated: { label: "Mitigated", className: "text-warning" },
- resolved: { label: "Resolved", className: "text-success" },
- canceled: { label: "Canceled", className: "text-muted-foreground" },
+ open: { label: "Open", variant: "destructive" },
+ mitigated: { label: "Mitigated", variant: "warning" },
+ resolved: { label: "Resolved", variant: "success" },
+ canceled: { label: "Canceled", variant: "default" },
} as const satisfies Record<
IncidentStatus,
- { label: string; className: string }
+ { label: string; variant: StatusVariant }
>;
+/** When the incident stopped being ongoing; `null` while it still is. */
+export function incidentEndedAt(incident: {
+ status: IncidentStatus;
+ resolvedAt: Date | null;
+ closedAt: Date | null;
+}): Date | null {
+ if (incident.status === "resolved" && incident.resolvedAt) {
+ return incident.resolvedAt;
+ }
+ return incident.closedAt;
+}
+
export function personName(
person: {
name: string | null;
diff --git a/apps/dashboard/src/data/status-report-updates.client.ts b/apps/dashboard/src/data/status-report-updates.client.ts
index a19f259c3..1cde9fcd0 100644
--- a/apps/dashboard/src/data/status-report-updates.client.ts
+++ b/apps/dashboard/src/data/status-report-updates.client.ts
@@ -2,6 +2,7 @@ import type { StatusReportStatus } from "@openstatus/db/src/schema";
import type { PageComponentImpact } from "@openstatus/db/src/schema/page_components/constants";
import { Settings, Delete } from "@openstatus/icons";
+import type { StatusVariant } from "@/components/common/status-dot";
import type { FormValues as StatusReportUpdateFormValues } from "@/components/forms/status-report-update/form";
export const impactConfig = {
@@ -88,6 +89,13 @@ export const colors = {
"text-warning/80 data-[state=selected]:bg-warning/10 data-[state=selected]:text-warning",
} as const satisfies Record<StatusReportStatus, string>;
+export const statusVariants = {
+ resolved: "success",
+ investigating: "destructive",
+ monitoring: "info",
+ identified: "warning",
+} as const satisfies Record<StatusReportStatus, StatusVariant>;
+
/**
* Get the next status in the progression:
* investigating → identified → monitoring → resolved