Skip to content

Open-source status page, incident response and uptime monitoring

chore: improve incidents communication section (#2876)

Maximilian Kaskee077444c9b16
diff --git a/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
index a766184c2..85cf6295f 100644
--- a/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
+++ b/apps/dashboard/src/app/(dashboard)/incidents/[id]/client.tsx
@@ -6,7 +6,6 @@ import { useQuery } from "@tanstack/react-query";
import { formatDistanceStrict, formatDistanceToNow } from "date-fns";
import { useState } from "react";
-import { Link } from "@/components/common/link";
import {
DetailAside,
DetailContent,
@@ -22,32 +21,22 @@ import {
EmptyStateContainer,
EmptyStateTitle,
} from "@/components/content/empty-state";
-import {
- Property,
- PropertyLabel,
- PropertyList,
- PropertyValue,
-} from "@/components/content/property-list";
import { SectionGroup } from "@/components/content/section";
import { Timeline } from "@/components/content/timeline";
import {
IncidentActions,
hasIncidentActions,
} from "@/components/incidents/incident-actions";
+import { IncidentCommunication } from "@/components/incidents/incident-communication";
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 { IncidentTimelineItem } from "@/components/incidents/incident-timeline";
import { ResolveReportDialog } from "@/components/incidents/resolve-report-dialog";
import { incidentEndedAt } from "@/data/managed-incidents.client";
import { useTRPC } from "@/lib/trpc/client";
-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();
const { data: workspace } = useQuery(trpc.workspace.get.queryOptions());
@@ -187,26 +176,7 @@ export function Client({ id }: { id: number }) {
</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>
+ <IncidentCommunication incident={incident} />
</DetailSection>
</DetailAside>
</DetailContent>
diff --git a/apps/dashboard/src/components/content/property-list.tsx b/apps/dashboard/src/components/content/property-list.tsx
index 1f07b9668..808bfb7d5 100644
--- a/apps/dashboard/src/components/content/property-list.tsx
+++ b/apps/dashboard/src/components/content/property-list.tsx
@@ -1,4 +1,4 @@
-import { ArrowUpRight } from "@openstatus/icons";
+import { ArrowUpRight, ChevronDown } from "@openstatus/icons";
import { Input } from "@openstatus/ui/components/ui/input";
import { SelectTrigger } from "@openstatus/ui/components/ui/select";
import { cn } from "@openstatus/ui/lib/utils";
@@ -121,6 +121,29 @@ export function PropertySelectTrigger({
);
}
+// Same chrome as PropertySelectTrigger, for rows that open a menu instead.
+export function PropertyMenuTrigger({
+ children,
+ className,
+ ...props
+}: React.ComponentProps<"button">) {
+ return (
+ <button
+ type="button"
+ data-slot="property-menu-trigger"
+ className={cn(
+ propertyControlClassName,
+ "focus-visible:border-ring focus-visible:ring-ring/50 data-[state=open]:bg-accent flex items-center justify-between gap-2 rounded-md border text-sm whitespace-nowrap transition-[color,box-shadow] outline-none focus-visible:ring-[3px] disabled:cursor-not-allowed disabled:opacity-50 [&_svg]:pointer-events-none [&_svg]:shrink-0",
+ className,
+ )}
+ {...props}
+ >
+ <span className="flex min-w-0 flex-1 items-center gap-2">{children}</span>
+ <ChevronDown className="size-4 opacity-50" />
+ </button>
+ );
+}
+
// The native date picker icon is pinned right to line up with select chevrons.
export function PropertyInput({
className,
diff --git a/apps/dashboard/src/components/forms/status-report-update/sheet-create.tsx b/apps/dashboard/src/components/forms/status-report-update/sheet-create.tsx
index 6eaf03632..2df621b8b 100644
--- a/apps/dashboard/src/components/forms/status-report-update/sheet-create.tsx
+++ b/apps/dashboard/src/components/forms/status-report-update/sheet-create.tsx
@@ -2,11 +2,10 @@
import type { RouterOutputs } from "@openstatus/api";
import { currentImpactsFromUpdates } from "@openstatus/db/src/schema/page_components/constants";
-import { useMutation, useQueryClient } from "@tanstack/react-query";
import { FormSheetStatusReportUpdate } from "@/components/forms/status-report-update/sheet";
+import { usePublishUpdate } from "@/components/status-reports/use-publish-update";
import { getNextStatus } from "@/data/status-report-updates.client";
-import { useTRPC } from "@/lib/trpc/client";
type StatusReport = RouterOutputs["statusReport"]["list"][number];
@@ -22,8 +21,6 @@ export function FormSheetStatusReportUpdateCreate({
open?: boolean;
onOpenChange?: (open: boolean) => void;
}) {
- const trpc = useTRPC();
- const queryClient = useQueryClient();
const reportComponents =
report.pageComponents?.map((c) => ({ id: c.id, name: c.name })) ?? [];
const reportHasImpacts = report.updates.some(
@@ -31,25 +28,7 @@ export function FormSheetStatusReportUpdateCreate({
);
const currentImpacts = currentImpactsFromUpdates(report.updates);
const nextStatus = getNextStatus(report.status);
- const sendStatusReportUpdateMutation = useMutation(
- trpc.subscriberNotification.statusReport.mutationOptions(),
- );
- const createStatusReportUpdateMutation = useMutation(
- trpc.statusReport.createStatusReportUpdate.mutationOptions({
- onSuccess: (update) => {
- if (update?.notifySubscribers) {
- sendStatusReportUpdateMutation.mutate({ id: update.id });
- }
- // no-input prefix key — matches every statusReport.list query
- queryClient.invalidateQueries({
- queryKey: trpc.statusReport.list.queryKey(),
- });
- queryClient.invalidateQueries({
- queryKey: trpc.page.list.queryKey(),
- });
- },
- }),
- );
+ const update = usePublishUpdate(report.id);
return (
<FormSheetStatusReportUpdate
@@ -72,7 +51,7 @@ export function FormSheetStatusReportUpdateCreate({
const sendImpacts =
reportHasImpacts ||
values.componentImpacts?.some((ci) => ci.impact !== "operational");
- await createStatusReportUpdateMutation.mutateAsync({
+ await update.publish({
statusReportId: report.id,
message: values.message,
status: values.status,
diff --git a/apps/dashboard/src/components/incidents/incident-communication.tsx b/apps/dashboard/src/components/incidents/incident-communication.tsx
new file mode 100644
index 000000000..0858770ae
--- /dev/null
+++ b/apps/dashboard/src/components/incidents/incident-communication.tsx
@@ -0,0 +1,333 @@
+"use client";
+
+import type { RouterOutputs } from "@openstatus/api";
+import { Add, ArrowUpRight, Linked, Send, Unlinked } from "@openstatus/icons";
+import {
+ AlertDialog,
+ AlertDialogAction,
+ AlertDialogCancel,
+ AlertDialogContent,
+ AlertDialogDescription,
+ AlertDialogFooter,
+ AlertDialogHeader,
+ AlertDialogTitle,
+} from "@openstatus/ui/components/ui/alert-dialog";
+import {
+ Command,
+ CommandEmpty,
+ CommandGroup,
+ CommandInput,
+ CommandItem,
+ CommandList,
+} from "@openstatus/ui/components/ui/command";
+import {
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuLabel,
+ DropdownMenuSeparator,
+ DropdownMenuTrigger,
+} from "@openstatus/ui/components/ui/dropdown-menu";
+import {
+ Popover,
+ PopoverContent,
+ PopoverTrigger,
+} from "@openstatus/ui/components/ui/popover";
+import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
+import NextLink from "next/link";
+import { useState } from "react";
+import { toast } from "sonner";
+
+import { Link } from "@/components/common/link";
+import { StatusDot } from "@/components/common/status-dot";
+import {
+ Property,
+ PropertyLabel,
+ PropertyList,
+ PropertyMenuTrigger,
+ PropertyValue,
+} from "@/components/content/property-list";
+import { FormSheetStatusReportUpdateCreate } from "@/components/forms/status-report-update/sheet-create";
+import { FormSheetStatusReportCreate } from "@/components/forms/status-report/sheet-create";
+import { statusVariants } from "@/data/status-report-updates.client";
+import { useTRPC } from "@/lib/trpc/client";
+import { errorMessage } from "@/lib/trpc/error";
+
+type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
+type Report = NonNullable<Incident["statusReport"]>;
+
+function slackChannelUrl(teamId: string, channelId: string): string {
+ return `https://slack.com/app_redirect?team=${teamId}&channel=${channelId}`;
+}
+
+export function IncidentCommunication({ incident }: { incident: Incident }) {
+ const report = incident.statusReport;
+ return (
+ <PropertyList>
+ {report ? (
+ <LinkedReport incident={incident} report={report} />
+ ) : (
+ <UnlinkedReport incident={incident} />
+ )}
+ <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>
+ );
+}
+
+function LinkedReport({
+ incident,
+ report,
+}: {
+ incident: Incident;
+ report: Report;
+}) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [composing, setComposing] = useState(false);
+ const [confirmUnlink, setConfirmUnlink] = useState(false);
+ const unlink = useMutation(
+ trpc.incident.unlinkStatusReport.mutationOptions({
+ onSuccess: () => {
+ setConfirmUnlink(false);
+ return Promise.all([
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.get.queryKey({ id: incident.id }),
+ }),
+ queryClient.invalidateQueries({
+ queryKey: trpc.incident.linkedStatusReportIds.queryKey(),
+ }),
+ ]);
+ },
+ onError: (error) => toast.error(errorMessage(error)),
+ }),
+ );
+ const closed = incident.closedAt !== null;
+ // The sheet needs components and past updates, which the incident
+ // embeds only in part: fetched once the operator asks for it.
+ const { data: fullReport } = useQuery({
+ ...trpc.statusReport.get.queryOptions({ id: report.id }),
+ enabled: composing,
+ });
+
+ return (
+ <Property>
+ <PropertyLabel>Status report</PropertyLabel>
+ <PropertyValue>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <PropertyMenuTrigger>
+ <StatusDot variant={statusVariants[report.status]} />
+ <span className="truncate">{report.title}</span>
+ </PropertyMenuTrigger>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className="w-[var(--radix-dropdown-menu-trigger-width)]"
+ >
+ <DropdownMenuItem onSelect={() => setComposing(true)}>
+ <Send />
+ Post public update
+ </DropdownMenuItem>
+ {report.pageId ? (
+ <DropdownMenuItem asChild>
+ <NextLink
+ href={`/status-pages/${report.pageId}/status-reports/${report.id}`}
+ >
+ <ArrowUpRight />
+ Open report
+ </NextLink>
+ </DropdownMenuItem>
+ ) : null}
+ {closed ? null : (
+ <>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem
+ variant="destructive"
+ onSelect={() => setConfirmUnlink(true)}
+ >
+ <Unlinked />
+ Unlink
+ </DropdownMenuItem>
+ </>
+ )}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </PropertyValue>
+ {composing && fullReport ? (
+ <FormSheetStatusReportUpdateCreate
+ report={fullReport}
+ open
+ onOpenChange={setComposing}
+ />
+ ) : null}
+ <AlertDialog open={confirmUnlink} onOpenChange={setConfirmUnlink}>
+ <AlertDialogContent>
+ <AlertDialogHeader>
+ <AlertDialogTitle>Unlink this status report?</AlertDialogTitle>
+ <AlertDialogDescription>
+ {report.title} stays on your status page as it is, but updates
+ from this incident no longer reach it. You can link it again
+ later.
+ </AlertDialogDescription>
+ </AlertDialogHeader>
+ <AlertDialogFooter>
+ <AlertDialogCancel>Keep linked</AlertDialogCancel>
+ <AlertDialogAction
+ disabled={unlink.isPending}
+ onClick={(e) => {
+ e.preventDefault();
+ unlink.mutate({ id: incident.id });
+ }}
+ >
+ Unlink
+ </AlertDialogAction>
+ </AlertDialogFooter>
+ </AlertDialogContent>
+ </AlertDialog>
+ </Property>
+ );
+}
+
+function UnlinkedReport({ incident }: { incident: Incident }) {
+ const trpc = useTRPC();
+ const queryClient = useQueryClient();
+ const [createOpen, setCreateOpen] = useState(false);
+ const [linking, setLinking] = useState(false);
+ 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.linkedStatusReportIds.queryKey(),
+ }),
+ ]);
+ const link = useMutation(
+ trpc.incident.linkStatusReport.mutationOptions({ onSuccess: refresh }),
+ );
+ const { data: reports } = useQuery({
+ ...trpc.statusReport.list.queryOptions({ order: "desc" }),
+ enabled: !closed,
+ });
+ const { data: linkedIds } = useQuery({
+ ...trpc.incident.linkedStatusReportIds.queryOptions(),
+ enabled: !closed,
+ });
+ // Until both load, the list could offer reports another incident holds.
+ const linked = linkedIds ? new Set(linkedIds) : null;
+ const linkable =
+ reports && linked ? reports.filter((r) => !linked.has(r.id)) : [];
+
+ function linkReport(statusReportId: number) {
+ setLinking(false);
+ toast.promise(link.mutateAsync({ id: incident.id, statusReportId }), {
+ loading: "Linking...",
+ success: "Status report linked",
+ error: (error) => errorMessage(error),
+ });
+ }
+
+ return (
+ <Property>
+ <PropertyLabel>Status report</PropertyLabel>
+ <PropertyValue>
+ {closed ? (
+ <span className="text-muted-foreground">Not published</span>
+ ) : linking ? (
+ <Popover open onOpenChange={(open) => !open && setLinking(false)}>
+ <PopoverTrigger asChild>
+ <PropertyMenuTrigger className="text-muted-foreground">
+ Search status reports...
+ </PropertyMenuTrigger>
+ </PopoverTrigger>
+ <PopoverContent
+ align="start"
+ className="w-[var(--radix-popover-trigger-width)] p-0"
+ >
+ <Command>
+ <CommandInput placeholder="Search status reports..." />
+ <CommandList>
+ <CommandEmpty>No status report found.</CommandEmpty>
+ <CommandGroup>
+ {linkable.map((r) => (
+ <CommandItem
+ key={r.id}
+ value={String(r.id)}
+ keywords={[r.title, r.page.title, r.status]}
+ onSelect={() => linkReport(r.id)}
+ >
+ <StatusDot variant={statusVariants[r.status]} />
+ <span className="truncate">{r.title}</span>
+ <span className="text-muted-foreground ml-auto truncate text-xs">
+ {r.page.title}
+ </span>
+ </CommandItem>
+ ))}
+ </CommandGroup>
+ </CommandList>
+ </Command>
+ </PopoverContent>
+ </Popover>
+ ) : (
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <PropertyMenuTrigger className="text-muted-foreground">
+ Not published
+ </PropertyMenuTrigger>
+ </DropdownMenuTrigger>
+ <DropdownMenuContent
+ align="start"
+ className="w-[var(--radix-dropdown-menu-trigger-width)]"
+ >
+ <DropdownMenuLabel className="text-muted-foreground font-normal whitespace-normal">
+ Nothing here is public. Customers only see what you publish on
+ your status page.
+ </DropdownMenuLabel>
+ <DropdownMenuSeparator />
+ <DropdownMenuItem onSelect={() => setCreateOpen(true)}>
+ <Add />
+ Create status report
+ </DropdownMenuItem>
+ {linkable.length > 0 ? (
+ <DropdownMenuItem onSelect={() => setLinking(true)}>
+ <Linked />
+ Link existing
+ </DropdownMenuItem>
+ ) : null}
+ </DropdownMenuContent>
+ </DropdownMenu>
+ )}
+ </PropertyValue>
+ {/* Mounted on demand: the sheet fetches pages as soon as it renders. */}
+ {createOpen ? (
+ <FormSheetStatusReportCreate
+ open
+ onOpenChange={setCreateOpen}
+ incidentId={incident.id}
+ onCreated={() => refresh().catch(console.error)}
+ />
+ ) : null}
+ </Property>
+ );
+}
diff --git a/apps/dashboard/src/components/incidents/incident-status-report.tsx b/apps/dashboard/src/components/incidents/incident-status-report.tsx
deleted file mode 100644
index a53f50b00..000000000
--- a/apps/dashboard/src/components/incidents/incident-status-report.tsx
+++ /dev/null
@@ -1,454 +0,0 @@
-"use client";
-
-import type { RouterOutputs } from "@openstatus/api";
-import { statusReportStatus } from "@openstatus/db/src/schema/status_reports/constants";
-import { Check, Expand } from "@openstatus/icons";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@openstatus/ui/components/ui/alert-dialog";
-import { Button } from "@openstatus/ui/components/ui/button";
-import { Checkbox } from "@openstatus/ui/components/ui/checkbox";
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
-} from "@openstatus/ui/components/ui/command";
-import { Label } from "@openstatus/ui/components/ui/label";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@openstatus/ui/components/ui/popover";
-import {
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@openstatus/ui/components/ui/select";
-import { Textarea } from "@openstatus/ui/components/ui/textarea";
-import { cn } from "@openstatus/ui/lib/utils";
-import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
-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 { FormSheetStatusReportCreate } from "@/components/forms/status-report/sheet-create";
-import { usePublishUpdate } from "@/components/status-reports/use-publish-update";
-import { statusVariants } from "@/data/status-report-updates.client";
-import { useTRPC } from "@/lib/trpc/client";
-import { errorMessage } from "@/lib/trpc/error";
-
-type Incident = NonNullable<RouterOutputs["incident"]["get"]>;
-
-export function IncidentStatusReport({
- incident,
- canNotify,
-}: {
- incident: Incident;
- canNotify: boolean;
-}) {
- if (incident.statusReport) {
- return (
- <LinkedReport
- incident={incident}
- report={incident.statusReport}
- canNotify={canNotify}
- />
- );
- }
- return <UnlinkedReport incident={incident} />;
-}
-
-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,
- canNotify,
-}: {
- incident: Incident;
- report: NonNullable<Incident["statusReport"]>;
- canNotify: boolean;
-}) {
- const trpc = useTRPC();
- const queryClient = useQueryClient();
- const [composing, setComposing] = useState(false);
- const [confirmUnlink, setConfirmUnlink] = useState(false);
- const [status, setStatus] = useState<string>(
- report.status === "resolved" ? "monitoring" : report.status,
- );
- const [message, setMessage] = useState("");
- const [notifySubscribers, setNotifySubscribers] = useState(canNotify);
- const update = usePublishUpdate(report.id);
- const unlink = useMutation(
- trpc.incident.unlinkStatusReport.mutationOptions({
- onSuccess: () => {
- setConfirmUnlink(false);
- return Promise.all([
- queryClient.invalidateQueries({
- queryKey: trpc.incident.get.queryKey({ id: incident.id }),
- }),
- queryClient.invalidateQueries({
- queryKey: trpc.incident.linkedStatusReportIds.queryKey(),
- }),
- ]);
- },
- onError: (error) => toast.error(errorMessage(error)),
- }),
- );
- const closed = incident.closedAt !== null;
-
- async function post() {
- const parsed = statusReportStatus.find((s) => s === status);
- if (!parsed) return;
- const promise = update.publish({
- statusReportId: report.id,
- status: parsed,
- message,
- date: new Date(),
- notifySubscribers,
- });
- toast.promise(promise, {
- loading: "Posting public update...",
- success: "Public update posted",
- error: (error) => errorMessage(error),
- });
- await promise;
- setMessage("");
- setComposing(false);
- }
-
- return (
- <ActionCard>
- <ActionCardHeader>
- <ActionCardTitle className="flex items-center gap-2 text-sm">
- Published
- <span className="text-muted-foreground ml-auto flex items-center gap-1.5 font-mono text-xs font-normal capitalize">
- <StatusDot variant={statusVariants[report.status]} />
- {report.status}
- </span>
- </ActionCardTitle>
- <ActionCardDescription>
- {report.pageId ? (
- <Link
- href={`/status-pages/${report.pageId}/status-reports/${report.id}`}
- >
- {report.title}
- </Link>
- ) : (
- <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={setNotifySubscribers}
- />
- ) : 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"
- onClick={() => setConfirmUnlink(true)}
- >
- Unlink
- </Button>
- )}
- </>
- )}
- </ActionCardFooter>
- <AlertDialog open={confirmUnlink} onOpenChange={setConfirmUnlink}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Unlink this status report?</AlertDialogTitle>
- <AlertDialogDescription>
- {report.title} stays on your status page as it is, but updates
- from this incident no longer reach it. You can link it again
- later.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Keep linked</AlertDialogCancel>
- <AlertDialogAction
- disabled={unlink.isPending}
- onClick={(e) => {
- e.preventDefault();
- unlink.mutate({ id: incident.id });
- }}
- >
- Unlink
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </ActionCard>
- );
-}
-
-function UnlinkedReport({ incident }: { incident: Incident }) {
- const trpc = useTRPC();
- const queryClient = useQueryClient();
- const [createOpen, setCreateOpen] = useState(false);
- const [linking, setLinking] = useState(false);
- const [pickerOpen, setPickerOpen] = useState(false);
- const [reportId, setReportId] = useState<number | null>(null);
- 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.linkedStatusReportIds.queryKey(),
- }),
- ]);
- const link = useMutation(
- trpc.incident.linkStatusReport.mutationOptions({ onSuccess: refresh }),
- );
- const { data: reports } = useQuery({
- ...trpc.statusReport.list.queryOptions({ order: "desc" }),
- enabled: !closed,
- });
- const { data: linkedIds } = useQuery({
- ...trpc.incident.linkedStatusReportIds.queryOptions(),
- enabled: !closed,
- });
- // Until both load, the list could offer reports another incident holds.
- const linked = linkedIds ? new Set(linkedIds) : null;
- const linkable =
- reports && linked ? reports.filter((r) => !linked.has(r.id)) : [];
- const selected = linkable.find((r) => r.id === reportId);
- // Closing mid-edit would otherwise strand a form whose footer is gone.
- const showLink = !closed && linking && linkable.length > 0;
-
- return (
- <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>
- {showLink ? (
- <ActionCardContent className="grid gap-2">
- <Popover open={pickerOpen} onOpenChange={setPickerOpen}>
- <PopoverTrigger asChild>
- <Button
- size="sm"
- variant="outline"
- role="combobox"
- aria-expanded={pickerOpen}
- className={cn(
- "w-full justify-between font-normal",
- !selected && "text-muted-foreground",
- )}
- >
- {selected ? (
- <span className="flex min-w-0 items-center gap-2">
- <StatusDot variant={statusVariants[selected.status]} />
- <span className="truncate">{selected.title}</span>
- </span>
- ) : (
- "Search status reports..."
- )}
- <Expand className="size-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-[var(--radix-popover-trigger-width)] p-0">
- <Command>
- <CommandInput placeholder="Search status reports..." />
- <CommandList>
- <CommandEmpty>No status report found.</CommandEmpty>
- <CommandGroup>
- {linkable.map((r) => (
- <CommandItem
- key={r.id}
- value={String(r.id)}
- keywords={[r.title, r.page.title, r.status]}
- onSelect={() => {
- setReportId(r.id);
- setPickerOpen(false);
- }}
- >
- <StatusDot variant={statusVariants[r.status]} />
- <span className="truncate">{r.title}</span>
- <span className="text-muted-foreground ml-auto truncate text-xs">
- {r.page.title}
- </span>
- <Check
- className={cn(
- "size-4 shrink-0",
- r.id === reportId ? "opacity-100" : "opacity-0",
- )}
- />
- </CommandItem>
- ))}
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- </ActionCardContent>
- ) : null}
- {closed ? null : (
- <ActionCardFooter className="flex-wrap gap-2">
- {showLink ? (
- <>
- <Button
- size="sm"
- disabled={!selected || link.isPending}
- onClick={() =>
- selected &&
- toast.promise(
- link.mutateAsync({
- id: incident.id,
- statusReportId: selected.id,
- }),
- {
- loading: "Linking...",
- success: "Status report linked",
- error: (error) => errorMessage(error),
- },
- )
- }
- >
- Link
- </Button>
- <Button
- size="sm"
- variant="ghost"
- onClick={() => setLinking(false)}
- >
- Cancel
- </Button>
- </>
- ) : (
- <>
- <Button size="sm" onClick={() => setCreateOpen(true)}>
- Create status report
- </Button>
- {linkable.length > 0 ? (
- <Button
- size="sm"
- variant="outline"
- onClick={() => setLinking(true)}
- >
- Link existing
- </Button>
- ) : null}
- </>
- )}
- </ActionCardFooter>
- )}
- {/* Mounted on demand: the sheet fetches pages as soon as it renders. */}
- {createOpen ? (
- <FormSheetStatusReportCreate
- open
- onOpenChange={setCreateOpen}
- incidentId={incident.id}
- onCreated={() => refresh().catch(console.error)}
- />
- ) : null}
- </ActionCard>
- );
-}