Skip to content

Open-source status page, incident response and uptime monitoring

i see dead code (#1578)

Thibault Le Ouay58935eba856d
diff --git a/apps/web/src/components/billing/pro-banner.tsx b/apps/web/src/components/billing/pro-banner.tsx
deleted file mode 100644
index 6b02b4d47..000000000
--- a/apps/web/src/components/billing/pro-banner.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-"use client";
-
-import { ArrowRight, ChevronRight, Rocket, X } from "lucide-react";
-import Link from "next/link";
-import { useParams } from "next/navigation";
-import { useEffect, useState } from "react";
-
-import { Button } from "@openstatus/ui/src/components/button";
-
-import { api } from "@/trpc/client";
-
-export function ProBanner() {
- const [hidden, setHidden] = useState(true);
- const params = useParams();
- const workspaceSlug = params?.workspaceSlug;
-
- function onClick() {
- if (document) {
- const expires = new Date();
- expires.setDate(expires.getDate() + 7);
- // store the cookie for 7 days and only for a specific workspace
- document.cookie = `hide-pro-banner=true; expires=${expires}; path=/app/${workspaceSlug}`;
- }
- setHidden(true);
- }
-
- useEffect(() => {
- async function configureProBanner() {
- const workspace = await api.workspace.getWorkspace.query();
- // make sure to display the banner only for free plans
- if (document && workspace?.plan === "free") {
- const cookie = document.cookie
- .split("; ")
- .find((row) => row.startsWith("hide-pro-banner"));
- if (!cookie) {
- setHidden(false);
- }
- }
- }
- configureProBanner();
- }, []);
-
- if (hidden) return null;
-
- return (
- <div className="grid gap-2 rounded-md border border-border p-3">
- <div className="flex items-center justify-between">
- <p className="inline-flex items-center font-medium text-sm">
- OpenStatus Subscription <Rocket className="ml-2 h-4 w-4" />
- </p>
- <Button
- variant="ghost"
- size="icon"
- onClick={onClick}
- className="h-7 w-7"
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
- <p className="text-muted-foreground text-sm">
- Unlock custom domains, teams, 1 min. checks and more.
- </p>
- <Button variant="secondary" size="sm" asChild>
- <Link href={`/app/${workspaceSlug}/settings/billing`} className="group">
- <span className="mr-0.5">Upgrade</span>{" "}
- <ArrowRight className="relative inline h-4 w-0 transition-all group-hover:w-4" />
- <ChevronRight className="relative inline h-4 w-4 transition-all group-hover:w-0" />
- </Link>
- </Button>
- </div>
- );
-}
diff --git a/apps/web/src/components/billing/pro-feature-alert.tsx b/apps/web/src/components/billing/pro-feature-alert.tsx
deleted file mode 100644
index e3232c067..000000000
--- a/apps/web/src/components/billing/pro-feature-alert.tsx
+++ /dev/null
@@ -1,38 +0,0 @@
-"use client";
-
-import { AlertTriangle } from "lucide-react";
-import Link from "next/link";
-import { useParams } from "next/navigation";
-
-import type { WorkspacePlan } from "@openstatus/db/src/schema/workspaces/validation";
-import { Alert, AlertDescription, AlertTitle } from "@openstatus/ui";
-
-interface Props {
- feature: string;
- workspacePlan?: WorkspacePlan;
-}
-
-export function ProFeatureAlert({ feature, workspacePlan = "team" }: Props) {
- const params = useParams<{ workspaceSlug: string }>();
- return (
- <Alert>
- <AlertTriangle className="h-4 w-4" />
- <AlertTitle>
- {feature} is a <span className="capitalize">{workspacePlan}</span>{" "}
- feature.
- </AlertTitle>
- <AlertDescription>
- If you want to use{" "}
- <span className="lowercase underline decoration-dotted">{feature}</span>
- , please upgrade your plan. Go to{" "}
- <Link
- href={`/app/${params.workspaceSlug}/settings/billing`}
- className="inline-flex items-center font-medium text-foreground underline underline-offset-4 hover:no-underline"
- >
- settings
- </Link>
- .
- </AlertDescription>
- </Alert>
- );
-}
diff --git a/apps/web/src/components/billing/pro-feature-badge.tsx b/apps/web/src/components/billing/pro-feature-badge.tsx
deleted file mode 100644
index 808ce0c6b..000000000
--- a/apps/web/src/components/billing/pro-feature-badge.tsx
+++ /dev/null
@@ -1,17 +0,0 @@
-import type { WorkspacePlan } from "@openstatus/db/src/schema";
-import { Badge } from "@openstatus/ui";
-import { upgradePlan } from "./utils";
-
-export function ProFeatureBadge({
- plan,
- minRequiredPlan,
-}: {
- plan: WorkspacePlan;
- minRequiredPlan: WorkspacePlan;
-}) {
- const shouldUpgrade = upgradePlan(plan, minRequiredPlan);
-
- if (!shouldUpgrade) return null;
-
- return <Badge>{minRequiredPlan}</Badge>;
-}
diff --git a/apps/web/src/components/billing/pro-feature-hover-card.tsx b/apps/web/src/components/billing/pro-feature-hover-card.tsx
deleted file mode 100644
index f33ad8535..000000000
--- a/apps/web/src/components/billing/pro-feature-hover-card.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-"use client";
-
-import { useState } from "react";
-
-import type { WorkspacePlan } from "@openstatus/db/src/schema/workspaces/validation";
-import { HoverCard, HoverCardContent, HoverCardTrigger } from "@openstatus/ui";
-import { ArrowUpRight } from "lucide-react";
-import Link from "next/link";
-import { upgradePlan } from "./utils";
-
-// TBD: we could useParams() to access workspaceSlug
-
-export function ProFeatureHoverCard({
- children,
- plan,
- minRequiredPlan,
- workspaceSlug,
-}: {
- children: React.ReactNode;
- plan: WorkspacePlan;
- minRequiredPlan: WorkspacePlan;
- workspaceSlug: string;
-}) {
- const [open, setOpen] = useState(false);
- const shouldUpgrade = upgradePlan(plan, minRequiredPlan);
-
- if (!shouldUpgrade) return children;
-
- // TODO: add a <Badge /> component to display the plan name
-
- return (
- <HoverCard openDelay={0} open={open} onOpenChange={setOpen}>
- <HoverCardTrigger
- onClick={() => setOpen(true)}
- className="relative cursor-not-allowed opacity-70"
- asChild
- >
- {children}
- </HoverCardTrigger>
- <HoverCardContent side="top" className="grid gap-2">
- <p className="text-muted-foreground text-sm">
- This feature is only available starting from the{" "}
- <span className="font-semibold capitalize">{minRequiredPlan}</span>{" "}
- plan.
- </p>
- <p className="text-sm">
- <Link
- href={`/app/${workspaceSlug}/settings/billing`}
- target="_blank"
- className="group inline-flex items-center font-medium text-foreground underline underline-offset-4 hover:no-underline"
- >
- Upgrade now
- <ArrowUpRight className="ml-1 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-foreground" />
- </Link>
- </p>
- </HoverCardContent>
- </HoverCard>
- );
-}
diff --git a/apps/web/src/components/billing/utils.ts b/apps/web/src/components/billing/utils.ts
deleted file mode 100644
index 5784872fb..000000000
--- a/apps/web/src/components/billing/utils.ts
+++ /dev/null
@@ -1,6 +0,0 @@
-import { workspacePlanHierarchy } from "@openstatus/db/src/schema";
-import type { WorkspacePlan } from "@openstatus/db/src/schema/workspaces/validation";
-
-export function upgradePlan(current: WorkspacePlan, required: WorkspacePlan) {
- return workspacePlanHierarchy[current] < workspacePlanHierarchy[required];
-}
diff --git a/apps/web/src/components/dashboard/help-callout.tsx b/apps/web/src/components/dashboard/help-callout.tsx
deleted file mode 100644
index b4f2c25d5..000000000
--- a/apps/web/src/components/dashboard/help-callout.tsx
+++ /dev/null
@@ -1,31 +0,0 @@
-import { HelpCircle } from "lucide-react";
-
-import { Alert, AlertDescription, AlertTitle } from "@openstatus/ui";
-
-export function HelpCallout() {
- return (
- <Alert className="max-w-md">
- <HelpCircle className="h-4 w-4" />
- <AlertTitle className="">Need help?</AlertTitle>
- <AlertDescription className="text-muted-foreground">
- Let us know at{" "}
- <a
- href="mailto:[email protected]"
- className="font-medium text-foreground underline hover:no-underline"
- >
- </a>{" "}
- or join our{" "}
- <a
- href="/discord"
- target="_blank"
- className="font-medium text-foreground underline hover:no-underline"
- rel="noreferrer"
- >
- Discord
- </a>
- .
- </AlertDescription>
- </Alert>
- );
-}
diff --git a/apps/web/src/components/dashboard/info-alert-dialog.tsx b/apps/web/src/components/dashboard/info-alert-dialog.tsx
deleted file mode 100644
index 02f186211..000000000
--- a/apps/web/src/components/dashboard/info-alert-dialog.tsx
+++ /dev/null
@@ -1,72 +0,0 @@
-"use client";
-import { useEffect, useState } from "react";
-
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
-} from "@openstatus/ui";
-
-interface InfoAlertDialogProps {
- workspaceSlug: string;
- /**
- * Default expiration time in days
- */
- expires?: number;
-
- id: string;
- title: React.ReactNode;
- description: React.ReactNode;
-}
-
-export function InfoAlertDialog({
- workspaceSlug,
- expires = 7,
- id,
- title,
- description,
-}: InfoAlertDialogProps) {
- const [open, setOpen] = useState(false);
-
- function onClick() {
- if (document) {
- const expiresAt = new Date();
- expiresAt.setDate(expiresAt.getDate() + expires);
- // store the cookie for 7 days and only for a specific workspace
- document.cookie = `${id}=true; expires=${expiresAt}; path=/app/${workspaceSlug}`;
- }
- setOpen(false);
- }
-
- useEffect(() => {
- async function configureProBanner() {
- if (document) {
- const cookie = document.cookie
- .split("; ")
- .find((row) => row.startsWith(id));
- if (!cookie) {
- setOpen(true);
- }
- }
- }
- configureProBanner();
- }, [id]);
-
- return (
- <AlertDialog open={open} onOpenChange={setOpen}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>{title}</AlertDialogTitle>
- <AlertDialogDescription>{description}</AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogAction onClick={onClick}>Continue</AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/dashboard/limit.tsx b/apps/web/src/components/dashboard/limit.tsx
deleted file mode 100644
index 4cfa4ab85..000000000
--- a/apps/web/src/components/dashboard/limit.tsx
+++ /dev/null
@@ -1,18 +0,0 @@
-import Link from "next/link";
-
-export function Limit() {
- return (
- <div className="col-span-full text-center">
- <p className="text-muted-foreground text-sm">
- You have reached the account limits. Please{" "}
- <Link
- href={"./settings/billing"}
- className="text-foreground underline underline-offset-4 hover:no-underline"
- >
- upgrade
- </Link>{" "}
- your account.
- </p>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/incident/columns.tsx b/apps/web/src/components/data-table/incident/columns.tsx
deleted file mode 100644
index 23faaec90..000000000
--- a/apps/web/src/components/data-table/incident/columns.tsx
+++ /dev/null
@@ -1,135 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import { formatDistanceStrict } from "date-fns";
-import Image from "next/image";
-import Link from "next/link";
-
-import type { Incident } from "@openstatus/db/src/schema";
-
-import { formatDateTime } from "@/lib/utils";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-export const columns: ColumnDef<Incident>[] = [
- {
- accessorKey: "monitorId",
- header: "Monitor",
- cell: ({ row }) => {
- return (
- <Link
- href={`./monitors/${row.original.monitorId}/overview`}
- className="group flex items-center gap-2"
- >
- <span className="max-w-[125px] truncate group-hover:underline">
- {row.original.monitorName}
- </span>
- </Link>
- );
- },
- },
- {
- accessorKey: "startedAt",
- header: "Started At",
- cell: ({ row }) => {
- const { startedAt, incidentScreenshotUrl } = row.original;
- const date = startedAt ? formatDateTime(startedAt) : "-";
- return (
- <div className="flex gap-2">
- <span className="max-w-[150px] truncate text-muted-foreground sm:max-w-[200px] lg:max-w-[250px] xl:max-w-[350px]">
- {date}
- </span>
- {incidentScreenshotUrl ? (
- <a
- href={incidentScreenshotUrl}
- target="_blank"
- rel="noreferrer"
- className="relative relative h-5 w-5 overflow-hidden rounded border"
- >
- <Image
- src={incidentScreenshotUrl}
- alt="incident screenshot"
- fill={true}
- />
- </a>
- ) : null}
- </div>
- );
- },
- },
- {
- accessorKey: "acknowledgetAt",
- header: "Acknowledged At",
- cell: ({ row }) => {
- const { acknowledgedAt } = row.original;
- const date = acknowledgedAt ? formatDateTime(acknowledgedAt) : "-";
- return (
- <div className="flex">
- <span className="max-w-[150px] truncate text-muted-foreground sm:max-w-[200px] lg:max-w-[250px] xl:max-w-[350px]">
- {date}
- </span>
- </div>
- );
- },
- },
- {
- accessorKey: "resolvedAt",
- header: "Resolved At",
- cell: ({ row }) => {
- const { resolvedAt, recoveryScreenshotUrl } = row.original;
- const date = resolvedAt ? formatDateTime(resolvedAt) : "-";
- return (
- <div className="flex gap-2">
- <span className="max-w-[150px] truncate text-muted-foreground sm:max-w-[200px] lg:max-w-[250px] xl:max-w-[350px]">
- {date}
- </span>
- {recoveryScreenshotUrl ? (
- <a
- href={recoveryScreenshotUrl}
- target="_blank"
- rel="noreferrer"
- className="relative h-5 w-5 overflow-hidden rounded border"
- >
- <Image
- src={recoveryScreenshotUrl}
- alt="recovery screenshot"
- fill={true}
- />
- </a>
- ) : null}
- </div>
- );
- },
- },
- {
- header: "Duration",
- cell: ({ row }) => {
- const { startedAt, resolvedAt } = row.original;
-
- if (!resolvedAt) {
- return <span className="text-muted-foreground">-</span>;
- }
-
- const duration = formatDistanceStrict(
- new Date(startedAt),
- new Date(resolvedAt),
- );
- return (
- <div className="flex">
- <span className="max-w-[150px] truncate text-muted-foreground sm:max-w-[200px] lg:max-w-[250px] xl:max-w-[350px]">
- {duration}
- </span>
- </div>
- );
- },
- },
- {
- id: "actions",
- cell: ({ row }) => {
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
-];
diff --git a/apps/web/src/components/data-table/incident/data-table-row-actions.tsx b/apps/web/src/components/data-table/incident/data-table-row-actions.tsx
deleted file mode 100644
index 3d68d5cba..000000000
--- a/apps/web/src/components/data-table/incident/data-table-row-actions.tsx
+++ /dev/null
@@ -1,147 +0,0 @@
-"use client";
-
-import type { Row } from "@tanstack/react-table";
-import { MoreHorizontal } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-
-import { selectIncidentSchema } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-interface DataTableRowActionsProps<TData> {
- row: Row<TData>;
-}
-
-export function DataTableRowActions<TData>({
- row,
-}: DataTableRowActionsProps<TData>) {
- const incident = selectIncidentSchema.parse(row.original);
- const router = useRouter();
- const [isPending, startTransition] = React.useTransition();
- const [alertOpen, setAlertOpen] = React.useState(false);
-
- async function resolved() {
- startTransition(async () => {
- try {
- if (!incident.id) return;
- await api.incident.resolvedIncident.mutate({ id: incident.id });
- toastAction("success");
- router.refresh();
- } catch {
- toastAction("error");
- }
- });
- }
-
- async function acknowledge() {
- startTransition(async () => {
- try {
- if (!incident.id) return;
- await api.incident.acknowledgeIncident.mutate({ id: incident.id });
- toastAction("success");
- router.refresh();
- } catch {
- toastAction("error");
- }
- });
- }
-
- async function onDelete() {
- startTransition(async () => {
- try {
- if (!incident.id) return;
- await api.incident.delete.mutate({ id: incident.id });
- toastAction("success");
- setAlertOpen(false);
- router.refresh();
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 data-[state=open]:bg-accent"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <DropdownMenuItem
- disabled={incident.acknowledgedAt !== null}
- onClick={acknowledge}
- >
- Acknowledge
- </DropdownMenuItem>
- <DropdownMenuItem
- disabled={
- incident.resolvedAt !== null || incident.acknowledgedAt === null
- }
- onClick={resolved}
- >
- Resolved
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <Link href={`./incidents/${incident.id}/overview`}>
- <DropdownMenuItem>Details</DropdownMenuItem>
- </Link>
- <DropdownMenuSeparator />
- <AlertDialogTrigger asChild>
- <DropdownMenuItem className="text-destructive focus:bg-destructive focus:text-background">
- Delete
- </DropdownMenuItem>
- </AlertDialogTrigger>
- </DropdownMenuContent>
- </DropdownMenu>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- monitor.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/data-table/incident/data-table.tsx b/apps/web/src/components/data-table/incident/data-table.tsx
deleted file mode 100644
index d2e862705..000000000
--- a/apps/web/src/components/data-table/incident/data-table.tsx
+++ /dev/null
@@ -1,83 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-// FIXME: right now, the mobile layout is messed up
-// https://github.com/TanStack/table/discussions/3192#discussioncomment-6458134
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/invitation/columns.tsx b/apps/web/src/components/data-table/invitation/columns.tsx
deleted file mode 100644
index 4618ab8d2..000000000
--- a/apps/web/src/components/data-table/invitation/columns.tsx
+++ /dev/null
@@ -1,47 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-
-import type { Invitation, WorkspaceRole } from "@openstatus/db/src/schema";
-import { Badge } from "@openstatus/ui/src/components/badge";
-
-import { formatDate } from "@/lib/utils";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-// TODO: add total number of monitors
-
-export const columns: ColumnDef<Invitation>[] = [
- {
- accessorKey: "email",
- header: "Email",
- },
- {
- accessorKey: "role",
- header: "Role",
- cell: ({ row }) => {
- const role = row.getValue("role") as WorkspaceRole;
- return (
- <Badge variant={role === "member" ? "outline" : "default"}>
- {row.getValue("role")}
- </Badge>
- );
- },
- },
- {
- accessorKey: "expiresAt",
- header: "Expires at",
- cell: ({ row }) => {
- return <span>{formatDate(row.getValue("expiresAt"))}</span>;
- },
- },
- {
- id: "actions",
- cell: ({ row }) => {
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
-];
diff --git a/apps/web/src/components/data-table/invitation/data-table-row-actions.tsx b/apps/web/src/components/data-table/invitation/data-table-row-actions.tsx
deleted file mode 100644
index bb30f5ff0..000000000
--- a/apps/web/src/components/data-table/invitation/data-table-row-actions.tsx
+++ /dev/null
@@ -1,82 +0,0 @@
-"use client";
-
-import type { Row } from "@tanstack/react-table";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-
-import { selectInvitationSchema } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-interface DataTableRowActionsProps<TData> {
- row: Row<TData>;
-}
-
-export function DataTableRowActions<TData>({
- row,
-}: DataTableRowActionsProps<TData>) {
- const invitation = selectInvitationSchema.parse(row.original);
- const router = useRouter();
- const [alertOpen, setAlertOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
-
- async function onRevoke() {
- startTransition(async () => {
- try {
- if (!invitation.id) return;
- await api.invitation.delete.mutate({ id: invitation.id });
- toastAction("deleted");
- router.refresh();
- setAlertOpen(false);
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>
- <AlertDialogTrigger asChild>
- <Button variant="outline" size="sm">
- Revoke
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- The invitation will be revoked and the user will no longer be able
- to join the workspace.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onRevoke();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Revoke" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/data-table/invitation/data-table.tsx b/apps/web/src/components/data-table/invitation/data-table.tsx
deleted file mode 100644
index d152669fc..000000000
--- a/apps/web/src/components/data-table/invitation/data-table.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/maintenance/columns.tsx b/apps/web/src/components/data-table/maintenance/columns.tsx
deleted file mode 100644
index 4b38442c3..000000000
--- a/apps/web/src/components/data-table/maintenance/columns.tsx
+++ /dev/null
@@ -1,58 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-
-import type { Maintenance } from "@openstatus/db/src/schema";
-import { format } from "date-fns";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-export const columns: ColumnDef<Maintenance>[] = [
- {
- accessorKey: "title",
- header: "Title",
- },
- {
- accessorKey: "message",
- header: "Message",
- cell: ({ row }) => {
- return (
- <p className="flex max-w-[125px] lg:max-w-[250px] xl:max-w-[350px]">
- <span className="truncate">{row.getValue("message")}</span>
- </p>
- );
- },
- },
- {
- accessorKey: "from",
- header: "Start",
- cell: ({ row }) => {
- return (
- <p className="text-muted-foreground">
- {format(row.getValue("from"), "LLL dd, y HH:mm zzzz")}
- </p>
- );
- },
- },
- {
- accessorKey: "to",
- header: "End",
- cell: ({ row }) => {
- return (
- <p className="text-muted-foreground">
- {format(row.getValue("to"), "LLL dd, y HH:mm zzzz")}
- </p>
- );
- },
- },
- // missing: from, to
- {
- id: "actions",
- cell: ({ row }) => {
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
-];
diff --git a/apps/web/src/components/data-table/maintenance/data-table-row-actions.tsx b/apps/web/src/components/data-table/maintenance/data-table-row-actions.tsx
deleted file mode 100644
index 6d30ded01..000000000
--- a/apps/web/src/components/data-table/maintenance/data-table-row-actions.tsx
+++ /dev/null
@@ -1,115 +0,0 @@
-"use client";
-
-import type { Row } from "@tanstack/react-table";
-import { MoreHorizontal } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-
-import { selectMaintenanceSchema } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-interface DataTableRowActionsProps<TData> {
- row: Row<TData>;
-}
-
-export function DataTableRowActions<TData>({
- row,
-}: DataTableRowActionsProps<TData>) {
- const maintenance = selectMaintenanceSchema.parse(row.original);
- const router = useRouter();
- const [alertOpen, setAlertOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
- const { copy } = useCopyToClipboard();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- if (!maintenance.id) return;
- await api.maintenance.delete.mutate({ id: maintenance.id });
- toastAction("deleted");
- router.refresh();
- setAlertOpen(false);
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 data-[state=open]:bg-accent"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <Link href={`./maintenances/${maintenance.id}/edit`}>
- <DropdownMenuItem>Edit</DropdownMenuItem>
- </Link>
- <DropdownMenuItem
- onClick={() =>
- copy(`${maintenance.id}`, {
- withToast: `Copied ID '${maintenance.id}'`,
- })
- }
- >
- Copy ID
- </DropdownMenuItem>
- <AlertDialogTrigger asChild>
- <DropdownMenuItem className="text-destructive focus:bg-destructive focus:text-background">
- Delete
- </DropdownMenuItem>
- </AlertDialogTrigger>
- </DropdownMenuContent>
- </DropdownMenu>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- monitor.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/data-table/maintenance/data-table.tsx b/apps/web/src/components/data-table/maintenance/data-table.tsx
deleted file mode 100644
index d152669fc..000000000
--- a/apps/web/src/components/data-table/maintenance/data-table.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/monitor/columns.tsx b/apps/web/src/components/data-table/monitor/columns.tsx
deleted file mode 100644
index e81247a12..000000000
--- a/apps/web/src/components/data-table/monitor/columns.tsx
+++ /dev/null
@@ -1,349 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import { formatDistanceToNowStrict } from "date-fns";
-import Link from "next/link";
-
-import type {
- Incident,
- Maintenance,
- Monitor,
- MonitorTag,
-} from "@openstatus/db/src/schema";
-import { Tracker } from "@openstatus/tracker";
-import {
- Badge,
- Checkbox,
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui";
-
-import { StatusDotWithTooltip } from "@/components/monitor/status-dot-with-tooltip";
-import { TagBadgeWithTooltip } from "@/components/monitor/tag-badge-with-tooltip";
-import { Bar } from "@/components/tracker/tracker";
-import { isActiveMaintenance } from "@/lib/maintenances/utils";
-
-import type { ResponseStatusTracker, ResponseTimeMetrics } from "@/lib/tb";
-import { Eye, EyeOff, Radio, View } from "lucide-react";
-import type { ReactNode } from "react";
-import { DataTableColumnHeader } from "./data-table-column-header";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-// EXAMPLE: get the type of the response of the endpoint
-
-export const columns: ColumnDef<{
- monitor: Monitor;
- metrics?: ResponseTimeMetrics;
- data?: ResponseStatusTracker[];
- incidents?: Incident[];
- maintenances?: Maintenance[];
- tags?: MonitorTag[];
-}>[] = [
- {
- id: "id",
- accessorKey: "id",
- accessorFn: (row) => row.monitor.id,
- },
- {
- id: "jobType",
- accessorKey: "jobType",
- accessorFn: (row) => row.monitor.jobType,
- filterFn: (row, _id, value) => {
- if (!Array.isArray(value)) return true;
- return value.includes(row.original.monitor.jobType);
- },
- },
- {
- id: "select",
- header: ({ table }) => (
- <Checkbox
- checked={
- table.getIsAllPageRowsSelected() ||
- (table.getIsSomePageRowsSelected() && "indeterminate")
- }
- onCheckedChange={(value) => table.toggleAllPageRowsSelected(!!value)}
- aria-label="Select all"
- className="translate-y-[2px]"
- />
- ),
- cell: ({ row }) => (
- <Checkbox
- checked={row.getIsSelected()}
- onCheckedChange={(value) => row.toggleSelected(!!value)}
- aria-label="Select row"
- className="translate-y-[2px]"
- />
- ),
- },
- {
- accessorKey: "active",
- accessorFn: (row) => row.monitor.active,
- header: () => <Radio className="h-4 w-4" />,
- cell: ({ row }) => {
- const { active, status } = row.original.monitor;
- const maintenance = isActiveMaintenance(row.original.maintenances);
- return (
- <div className="flex w-4 items-center justify-center">
- <StatusDotWithTooltip
- active={active}
- status={status}
- maintenance={maintenance}
- />
- </div>
- );
- },
- filterFn: (row, _id, value) => {
- if (!Array.isArray(value)) return true;
- return value.includes(row.original.monitor.active);
- },
- meta: {
- headerClassName: "w-4",
- },
- },
- {
- accessorKey: "name",
- accessorFn: (row) => row.monitor.name, // used for filtering as name is nested within the monitor object
- header: ({ column }) => (
- <DataTableColumnHeader column={column} title="Name" />
- ),
- cell: ({ row }) => {
- const { name, public: _public } = row.original.monitor;
- return (
- <div className="flex gap-2">
- <Link
- href={`./monitors/${row.original.monitor.id}/overview`}
- className="group flex max-w-full items-center gap-2"
- prefetch={false}
- >
- <span className="truncate group-hover:underline">{name}</span>
- </Link>
- {_public ? <Badge variant="secondary">public</Badge> : null}
- </div>
- );
- },
- },
- {
- accessorKey: "tags",
- header: "Tags",
- cell: ({ row }) => {
- const { tags } = row.original;
- if (!tags?.length)
- return <span className="text-muted-foreground">-</span>;
- return <TagBadgeWithTooltip tags={tags} />;
- },
- filterFn: (row, _id, value) => {
- if (!Array.isArray(value)) return true;
- // REMINDER: if one value is found, return true
- // we could consider restricting it to all the values have to be found
- return value.some((item) =>
- row.original.tags?.some((tag) => tag.name === item),
- );
- },
- },
- {
- accessorKey: "public",
- accessorFn: (row) => row.monitor.public,
- header: () => (
- <div className="w-4">
- <View className="h-4 w-4" />
- </div>
- ),
- cell: ({ row }) => {
- const { public: _public } = row.original.monitor;
- return (
- <>
- {_public ? (
- <Eye className="h-4 w-4" />
- ) : (
- <EyeOff className="h-4 w-4" />
- )}
- </>
- );
- },
- filterFn: (row, _id, value) => {
- if (!Array.isArray(value)) return true;
- return value.includes(row.original.monitor.public);
- },
- },
- {
- accessorKey: "tracker",
- header: () => (
- <HeaderTooltip text="UTC time period">
- <span className="underline decoration-dotted">Last 7 days</span>
- </HeaderTooltip>
- ),
- cell: ({ row }) => {
- const tracker = new Tracker({
- data: row.original.data?.slice(0, 7).reverse(),
- incidents: row.original.incidents,
- maintenances: row.original.maintenances,
- });
- return (
- <div className="flex w-24 gap-1">
- {tracker.days?.map((tracker) => (
- <Bar
- key={tracker.day}
- className="h-5"
- showValues={true}
- {...tracker}
- />
- ))}
- </div>
- );
- },
- },
- {
- accessorKey: "lastTimestamp",
- header: "Last ping",
- cell: ({ row }) => {
- const timestamp = row.original.metrics?.lastTimestamp;
- if (timestamp) {
- const distance = formatDistanceToNowStrict(new Date(timestamp), {
- addSuffix: true,
- });
- return (
- <div className="flex max-w-[84px] text-muted-foreground sm:max-w-none">
- <span className="truncate">{distance}</span>
- </div>
- );
- }
- return <span className="text-muted-foreground">-</span>;
- },
- },
- {
- accessorKey: "uptime",
- header: ({ column }) => (
- <DataTableColumnHeader column={column} title="Uptime" />
- ),
- cell: ({ row }) => {
- const { count, ok } = row.original?.metrics || {};
- if (!count || !ok)
- return <span className="text-muted-foreground">-</span>;
- const rounded = Math.round((ok / count) * 10_000) / 100;
- return <DisplayNumber value={rounded} suffix="%" />;
- },
- sortingFn: (rowA, rowB, columnId) => {
- const valueA = rowA.getValue(columnId) as number | undefined;
- const valueB = rowB.getValue(columnId) as number | undefined;
- if (!valueB) return valueA || 1;
- if (!valueA) return -valueB;
- return valueA - valueB;
- },
- },
- {
- accessorKey: "p50Latency",
- accessorFn: (row) => row.metrics?.p50Latency,
- header: ({ column }) => (
- <DataTableColumnHeader column={column} title="P50" />
- ),
- cell: ({ row }) => {
- const latency = row.original.metrics?.p50Latency;
- if (latency) return <DisplayNumber value={latency} suffix="ms" />;
- return <span className="text-muted-foreground">-</span>;
- },
- sortingFn: (rowA, rowB, columnId) => {
- const valueA = rowA.getValue(columnId) as number | undefined;
- const valueB = rowB.getValue(columnId) as number | undefined;
- if (!valueB) return valueA || 1;
- if (!valueA) return -valueB;
- return valueA - valueB;
- },
- },
- {
- accessorKey: "p75Latency",
- accessorFn: (row) => row.metrics?.p75Latency,
- header: ({ column }) => (
- <DataTableColumnHeader column={column} title="P75" />
- ),
- cell: ({ row }) => {
- const latency = row.original.metrics?.p75Latency;
- if (latency) return <DisplayNumber value={latency} suffix="ms" />;
- return <span className="text-muted-foreground">-</span>;
- },
- sortingFn: (rowA, rowB, columnId) => {
- const valueA = rowA.getValue(columnId) as number | undefined;
- const valueB = rowB.getValue(columnId) as number | undefined;
- if (!valueB) return valueA || 1;
- if (!valueA) return -valueB;
- return valueA - valueB;
- },
- },
- {
- accessorKey: "p95Latency",
- accessorFn: (row) => row.metrics?.p95Latency,
- header: ({ column }) => (
- <DataTableColumnHeader column={column} title="P95" />
- ),
- cell: ({ row }) => {
- const latency = row.original.metrics?.p95Latency;
- if (latency) return <DisplayNumber value={latency} suffix="ms" />;
- return <span className="text-muted-foreground">-</span>;
- },
- sortingFn: (rowA, rowB, columnId) => {
- const valueA = rowA.getValue(columnId) as number | undefined;
- const valueB = rowB.getValue(columnId) as number | undefined;
- if (!valueB) return valueA || 1;
- if (!valueA) return -valueB;
- return valueA - valueB;
- },
- },
- {
- accessorKey: "p99Latency",
- accessorFn: (row) => row.metrics?.p99Latency,
- header: ({ column }) => (
- <DataTableColumnHeader column={column} title="P99" />
- ),
- cell: ({ row }) => {
- const latency = row.original.metrics?.p99Latency;
- if (latency) return <DisplayNumber value={latency} suffix="ms" />;
- return <span className="text-muted-foreground">-</span>;
- },
- sortingFn: (rowA, rowB, columnId) => {
- const valueA = rowA.getValue(columnId) as number | undefined;
- const valueB = rowB.getValue(columnId) as number | undefined;
- if (!valueB) return valueA || 1;
- if (!valueA) return -valueB;
- return valueA - valueB;
- },
- },
- {
- id: "actions",
- cell: ({ row }) => {
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
-];
-
-function HeaderTooltip({
- text,
- children,
-}: {
- text: string;
- children: ReactNode;
-}) {
- return (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger suppressHydrationWarning>{children}</TooltipTrigger>
- <TooltipContent>{text}</TooltipContent>
- </Tooltip>
- </TooltipProvider>
- );
-}
-
-function DisplayNumber({ value, suffix }: { value: number; suffix: string }) {
- return (
- <span className="font-mono">
- {new Intl.NumberFormat("us").format(value).toString()}
- <span className="font-normal text-muted-foreground text-xs">
- {suffix}
- </span>
- </span>
- );
-}
diff --git a/apps/web/src/components/data-table/monitor/data-table-column-header.tsx b/apps/web/src/components/data-table/monitor/data-table-column-header.tsx
deleted file mode 100644
index 68b1fea9d..000000000
--- a/apps/web/src/components/data-table/monitor/data-table-column-header.tsx
+++ /dev/null
@@ -1,66 +0,0 @@
-import type { Column } from "@tanstack/react-table";
-import { ArrowDown, ArrowUp, ChevronsUpDown } from "lucide-react";
-
-import {
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@openstatus/ui";
-
-import { cn } from "@/lib/utils";
-
-interface DataTableColumnHeaderProps<TData, TValue>
- extends React.HTMLAttributes<HTMLDivElement> {
- column: Column<TData, TValue>;
- title: string;
-}
-
-export function DataTableColumnHeader<TData, TValue>({
- column,
- title,
- className,
-}: DataTableColumnHeaderProps<TData, TValue>) {
- if (!column.getCanSort()) {
- return <div className={cn(className)}>{title}</div>;
- }
-
- return (
- <div className={cn("flex items-center space-x-2", className)}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- size="sm"
- className="-ml-3 h-8 data-[state=open]:bg-accent"
- >
- <span>{title}</span>
- {column.getIsSorted() === "desc" ? (
- <ArrowUp className="ml-2 h-4 w-4" />
- ) : column.getIsSorted() === "asc" ? (
- <ArrowDown className="ml-2 h-4 w-4" />
- ) : (
- <ChevronsUpDown className="ml-2 h-4 w-4" />
- )}
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="start">
- <DropdownMenuItem onClick={() => column.toggleSorting(false)}>
- <ArrowDown className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
- Asc
- </DropdownMenuItem>
- <DropdownMenuItem onClick={() => column.toggleSorting(true)}>
- <ArrowUp className="mr-2 h-3.5 w-3.5 text-muted-foreground/70" />
- Desc
- </DropdownMenuItem>
- {/* <DropdownMenuSeparator />
- <DropdownMenuItem onClick={() => column.toggleVisibility(false)}>
- <EyeOff className="text-muted-foreground/70 mr-2 h-3.5 w-3.5" />
- Hide
- </DropdownMenuItem> */}
- </DropdownMenuContent>
- </DropdownMenu>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/monitor/data-table-floating-actions.tsx b/apps/web/src/components/data-table/monitor/data-table-floating-actions.tsx
deleted file mode 100644
index 016064690..000000000
--- a/apps/web/src/components/data-table/monitor/data-table-floating-actions.tsx
+++ /dev/null
@@ -1,363 +0,0 @@
-"use client";
-
-import * as Portal from "@radix-ui/react-portal";
-import type { Table } from "@tanstack/react-table";
-import { useEffect, useState, useTransition } from "react";
-
-import { Kbd } from "@/components/kbd";
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toast, toastAction } from "@/lib/toast";
-import { cn } from "@/lib/utils";
-import { api } from "@/trpc/client";
-import type { Monitor, MonitorTag } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
- Popover,
- PopoverContent,
- PopoverTrigger,
- Select,
- SelectContent,
- SelectGroup,
- SelectItem,
- SelectLabel,
- SelectTrigger,
- SelectValue,
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui";
-import { Check, X } from "lucide-react";
-import { useRouter } from "next/navigation";
-
-interface DataTableFloatingActions<TData> {
- table: Table<TData>;
- actions?: [];
- tags?: MonitorTag[];
-}
-
-export function DataTableFloatingActions<TData>({
- table,
- tags,
-}: DataTableFloatingActions<TData>) {
- const router = useRouter();
- const [alertOpen, setAlertOpen] = useState(false);
- const [isPending, startTransition] = useTransition();
- const [method, setMethod] = useState<
- "delete" | "active" | "public" | "tag" | null
- >(null);
- const rows = table.getFilteredSelectedRowModel().rows;
-
- // clear selection on escape key
- useEffect(() => {
- function handleKeyDown(event: KeyboardEvent) {
- if (event.key === "Escape") {
- table.toggleAllRowsSelected(false);
- }
- }
-
- window.addEventListener("keydown", handleKeyDown);
- return () => window.removeEventListener("keydown", handleKeyDown);
- }, [table]);
-
- if (table.getFilteredSelectedRowModel().rows.length === 0) {
- return null;
- }
-
- function handleUpdates(props: Partial<Pick<Monitor, "active" | "public">>) {
- startTransition(async () => {
- toast.promise(
- async () => {
- await api.monitor.updateMonitors.mutate({
- ids: rows.map((row) => row.getValue("id")),
- ...props,
- });
- router.refresh();
- },
- {
- loading: "Updating monitor(s)...",
- success: "Monitor(s) updated!",
- error: "Something went wrong!",
- finally: () => {},
- },
- );
- });
- }
-
- function handleTagUpdates(props: {
- tagId: number;
- action: "add" | "remove";
- }) {
- startTransition(async () => {
- toast.promise(
- async () => {
- await api.monitor.updateMonitorsTag.mutate({
- ids: rows.map((row) => row.getValue("id")),
- ...props,
- });
- router.refresh();
- },
- {
- loading:
- props.action === "add"
- ? "Adding tag to monitor(s)..."
- : "Removing tag from monitor(s)...",
- success:
- props.action === "add"
- ? "Tag added to monitor(s)!"
- : "Tag removed from monitor(s)",
- error: "Something went wrong!",
- finally: () => {},
- },
- );
- });
- }
-
- function handleDeletes() {
- startTransition(async () => {
- try {
- await api.monitor.deleteMonitors.mutate({
- ids: rows.map((row) => row.getValue("id")),
- });
- setAlertOpen(false);
- table.toggleAllRowsSelected(false);
- router.refresh();
- } catch (error) {
- console.error(error);
- toastAction("error");
- }
- });
- }
-
- // TODO: can we make it smarter! Its ugly as hell
-
- const statusValue = rows.every((row) => row.getValue("active") === true)
- ? "true"
- : rows.every((row) => row.getValue("active") === false)
- ? "false"
- : undefined;
-
- const visibilityValue = rows.every((row) => row.getValue("public") === true)
- ? "true"
- : rows.every((row) => row.getValue("public") === false)
- ? "false"
- : undefined;
-
- const everyTagValue =
- tags?.filter((tag) => {
- return rows.every((row) => {
- const _tags = row.getValue("tags");
- if (Array.isArray(_tags)) {
- return _tags.map(({ id }) => id)?.includes(tag.id);
- }
- return false;
- });
- }) || [];
-
- const someTagValue =
- tags?.filter((tag) => {
- return rows.some((row) => {
- const _tags = row.getValue("tags");
- if (Array.isArray(_tags)) {
- return _tags.map(({ id }) => id)?.includes(tag.id);
- }
- return false;
- });
- }) || [];
-
- return (
- <Portal.Root>
- <div className="fixed inset-x-0 bottom-4 z-50 mx-auto w-fit px-4">
- <div className="flex flex-wrap items-center gap-2 rounded-md border bg-background px-4 py-2 shadow-sm">
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- variant="ghost"
- onClick={() => table.toggleAllRowsSelected(false)}
- className="border border-dashed"
- >
- <span className="whitespace-nowrap">
- {rows.length} selected
- </span>
- <X className="ml-1.5 size-4 shrink-0" />
- </Button>
- </TooltipTrigger>
- <TooltipContent className="flex items-center">
- <p className="mr-2">Clear selection</p>
- <Kbd abbrTitle="Escape" variant="outline">
- Esc
- </Kbd>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- <AlertDialog
- open={alertOpen}
- onOpenChange={(value) => setAlertOpen(value)}
- >
- <AlertDialogTrigger asChild>
- <Button
- variant="outline"
- className="border-destructive text-destructive hover:bg-destructive hover:text-background"
- >
- Delete
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- selected monitor(s).
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={() => {
- setMethod("delete");
- handleDeletes();
- }}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {isPending && method === "delete" ? (
- <LoadingAnimation />
- ) : (
- "Delete"
- )}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- <Select
- disabled={isPending && method === "active"}
- value={statusValue}
- onValueChange={(value) => {
- setMethod("active");
- handleUpdates({ active: value === "true" });
- }}
- >
- <SelectTrigger className="h-9 max-w-fit">
- <SelectValue placeholder="Status" />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectLabel>Status</SelectLabel>
- <SelectItem value="true">Active</SelectItem>
- <SelectItem value="false">Inactive</SelectItem>
- </SelectGroup>
- </SelectContent>
- </Select>
- <Popover>
- <PopoverTrigger disabled={isPending && method === "tag"} asChild>
- <Button variant="outline" className="flex items-center gap-2">
- <span>Tags</span>
- {everyTagValue.length ? (
- <div className="relative flex overflow-hidden">
- {everyTagValue.map((tag) => (
- <div
- key={tag.id}
- style={{ backgroundColor: tag.color }}
- className="h-2.5 w-2.5 rounded-full ring-2 ring-background"
- />
- ))}
- </div>
- ) : null}
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-[200px] p-0" align="start">
- <Command>
- <CommandInput placeholder={"Tags"} />
- <CommandList>
- <CommandEmpty>No results found.</CommandEmpty>
- <CommandGroup>
- {tags?.map((tag) => {
- const isSelected = everyTagValue
- .map((tag) => tag.id)
- ?.includes(tag.id);
- const isIndeterminated = !isSelected
- ? someTagValue.map((tag) => tag.id)?.includes(tag.id)
- : false;
- return (
- <CommandItem
- key={String(tag.name)}
- onSelect={() => {
- setMethod("tag");
- handleTagUpdates({
- tagId: tag.id,
- action:
- !isSelected || isIndeterminated
- ? "add"
- : "remove",
- });
- }}
- >
- <div
- className={cn(
- "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
- {
- "bg-primary text-primary-foreground":
- isSelected,
- "text-muted-foreground": isIndeterminated,
- "opacity-50 [&_svg]:invisible":
- !isSelected && !isIndeterminated,
- },
- )}
- >
- <Check className={cn("h-4 w-4")} />
- </div>
- <div className="flex w-full items-center justify-between">
- <span>{tag.name}</span>
- <div
- key={tag.id}
- style={{ backgroundColor: tag.color }}
- className="h-2.5 w-2.5 rounded-full"
- />
- </div>
- </CommandItem>
- );
- })}
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- <Select
- disabled={isPending && method === "public"}
- value={visibilityValue}
- onValueChange={(value) => {
- setMethod("public");
- handleUpdates({ public: value === "true" });
- }}
- >
- <SelectTrigger className="h-9 max-w-fit">
- <SelectValue placeholder="Visibility" />
- </SelectTrigger>
- <SelectContent>
- <SelectGroup>
- <SelectLabel>Visibility</SelectLabel>
- <SelectItem value="true">Public</SelectItem>
- <SelectItem value="false">Private</SelectItem>
- </SelectGroup>
- </SelectContent>
- </Select>
- </div>
- </div>
- </Portal.Root>
- );
-}
diff --git a/apps/web/src/components/data-table/monitor/data-table-pagination.tsx b/apps/web/src/components/data-table/monitor/data-table-pagination.tsx
deleted file mode 100644
index 4ca633141..000000000
--- a/apps/web/src/components/data-table/monitor/data-table-pagination.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-"use client";
-
-import type { Table } from "@tanstack/react-table";
-import {
- ChevronLeft,
- ChevronRight,
- ChevronsLeft,
- ChevronsRight,
-} from "lucide-react";
-
-import {
- Button,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@openstatus/ui";
-
-import { parseAsInteger, useQueryStates } from "nuqs";
-
-// REMINDER: pageIndex pagination issue - jumping back to 0 after change
-
-interface DataTablePaginationProps<TData> {
- table: Table<TData>;
-}
-
-export function DataTablePagination<TData>({
- table,
-}: DataTablePaginationProps<TData>) {
- const [_, setSearchParams] = useQueryStates({
- pageSize: parseAsInteger.withDefault(10),
- // pageIndex: parseAsInteger.withDefault(0),
- });
-
- return (
- <div className="flex flex-wrap-reverse items-center justify-between gap-4 px-2">
- <div>
- <p className="text-muted-foreground text-sm">
- {table.getFilteredSelectedRowModel().rows.length} of{" "}
- {table.getFilteredRowModel().rows.length} row(s) selected.
- </p>
- </div>
- <div className="flex items-center space-x-6 lg:space-x-8">
- <div className="flex items-center space-x-2">
- <p className="font-medium text-sm">Rows per page</p>
- <Select
- value={`${table.getState().pagination.pageSize}`}
- onValueChange={(value) => {
- table.setPageSize(Number(value));
- setSearchParams({ pageSize: Number(value) });
- }}
- >
- <SelectTrigger className="h-8 w-[70px]">
- <SelectValue placeholder={table.getState().pagination.pageSize} />
- </SelectTrigger>
- <SelectContent side="top">
- {[10, 20, 30, 40, 50].map((pageSize) => (
- <SelectItem key={pageSize} value={`${pageSize}`}>
- {pageSize}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </div>
- <div className="flex w-[100px] items-center justify-center font-medium text-sm">
- Page {table.getState().pagination.pageIndex + 1} of{" "}
- {table.getPageCount()}
- </div>
- <div className="flex items-center space-x-2">
- <Button
- variant="outline"
- className="hidden h-8 w-8 p-0 lg:flex"
- onClick={() => {
- table.setPageIndex(0);
- }}
- disabled={!table.getCanPreviousPage()}
- >
- <span className="sr-only">Go to first page</span>
- <ChevronsLeft className="h-4 w-4" />
- </Button>
- <Button
- variant="outline"
- className="h-8 w-8 p-0"
- onClick={() => {
- table.previousPage();
- }}
- disabled={!table.getCanPreviousPage()}
- >
- <span className="sr-only">Go to previous page</span>
- <ChevronLeft className="h-4 w-4" />
- </Button>
- <Button
- variant="outline"
- className="h-8 w-8 p-0"
- onClick={() => {
- table.nextPage();
- }}
- disabled={!table.getCanNextPage()}
- >
- <span className="sr-only">Go to next page</span>
- <ChevronRight className="h-4 w-4" />
- </Button>
- <Button
- variant="outline"
- className="hidden h-8 w-8 p-0 lg:flex"
- onClick={() => {
- table.setPageIndex(table.getPageCount() - 1);
- }}
- disabled={!table.getCanNextPage()}
- >
- <span className="sr-only">Go to last page</span>
- <ChevronsRight className="h-4 w-4" />
- </Button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/monitor/data-table-row-actions.tsx b/apps/web/src/components/data-table/monitor/data-table-row-actions.tsx
deleted file mode 100644
index 93857e3c0..000000000
--- a/apps/web/src/components/data-table/monitor/data-table-row-actions.tsx
+++ /dev/null
@@ -1,202 +0,0 @@
-"use client";
-
-import type { Row } from "@tanstack/react-table";
-import { MoreHorizontal } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import { useState, useTransition } from "react";
-import { z } from "zod";
-
-import { selectMonitorSchema } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import type { RegionChecker } from "@/components/ping-response-analysis/utils";
-import { toast, toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-import type { TCPResponseTest } from "@/app/api/checker/test/tcp/schema";
-import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
-
-interface DataTableRowActionsProps<TData> {
- row: Row<TData>;
-}
-
-export function DataTableRowActions<TData>({
- row,
-}: DataTableRowActionsProps<TData>) {
- const { monitor, isLimitReached } = z
- .object({ monitor: selectMonitorSchema, isLimitReached: z.boolean() })
- .parse(row.original);
- const router = useRouter();
- const [alertOpen, setAlertOpen] = useState(false);
- const [isPending, startTransition] = useTransition();
- const { copy } = useCopyToClipboard();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- if (!monitor.id) return;
- await api.monitor.delete.mutate({ id: monitor.id });
- toastAction("deleted");
- router.refresh();
- setAlertOpen(false);
- } catch {
- toastAction("error");
- }
- });
- }
-
- // FIXME: the test doenst take the assertions into account!
- // FIXME: improve (similar to the one in the edit form - also include toast.promise + better error message!)
- async function onTest() {
- startTransition(async () => {
- const { url, body, method, headers, jobType } = monitor;
-
- try {
- const res = await fetch(`/api/checker/test/${jobType}`, {
- method: "POST",
- headers: new Headers({
- "Content-Type": "application/json",
- }),
- body: JSON.stringify({ url, body, method, headers }),
- });
- const data = (await res.json()) as
- | RegionChecker
- | z.infer<typeof TCPResponseTest>;
-
- // FIXME: assertions
- // it's getting 😭
- const success =
- data.state === "success" && data.type === "http"
- ? data.status >= 200 && data.status < 300
- : data.state === "success" && data.type === "tcp" && !data.error;
-
- if (success) {
- toastAction("test-success");
- } else {
- toastAction("test-error");
- }
- } catch {
- toastAction("error");
- }
- });
- }
- async function onClone() {
- startTransition(async () => {
- try {
- const id = monitor.id;
- if (!id) return;
-
- const selectedMonitorData = await api.monitor.getMonitorById.query({
- id,
- });
-
- const { notificationIds, pageIds, monitorTagIds } =
- await api.monitor.getMonitorRelationsById.query({ id });
-
- const cloneMonitorData = {
- ...selectedMonitorData,
- name: `${selectedMonitorData.name} - copy`,
- tags: monitorTagIds,
- notifications: notificationIds,
- pages: pageIds,
- active: false,
- id: undefined,
- updatedAt: undefined,
- createdAt: undefined,
- };
-
- // Create a clone function in the api
- await api.monitor.create.mutate(cloneMonitorData);
-
- toast.success("Monitor cloned!");
- router.refresh();
- } catch (error) {
- console.log("error", error);
- toastAction("error");
- }
- });
- }
-
- return (
- <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 data-[state=open]:bg-accent"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <Link href={`./monitors/${monitor.id}/edit`}>
- <DropdownMenuItem>Edit</DropdownMenuItem>
- </Link>
- <Link href={`./monitors/${monitor.id}/overview`}>
- <DropdownMenuItem>Details</DropdownMenuItem>
- </Link>
- <DropdownMenuItem onClick={onClone} disabled={isLimitReached}>
- Clone
- </DropdownMenuItem>
- <DropdownMenuItem onClick={onTest}>Test</DropdownMenuItem>
- <DropdownMenuItem
- onClick={() =>
- copy(`${monitor.id}`, {
- withToast: `Copied ID '${monitor.id}'`,
- })
- }
- >
- Copy ID
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <AlertDialogTrigger asChild>
- <DropdownMenuItem className="text-destructive focus:bg-destructive focus:text-background">
- Delete
- </DropdownMenuItem>
- </AlertDialogTrigger>
- </DropdownMenuContent>
- </DropdownMenu>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- monitor.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/data-table/monitor/data-table-toolbar.tsx b/apps/web/src/components/data-table/monitor/data-table-toolbar.tsx
deleted file mode 100644
index 5caae51b3..000000000
--- a/apps/web/src/components/data-table/monitor/data-table-toolbar.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-"use client";
-
-import type { Table } from "@tanstack/react-table";
-import { X } from "lucide-react";
-
-import type { MonitorTag } from "@openstatus/db/src/schema";
-import { Button, Input } from "@openstatus/ui";
-
-import { DataTableFacetedFilter } from "../data-table-faceted-filter";
-
-interface DataTableToolbarProps<TData> {
- table: Table<TData>;
- tags?: MonitorTag[];
-}
-
-export function DataTableToolbar<TData>({
- table,
- tags,
-}: DataTableToolbarProps<TData>) {
- const isFiltered = table.getState().columnFilters.length > 0;
-
- return (
- <div className="flex flex-wrap items-center justify-between gap-3">
- <div className="flex flex-1 flex-wrap items-center gap-2">
- <Input
- placeholder="Filter names..."
- value={(table.getColumn("name")?.getFilterValue() as string) ?? ""}
- onChange={(event) =>
- table.getColumn("name")?.setFilterValue(event.target.value)
- }
- className="h-8 w-[150px] lg:w-[250px]"
- />
- {table.getColumn("tags") && tags && (
- <DataTableFacetedFilter
- column={table.getColumn("tags")}
- title="Tags"
- options={tags?.map((tag) => ({
- label: tag.name,
- value: tag.name,
- }))}
- />
- )}
- {table.getColumn("public") && (
- <DataTableFacetedFilter
- column={table.getColumn("public")}
- title="Visibility"
- options={[
- { label: "Public", value: true },
- { label: "Private", value: false },
- ]}
- />
- )}
- {table.getColumn("active") && (
- <DataTableFacetedFilter
- column={table.getColumn("active")}
- title="Active"
- options={[
- { label: "True", value: true },
- { label: "False", value: false },
- ]}
- />
- )}
- {table.getColumn("jobType") && (
- <DataTableFacetedFilter
- column={table.getColumn("jobType")}
- title="Type"
- options={[
- { label: "HTTP", value: "http" },
- { label: "TCP", value: "tcp" },
- ]}
- />
- )}
- {isFiltered && (
- <Button
- variant="ghost"
- onClick={() => table.resetColumnFilters()}
- className="h-8 px-2 lg:px-3"
- >
- Reset
- <X className="ml-2 h-4 w-4" />
- </Button>
- )}
- </div>
- <div className="flex items-center self-end rounded-lg border border-dashed bg-muted/50 px-3 py-2">
- <p className="text-muted-foreground text-xs">
- Quantiles and Uptime are aggregated data from the{" "}
- <span className="text-foreground">last 24h</span>.
- </p>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/monitor/data-table.tsx b/apps/web/src/components/data-table/monitor/data-table.tsx
deleted file mode 100644
index 4ada7d05e..000000000
--- a/apps/web/src/components/data-table/monitor/data-table.tsx
+++ /dev/null
@@ -1,176 +0,0 @@
-"use client";
-
-import type {
- ColumnDef,
- ColumnFiltersState,
- PaginationState,
- SortingState,
- Table as TTable,
- VisibilityState,
-} from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- getFacetedRowModel,
- getFacetedUniqueValues,
- getFilteredRowModel,
- getPaginationRowModel,
- getSortedRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-import * as React from "react";
-import { z } from "zod";
-
-import { selectMonitorTagSchema } from "@openstatus/db/src/schema";
-import type { MonitorTag } from "@openstatus/db/src/schema";
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-import { DataTableFloatingActions } from "./data-table-floating-actions";
-import { DataTablePagination } from "./data-table-pagination";
-import { DataTableToolbar } from "./data-table-toolbar";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
- tags?: MonitorTag[];
- defaultColumnFilters?: ColumnFiltersState;
- defaultPagination?: PaginationState;
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
- tags,
- defaultColumnFilters = [],
- defaultPagination = { pageIndex: 0, pageSize: 10 },
-}: DataTableProps<TData, TValue>) {
- const [sorting, setSorting] = React.useState<SortingState>([]);
- const [columnFilters, setColumnFilters] =
- React.useState<ColumnFiltersState>(defaultColumnFilters);
- const [columnVisibility, setColumnVisibility] =
- React.useState<VisibilityState>({
- public: false,
- id: false,
- jobType: false,
- });
-
- const [pagination, setPagination] =
- React.useState<PaginationState>(defaultPagination);
-
- const table = useReactTable({
- data,
- columns,
- state: {
- columnFilters,
- columnVisibility,
- pagination,
- sorting,
- },
- // @ts-expect-error - REMINDER: unfortunately we cannot pass a function from a RSC to a client component
- getRowId: (row, index) => row.monitor?.id?.toString() ?? index,
- onPaginationChange: setPagination,
- getPaginationRowModel: getPaginationRowModel(),
- onColumnFiltersChange: setColumnFilters,
- onColumnVisibilityChange: setColumnVisibility,
- getFilteredRowModel: getFilteredRowModel(),
- getCoreRowModel: getCoreRowModel(),
- onSortingChange: setSorting,
- getSortedRowModel: getSortedRowModel(),
- getFacetedRowModel: getFacetedRowModel(),
- // TODO: check if we can optimize it - because it gets bigger and bigger with every new filter
- // getFacetedUniqueValues: getFacetedUniqueValues(),
- // REMINDER: We cannot use the default getFacetedUniqueValues as it doesnt support Array of Objects
- getFacetedUniqueValues: (_table: TTable<TData>, columnId: string) => () => {
- const map = getFacetedUniqueValues<TData>()(_table, columnId)();
- if (columnId === "tags") {
- if (tags) {
- for (const tag of tags) {
- const tagsNumber = data.reduce((prev, curr) => {
- const values = z
- .object({ tags: z.array(selectMonitorTagSchema) })
- .safeParse(curr);
- if (!values.success) return prev;
- if (values.data.tags?.find((t) => t.name === tag.name))
- return prev + 1;
- return prev;
- }, 0);
- map.set(tag.name, tagsNumber);
- }
- }
- }
- return map;
- },
- });
-
- return (
- <div className="space-y-4">
- <DataTableToolbar table={table} tags={tags} />
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- // FIXME: className="[&:has(svg)]:w-4" takes the svg of the button > checkbox into account
- <TableHead
- key={header.id}
- className={header.column.columnDef.meta?.headerClassName}
- >
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell
- key={cell.id}
- className={cell.column.columnDef.meta?.cellClassName}
- >
- {flexRender(
- cell.column.columnDef.cell,
- cell.getContext(),
- )}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell
- colSpan={columns.length}
- className="h-24 text-center"
- >
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- <DataTablePagination table={table} />
- <DataTableFloatingActions table={table} tags={tags} />
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/notification/columns.tsx b/apps/web/src/components/data-table/notification/columns.tsx
deleted file mode 100644
index bfe4b7d47..000000000
--- a/apps/web/src/components/data-table/notification/columns.tsx
+++ /dev/null
@@ -1,73 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-
-import type { Monitor, Notification } from "@openstatus/db/src/schema";
-import { Badge } from "@openstatus/ui/src/components/badge";
-
-import Link from "next/link";
-import { z } from "zod";
-import { DataTableBadges } from "../data-table-badges";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-// TODO: use the getProviderMetaData function from the notification form to access the data
-
-export const columns: ColumnDef<
- Notification & { monitor: { monitor: Monitor }[] }
->[] = [
- {
- accessorKey: "name",
- header: "Name",
- cell: ({ row }) => {
- const { name } = row.original;
- return (
- <div className="flex gap-2">
- <Link
- href={`./notifications/${row.original.id}/edit`}
- className="group flex max-w-full items-center gap-2"
- prefetch={false}
- >
- <span className="truncate group-hover:underline">{name}</span>
- </Link>
- </div>
- );
- },
- },
- {
- accessorKey: "provider",
- header: "Provider",
- cell: ({ row }) => {
- return (
- <Badge variant="secondary" className="capitalize">
- {row.getValue("provider")}
- </Badge>
- );
- },
- },
- {
- accessorKey: "monitor",
- header: "Monitors",
- cell: ({ row }) => {
- const monitor = row.getValue("monitor");
- const monitors = z
- .object({ monitor: z.object({ name: z.string() }) })
- .array()
- .parse(monitor);
- return (
- <DataTableBadges
- names={monitors.map((monitor) => monitor.monitor.name)}
- />
- );
- },
- },
- {
- id: "actions",
- cell: ({ row }) => {
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
-];
diff --git a/apps/web/src/components/data-table/notification/data-table-row-actions.tsx b/apps/web/src/components/data-table/notification/data-table-row-actions.tsx
deleted file mode 100644
index a55e58a61..000000000
--- a/apps/web/src/components/data-table/notification/data-table-row-actions.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-"use client";
-
-import type { Row } from "@tanstack/react-table";
-import { MoreHorizontal } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-
-import { selectNotificationSchema } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-interface DataTableRowActionsProps<TData> {
- row: Row<TData>;
-}
-
-export function DataTableRowActions<TData>({
- row,
-}: DataTableRowActionsProps<TData>) {
- const notification = selectNotificationSchema.parse(row.original);
- const router = useRouter();
- const [alertOpen, setAlertOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
- const { copy } = useCopyToClipboard();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- if (!notification.id) return;
- await api.notification.deleteNotification.mutate({
- id: notification.id,
- });
- toastAction("deleted");
- router.refresh();
- setAlertOpen(false);
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 data-[state=open]:bg-accent"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <Link href={`./notifications/${notification.id}/edit`}>
- <DropdownMenuItem>Edit</DropdownMenuItem>
- </Link>
- <DropdownMenuItem
- onClick={() =>
- copy(`${notification.id}`, {
- withToast: `Copied ID '${notification.id}'`,
- })
- }
- >
- Copy ID
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <AlertDialogTrigger asChild>
- <DropdownMenuItem className="text-destructive focus:bg-destructive focus:text-background">
- Delete
- </DropdownMenuItem>
- </AlertDialogTrigger>
- </DropdownMenuContent>
- </DropdownMenu>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- notification.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/data-table/notification/data-table.tsx b/apps/web/src/components/data-table/notification/data-table.tsx
deleted file mode 100644
index d152669fc..000000000
--- a/apps/web/src/components/data-table/notification/data-table.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/page-subscriber/columns.tsx b/apps/web/src/components/data-table/page-subscriber/columns.tsx
deleted file mode 100644
index 87da02862..000000000
--- a/apps/web/src/components/data-table/page-subscriber/columns.tsx
+++ /dev/null
@@ -1,46 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-
-import type { PageSubscriber } from "@openstatus/db/src/schema";
-
-import { formatDateTime } from "@/lib/utils";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-export const columns: ColumnDef<PageSubscriber>[] = [
- {
- accessorKey: "email",
- header: "Email",
- cell: ({ row }) => {
- return <span>{row.getValue("email")}</span>;
- },
- },
- {
- accessorKey: "acceptedAt",
- header: "Accepted",
- cell: ({ row }) => {
- const { acceptedAt } = row.original;
- const date = acceptedAt ? formatDateTime(acceptedAt) : "-";
- return <span className="text-muted-foreground">{date}</span>;
- },
- },
- {
- accessorKey: "createdAt",
- header: "Created",
- cell: ({ row }) => {
- const { createdAt } = row.original;
- const date = createdAt ? formatDateTime(createdAt) : "-";
- return <span className="text-muted-foreground">{date}</span>;
- },
- },
- {
- id: "actions",
- cell: ({ row }) => {
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
-];
diff --git a/apps/web/src/components/data-table/page-subscriber/data-table-row-actions.tsx b/apps/web/src/components/data-table/page-subscriber/data-table-row-actions.tsx
deleted file mode 100644
index d4a155d62..000000000
--- a/apps/web/src/components/data-table/page-subscriber/data-table-row-actions.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-"use client";
-
-import type { Row } from "@tanstack/react-table";
-import { MoreHorizontal } from "lucide-react";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-
-import { selectPageSubscriberSchema } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-interface DataTableRowActionsProps<TData> {
- row: Row<TData>;
-}
-
-export function DataTableRowActions<TData>({
- row,
-}: DataTableRowActionsProps<TData>) {
- const subscriber = selectPageSubscriberSchema.parse(row.original);
- const router = useRouter();
- const [alertOpen, setAlertOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- if (!subscriber.id) return;
- await api.pageSubscriber.unsubscribeById.mutate({
- id: subscriber.id,
- });
- toastAction("deleted");
- router.refresh();
- setAlertOpen(false);
- } catch {
- toastAction("error");
- }
- });
- }
-
- async function onAccept() {
- startTransition(async () => {
- try {
- if (!subscriber.id) return;
- await api.pageSubscriber.acceptSubscriberById.mutate({
- id: subscriber.id,
- });
- toastAction("success");
- router.refresh();
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 data-[state=open]:bg-accent"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- {!subscriber.acceptedAt ? (
- <DropdownMenuItem onClick={onAccept}>Accept</DropdownMenuItem>
- ) : null}
- <AlertDialogTrigger asChild>
- <DropdownMenuItem className="text-destructive focus:bg-destructive focus:text-background">
- Delete
- </DropdownMenuItem>
- </AlertDialogTrigger>
- </DropdownMenuContent>
- </DropdownMenu>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- The user will not be able to receive the latest status reports. But
- will be able to subscribe again.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/data-table/page-subscriber/data-table.tsx b/apps/web/src/components/data-table/page-subscriber/data-table.tsx
deleted file mode 100644
index d152669fc..000000000
--- a/apps/web/src/components/data-table/page-subscriber/data-table.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/status-page/columns.tsx b/apps/web/src/components/data-table/status-page/columns.tsx
deleted file mode 100644
index ab9518166..000000000
--- a/apps/web/src/components/data-table/status-page/columns.tsx
+++ /dev/null
@@ -1,173 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import Image from "next/image";
-import Link from "next/link";
-import * as z from "zod";
-
-import type {
- Maintenance,
- Page,
- StatusReport,
- StatusReportUpdate,
-} from "@openstatus/db/src/schema";
-import {
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui";
-
-import { formatDate } from "@/lib/utils";
-import { ArrowUpRight, Check } from "lucide-react";
-import { DataTableBadges } from "../data-table-badges";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-export const columns: ColumnDef<
- Page & {
- monitorsToPages: { monitor: { name: string } }[];
- maintenances: Maintenance[]; // we get only the active maintenances!
- statusReports: (StatusReport & {
- statusReportUpdates: StatusReportUpdate[];
- })[];
- }
->[] = [
- {
- accessorKey: "title",
- header: "Title",
- cell: ({ row }) => {
- return (
- <Link
- href={`./status-pages/${row.original.id}/reports`}
- className="group flex items-center gap-2"
- >
- <span className="max-w-[125px] truncate group-hover:underline">
- {row.getValue("title")}
- </span>
- </Link>
- );
- },
- },
- {
- accessorKey: "slug",
- header: "Slug",
- cell: ({ row }) => {
- return (
- <TooltipProvider>
- <Tooltip delayDuration={100}>
- <TooltipTrigger>
- <a
- href={
- process.env.NODE_ENV === "production"
- ? `https://${row.original.slug}.openstatus.dev`
- : `/status-page/${row.original.slug}`
- }
- target="_blank"
- rel="noreferrer"
- className="group flex items-center gap-1"
- >
- <span className="max-w-[125px] truncate font-mono group-hover:underline">
- {row.getValue("slug")}
- </span>
- <ArrowUpRight className="h-4 w-4 shrink-0 text-muted-foreground group-hover:text-foreground" />
- </a>
- </TooltipTrigger>
- <TooltipContent>Visit page</TooltipContent>
- </Tooltip>
- </TooltipProvider>
- );
- },
- },
- {
- accessorKey: "monitorsToPages",
- header: "Monitors",
- cell: ({ row }) => {
- const monitorsToPages = row.getValue("monitorsToPages");
- const monitors = z
- .object({ monitor: z.object({ name: z.string() }) })
- .array()
- .parse(monitorsToPages);
- return (
- <DataTableBadges
- names={monitors.map((monitor) => monitor.monitor.name)}
- />
- );
- },
- },
- {
- accessorKey: "statusReports",
- header: "Last Report",
- cell: ({ row }) => {
- const lastReport = row.original.statusReports?.[0];
-
- if (!lastReport) {
- return <span className="text-muted-foreground/50">-</span>;
- }
-
- const date =
- lastReport.statusReportUpdates?.[0].date || lastReport.updatedAt;
-
- return (
- <div className="group relative">
- <span className="group-hover:text-muted-foreground/70">
- {formatDate(date)}
- </span>
- <div className="-inset-x-2 -inset-y-1 invisible absolute flex items-center px-2 py-1 backdrop-blur-xs group-hover:visible">
- <Link
- href={`./status-pages/${row.original.id}/reports/${lastReport.id}`}
- className="hover:underline"
- >
- Go to report
- </Link>
- </div>
- </div>
- );
- },
- },
- {
- accessorKey: "icon",
- header: "Favicon",
- cell: ({ row }) => {
- if (!row.getValue("icon")) {
- return <span className="text-muted-foreground/50">-</span>;
- }
- return (
- <Image
- src={row.getValue("icon")}
- alt=""
- className="rounded-sm border border-border"
- width={20}
- height={20}
- />
- );
- },
- },
- {
- accessorKey: "passwordProtected",
- header: "Protected",
- cell: ({ row }) => {
- const passwordProtected = Boolean(row.getValue("passwordProtected"));
- if (passwordProtected) {
- return <Check className="h-4 w-4 text-foreground" />;
- }
- return <span className="text-muted-foreground/50">-</span>;
- },
- },
- // {
- // accessorKey: "createdAt",
- // header: "Created",
- // cell: ({ row }) => {
- // return <span>{formatDate(row.getValue("createdAt"))}</span>;
- // },
- // },
- {
- id: "actions",
- cell: ({ row }) => {
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
-];
diff --git a/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx b/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx
deleted file mode 100644
index 34ecf1bca..000000000
--- a/apps/web/src/components/data-table/status-page/data-table-row-actions.tsx
+++ /dev/null
@@ -1,224 +0,0 @@
-"use client";
-
-import type { Row } from "@tanstack/react-table";
-import { MoreHorizontal } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-
-import { selectPageSchema } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
- Label,
- RadioGroup,
- RadioGroupItem,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-export const SIZE: Record<string, { width: number; height: number }> = {
- sm: { width: 120, height: 34 },
- md: { width: 160, height: 46 },
- lg: { width: 200, height: 56 },
- xl: { width: 240, height: 68 },
-};
-
-interface DataTableRowActionsProps<TData> {
- row: Row<TData>;
-}
-
-export function DataTableRowActions<TData>({
- row,
-}: DataTableRowActionsProps<TData>) {
- const page = selectPageSchema.parse(row.original);
- const router = useRouter();
- const [alertOpen, setAlertOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
- const [size, setSize] = React.useState<"sm" | "md" | "lg" | "xl">("sm");
- const [theme, setTheme] = React.useState<"light" | "dark">("light");
- const { copy } = useCopyToClipboard();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- if (!page.id) return;
- await api.page.delete.mutate({ id: page.id });
- toastAction("deleted");
- router.refresh();
- setAlertOpen(false);
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <Dialog>
- <AlertDialog
- open={alertOpen}
- onOpenChange={(value) => setAlertOpen(value)}
- >
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 data-[state=open]:bg-accent"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <Link href={`./status-pages/${page.id}/edit`}>
- <DropdownMenuItem>Edit</DropdownMenuItem>
- </Link>
- <Link
- href={
- process.env.NODE_ENV === "production"
- ? `https://${page.slug}.openstatus.dev`
- : `/status-page/${page.slug}`
- }
- target="_blank"
- >
- <DropdownMenuItem>Visit</DropdownMenuItem>
- </Link>
- <DropdownMenuItem
- onClick={() =>
- copy(`${page.id}`, {
- withToast: `Copied ID '${page.id}'`,
- })
- }
- >
- Copy ID
- </DropdownMenuItem>
- <DropdownMenuSeparator />
- <Link href={`./status-pages/${page.id}/reports/new`}>
- <DropdownMenuItem>Create Report</DropdownMenuItem>
- </Link>
- <DialogTrigger asChild>
- <DropdownMenuItem>Create Badge</DropdownMenuItem>
- </DialogTrigger>
- <DropdownMenuSeparator />
- <AlertDialogTrigger asChild>
- <DropdownMenuItem className="text-destructive focus:bg-destructive focus:text-background">
- Delete
- </DropdownMenuItem>
- </AlertDialogTrigger>
- </DropdownMenuContent>
- </DropdownMenu>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- monitor.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- <DialogContent>
- <DialogHeader>
- <DialogTitle>Create Badge</DialogTitle>
- </DialogHeader>
- <DialogDescription>
- Create an uptime badge for your status page.
- </DialogDescription>
- <div className="flex items-center justify-center">
- <div className="flex w-full items-center justify-center rounded-md border p-4">
- <img
- src={`/status-page/${page.slug}/badge?size=${size}&theme=${theme}`}
- alt="Badge"
- width={SIZE[size].width}
- height={SIZE[size].height}
- />
- </div>
- </div>
- <div className="flex items-center justify-between">
- <RadioGroup
- className="flex"
- onValueChange={(value) =>
- setSize(value as "sm" | "md" | "lg" | "xl")
- }
- value={size}
- >
- {Object.keys(SIZE).map((size) => (
- <div className="flex items-center space-x-2" key={size}>
- <RadioGroupItem value={size} id={size} />
- <Label htmlFor={size}>{size}</Label>
- </div>
- ))}
- </RadioGroup>
- <div>
- <span className="font-mono text-muted-foreground text-sm">
- {SIZE[size].width}x{SIZE[size].height}
- </span>
- </div>
- </div>
- <RadioGroup
- className="flex"
- onValueChange={(value) => setTheme(value as "light" | "dark")}
- value={theme}
- >
- {["light", "dark"].map((theme) => (
- <div className="flex items-center space-x-2" key={theme}>
- <RadioGroupItem value={theme} id={theme} />
- <Label htmlFor={theme}>{theme}</Label>
- </div>
- ))}
- </RadioGroup>
- <div className="flex items-center justify-center">
- <Button
- variant="outline"
- className="w-full"
- size="sm"
- onClick={() =>
- copy(
- `https://openstatus.dev/status-page/${page.slug}/badge?size=${size}&theme=${theme}`,
- { withToast: true },
- )
- }
- >
- https://openstatus.dev/status-page/{page.slug}/badge?size={size}
- &theme={theme}
- </Button>
- </div>
- </DialogContent>
- </AlertDialog>
- </Dialog>
- );
-}
diff --git a/apps/web/src/components/data-table/status-page/data-table.tsx b/apps/web/src/components/data-table/status-page/data-table.tsx
deleted file mode 100644
index d152669fc..000000000
--- a/apps/web/src/components/data-table/status-page/data-table.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/status-report/columns.tsx b/apps/web/src/components/data-table/status-report/columns.tsx
deleted file mode 100644
index a751400bb..000000000
--- a/apps/web/src/components/data-table/status-report/columns.tsx
+++ /dev/null
@@ -1,63 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import Link from "next/link";
-
-import type {
- StatusReport,
- StatusReportUpdate,
-} from "@openstatus/db/src/schema";
-
-import { StatusBadge } from "@/components/status-update/status-badge";
-import { formatDate } from "@/lib/utils";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-export const columns: ColumnDef<
- StatusReport & { statusReportUpdates: StatusReportUpdate[] }
->[] = [
- {
- accessorKey: "title",
- header: "Title",
- cell: ({ row }) => {
- const id = row.original.id;
- return (
- <Link href={`./reports/${id}/overview`} className="hover:underline">
- <span className="truncate">{row.getValue("title")}</span>
- </Link>
- );
- },
- },
- {
- accessorKey: "status",
- header: "Status",
- cell: ({ row }) => {
- const status = row.original.status;
- return <StatusBadge status={status} />;
- },
- },
- {
- accessorKey: "statusReportUpdates",
- header: "Updates",
- cell: ({ row }) => {
- const statusReportUpdates = row.original.statusReportUpdates;
- return <code>{statusReportUpdates.length}</code>;
- },
- },
- {
- accessorKey: "updatedAt",
- header: "Last Updated",
- cell: ({ row }) => {
- return <span>{formatDate(row.getValue("updatedAt"))}</span>;
- },
- },
- {
- id: "actions",
- cell: ({ row }) => {
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
-];
diff --git a/apps/web/src/components/data-table/status-report/data-table-row-actions.tsx b/apps/web/src/components/data-table/status-report/data-table-row-actions.tsx
deleted file mode 100644
index fe2148f67..000000000
--- a/apps/web/src/components/data-table/status-report/data-table-row-actions.tsx
+++ /dev/null
@@ -1,120 +0,0 @@
-"use client";
-
-import type { Row } from "@tanstack/react-table";
-import { MoreHorizontal } from "lucide-react";
-import Link from "next/link";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-
-import { selectStatusReportSchema } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { useCopyToClipboard } from "@/hooks/use-copy-to-clipboard";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-interface DataTableRowActionsProps<TData> {
- row: Row<TData>;
-}
-
-export function DataTableRowActions<TData>({
- row,
-}: DataTableRowActionsProps<TData>) {
- const statusReport = selectStatusReportSchema.parse(row.original);
- const router = useRouter();
- const [alertOpen, setAlertOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
- const { copy } = useCopyToClipboard();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- if (!statusReport.id) return;
- await api.statusReport.deleteStatusReport.mutate({
- id: statusReport.id,
- });
- toastAction("deleted");
- router.refresh();
- setAlertOpen(false);
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 data-[state=open]:bg-accent"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <Link href={`./reports/${statusReport.id}/edit`}>
- <DropdownMenuItem>Edit</DropdownMenuItem>
- </Link>
- <Link href={`./reports/${statusReport.id}/overview`}>
- <DropdownMenuItem>View</DropdownMenuItem>
- </Link>
- <DropdownMenuItem
- onClick={() =>
- copy(`${statusReport.id}`, {
- withToast: `Copied ID '${statusReport.id}'`,
- })
- }
- >
- Copy ID
- </DropdownMenuItem>
- <AlertDialogTrigger asChild>
- <DropdownMenuItem className="text-destructive focus:bg-destructive focus:text-background">
- Delete
- </DropdownMenuItem>
- </AlertDialogTrigger>
- </DropdownMenuContent>
- </DropdownMenu>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- monitor.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/data-table/status-report/data-table.tsx b/apps/web/src/components/data-table/status-report/data-table.tsx
deleted file mode 100644
index d152669fc..000000000
--- a/apps/web/src/components/data-table/status-report/data-table.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/data-table/user/columns.tsx b/apps/web/src/components/data-table/user/columns.tsx
deleted file mode 100644
index f1f43de09..000000000
--- a/apps/web/src/components/data-table/user/columns.tsx
+++ /dev/null
@@ -1,59 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-
-import type { User, WorkspaceRole } from "@openstatus/db/src/schema";
-import { Badge } from "@openstatus/ui/src/components/badge";
-
-import { formatDate } from "@/lib/utils";
-import { DataTableRowActions } from "./data-table-row-actions";
-
-// TODO: add total number of monitors
-
-export const columns: ColumnDef<User & { role: WorkspaceRole }>[] = [
- {
- accessorKey: "email",
- header: "Email",
- cell: ({ row }) => {
- return (
- <div>
- <p>
- {row.original.firstName} {row.original.lastName}
- </p>
- <p className="text-muted-foreground">{row.getValue("email")}</p>
- </div>
- );
- },
- },
- {
- accessorKey: "role",
- header: "Role",
- cell: ({ row }) => {
- const role = row.getValue("role") as WorkspaceRole;
- return (
- <Badge variant={role === "member" ? "outline" : "default"}>
- {row.getValue("role")}
- </Badge>
- );
- },
- },
- {
- accessorKey: "createdAt",
- header: "Created",
- cell: ({ row }) => {
- return <span>{formatDate(row.getValue("createdAt"))}</span>;
- },
- },
- {
- id: "actions",
- cell: ({ row }) => {
- const role = row.original.role;
- if (role === "owner") return null;
- return (
- <div className="text-right">
- <DataTableRowActions row={row} />
- </div>
- );
- },
- },
-];
diff --git a/apps/web/src/components/data-table/user/data-table-row-actions.tsx b/apps/web/src/components/data-table/user/data-table-row-actions.tsx
deleted file mode 100644
index a1d527ee3..000000000
--- a/apps/web/src/components/data-table/user/data-table-row-actions.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-"use client";
-
-import type { Row } from "@tanstack/react-table";
-import { MoreHorizontal } from "lucide-react";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-
-import { selectUserSchema } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuTrigger,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toast, toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-interface DataTableRowActionsProps<TData> {
- row: Row<TData>;
-}
-
-export function DataTableRowActions<TData>({
- row,
-}: DataTableRowActionsProps<TData>) {
- const user = selectUserSchema.parse(row.original);
- const router = useRouter();
- const [alertOpen, setAlertOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- if (!user.id) return;
- await api.workspace.removeWorkspaceUser.mutate({ id: user.id });
- toastAction("removed");
- router.refresh();
- setAlertOpen(false);
- } catch (error) {
- if (error instanceof Error) {
- toast.error(error.message);
- } else {
- toastAction("error");
- }
- setAlertOpen(false);
- }
- });
- }
-
- return (
- <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="h-8 w-8 p-0 data-[state=open]:bg-accent"
- >
- <span className="sr-only">Open menu</span>
- <MoreHorizontal className="h-4 w-4" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent align="end">
- <AlertDialogTrigger asChild>
- <DropdownMenuItem className="text-destructive focus:bg-destructive focus:text-background">
- Remove
- </DropdownMenuItem>
- </AlertDialogTrigger>
- </DropdownMenuContent>
- </DropdownMenu>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will remove the user from your
- team.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Remove" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/data-table/user/data-table.tsx b/apps/web/src/components/data-table/user/data-table.tsx
deleted file mode 100644
index d152669fc..000000000
--- a/apps/web/src/components/data-table/user/data-table.tsx
+++ /dev/null
@@ -1,80 +0,0 @@
-"use client";
-
-import type { ColumnDef } from "@tanstack/react-table";
-import {
- flexRender,
- getCoreRowModel,
- useReactTable,
-} from "@tanstack/react-table";
-
-import {
- Table,
- TableBody,
- TableCell,
- TableHead,
- TableHeader,
- TableRow,
-} from "@openstatus/ui";
-
-interface DataTableProps<TData, TValue> {
- columns: ColumnDef<TData, TValue>[];
- data: TData[];
-}
-
-export function DataTable<TData, TValue>({
- columns,
- data,
-}: DataTableProps<TData, TValue>) {
- const table = useReactTable({
- data,
- columns,
- getCoreRowModel: getCoreRowModel(),
- });
-
- return (
- <div className="rounded-md border">
- <Table>
- <TableHeader className="bg-muted/50">
- {table.getHeaderGroups().map((headerGroup) => (
- <TableRow key={headerGroup.id} className="hover:bg-transparent">
- {headerGroup.headers.map((header) => {
- return (
- <TableHead key={header.id}>
- {header.isPlaceholder
- ? null
- : flexRender(
- header.column.columnDef.header,
- header.getContext(),
- )}
- </TableHead>
- );
- })}
- </TableRow>
- ))}
- </TableHeader>
- <TableBody>
- {table.getRowModel().rows?.length ? (
- table.getRowModel().rows.map((row) => (
- <TableRow
- key={row.id}
- data-state={row.getIsSelected() && "selected"}
- >
- {row.getVisibleCells().map((cell) => (
- <TableCell key={cell.id}>
- {flexRender(cell.column.columnDef.cell, cell.getContext())}
- </TableCell>
- ))}
- </TableRow>
- ))
- ) : (
- <TableRow>
- <TableCell colSpan={columns.length} className="h-24 text-center">
- No results.
- </TableCell>
- </TableRow>
- )}
- </TableBody>
- </Table>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/maintenance/form.tsx b/apps/web/src/components/forms/maintenance/form.tsx
deleted file mode 100644
index 0ace2cb8e..000000000
--- a/apps/web/src/components/forms/maintenance/form.tsx
+++ /dev/null
@@ -1,119 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { usePathname, useRouter } from "next/navigation";
-import { useTransition } from "react";
-import { useForm } from "react-hook-form";
-
-import { insertMaintenanceSchema } from "@openstatus/db/src/schema";
-import type { InsertMaintenance, Monitor } from "@openstatus/db/src/schema";
-import { Form } from "@openstatus/ui";
-
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@/components/dashboard/tabs";
-
-import { SaveButton } from "../shared/save-button";
-import { General } from "./general";
-import { SectionConnect } from "./section-connect";
-
-interface Props {
- defaultSection?: string;
- defaultValues?: InsertMaintenance;
- monitors?: Monitor[];
- nextUrl?: string;
- pageId: number;
-}
-
-export function MaintenanceForm({
- defaultSection,
- defaultValues,
- monitors,
- nextUrl,
- pageId,
-}: Props) {
- const form = useForm<InsertMaintenance>({
- resolver: zodResolver(insertMaintenanceSchema),
- defaultValues: {
- ...defaultValues,
- title: defaultValues?.title || "",
- message: defaultValues?.message || "",
- from: defaultValues?.from ? new Date(defaultValues.from) : new Date(),
- to: defaultValues?.to
- ? new Date(defaultValues.to)
- : new Date(Date.now() + 1000 * 60 * 60),
- pageId,
- },
- });
- const router = useRouter();
- const pathname = usePathname();
- const [isPending, startTransition] = useTransition();
-
- const onSubmit = async ({ ...props }: InsertMaintenance) => {
- startTransition(async () => {
- try {
- if (defaultValues) {
- await api.maintenance.updateLegacy.mutate(props);
- } else {
- await api.maintenance.create.mutate(props);
- }
- toastAction("saved");
- // otherwise, the form will stay dirty - keepValues is used to keep the current values in the form
- form.reset({}, { keepValues: true });
- if (nextUrl) {
- router.push(nextUrl);
- }
- router.refresh();
- } catch {
- toastAction("error");
- }
- });
- };
-
- function onValueChange(value: string) {
- // REMINDER: we are not merging the searchParams here
- // we are just setting the section to allow refreshing the page
- const params = new URLSearchParams();
- params.set("section", value);
- router.push(`${pathname}?${params.toString()}`);
- }
-
- console.log(form.formState.errors);
-
- return (
- <Form {...form}>
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- form.handleSubmit(onSubmit)(e);
- }}
- className="grid w-full gap-6"
- >
- <General form={form} />
- <Tabs
- defaultValue={defaultSection}
- className="w-full"
- onValueChange={onValueChange}
- >
- <TabsList>
- <TabsTrigger value="connect">Connect</TabsTrigger>
- </TabsList>
- <TabsContent value="connect">
- <SectionConnect form={form} monitors={monitors} />
- </TabsContent>
- </Tabs>
- <SaveButton
- isPending={isPending}
- isDirty={form.formState.isDirty}
- onSubmit={form.handleSubmit(onSubmit)}
- />
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/forms/maintenance/general.tsx b/apps/web/src/components/forms/maintenance/general.tsx
deleted file mode 100644
index c80d6148f..000000000
--- a/apps/web/src/components/forms/maintenance/general.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-"use client";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertMaintenance } from "@openstatus/db/src/schema";
-import {
- DateTimePickerPopover,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
- Textarea,
-} from "@openstatus/ui";
-
-import { format } from "date-fns";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- form: UseFormReturn<InsertMaintenance>;
-}
-
-export function General({ form }: Props) {
- return (
- <div className="grid gap-4 sm:grid-cols-3 sm:gap-6">
- <SectionHeader
- title="Maintenance Information"
- description="Give your users a heads up when you're doing maintenance."
- />
- <div className="flex w-full flex-col gap-4 sm:col-span-2">
- <FormField
- control={form.control}
- name="title"
- render={({ field }) => (
- <FormItem className="w-full">
- <FormLabel>Title</FormLabel>
- <FormControl>
- <Input placeholder="Database migration" {...field} />
- </FormControl>
- <FormDescription>Displayed on the status page.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="message"
- render={({ field }) => (
- <FormItem className="col-span-full">
- <FormLabel>Message</FormLabel>
- <FormControl>
- <Textarea
- placeholder="We're doing some maintenance. We'll be back soon!"
- {...field}
- />
- </FormControl>
- <FormDescription>Give your users some context.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="grid grid-cols-2 gap-4">
- <FormField
- control={form.control}
- name="from"
- render={({ field }) => (
- <FormItem className="flex w-full flex-col">
- <FormLabel>From</FormLabel>
- <DateTimePickerPopover
- date={field.value ? new Date(field.value) : new Date()}
- setDate={(date) => {
- field.onChange(date);
- }}
- className="w-full"
- />
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="to"
- render={({ field }) => (
- <FormItem className="flex w-full flex-col">
- <FormLabel>To</FormLabel>
- <DateTimePickerPopover
- date={
- field.value
- ? new Date(field.value)
- : new Date(Date.now() + 1000 * 60 * 60)
- }
- setDate={(date) => {
- field.onChange(date);
- }}
- className="w-full"
- />
- <FormMessage />
- </FormItem>
- )}
- />
- <FormDescription className="sm:-mt-2 col-span-full">
- The period{" "}
- <span className="font-medium">
- in local time {format(new Date(), "z")}
- </span>{" "}
- when the maintenance takes place.
- </FormDescription>
- </div>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/maintenance/section-connect.tsx b/apps/web/src/components/forms/maintenance/section-connect.tsx
deleted file mode 100644
index b4d0e9b01..000000000
--- a/apps/web/src/components/forms/maintenance/section-connect.tsx
+++ /dev/null
@@ -1,85 +0,0 @@
-"use client";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertMaintenance, Monitor } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@openstatus/ui";
-
-import { CheckboxLabel } from "../shared/checkbox-label";
-
-interface Props {
- form: UseFormReturn<InsertMaintenance>;
- monitors?: Monitor[];
-}
-
-export function SectionConnect({ form, monitors }: Props) {
- return (
- <div className="grid w-full gap-4">
- <div className="flex flex-col gap-3">
- <FormField
- control={form.control}
- name="monitors"
- render={() => (
- <FormItem>
- <div className="mb-4">
- <FormLabel>Monitors</FormLabel>
- <FormDescription>
- Select the monitors that are affected by this maintenance.{" "}
- <span className="font-medium">
- We will not trigger any ping during that period.
- </span>
- </FormDescription>
- </div>
- <div className="grid grid-cols-1 grid-rows-1 gap-6 sm:grid-cols-2 md:grid-cols-3">
- {monitors?.map((item) => (
- <FormField
- key={item.id}
- control={form.control}
- name="monitors"
- render={({ field }) => {
- return (
- <FormItem key={item.id} className="h-full w-full">
- <FormControl className="w-full">
- <CheckboxLabel
- id={String(item.id)}
- name="monitor"
- checked={field.value?.includes(item.id)}
- onCheckedChange={(checked) => {
- return checked
- ? field.onChange([
- ...(field.value || []),
- item.id,
- ])
- : field.onChange(
- field.value?.filter(
- (value) => value !== item.id,
- ),
- );
- }}
- >
- {item.name}
- </CheckboxLabel>
- </FormControl>
- </FormItem>
- );
- }}
- />
- ))}
- </div>
- {!monitors || monitors.length === 0 ? (
- <FormDescription>Missing monitors.</FormDescription>
- ) : null}
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor-tag/form.tsx b/apps/web/src/components/forms/monitor-tag/form.tsx
deleted file mode 100644
index f9fde2913..000000000
--- a/apps/web/src/components/forms/monitor-tag/form.tsx
+++ /dev/null
@@ -1,97 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-import { useForm } from "react-hook-form";
-
-import { insertMonitorTagSchema } from "@openstatus/db/src/schema";
-import type { InsertMonitorTag, MonitorTag } from "@openstatus/db/src/schema";
-import {
- Form,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-import { SaveButton } from "../shared/save-button";
-
-interface Props {
- defaultValues?: MonitorTag;
-}
-
-export function MonitorTagForm({ defaultValues }: Props) {
- const form = useForm<InsertMonitorTag>({
- resolver: zodResolver(insertMonitorTagSchema),
- defaultValues,
- });
- const router = useRouter();
- const [isPending, startTransition] = React.useTransition();
-
- const onSubmit = ({ ...props }: InsertMonitorTag) => {
- startTransition(async () => {
- try {
- if (defaultValues) {
- await api.monitorTag.update.mutate({ ...props });
- } else {
- await api.monitorTag.create.mutate({ ...props });
- }
- router.refresh();
- toastAction("saved");
- } catch {
- toastAction("error");
- }
- });
- };
-
- return (
- <Form {...form}>
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- form.handleSubmit(onSubmit)(e);
- }}
- className="grid w-full gap-6"
- >
- <div className="flex gap-6">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Name</FormLabel>
- <FormControl>
- <Input placeholder="API" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="color"
- render={({ field }) => (
- <FormItem className="w-12">
- <FormLabel>Color</FormLabel>
- <FormControl>
- <Input type="color" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <SaveButton
- isPending={isPending}
- isDirty={form.formState.isDirty}
- onSubmit={form.handleSubmit(onSubmit)}
- />
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/form.tsx b/apps/web/src/components/forms/monitor/form.tsx
deleted file mode 100644
index b8c2ec11f..000000000
--- a/apps/web/src/components/forms/monitor/form.tsx
+++ /dev/null
@@ -1,370 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { getLimit } from "@openstatus/db/src/schema/plan/utils";
-import { usePathname, useRouter } from "next/navigation";
-import * as React from "react";
-import { useForm } from "react-hook-form";
-
-import * as assertions from "@openstatus/assertions";
-import type {
- InsertMonitor,
- MonitorTag,
- Notification,
- Page,
- WorkspacePlan,
-} from "@openstatus/db/src/schema";
-import { insertMonitorSchema } from "@openstatus/db/src/schema";
-import { Badge, Form } from "@openstatus/ui";
-
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@/components/dashboard/tabs";
-import { FailedPingAlertConfirmation } from "@/components/modals/failed-ping-alert-confirmation";
-import type { RegionChecker } from "@/components/ping-response-analysis/utils";
-import { toast, toastAction } from "@/lib/toast";
-import { formatDuration } from "@/lib/utils";
-import { api } from "@/trpc/client";
-import type { Region } from "@openstatus/db/src/schema/constants";
-import type { Limits } from "@openstatus/db/src/schema/plan/schema";
-import { SaveButton } from "../shared/save-button";
-import { General } from "./general";
-import { RequestTestButton } from "./request-test-button";
-import { SectionAssertions } from "./section-assertions";
-import { SectionDanger } from "./section-danger";
-import { SectionNotifications } from "./section-notifications";
-import { SectionOtel } from "./section-otel";
-import { SectionRequests } from "./section-requests";
-import { SectionScheduling } from "./section-scheduling";
-import { SectionStatusPage } from "./section-status-page";
-
-interface Props {
- defaultSection?: string;
- limits: Limits;
- plan: WorkspacePlan;
- defaultValues?: InsertMonitor;
- notifications?: Notification[];
- tags?: MonitorTag[];
- pages?: Page[];
- nextUrl?: string;
- withTestButton?: boolean;
-}
-
-const ABORT_TIMEOUT = 7_000; // in ms
-
-export function MonitorForm({
- defaultSection,
- defaultValues,
- notifications,
- pages,
- tags,
- nextUrl,
- limits,
- plan,
- withTestButton = true,
-}: Props) {
- const _assertions = defaultValues?.assertions
- ? assertions.deserialize(defaultValues?.assertions).map((a) => a.schema)
- : [];
-
- const form = useForm<InsertMonitor>({
- resolver: zodResolver(insertMonitorSchema),
- defaultValues: {
- url: defaultValues?.url || "",
- name: defaultValues?.name || "",
- description: defaultValues?.description || "",
- periodicity: defaultValues?.periodicity || "30m",
- active: defaultValues?.active ?? true,
- id: defaultValues?.id || 0,
- regions: defaultValues?.regions || getLimit(limits, "regions"),
- headers: defaultValues?.headers?.length
- ? defaultValues?.headers
- : [{ key: "", value: "" }],
- body: defaultValues?.body ?? "",
- method: defaultValues?.method ?? "GET",
- notifications: defaultValues?.notifications ?? [],
- pages: defaultValues?.pages ?? [],
- tags: defaultValues?.tags ?? [],
- public: defaultValues?.public ?? false,
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
- statusAssertions: _assertions.filter((a) => a.type === "status") as any, // TS considers a.type === "header"
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
- headerAssertions: _assertions.filter((a) => a.type === "header") as any, // TS considers a.type === "status"
- textBodyAssertions: _assertions.filter(
- (a) => a.type === "textBody",
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
- ) as any, // TS considers a.type === "textBody"
- degradedAfter: defaultValues?.degradedAfter,
- timeout: defaultValues?.timeout || 45000,
- jobType: defaultValues?.jobType || "http",
- otelEndpoint: defaultValues?.otelEndpoint ?? "",
- otelHeaders: defaultValues?.otelHeaders ?? [],
- },
- });
- const router = useRouter();
- const pathname = usePathname();
- const [isPending, setPending] = React.useState(false);
- const [pingFailed, setPingFailed] = React.useState(false);
- const type = React.useMemo(
- () => (defaultValues ? "update" : "create"),
- [defaultValues],
- );
-
- const handleDataUpdateOrInsertion = async (props: InsertMonitor) => {
- if (defaultValues) {
- await api.monitor.update.mutate(props);
- } else {
- await api.monitor.create.mutate(props);
- }
- if (nextUrl) {
- router.push(nextUrl);
- }
- // to reset the `isDirty` state of them form while keeping the values for optimistic UI
- form.reset(undefined, { keepValues: true });
- router.refresh();
- };
-
- const handleForceDataUpdateOrInsertion = async (props: InsertMonitor) => {
- try {
- handleDataUpdateOrInsertion(props);
- toastAction("saved");
- } catch (_error) {
- toastAction("error");
- }
- };
-
- const onSubmit = ({ ...props }: InsertMonitor) => {
- toast.promise(
- async () => {
- setPending(true);
- const { error } = await pingEndpoint();
- if (error) {
- setPingFailed(true);
- throw new Error(error);
- }
- await handleDataUpdateOrInsertion(props);
- },
- {
- loading: "Checking the endpoint before saving...",
- success: () => "Endpoint is working fine. Saved!",
- error: (error: Error) => {
- if (error instanceof Error) return error.message;
- return "Endpoint is not working.";
- },
- finally: () => {
- setPending(false);
- },
- },
- );
- };
-
- const validateJSON = (value?: string) => {
- if (!value) return;
- try {
- const obj = JSON.parse(value) as Record<string, unknown>;
- form.clearErrors("body");
- return obj;
- } catch (_e) {
- form.setError("body", {
- message: "Not a valid JSON object",
- });
- return false;
- }
- };
-
- const pingEndpoint = async (region?: Region) => {
- try {
- const {
- url,
- body,
- method,
- headers,
- statusAssertions,
- headerAssertions,
- textBodyAssertions,
- jobType,
- } = form.getValues();
-
- if (
- body &&
- body !== "" &&
- headers?.some(
- (h) => h.key === "Content-Type" && h.value === "application/json",
- )
- ) {
- const validJSON = validateJSON(body);
- if (!validJSON) {
- return { error: "Not a valid JSON object.", data: undefined };
- }
- }
-
- const res = await fetch(`/api/checker/test/${jobType}`, {
- method: "POST",
- headers: new Headers({
- "Content-Type": "application/json",
- }),
- body: JSON.stringify({ url, body, method, headers, region }),
- signal: AbortSignal.timeout(ABORT_TIMEOUT),
- });
-
- if (!res.ok) {
- return {
- error: "Something went wrong. Please try again.",
- };
- }
-
- const as = assertions.deserialize(
- JSON.stringify([
- ...(statusAssertions || []),
- ...(headerAssertions || []),
- ...(textBodyAssertions || []),
- ]),
- );
-
- const data = (await res.json()) as RegionChecker;
-
- const _headers: Record<string, string> = {};
- // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
- res.headers.forEach((value, key) => (_headers[key] = value));
- if (data.state === "success") {
- if (as.length > 0) {
- for (const a of as) {
- const { success, message } = a.assert({
- body: data.body ?? "",
- header: data.headers ?? {},
- status: data.status,
- });
- if (!success) {
- return { data, error: `Assertion error: ${message}` };
- }
- }
- } else {
- // default assertion if no assertions are provided
- if (res.status < 200 || res.status >= 300) {
- return {
- data,
- error: `Assertion error: The response status was not 2XX: ${data.status}.`,
- };
- }
- }
- } else {
- return { data, error: `Request error: ${data}` };
- }
-
- return { data, error: undefined };
- } catch (error) {
- console.error(error);
- if (error instanceof Error && error.name === "AbortError") {
- return {
- error: `Abort error: request takes more then ${formatDuration(
- ABORT_TIMEOUT,
- )}.`,
- };
- }
- return {
- error: "Something went wrong. Please try again.",
- };
- }
- };
-
- function onValueChange(value: string) {
- // REMINDER: we are not merging the searchParams here
- // we are just setting the section to allow refreshing the page
- const params = new URLSearchParams();
- params.set("section", value);
- router.push(`${pathname}?${params.toString()}`);
- }
-
- return (
- <>
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(onSubmit)}
- onKeyDown={(e) => e.key === "Enter" && e.preventDefault()}
- className="flex w-full flex-col gap-6"
- >
- <General {...{ form, tags }} />
- <Tabs
- defaultValue={defaultSection}
- className="w-full"
- onValueChange={onValueChange}
- >
- <TabsList>
- <TabsTrigger value="request">Request</TabsTrigger>
- <TabsTrigger value="scheduling">Scheduling & Regions</TabsTrigger>
- <TabsTrigger value="assertions">
- Timing & Assertions{" "}
- {_assertions.length ? (
- <Badge variant="secondary" className="ml-1">
- {_assertions.length}
- </Badge>
- ) : null}
- </TabsTrigger>
- <TabsTrigger value="notifications">
- Notifications{" "}
- {defaultValues?.notifications?.length ? (
- <Badge variant="secondary" className="ml-1">
- {defaultValues.notifications.length}
- </Badge>
- ) : null}
- </TabsTrigger>
- <TabsTrigger value="status-page">
- Status Page{" "}
- {defaultValues?.pages?.length ? (
- <Badge variant="secondary" className="ml-1">
- {defaultValues.pages.length}
- </Badge>
- ) : null}
- </TabsTrigger>
- <TabsTrigger value="otel">OTel</TabsTrigger>
- {defaultValues?.id ? (
- <TabsTrigger value="danger">Danger</TabsTrigger>
- ) : null}
- </TabsList>
- <TabsContent value="request">
- <SectionRequests {...{ form, pingEndpoint, type }} />
- </TabsContent>
- <TabsContent value="assertions">
- <SectionAssertions {...{ form }} />
- </TabsContent>
- <TabsContent value="scheduling">
- <SectionScheduling {...{ form, limits, plan }} />
- </TabsContent>
- <TabsContent value="otel">
- <SectionOtel {...{ form, limits }} />
- </TabsContent>
- <TabsContent value="notifications">
- <SectionNotifications {...{ form, notifications }} />
- </TabsContent>
- <TabsContent value="status-page">
- <SectionStatusPage {...{ form, pages }} />
- </TabsContent>
- {defaultValues?.id ? (
- <TabsContent value="danger">
- <SectionDanger monitorId={defaultValues.id} {...{ form }} />
- </TabsContent>
- ) : null}
- </Tabs>
- <div className="grid gap-4 sm:flex sm:items-start sm:justify-end">
- {withTestButton ? (
- <RequestTestButton {...{ form, limits, pingEndpoint }} />
- ) : null}
- <SaveButton
- isPending={isPending}
- isDirty={form.formState.isDirty}
- onSubmit={form.handleSubmit(onSubmit)}
- />
- </div>
- </form>
- </Form>
- <FailedPingAlertConfirmation
- monitor={form.getValues()}
- {...{ pingFailed, setPingFailed }}
- onConfirm={handleForceDataUpdateOrInsertion}
- />
- </>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/general.tsx b/apps/web/src/components/forms/monitor/general.tsx
deleted file mode 100644
index f9c384db4..000000000
--- a/apps/web/src/components/forms/monitor/general.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-"use client";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertMonitor, MonitorTag } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
- Switch,
-} from "@openstatus/ui";
-
-import { SectionHeader } from "../shared/section-header";
-import { TagsMultiBox } from "./tags-multi-box";
-
-interface Props {
- form: UseFormReturn<InsertMonitor>;
- tags?: MonitorTag[];
-}
-
-export function General({ form, tags }: Props) {
- return (
- <div className="grid gap-4 sm:grid-cols-3 sm:gap-6">
- <SectionHeader
- title="Basic Information"
- description="Be able to find your monitor easily."
- />
- <div className="flex w-full flex-col gap-4 sm:col-span-2">
- <div className="flex w-full gap-4">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem className="w-full">
- <FormLabel>Name</FormLabel>
- <FormControl>
- <Input placeholder="Documenso" {...field} />
- </FormControl>
- <FormDescription>Displayed on the status page.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="active"
- render={({ field }) => (
- <FormItem className="flex flex-row items-center justify-between space-x-1 space-y-0">
- <FormLabel>Active</FormLabel>
- <FormControl>
- <Switch
- checked={field.value || false}
- onCheckedChange={(value) => field.onChange(value)}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <div className="grid gap-4 sm:grid-cols-3">
- <FormField
- control={form.control}
- name="tags"
- render={({ field }) => (
- <FormItem className="sm:col-span-2">
- <FormLabel>Tags</FormLabel>
- <FormControl>
- <TagsMultiBox
- tags={tags}
- onChange={field.onChange}
- values={field.value}
- // {...field}
- />
- </FormControl>
- <FormDescription>
- Categorize your monitors. Create new tags by typing a name.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/request-test-button.tsx b/apps/web/src/components/forms/monitor/request-test-button.tsx
deleted file mode 100644
index 889800f9d..000000000
--- a/apps/web/src/components/forms/monitor/request-test-button.tsx
+++ /dev/null
@@ -1,159 +0,0 @@
-"use client";
-
-import { Send } from "lucide-react";
-import React from "react";
-import type { UseFormReturn } from "react-hook-form";
-
-import { deserialize } from "@openstatus/assertions";
-import type { InsertMonitor } from "@openstatus/db/src/schema";
-import {
- type Region,
- monitorRegions,
-} from "@openstatus/db/src/schema/constants";
-import { regionDict } from "@openstatus/regions";
-import {
- Button,
- Dialog,
- DialogContent,
- DialogHeader,
- DialogTitle,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { RegionInfo } from "@/components/ping-response-analysis/region-info";
-import { ResponseDetailTabs } from "@/components/ping-response-analysis/response-detail-tabs";
-import type { RegionChecker } from "@/components/ping-response-analysis/utils";
-import { toast, toastAction } from "@/lib/toast";
-import type { Limits } from "@openstatus/db/src/schema/plan/schema";
-import { getLimit } from "@openstatus/db/src/schema/plan/utils";
-
-interface Props {
- form: UseFormReturn<InsertMonitor>;
- limits: Limits;
- pingEndpoint(
- region?: Region,
- ): Promise<{ data?: RegionChecker; error?: string }>;
-}
-
-export function RequestTestButton({ form, pingEndpoint, limits }: Props) {
- const [check, setCheck] = React.useState<
- { data: RegionChecker; error?: string } | undefined
- >();
- const [value, setValue] = React.useState<Region>(monitorRegions[0]);
- const [isPending, startTransition] = React.useTransition();
-
- const onClick = () => {
- if (isPending) return;
-
- const { url } = form.getValues();
-
- if (!url) {
- toastAction("test-warning-empty-url");
- return;
- }
-
- startTransition(async () => {
- try {
- const { data, error } = await pingEndpoint(value);
- if (data) setCheck({ data, error });
- const isOk = !error;
- if (isOk) {
- toastAction("test-success");
- } else {
- toast.error(error);
- }
- } catch {
- toastAction("error");
- }
- });
- };
-
- const { flag } = regionDict[value as keyof typeof regionDict];
-
- const { statusAssertions, headerAssertions } = form.getValues();
-
- const regions = getLimit(limits, "regions");
-
- return (
- <Dialog open={!!check} onOpenChange={() => setCheck(undefined)}>
- <div className="group flex h-10 items-center rounded-md bg-transparent text-sm ring-offset-background focus-within:outline-hidden focus-within:ring-2 focus-within:ring-ring focus-within:ring-offset-2">
- <Select
- value={value}
- onValueChange={(value: Region) => setValue(value)}
- >
- <SelectTrigger
- className="flex-1 rounded-r-none border-accent focus:ring-0"
- aria-label={value}
- >
- <SelectValue>{flag}</SelectValue>
- </SelectTrigger>
- <SelectContent>
- {regions.map((region) => {
- const { flag } = regionDict[region];
- return (
- <SelectItem key={region} value={region}>
- {flag} <span className="ml-1 font-mono">{region}</span>
- </SelectItem>
- );
- })}
- </SelectContent>
- </Select>
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- onClick={onClick}
- disabled={isPending}
- className="h-full flex-1 rounded-l-none focus:ring-0"
- variant="secondary"
- >
- {isPending ? (
- <LoadingAnimation variant="inverse" />
- ) : (
- <>
- Test <Send className="ml-2 h-4 w-4" />
- </>
- )}
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Ping your endpoint</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- </div>
- <DialogContent className="max-h-screen w-full overflow-auto sm:max-w-3xl sm:p-8">
- <DialogHeader>
- <DialogTitle>Response</DialogTitle>
- </DialogHeader>
- {check?.data.state === "success" ? (
- <div className="grid gap-8">
- <RegionInfo check={check.data} error={check.error} />
- {check.data.state === "success" && check.data.type === "http" ? (
- <ResponseDetailTabs
- timing={check.data.timing}
- headers={check.data.headers}
- status={check.data.status}
- assertions={deserialize(
- JSON.stringify([
- ...(statusAssertions || []),
- ...(headerAssertions || []),
- ]),
- )}
- />
- ) : null}
- </div>
- ) : null}
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/section-danger.tsx b/apps/web/src/components/forms/monitor/section-danger.tsx
deleted file mode 100644
index 35bcd1981..000000000
--- a/apps/web/src/components/forms/monitor/section-danger.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertMonitor } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- Checkbox,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-import React from "react";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- monitorId: number;
- form: UseFormReturn<InsertMonitor>;
-}
-
-export function SectionDanger({ monitorId, form }: Props) {
- const router = useRouter();
- const [open, setOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- await api.monitor.delete.mutate({ id: monitorId });
- toastAction("deleted");
- setOpen(false);
- router.push("/app");
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <div className="grid w-full gap-4">
- <SectionHeader
- title="Danger Zone"
- description="Be aware of the changes you are about to make."
- />
- <div className="grid gap-4 sm:grid-cols-3">
- <FormField
- control={form.control}
- name="public"
- render={({ field }) => (
- <FormItem className="flex flex-row items-start space-x-3 space-y-0 sm:col-span-2">
- <FormControl>
- <Checkbox
- checked={field.value ?? false}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- <div className="space-y-1 leading-none">
- <FormLabel>Allow public monitor</FormLabel>
- <FormDescription>
- Change monitor visibility. When checked, the monitor stats
- from the overview page will be public. You will be able to
- share it via a connected status page or{" "}
- <code className="underline underline-offset-4">
- openstatus.dev/public/monitors/{form.getValues("id")}
- </code>
- .
- </FormDescription>
- </div>
- </FormItem>
- )}
- />
- <div className="col-start-1 flex flex-col items-center gap-4 sm:col-span-2 sm:flex-row">
- <AlertDialog open={open} onOpenChange={setOpen}>
- <AlertDialogTrigger asChild>
- <Button variant="destructive" className="w-full sm:w-auto">
- Delete
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- monitor.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- <FormDescription className="order-1 text-red-500 sm:order-2">
- This action cannot be undone. This will permanently delete the
- monitor.
- </FormDescription>
- </div>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/section-limits.tsx b/apps/web/src/components/forms/monitor/section-limits.tsx
deleted file mode 100644
index bc7edb6d3..000000000
--- a/apps/web/src/components/forms/monitor/section-limits.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertMonitor } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@openstatus/ui";
-
-import { formatDuration } from "@/lib/utils";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- form: UseFormReturn<InsertMonitor>;
-}
-
-// FIXME: replace with enum
-// TODO: can be also replaced by a custom number input with max value (+ validation)
-const limits = [100, 250, 500, 1_000, 2_000, 5_000, 10_000, 20_000, 40_000];
-
-export function SectionLimits({ form }: Props) {
- return (
- <div className="grid w-full gap-4">
- <SectionHeader
- title="Response Time Limits"
- description="Check when your endpoint is taking too long to respond. And set the limit to be considered degraded."
- />
- <FormField
- control={form.control}
- name="id" // FIXME: should be something like 'limitDegraded'
- render={({ field }) => (
- <FormItem>
- <FormLabel>Degraded limit</FormLabel>
- <Select
- onValueChange={(value) => field.onChange(Number.parseInt(value))}
- defaultValue={String(field.value)}
- >
- <FormControl>
- <SelectTrigger className="sm:w-[200px]">
- <SelectValue placeholder="Select" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {limits.map((limit) => (
- <SelectItem key={limit} value={String(limit)}>
- {formatDuration(limit)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormDescription>
- When the response time exceeds this limit, the monitor is will be
- considered as{" "}
- <span className="text-status-degraded">degraded</span>.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="id" // FIXME: should be something like 'limitFailed'
- render={({ field }) => (
- <FormItem>
- <FormLabel>Failed limit</FormLabel>
- <Select
- onValueChange={(value) => field.onChange(Number.parseInt(value))}
- defaultValue={String(field.value)}
- >
- <FormControl>
- <SelectTrigger className="sm:w-[200px]">
- <SelectValue placeholder="Select" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {limits.map((limit) => (
- <SelectItem key={limit} value={String(limit)}>
- {formatDuration(limit)}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormDescription>
- When the response time exceeds this limit, the monitor is will be
- considered as <span className="text-status-down">failed</span>.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/section-otel.tsx b/apps/web/src/components/forms/monitor/section-otel.tsx
deleted file mode 100644
index 071d28e8c..000000000
--- a/apps/web/src/components/forms/monitor/section-otel.tsx
+++ /dev/null
@@ -1,117 +0,0 @@
-"use client";
-
-import { X } from "lucide-react";
-import { type UseFormReturn, useFieldArray } from "react-hook-form";
-
-import type { InsertMonitor } from "@openstatus/db/src/schema";
-import type { Limits } from "@openstatus/db/src/schema/plan/schema";
-
-import {
- Button,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { ProFeatureAlert } from "@/components/billing/pro-feature-alert";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- form: UseFormReturn<InsertMonitor>;
- limits: Limits;
-}
-
-export function SectionOtel({ form, limits }: Props) {
- const { fields, append, remove } = useFieldArray({
- name: "otelHeaders",
- control: form.control,
- });
-
- if (!limits.otel) {
- return <ProFeatureAlert feature="OpenTelemetry" workspacePlan="team" />;
- }
-
- return (
- <div className="grid w-full gap-4">
- <SectionHeader
- title="OpenTelemetry"
- description="Configure your OpenTelemetry Exporter."
- />
- <div className="grid sm:grid-cols-2 md:grid-cols-3">
- <FormField
- control={form.control}
- name="otelEndpoint"
- render={({ field }) => (
- <FormItem className="col-span-full">
- <FormLabel>Endpoint</FormLabel>
- <FormControl>
- <Input
- type="text"
- placeholder="https://otel.openstatus.dev/api/v1/metrics"
- {...field}
- value={field.value ?? ""}
- />
- </FormControl>
- <FormDescription>
- The endpoint to send the metrics to.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <div className="space-y-2 sm:col-span-full">
- <FormLabel>Request Header</FormLabel>
- {fields.map((field, index) => (
- <div key={field.id} className="grid grid-cols-6 gap-4">
- <FormField
- control={form.control}
- name={`otelHeaders.${index}.key`}
- render={({ field }) => (
- <FormItem className="col-span-2">
- <FormControl>
- <Input placeholder="key" {...field} />
- </FormControl>
- </FormItem>
- )}
- />
- <div className="col-span-4 flex items-center space-x-2">
- <FormField
- control={form.control}
- name={`otelHeaders.${index}.value`}
- render={({ field }) => (
- <FormItem className="w-full">
- <FormControl>
- <Input placeholder="value" {...field} />
- </FormControl>
- </FormItem>
- )}
- />
- <Button
- size="icon"
- variant="ghost"
- type="button"
- onClick={() => remove(index)}
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
- </div>
- ))}
- <div>
- <Button
- type="button"
- variant="outline"
- onClick={() => append({ key: "", value: "" })}
- >
- Add Custom Header
- </Button>
- </div>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/section-request-http.tsx b/apps/web/src/components/forms/monitor/section-request-http.tsx
deleted file mode 100644
index 8710064da..000000000
--- a/apps/web/src/components/forms/monitor/section-request-http.tsx
+++ /dev/null
@@ -1,334 +0,0 @@
-"use client";
-
-import { Wand2, X } from "lucide-react";
-import type * as React from "react";
-import { useFieldArray } from "react-hook-form";
-import type { UseFormReturn } from "react-hook-form";
-
-import {
- monitorMethods,
- monitorMethodsSchema,
-} from "@openstatus/db/src/schema";
-import type { InsertMonitor } from "@openstatus/db/src/schema";
-import {
- Button,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
- Textarea,
- Tooltip,
- TooltipContent,
- TooltipProvider,
- TooltipTrigger,
-} from "@openstatus/ui";
-
-import { toast } from "@/lib/toast";
-import { useRef, useState } from "react";
-
-const contentTypes = [
- { value: "application/octet-stream", label: "Binary File" },
- { value: "application/json", label: "JSON" },
- { value: "application/xml", label: "XML" },
- { value: "application/yaml", label: "YAML" },
- { value: "application/edn", label: "EDN" },
- { value: "application/other", label: "Other" },
- { value: "none", label: "None" },
-];
-
-interface Props {
- form: UseFormReturn<InsertMonitor>;
-}
-
-// TODO: add Dialog with response informations when pingEndpoint!
-
-export function SectionRequestHTTP({ form }: Props) {
- const { fields, append, prepend, remove, update } = useFieldArray({
- name: "headers",
- control: form.control,
- });
- const inputRef = useRef<HTMLInputElement>(null);
- const watchMethod = form.watch("method");
- const [file, setFile] = useState<string | undefined>(undefined);
- const [content, setContent] = useState<string | undefined>(
- fields.find((field) => field.key === "Content-Type")?.value,
- );
-
- const validateJSON = (value?: string) => {
- if (!value) return;
- try {
- const obj = JSON.parse(value) as Record<string, unknown>;
- form.clearErrors("body");
- return obj;
- } catch (_e) {
- form.setError("body", {
- message: "Not a valid JSON object",
- });
- return false;
- }
- };
-
- const uploadFile = async (event: React.ChangeEvent<HTMLInputElement>) => {
- if (event.target.files?.[0]) {
- const file = event.target.files[0];
-
- // File too big, return error
- const fileSize = file.size / 1024 / 1024; // in MiB
- if (fileSize > 10) {
- // Display error message
- toast.error("File size is too big. Max 10MB allowed.");
- return;
- }
-
- const reader = new FileReader();
- reader.onload = (event) => {
- if (event.target?.result && typeof event.target.result === "string") {
- form.setValue("body", event.target?.result);
- setFile(file.name);
- }
- };
-
- reader.readAsDataURL(file);
- }
- };
-
- const onPrettifyJSON = () => {
- const body = form.getValues("body");
- const obj = validateJSON(body);
- if (obj) {
- const pretty = JSON.stringify(obj, undefined, 4);
- form.setValue("body", pretty);
- }
- };
-
- return (
- <div className="grid w-full gap-4">
- <div className="grid gap-4 sm:grid-cols-7">
- <FormField
- control={form.control}
- name="method"
- render={({ field }) => (
- <FormItem className="sm:col-span-1">
- <FormLabel>Method</FormLabel>
- <Select
- onValueChange={(value) => {
- field.onChange(monitorMethodsSchema.parse(value));
- form.resetField("body", { defaultValue: "" });
- setContent(undefined);
- }}
- defaultValue={field.value}
- >
- <FormControl>
- <SelectTrigger>
- <SelectValue placeholder="Select" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {monitorMethods.map((method) => (
- <SelectItem key={method} value={method}>
- {method}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="url"
- render={({ field }) => (
- <FormItem className="sm:col-span-6">
- <FormLabel>URL</FormLabel>
- <FormControl>
- <Input
- className="bg-muted"
- placeholder="https://documenso.com/api/health"
- {...field}
- />
- </FormControl>
- </FormItem>
- )}
- />
- </div>
- <div className="space-y-2 sm:col-span-full">
- <FormLabel>Request Header</FormLabel>
- {fields.map((field, index) => (
- <div key={field.id} className="grid grid-cols-6 gap-4">
- <FormField
- control={form.control}
- name={`headers.${index}.key`}
- render={({ field }) => (
- <FormItem className="col-span-2">
- <FormControl>
- <Input placeholder="key" {...field} />
- </FormControl>
- </FormItem>
- )}
- />
- <div className="col-span-4 flex items-center space-x-2">
- <FormField
- control={form.control}
- name={`headers.${index}.value`}
- render={({ field }) => (
- <FormItem className="w-full">
- <FormControl>
- <Input placeholder="value" {...field} />
- </FormControl>
- </FormItem>
- )}
- />
- <Button
- size="icon"
- variant="ghost"
- type="button"
- onClick={() => remove(index)}
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
- </div>
- ))}
- <div>
- <Button
- type="button"
- variant="outline"
- onClick={() => append({ key: "", value: "" })}
- >
- Add Custom Header
- </Button>
- </div>
- </div>
- {(watchMethod === "POST" ||
- watchMethod === "PUT" ||
- watchMethod === "PATCH" ||
- watchMethod === "DELETE") && (
- <div className="sm:col-span-full">
- <FormField
- control={form.control}
- name="body"
- render={({ field }) => (
- <FormItem className="space-y-1.5">
- <div className="flex items-end justify-between">
- <FormLabel className="flex items-center space-x-2">
- Body
- <Select
- defaultValue={content}
- onValueChange={(value) => {
- setContent(value);
-
- if (content === "application/octet-stream") {
- form.setValue("body", "");
- setFile(undefined);
- }
-
- const contentIndex = fields.findIndex(
- (field) => field.key === "Content-Type",
- );
-
- if (contentIndex >= 0) {
- if (value === "none") {
- remove(contentIndex);
- } else {
- update(contentIndex, {
- key: "Content-Type",
- value,
- });
- }
- } else {
- prepend({ key: "Content-Type", value });
- }
- }}
- >
- <SelectTrigger
- variant={"ghost"}
- className="ml-1 h-7 text-muted-foreground text-xs"
- >
- <SelectValue placeholder="Content-Type" />
- </SelectTrigger>
- <SelectContent>
- {contentTypes.map((type) => (
- <SelectItem key={type.value} value={type.value}>
- {type.label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- </FormLabel>
- {watchMethod === "POST" &&
- fields.some(
- (field) =>
- field.key === "Content-Type" &&
- field.value === "application/json",
- ) && (
- <TooltipProvider>
- <Tooltip>
- <TooltipTrigger asChild>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="h-7 w-7"
- onClick={onPrettifyJSON}
- >
- <Wand2 className="h-3 w-3" />
- </Button>
- </TooltipTrigger>
- <TooltipContent>
- <p>Prettify JSON</p>
- </TooltipContent>
- </Tooltip>
- </TooltipProvider>
- )}
- </div>
- <div className="space-y-2">
- <FormControl>
- {content === "application/octet-stream" ? (
- <>
- <Button
- type="button"
- variant="outline"
- onClick={() => inputRef.current?.click()}
- className="max-w-56"
- >
- <span className="truncate">
- {file || form.getValues("body") || "Upload file"}
- </span>
- </Button>
- <input
- type="file"
- onChange={uploadFile}
- ref={inputRef}
- hidden
- />
- </>
- ) : (
- <>
- <Textarea
- rows={8}
- placeholder='{ "hello": "world" }'
- {...field}
- />
- <FormDescription>Write your payload.</FormDescription>
- </>
- )}
- </FormControl>
- <FormMessage />
- </div>
- </FormItem>
- )}
- />
- </div>
- )}
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/section-request-tcp.tsx b/apps/web/src/components/forms/monitor/section-request-tcp.tsx
deleted file mode 100644
index 4740b0917..000000000
--- a/apps/web/src/components/forms/monitor/section-request-tcp.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-"use client";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertMonitor } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-// TODO: add `port` and `host` field instead!
-
-interface Props {
- form: UseFormReturn<InsertMonitor>;
-}
-
-export function SectionRequestTCP({ form }: Props) {
- return (
- <div className="grid w-full gap-4">
- <div className="grid gap-4 sm:grid-cols-7">
- <FormField
- control={form.control}
- name="url"
- render={({ field }) => (
- <FormItem className="sm:col-span-5">
- <FormLabel>Host:Port</FormLabel>
- <FormControl>
- <Input
- className="bg-muted"
- placeholder="192.168.1.1:80"
- {...field}
- />
- </FormControl>
- <FormMessage />
- <FormDescription>
- The input supports both IPv4 addresses and IPv6 addresses.
- </FormDescription>
- </FormItem>
- )}
- />
- </div>
- <div className="text-sm">
- <p>Examples:</p>
- <ul className="list-inside list-disc text-muted-foreground">
- <li>
- Domain: <code className="text-foreground">openstatus.dev:443</code>
- </li>
- <li>
- IPv4: <code className="text-foreground">192.168.1.1:443</code>
- </li>
- <li>
- IPv6:{" "}
- <code className="text-foreground">
- [2001:db8:85a3:8d3:1319:8a2e:370:7348]:443
- </code>
- </li>
- </ul>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/section-requests.tsx b/apps/web/src/components/forms/monitor/section-requests.tsx
deleted file mode 100644
index 4598f0f0c..000000000
--- a/apps/web/src/components/forms/monitor/section-requests.tsx
+++ /dev/null
@@ -1,126 +0,0 @@
-"use client";
-
-import * as React from "react";
-import type { UseFormReturn } from "react-hook-form";
-
-import { monitorJobTypesSchema } from "@openstatus/db/src/schema";
-import type { InsertMonitor } from "@openstatus/db/src/schema";
-
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@/components/dashboard/tabs";
-
-import { Alert, AlertDescription, AlertTitle } from "@openstatus/ui";
-import { SectionHeader } from "../shared/section-header";
-import { SectionRequestHTTP } from "./section-request-http";
-import { SectionRequestTCP } from "./section-request-tcp";
-
-interface Props {
- form: UseFormReturn<InsertMonitor>;
- type: "create" | "update";
-}
-
-// TODO: add Dialog with response informations when pingEndpoint!
-
-export function SectionRequests({ form, type }: Props) {
- const jobType = form.getValues("jobType");
- const [prevJobType, setPrevJobType] = React.useState(jobType);
-
- if (prevJobType !== jobType) {
- setPrevJobType(jobType);
- if (type === "create") {
- form.resetField("url");
- form.resetField("method");
- form.resetField("body");
- form.resetField("headers");
- form.resetField("headerAssertions");
- form.resetField("statusAssertions");
- form.resetField("textBodyAssertions");
- }
- }
-
- return (
- <div className="grid w-full gap-4">
- <SectionHeader
- title="Request Settings"
- description={
- type === "create" ? (
- <>
- Create your{" "}
- <span className="font-medium font-mono text-foreground">
- HTTP
- </span>{" "}
- or{" "}
- <span className="font-medium font-mono text-foreground">TCP</span>{" "}
- request type. Add custom headers, payload and test your endpoint
- before submitting.{" "}
- <span className="font-medium">
- You will not be able to switch type after saving.
- </span>
- </>
- ) : (
- <>
- Update your{" "}
- <span className="font-medium font-mono text-foreground">
- {jobType?.toUpperCase()}
- </span>{" "}
- request. Add custom headers, payload and test your endpoint before
- submitting.
- </>
- )
- }
- />
- {type === "create" ? (
- <Tabs
- value={jobType}
- onValueChange={(value) => {
- const validate = monitorJobTypesSchema.safeParse(value);
- if (!validate.success) return;
- form.setValue("jobType", validate.data, {
- shouldDirty: true,
- shouldTouch: true,
- shouldValidate: true,
- });
- }}
- >
- <TabsList>
- <TabsTrigger value="http">HTTP</TabsTrigger>
- <TabsTrigger value="tcp">TCP</TabsTrigger>
- </TabsList>
- <TabsContent value="http">
- <SectionRequestHTTP {...{ form }} />
- </TabsContent>
- <TabsContent value="tcp">
- <SectionRequestTCP {...{ form }} />
- </TabsContent>
- </Tabs>
- ) : null}
- {type === "update"
- ? (() => {
- switch (jobType) {
- case "http":
- return <SectionRequestHTTP {...{ form }} />;
- case "tcp":
- return <SectionRequestTCP {...{ form }} />;
- default:
- return (
- <Alert>
- <AlertTitle>Missing Type</AlertTitle>
- <AlertDescription>
- The job type{" "}
- <span className="font-mono text-foreground uppercase">
- {jobType}
- </span>{" "}
- is missing. Please select a valid job type.
- </AlertDescription>
- </Alert>
- );
- }
- })()
- : null}
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/section-scheduling.tsx b/apps/web/src/components/forms/monitor/section-scheduling.tsx
deleted file mode 100644
index 8d28b9a1e..000000000
--- a/apps/web/src/components/forms/monitor/section-scheduling.tsx
+++ /dev/null
@@ -1,228 +0,0 @@
-"use client";
-
-import { Info } from "lucide-react";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertMonitor, WorkspacePlan } from "@openstatus/db/src/schema";
-import { monitorPeriodicitySchema } from "@openstatus/db/src/schema/constants";
-import type { Limits } from "@openstatus/db/src/schema/plan/schema";
-import { getLimit } from "@openstatus/db/src/schema/plan/utils";
-
-import { cn } from "@/lib/utils";
-import { groupByContinent } from "@openstatus/regions";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@openstatus/ui";
-
-import { CheckboxLabel } from "../shared/checkbox-label";
-import { SectionHeader } from "../shared/section-header";
-import { SelectRegion } from "./select-region";
-
-// TODO: centralize in a shared file!
-const cronJobs = [
- { value: "30s", label: "30 seconds" },
- { value: "1m", label: "1 minute" },
- { value: "5m", label: "5 minutes" },
- { value: "10m", label: "10 minutes" },
- { value: "30m", label: "30 minutes" },
- { value: "1h", label: "1 hour" },
-] as const;
-
-interface Props {
- form: UseFormReturn<InsertMonitor>;
- limits: Limits;
- plan: WorkspacePlan;
-}
-
-export function SectionScheduling({ form, limits, plan }: Props) {
- const periodicityLimit = getLimit(limits, "periodicity");
- const regionsLimit = getLimit(limits, "regions");
- return (
- <div className="grid w-full gap-4">
- <SectionHeader
- title="Schedule and Regions"
- description="Customize the period of time and the regions where your endpoint will be monitored."
- />
- <div className="grid sm:grid-cols-2 md:grid-cols-3">
- <FormField
- control={form.control}
- name="periodicity"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Frequency</FormLabel>
- <Select
- onValueChange={(value) =>
- field.onChange(monitorPeriodicitySchema.parse(value))
- }
- defaultValue={field.value}
- >
- <FormControl>
- <SelectTrigger className="w-full">
- <SelectValue placeholder="How often should it check your endpoint?" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- {cronJobs.map(({ label, value }) => (
- <SelectItem
- key={value}
- value={value}
- disabled={!periodicityLimit.includes(value)}
- >
- {label}
- </SelectItem>
- ))}
- </SelectContent>
- </Select>
- <FormDescription>
- Frequency of how often your endpoint will be pinged.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- <FormField
- control={form.control}
- name="regions"
- render={({ field }) => {
- return (
- <FormItem>
- <FormLabel className="text-base">Regions</FormLabel>
- <div>
- <FormControl>
- <SelectRegion
- value={field.value}
- allowedRegions={regionsLimit}
- onChange={field.onChange}
- />
- </FormControl>
- </div>
- <FormDescription>
- Select the regions you want to monitor your endpoint from.{" "}
- <br />
- <span className="text-xs">
- {plan === "free"
- ? "Only a few regions are available in the free plan. Upgrade to access all regions."
- : ""}
- </span>
- </FormDescription>
- <FewRegionsBanner form={form} className="max-w-md" />
- <div>
- {Object.entries(groupByContinent)
- .sort((a, b) => a[0].localeCompare(b[0]))
- .map(([continent, regions]) => {
- return { continent, regions };
- })
- .map((current) => {
- return (
- <div key={current.continent} className="py-2">
- <p className="font-medium text-muted-foreground text-sm">
- {current.continent}
- </p>
- <div className="grid grid-cols-3 gap-2">
- {current.regions
- .sort((a, b) =>
- a.location.localeCompare(b.location),
- )
- .map((item) => {
- return (
- <FormField
- key={item.code}
- control={form.control}
- name="regions"
- render={({ field }) => {
- const { flag, location } = item;
- return (
- <FormItem
- key={item.code}
- className="h-full w-full"
- >
- <FormControl className="h-full">
- <CheckboxLabel
- disabled={
- !regionsLimit.includes(item.code)
- }
- id={item.code}
- name="region"
- checked={field.value?.includes(
- item.code,
- )}
- onCheckedChange={(checked) => {
- return checked
- ? field.onChange([
- ...(field.value
- ? field.value
- : []),
- item.code,
- ])
- : field.onChange(
- field.value?.filter(
- (value) =>
- value !== item.code,
- ),
- );
- }}
- className="p-3"
- >
- {location} {flag}
- </CheckboxLabel>
- </FormControl>
- </FormItem>
- );
- }}
- />
- );
- })}
- </div>
- </div>
- );
- })}
- </div>
- <FormMessage />
- </FormItem>
- );
- }}
- />
- </div>
- );
-}
-
-// REMINDER: only watch the regions in a new component to avoid re-renders
-function FewRegionsBanner({
- form,
- className,
-}: Pick<Props, "form"> & { className?: string }) {
- const watchRegions = form.watch("regions");
-
- if (watchRegions?.length && watchRegions.length > 2) return null;
-
- return (
- <div
- className={cn(
- "flex items-center gap-3 rounded-lg border border-border px-3 py-2",
- className,
- )}
- >
- <Info
- className="-mt-0.5 shrink-0 text-status-monitoring"
- size={16}
- strokeWidth={2}
- aria-hidden="true"
- />
- <p className="text-sm">
- To minimize false positives, we recommend monitoring your endpoint in at
- least 3 regions.
- </p>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/section-status-page.tsx b/apps/web/src/components/forms/monitor/section-status-page.tsx
deleted file mode 100644
index f9fff3c73..000000000
--- a/apps/web/src/components/forms/monitor/section-status-page.tsx
+++ /dev/null
@@ -1,111 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertMonitor, Page } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { CheckboxLabel } from "../shared/checkbox-label";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- form: UseFormReturn<InsertMonitor>;
- pages?: Page[];
-}
-
-// FIXME: the `CheckLabel` doesn't take the full space
-
-export function SectionStatusPage({ form, pages }: Props) {
- return (
- <div className="flex w-full flex-col gap-4">
- <SectionHeader
- title="Status Page"
- description="Customize the informations about your monitor on the corresponding status page."
- />
- <FormField
- control={form.control}
- name="description"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Description</FormLabel>
- <FormControl>
- <Input
- placeholder="Determines the api health of our services."
- {...field}
- />
- </FormControl>
- <FormDescription>
- Provide your users with information about it.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="pages"
- // biome-ignore lint/correctness/noUnusedVariables: <explanation>
- render={({ field }) => {
- return (
- <FormItem>
- <div className="mb-4">
- <FormLabel className="text-base">Status Pages</FormLabel>
- <FormDescription>
- Select the pages where you want to display the monitor.
- </FormDescription>
- </div>
- <div className="grid grid-cols-1 grid-rows-1 gap-4 sm:grid-cols-2 md:grid-cols-3">
- {pages?.map((item) => (
- <FormField
- key={item.id}
- control={form.control}
- name="pages"
- render={({ field }) => {
- return (
- <FormItem key={item.id} className="h-full w-full">
- <FormControl className="h-full">
- <CheckboxLabel
- id={String(item.id)}
- name="page"
- checked={field.value?.includes(item.id)}
- onCheckedChange={(checked) => {
- return checked
- ? field.onChange([
- ...(field.value ? field.value : []),
- item.id,
- ])
- : field.onChange(
- field.value?.filter(
- (value) => value !== item.id,
- ),
- );
- }}
- >
- <span>{item.title}</span>
- </CheckboxLabel>
- </FormControl>
- </FormItem>
- );
- }}
- />
- ))}
- </div>
- {!pages || pages.length === 0 ? (
- <FormDescription>Missing status pages.</FormDescription>
- ) : null}
- <FormMessage />
- </FormItem>
- );
- }}
- />
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/select-region.tsx b/apps/web/src/components/forms/monitor/select-region.tsx
deleted file mode 100644
index 8cfee7b14..000000000
--- a/apps/web/src/components/forms/monitor/select-region.tsx
+++ /dev/null
@@ -1,144 +0,0 @@
-"use client";
-
-import { Check, ChevronsUpDown, Globe2 } from "lucide-react";
-
-import {
- type Continent,
- type RegionInfo,
- formatRegionCode,
- regionDict,
-} from "@openstatus/regions";
-import { Button, type ButtonProps } from "@openstatus/ui/src/components/button";
-import {
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
- CommandSeparator,
-} from "@openstatus/ui/src/components/command";
-import {
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@openstatus/ui/src/components/popover";
-
-import { cn } from "@/lib/utils";
-import {
- type Region,
- monitorRegions,
-} from "@openstatus/db/src/schema/constants";
-
-interface SelectRegionProps extends Omit<ButtonProps, "onChange"> {
- allowedRegions: Region[];
- value?: Region[];
- onChange?: (value: Region[]) => void;
-}
-
-export function SelectRegion({
- value = [],
- onChange,
- allowedRegions,
- className,
- ...props
-}: SelectRegionProps) {
- const regionsByContinent = monitorRegions.reduce(
- (prev, curr) => {
- const region = regionDict[curr];
-
- const item = prev.find((r) => r.continent === region.continent);
-
- if (item) {
- item.data.push(region);
- } else {
- prev.push({
- continent: region.continent,
- data: [region],
- });
- }
-
- return prev;
- },
- [] as { continent: Continent; data: RegionInfo[] }[],
- );
-
- return (
- <Popover>
- <PopoverTrigger asChild>
- <Button
- size="lg"
- variant="outline"
- className={cn("px-3 shadow-none", className)}
- {...props}
- >
- <Globe2 className="mr-2 h-4 w-4" />
- <span className="whitespace-nowrap">
- <code>{value.length}</code> Regions
- </span>
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="p-0" align="start">
- <Command>
- <CommandInput placeholder="Search regions..." />
- <CommandList className="max-h-64">
- <CommandEmpty>No results found.</CommandEmpty>
- <CommandGroup>
- <CommandItem
- onSelect={() => onChange?.(value.length ? [] : allowedRegions)}
- >
- {value.length ? "Clear all" : "Select all"}
- </CommandItem>
- </CommandGroup>
- <CommandSeparator />
- {regionsByContinent.map(({ continent, data }) => {
- return (
- <CommandGroup key={continent} heading={continent}>
- {data.map((region) => {
- const { code, flag, location, continent } = region;
- const isSelected = value.includes(code);
- return (
- <CommandItem
- key={code}
- value={code}
- keywords={[code, location, continent]}
- disabled={!allowedRegions.includes(code)}
- onSelect={(checked) => {
- const newValue = !value.includes(checked as Region)
- ? [...value, code]
- : value.filter((r) => r !== code);
- onChange?.(newValue);
- }}
- >
- <div
- className={cn(
- "mr-2 flex h-4 w-4 items-center justify-center rounded-sm border border-primary",
- isSelected
- ? "bg-primary text-primary-foreground"
- : "opacity-50 [&_svg]:invisible",
- )}
- >
- <Check className={cn("h-4 w-4")} />
- </div>
- <div className="flex w-full justify-between">
- <span>
- {formatRegionCode(code)}{" "}
- <span className="truncate text-muted-foreground">
- {location}
- </span>
- </span>
- <span>{flag}</span>
- </div>
- </CommandItem>
- );
- })}
- </CommandGroup>
- );
- })}
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- );
-}
diff --git a/apps/web/src/components/forms/monitor/tags-multi-box.tsx b/apps/web/src/components/forms/monitor/tags-multi-box.tsx
deleted file mode 100644
index d17a71aeb..000000000
--- a/apps/web/src/components/forms/monitor/tags-multi-box.tsx
+++ /dev/null
@@ -1,397 +0,0 @@
-"use client";
-
-import { Check, ChevronsUpDown, Edit2 } from "lucide-react";
-import * as React from "react";
-
-import type { MonitorTag } from "@openstatus/db/src/schema";
-import {
- Accordion,
- AccordionContent,
- AccordionItem,
- AccordionTrigger,
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- Command,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
- CommandSeparator,
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- Input,
- Label,
- Popover,
- PopoverContent,
- PopoverTrigger,
-} from "@openstatus/ui";
-
-import { Icons } from "@/components/icons";
-import { LoadingAnimation } from "@/components/loading-animation";
-import { TagBadge } from "@/components/monitor/tag-badge";
-import { toastAction } from "@/lib/toast";
-import { cn } from "@/lib/utils";
-import { api } from "@/trpc/client";
-
-const colors = [
- "#ff5c5c", // Red
- "#6fcf97", // Green
- "#70a1ff", // Blue
- "#ffb74d", // Orange
- "#b19cd9", // Violet
- "#7986cb", // Indigo
- "#64b5f6", // Turquoise
- "#ffee58", // Yellow
- "#f06292", // Pink
- "#ff77ff", // Fuchsia
- "#808080", // Gray
-];
-
-interface TagsMultiBoxProps {
- tags?: MonitorTag[];
- values: number[]; // values from the form
- onChange: (values: number[]) => void;
-}
-
-export function TagsMultiBox({
- tags: defaultTags = [],
- values,
- onChange,
-}: TagsMultiBoxProps) {
- const inputRef = React.useRef<HTMLInputElement>(null);
- const [tags, setTags] = React.useState<MonitorTag[]>(defaultTags);
- const [openCombobox, setOpenCombobox] = React.useState(false);
- const [openDialog, setOpenDialog] = React.useState(false);
- const [inputValue, setInputValue] = React.useState<string>("");
-
- const create = async (name: string) => {
- try {
- const randomIndex = Math.floor(Math.random() * colors.length);
- const newTag = await api.monitorTag.create.mutate({
- name: name.trim(),
- color: colors[randomIndex] || "#808080", // gray as default
- });
- toastAction("saved");
- setTags((prev) => [...prev, newTag]);
- // TODO: seems like the new value is not taken into account....
- // That's mainly because we only update the id, and not the name! Same is for the update() function
- onChange([...values, newTag.id]);
- } catch {
- toastAction("error");
- }
- };
-
- const toggle = (item: MonitorTag) => {
- onChange(
- values?.includes(item.id)
- ? values.filter((v) => v !== item.id)
- : [...values, item.id],
- );
- inputRef?.current?.focus();
- };
-
- const update = async (tag: MonitorTag) => {
- try {
- const updateTag = await api.monitorTag.update.mutate(tag);
- if (!updateTag) return;
- setTags((prev) => prev.map((f) => (f.id === tag.id ? updateTag : f)));
- toastAction("saved");
- } catch {
- toastAction("error");
- }
- };
-
- const _delete = async (item: MonitorTag) => {
- try {
- await api.monitorTag.delete.mutate({ id: item.id });
- setTags((prev) => prev.filter((f) => f.id !== item.id));
- onChange(values?.filter((v) => v !== item.id));
- toastAction("deleted");
- } catch {
- toastAction("error");
- }
- };
-
- const onComboboxOpenChange = (value: boolean) => {
- inputRef.current?.blur(); // HACK: otherwise, would scroll automatically to the bottom of page
- setOpenCombobox(value);
- };
-
- return (
- <div className="w-full">
- <Popover open={openCombobox} onOpenChange={onComboboxOpenChange}>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- aria-expanded={openCombobox}
- className="h-auto w-full justify-between text-foreground"
- >
- <span className="flex flex-wrap gap-2 truncate">
- {values.length > 0
- ? values.map((id) => {
- const tag = tags.find((tag) => tag.id === id);
- return tag ? <TagBadge key={tag.id} {...tag} /> : null;
- })
- : "Select tags"}
- </span>
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent className="w-full p-0">
- <Command className="w-(--radix-popover-trigger-width)" loop>
- <CommandInput
- // biome-ignore lint/suspicious/noExplicitAny: <explanation>
- ref={inputRef as any}
- placeholder="Search tag..."
- value={inputValue}
- onValueChange={setInputValue}
- />
- <CommandList>
- <CommandGroup className="max-h-[145px] overflow-auto">
- {tags.map((item) => {
- const isActive = values?.includes(item.id);
- return (
- <CommandItem
- key={item.id}
- value={item.name}
- onSelect={() => toggle(item)}
- >
- <Check
- className={cn(
- "mr-2 h-4 w-4",
- isActive ? "opacity-100" : "opacity-0",
- )}
- />
- <div className="flex-1">{item.name}</div>
- <div
- className="h-4 w-4 rounded-full"
- style={{ backgroundColor: item.color }}
- />
- </CommandItem>
- );
- })}
- <CommandItemCreate
- onSelect={() => create(inputValue)}
- {...{ inputValue, tags }}
- />
- </CommandGroup>
- <CommandSeparator alwaysRender />
- <CommandGroup>
- <CommandItem
- value={`:${inputValue}:`} // HACK: that way, the edit button will always be shown
- className="text-muted-foreground text-xs"
- onSelect={() => setOpenDialog(true)}
- >
- <div className={cn("mr-2 h-4 w-4")} />
- <Edit2 className="mr-2 h-2.5 w-2.5" />
- Edit tags
- </CommandItem>
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- <Dialog
- open={openDialog}
- onOpenChange={(open) => {
- if (!open) setOpenCombobox(true);
- setOpenDialog(open);
- }}
- >
- <DialogContent className="flex max-h-[90vh] flex-col">
- <DialogHeader>
- <DialogTitle>Edit Tags</DialogTitle>
- <DialogDescription>
- Update or delete tags. Create a tag through the combobox.
- </DialogDescription>
- </DialogHeader>
- <div className="flex-1 overflow-scroll">
- {tags.map((item) => {
- return (
- <DialogListItem
- key={item.id}
- onDelete={() => _delete(item)}
- onSubmit={async (values) => {
- await update({
- ...item,
- ...values,
- });
- }}
- {...item}
- />
- );
- })}
- </div>
- </DialogContent>
- </Dialog>
- </div>
- );
-}
-
-const CommandItemCreate = ({
- inputValue,
- tags,
- onSelect,
-}: {
- inputValue: string;
- tags: MonitorTag[];
- onSelect: () => Promise<void>;
-}) => {
- const [isPending, startTransition] = React.useTransition();
- const hasNoTag = !tags
- .map(({ name }) => name.toLowerCase())
- .includes(`${inputValue.toLowerCase()}`);
-
- const render = inputValue !== "" && hasNoTag;
-
- if (!render) return null;
-
- // BUG: whenever a space is appended, the Create-Button will not be shown.
- return (
- <CommandItem
- key={`${inputValue}`}
- value={`${inputValue}`}
- className="text-muted-foreground text-xs"
- onSelect={() => {
- startTransition(async () => {
- await onSelect();
- });
- }}
- disabled={isPending}
- >
- <div className={cn("mr-2 h-4 w-4")} />
- {isPending ? "Creating" : "Create"} new label &quot;{inputValue}&quot;
- </CommandItem>
- );
-};
-
-const DialogListItem = ({
- id,
- name,
- color,
- onSubmit,
- onDelete,
-}: MonitorTag & {
- onSubmit: (values: { name: string; color: string }) => Promise<void>;
- onDelete: () => Promise<void>;
-}) => {
- const inputRef = React.useRef<HTMLInputElement>(null);
- const [accordionValue, setAccordionValue] = React.useState<string>("");
- const [inputValue, setInputValue] = React.useState<string>(name);
- const [colorValue, setColorValue] = React.useState<string>(color);
- const [isPending, startTransition] = React.useTransition();
- const disabled = name === inputValue && color === colorValue;
-
- React.useEffect(() => {
- if (accordionValue !== "") {
- inputRef.current?.focus();
- }
- }, [accordionValue]);
-
- // const handleSubmit = () => {}
- // const handleDelete = () => {}
-
- return (
- <Accordion
- key={id}
- type="single" // will never work as we have only one accordion for each tag
- collapsible
- value={accordionValue}
- onValueChange={setAccordionValue}
- >
- <AccordionItem value={`item-${id}`}>
- <AccordionTrigger className="w-full hover:no-underline">
- <TagBadge color={color} name={name} />
- </AccordionTrigger>
- <AccordionContent>
- {/* REMINDER: cannot nest form within form! HOTFIX: no form */}
- <div className="flex items-end gap-4 px-1">
- <div className="grid w-full gap-3">
- <Label htmlFor="name">Label name</Label>
- <Input
- ref={inputRef}
- id="name"
- value={inputValue}
- onChange={(e) => setInputValue(e.target.value)}
- className="h-8"
- />
- </div>
- <div className="grid gap-3">
- <Label htmlFor="color">Color</Label>
- <Input
- id="color"
- type="color"
- value={colorValue}
- onChange={(e) => setColorValue(e.target.value)}
- className="h-8 px-2 py-1"
- />
- </div>
- {/* FIXME: shouldnt saves the monitor form */}
- <Button
- onClick={() => {
- startTransition(() => {
- onSubmit({
- name: inputValue.trim(),
- color: colorValue,
- });
- setAccordionValue("");
- });
- }}
- disabled={disabled || isPending}
- >
- {isPending ? <LoadingAnimation /> : "Save"}
- </Button>
- <div className="flex items-center gap-4">
- <AlertDialog>
- <AlertDialogTrigger asChild>
- <Button
- size="icon"
- variant="destructive"
- disabled={isPending}
- >
- <Icons.trash className="h-4 w-4" />
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you sure sure?</AlertDialogTitle>
- <AlertDialogDescription asChild>
- <div>
- You are about to delete the tag{" "}
- <TagBadge color={color} name={name} /> .
- </div>
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={() => {
- startTransition(async () => {
- await onDelete();
- });
- }}
- >
- {isPending ? <LoadingAnimation /> : "Delete"}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- </div>
- </AccordionContent>
- </AccordionItem>
- </Accordion>
- );
-};
diff --git a/apps/web/src/components/forms/notification/form.tsx b/apps/web/src/components/forms/notification/form.tsx
deleted file mode 100644
index 52aa6bc71..000000000
--- a/apps/web/src/components/forms/notification/form.tsx
+++ /dev/null
@@ -1,138 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useRouter } from "next/navigation";
-import { useTransition } from "react";
-import { useForm } from "react-hook-form";
-
-import type {
- InsertNotification,
- InsertNotificationWithData,
- Monitor,
- NotificationProvider,
- WorkspacePlan,
-} from "@openstatus/db/src/schema";
-import { InsertNotificationWithDataSchema } from "@openstatus/db/src/schema";
-import { Badge, Form } from "@openstatus/ui";
-
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@/components/dashboard/tabs";
-import { toast, toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-import { TRPCClientError } from "@trpc/client";
-import { SaveButton } from "../shared/save-button";
-import { General } from "./general";
-import { SectionConnect } from "./section-connect";
-
-interface Props {
- defaultValues?: InsertNotification;
- defaultSection?: string;
- onSubmit?: () => void;
- monitors?: Monitor[];
- workspacePlan: WorkspacePlan;
- nextUrl?: string;
- provider: NotificationProvider;
- callbackData?: string;
-}
-
-export function NotificationForm({
- defaultValues,
- defaultSection = "connect",
- onSubmit: onExternalSubmit,
- workspacePlan,
- monitors,
- nextUrl,
- provider,
- callbackData,
-}: Props) {
- const [isPending, startTransition] = useTransition();
- const router = useRouter();
- const form = useForm<InsertNotificationWithData>({
- resolver: zodResolver(InsertNotificationWithDataSchema),
- defaultValues: {
- ...defaultValues,
- provider,
- name: defaultValues?.name || "",
- data: JSON.parse(defaultValues?.data || "{}"),
- },
- });
-
- async function onSubmit({
- provider,
- data,
- ...rest
- }: InsertNotificationWithData) {
- console.log({ provider, data, ...rest });
- startTransition(async () => {
- try {
- if (provider === "pagerduty") {
- if (callbackData) {
- data.pagerduty = callbackData;
- }
- }
- if (defaultValues) {
- await api.notification.update.mutate({
- provider,
- data: JSON.stringify(data),
- ...rest,
- });
- } else {
- await api.notification.create.mutate({
- provider,
- data: JSON.stringify(data),
- ...rest,
- });
- }
- if (nextUrl) {
- router.push(nextUrl);
- }
- router.refresh();
- toastAction("saved");
- } catch (e) {
- if (e instanceof TRPCClientError) toast.error(e.message);
- else toastAction("error");
- } finally {
- onExternalSubmit?.();
- }
- });
- }
-
- return (
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(onSubmit)}
- id="notification-form" // we use a form id to connect the submit button to the form (as we also have the form nested inside of `MonitorForm`)
- className="flex flex-col gap-4"
- >
- <General form={form} plan={workspacePlan} />
- <Tabs defaultValue={defaultSection} className="w-full">
- <TabsList>
- <TabsTrigger value="connect">
- Connect{" "}
- {defaultValues?.monitors.length ? (
- <Badge variant="secondary" className="ml-1">
- {defaultValues?.monitors.length}
- </Badge>
- ) : null}
- </TabsTrigger>
- </TabsList>
- <TabsContent value="connect">
- <SectionConnect form={form} monitors={monitors} />
- </TabsContent>
- </Tabs>
- <div className="flex gap-4 sm:justify-end">
- <SaveButton
- form="notification-form"
- isPending={isPending}
- isDirty={form.formState.isDirty}
- onSubmit={form.handleSubmit(onSubmit)}
- />
- </div>
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/forms/notification/general.tsx b/apps/web/src/components/forms/notification/general.tsx
deleted file mode 100644
index e5ec69b1a..000000000
--- a/apps/web/src/components/forms/notification/general.tsx
+++ /dev/null
@@ -1,96 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import type {
- InsertNotificationWithData,
- WorkspacePlan,
-} from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { SectionHeader } from "../shared/section-header";
-import { SectionDiscord } from "./provider/section-discord";
-import { SectionEmail } from "./provider/section-email";
-import { SectionNtfy } from "./provider/section-ntfy";
-import { SectionOpsGenie } from "./provider/section-opsgenie";
-import { SectionPagerDuty } from "./provider/section-pagerduty";
-import { SectionSlack } from "./provider/section-slack";
-import { SectionSms } from "./provider/section-sms";
-import { SectionWebhook } from "./provider/section-webhook";
-
-const LABELS = {
- slack: "Slack",
- discord: "Discord",
- sms: "SMS",
- pagerduty: "PagerDuty",
- opsgenie: "OpsGenie",
- email: "Email",
- ntfy: "Ntfy.sh",
- webhook: "Webhook",
-};
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
- plan: WorkspacePlan;
-}
-
-export function General({ form, plan }: Props) {
- const watchProvider = form.watch("provider");
-
- function renderProviderSection() {
- switch (watchProvider) {
- case "slack":
- return <SectionSlack form={form} />;
- case "discord":
- return <SectionDiscord form={form} />;
- case "sms":
- return <SectionSms form={form} />;
- case "pagerduty":
- return <SectionPagerDuty form={form} plan={plan} />;
- case "opsgenie":
- return <SectionOpsGenie form={form} plan={plan} />;
- case "email":
- return <SectionEmail form={form} />;
- case "ntfy":
- return <SectionNtfy form={form} />;
- case "webhook":
- return <SectionWebhook form={form} />;
- default:
- return <div>No provider selected</div>;
- }
- }
-
- return (
- <div className="grid gap-4 sm:grid-cols-3 sm:gap-6">
- <SectionHeader
- title="Alert"
- description={`Update your ${LABELS[watchProvider]} settings`}
- />
- <div className="grid gap-4 sm:col-span-2 sm:grid-cols-2">
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem className="sm:col-span-1 sm:self-baseline">
- <FormLabel>Name</FormLabel>
- <FormControl>
- <Input placeholder="Dev Team" {...field} />
- </FormControl>
- <FormDescription>Define a name for the channel.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- {renderProviderSection()}
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/notification/provider/actions.ts b/apps/web/src/components/forms/notification/provider/actions.ts
deleted file mode 100644
index 78bc2859c..000000000
--- a/apps/web/src/components/forms/notification/provider/actions.ts
+++ /dev/null
@@ -1,48 +0,0 @@
-"use server";
-
-import { sendTest as sendOpsGenieAlert } from "@openstatus/notification-opsgenie";
-
-import { sendTest as sendPagerDutyAlert } from "@openstatus/notification-pagerduty";
-
-import { sendTest as sendNtfyAlert } from "@openstatus/notification-ntfy";
-
-import { sendTest as sendWebhookAlert } from "@openstatus/notification-webhook";
-
-export async function sendOpsGenieTestAlert(
- apiKey: string,
- region: "us" | "eu",
-) {
- const isSuccessfull = await sendOpsGenieAlert({ apiKey, region });
- return isSuccessfull;
-}
-
-export async function sendPagerDutyTestAlert(integrationKey: string) {
- const isSuccessfull = await sendPagerDutyAlert({
- integrationKey: integrationKey,
- });
- return isSuccessfull;
-}
-
-export async function sendNtfyTestAlert({
- topic,
- serverUrl,
- token,
-}: {
- topic: string;
- serverUrl?: string;
- token?: string;
-}) {
- const isSuccessfull = await sendNtfyAlert({ topic, serverUrl, token });
- return isSuccessfull;
-}
-
-export async function sendWebhookTestAlert({
- url,
- headers,
-}: {
- url: string;
- headers?: { key: string; value: string }[];
-}) {
- const isSuccessfull = await sendWebhookAlert({ url, headers });
- return isSuccessfull;
-}
diff --git a/apps/web/src/components/forms/notification/provider/section-discord.tsx b/apps/web/src/components/forms/notification/provider/section-discord.tsx
deleted file mode 100644
index aecb87d00..000000000
--- a/apps/web/src/components/forms/notification/provider/section-discord.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-"use client";
-
-import { useTransition } from "react";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertNotificationWithData } from "@openstatus/db/src/schema";
-import {
- Button,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { sendTestDiscordMessage } from "@openstatus/notification-discord";
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
-}
-
-export function SectionDiscord({ form }: Props) {
- const [isTestPending, startTestTransition] = useTransition();
- const watchUrl = form.watch("data.discord");
-
- async function sendTestWebhookPing() {
- if (!watchUrl) return;
- startTestTransition(async () => {
- const isSuccessfull = await sendTestDiscordMessage(watchUrl);
- if (isSuccessfull) {
- toastAction("test-success");
- } else {
- toastAction("test-error");
- }
- });
- }
-
- return (
- <>
- <FormField
- control={form.control}
- name="data.discord"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Webhook URL</FormLabel>
- <FormControl>
- <Input
- type="url"
- placeholder="https://discord.com/api/webhooks/{channelId}/xxx..."
- required
- {...field}
- />
- </FormControl>
- <FormDescription className="flex items-center justify-between">
- The data is required.
- <a
- href={"https://support.discord.com/hc/en-us/articles/228383668"}
- target="_blank"
- className="underline hover:no-underline"
- rel="noreferrer"
- >
- How to setup your Discord webhook
- </a>
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="col-span-full text-right">
- <Button
- type="button"
- variant="secondary"
- className="w-full sm:w-auto"
- disabled={isTestPending || !watchUrl}
- onClick={sendTestWebhookPing}
- >
- {!isTestPending ? (
- "Test Webhook"
- ) : (
- <LoadingAnimation variant="inverse" />
- )}
- </Button>
- </div>
- </>
- );
-}
diff --git a/apps/web/src/components/forms/notification/provider/section-email.tsx b/apps/web/src/components/forms/notification/provider/section-email.tsx
deleted file mode 100644
index 92405b811..000000000
--- a/apps/web/src/components/forms/notification/provider/section-email.tsx
+++ /dev/null
@@ -1,44 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertNotificationWithData } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
-}
-
-export function SectionEmail({ form }: Props) {
- return (
- <FormField
- control={form.control}
- name="data.email"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Email</FormLabel>
- <FormControl>
- <Input
- type="email"
- placeholder="[email protected]"
- required
- {...field}
- />
- </FormControl>
- <FormDescription className="flex items-center justify-between">
- The email is required.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- );
-}
diff --git a/apps/web/src/components/forms/notification/provider/section-ntfy.tsx b/apps/web/src/components/forms/notification/provider/section-ntfy.tsx
deleted file mode 100644
index 734b7ace2..000000000
--- a/apps/web/src/components/forms/notification/provider/section-ntfy.tsx
+++ /dev/null
@@ -1,105 +0,0 @@
-"use client";
-
-import { toastAction } from "@/lib/toast";
-import type { UseFormReturn } from "react-hook-form";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import type { InsertNotificationWithData } from "@openstatus/db/src/schema";
-import {
- Button,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-import { useTransition } from "react";
-import { sendNtfyTestAlert } from "./actions";
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
-}
-
-export function SectionNtfy({ form }: Props) {
- const [isTestPending, startTestTransition] = useTransition();
-
- const watchTopic = form.watch("data.ntfy.topic");
- const watchUrl = form.watch("data.ntfy.serverUrl");
- const watchToken = form.watch("data.ntfy.token");
-
- async function sendTestAlert() {
- if (!watchTopic) return;
- startTestTransition(async () => {
- const isSuccessfull = await sendNtfyTestAlert({
- topic: watchTopic,
- serverUrl: watchUrl || undefined,
- token: watchToken || undefined,
- });
- if (isSuccessfull) {
- toastAction("test-success");
- } else {
- toastAction("test-error");
- }
- });
- }
-
- return (
- <>
- <FormField
- control={form.control}
- name="data.ntfy.topic"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Topic</FormLabel>
- <FormControl>
- <Input type="text" placeholder="your-topic" required {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="data.ntfy.serverUrl"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>URL</FormLabel>
- <FormControl>
- <Input type="url" placeholder="https://ntfy.sh" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="data.ntfy.token"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Bearer Token</FormLabel>
- <FormControl>
- <Input type="url" placeholder="tk_iloveopenstatus" {...field} />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="col-span-full text-right">
- <Button
- type="button"
- variant="secondary"
- className="w-full sm:w-auto"
- disabled={isTestPending || !watchTopic}
- onClick={sendTestAlert}
- >
- {!isTestPending ? (
- "Test Webhook"
- ) : (
- <LoadingAnimation variant="inverse" />
- )}
- </Button>
- </div>
- </>
- );
-}
diff --git a/apps/web/src/components/forms/notification/provider/section-opsgenie.tsx b/apps/web/src/components/forms/notification/provider/section-opsgenie.tsx
deleted file mode 100644
index 007f72fe5..000000000
--- a/apps/web/src/components/forms/notification/provider/section-opsgenie.tsx
+++ /dev/null
@@ -1,124 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import type {
- InsertNotificationWithData,
- WorkspacePlan,
-} from "@openstatus/db/src/schema";
-import {
- Button,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
- Select,
- SelectContent,
- SelectItem,
- SelectTrigger,
- SelectValue,
-} from "@openstatus/ui";
-import { useTransition } from "react";
-
-import { sendOpsGenieTestAlert } from "./actions";
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
- plan: WorkspacePlan;
-}
-
-export function SectionOpsGenie({ form }: Props) {
- const [isTestPending, startTestTransition] = useTransition();
- const watchApiKey = form.watch("data.opsgenie.apiKey");
- const watchRegion = form.watch("data.opsgenie.region");
-
- async function sendTestAlert() {
- if (!watchApiKey || !watchRegion) return;
- startTestTransition(async () => {
- const isSuccessfull = await sendOpsGenieTestAlert(
- watchApiKey,
- watchRegion,
- );
- if (isSuccessfull) {
- toastAction("test-success");
- } else {
- toastAction("test-error");
- }
- });
- }
-
- return (
- <>
- <FormField
- control={form.control}
- name="data.opsgenie.apiKey"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>API Key</FormLabel>
- <FormControl>
- <Input placeholder={"xxx-yyy-zzz"} {...field} />
- </FormControl>
- <FormDescription className="flex items-center justify-between">
- The API key is required.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="data.opsgenie.region"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Region</FormLabel>
- <FormControl>
- <Select onValueChange={field.onChange} defaultValue={field.value}>
- <FormControl>
- <SelectTrigger>
- <SelectValue placeholder="Select a region" />
- </SelectTrigger>
- </FormControl>
- <SelectContent>
- <SelectItem value="us">US</SelectItem>
- <SelectItem value="eu">EU</SelectItem>
- </SelectContent>
- </Select>
- </FormControl>
- <FormDescription className="flex items-center justify-between">
- The region is required.
- <a
- href="https://docs.openstatus.dev/synthetic/features/notification/opsgenie"
- target="_blank"
- className="underline hover:no-underline"
- rel="noreferrer"
- >
- How to setup your OpsGenie.
- </a>
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="col-span-full text-right">
- <Button
- type="button"
- variant="secondary"
- className="w-full sm:w-auto"
- disabled={isTestPending || !watchApiKey || !watchRegion}
- onClick={sendTestAlert}
- >
- {!isTestPending ? (
- "Test Alert"
- ) : (
- <LoadingAnimation variant="inverse" />
- )}
- </Button>
- </div>
- </>
- );
-}
diff --git a/apps/web/src/components/forms/notification/provider/section-pagerduty.tsx b/apps/web/src/components/forms/notification/provider/section-pagerduty.tsx
deleted file mode 100644
index 8dc39033d..000000000
--- a/apps/web/src/components/forms/notification/provider/section-pagerduty.tsx
+++ /dev/null
@@ -1,65 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import type {
- InsertNotificationWithData,
- WorkspacePlan,
-} from "@openstatus/db/src/schema";
-import { PagerDutySchema } from "@openstatus/notification-pagerduty";
-import { Button } from "@openstatus/ui";
-import { useSearchParams } from "next/navigation";
-import { useTransition } from "react";
-import { sendPagerDutyTestAlert } from "./actions";
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
- plan: WorkspacePlan;
-}
-
-export function SectionPagerDuty({ form }: Props) {
- const [isTestPending, startTestTransition] = useTransition();
- const searchParams = useSearchParams();
-
- const config = searchParams.get("config") || form.getValues("data.pagerduty");
-
- const result = PagerDutySchema.safeParse(JSON.parse(config || ""));
-
- if (result.success === false) {
- return null;
- }
-
- const data = result.data;
-
- if (config) {
- form.setValue("data.pagerduty", config);
- }
-
- async function sendTestAlert() {
- startTestTransition(async () => {
- const isSuccessfull = await sendPagerDutyTestAlert(
- data.integration_keys[0].integration_key,
- );
- if (isSuccessfull) {
- toastAction("test-success");
- } else {
- toastAction("test-error");
- }
- });
- }
-
- return (
- <div className="col-span-full text-right">
- <Button
- type="button"
- variant="secondary"
- className="w-full sm:w-auto"
- onClick={sendTestAlert}
- >
- {!isTestPending ? "Test Alert" : <LoadingAnimation variant="inverse" />}
- </Button>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/notification/provider/section-slack.tsx b/apps/web/src/components/forms/notification/provider/section-slack.tsx
deleted file mode 100644
index af2dba438..000000000
--- a/apps/web/src/components/forms/notification/provider/section-slack.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-"use client";
-
-import { useTransition } from "react";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertNotificationWithData } from "@openstatus/db/src/schema";
-import {
- Button,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { sendTestSlackMessage } from "@openstatus/notification-slack";
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
-}
-
-export function SectionSlack({ form }: Props) {
- const [isTestPending, startTestTransition] = useTransition();
- const watchUrl = form.watch("data.slack");
-
- async function sendTestWebhookPing() {
- if (!watchUrl) return;
- startTestTransition(async () => {
- const isSuccessfull = await sendTestSlackMessage(watchUrl);
- if (isSuccessfull) {
- toastAction("test-success");
- } else {
- toastAction("test-error");
- }
- });
- }
-
- return (
- <>
- <FormField
- control={form.control}
- name="data.slack"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Webhook URL</FormLabel>
- <FormControl>
- <Input
- type="url"
- placeholder="https://hooks.slack.com/services/xxx..."
- required
- {...field}
- />
- </FormControl>
- <FormDescription className="flex items-center justify-between">
- The data is required.
- <a
- href={
- "https://api.slack.com/messaging/webhooks#getting_started"
- }
- target="_blank"
- className="underline hover:no-underline"
- rel="noreferrer"
- >
- How to setup your Slack webhook
- </a>
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="col-span-full text-right">
- <Button
- type="button"
- variant="secondary"
- className="w-full sm:w-auto"
- disabled={isTestPending || !watchUrl}
- onClick={sendTestWebhookPing}
- >
- {!isTestPending ? (
- "Test Webhook"
- ) : (
- <LoadingAnimation variant="inverse" />
- )}
- </Button>
- </div>
- </>
- );
-}
diff --git a/apps/web/src/components/forms/notification/provider/section-sms.tsx b/apps/web/src/components/forms/notification/provider/section-sms.tsx
deleted file mode 100644
index b0c63f8f5..000000000
--- a/apps/web/src/components/forms/notification/provider/section-sms.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertNotificationWithData } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
-}
-
-export function SectionSms({ form }: Props) {
- return (
- <FormField
- control={form.control}
- name="data.sms"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Phone Number</FormLabel>
- <FormControl>
- <Input type="tel" placeholder="+1234567890" required {...field} />
- </FormControl>
- <FormDescription className="flex items-center justify-between">
- The phone number is required.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- );
-}
diff --git a/apps/web/src/components/forms/notification/provider/section-webhook.tsx b/apps/web/src/components/forms/notification/provider/section-webhook.tsx
deleted file mode 100644
index af963ad59..000000000
--- a/apps/web/src/components/forms/notification/provider/section-webhook.tsx
+++ /dev/null
@@ -1,137 +0,0 @@
-"use client";
-
-import { toastAction } from "@/lib/toast";
-import { type UseFormReturn, useFieldArray } from "react-hook-form";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import type { InsertNotificationWithData } from "@openstatus/db/src/schema";
-import {
- Button,
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-import { X } from "lucide-react";
-import { useTransition } from "react";
-import { sendWebhookTestAlert } from "./actions";
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
-}
-
-export function SectionWebhook({ form }: Props) {
- const [isTestPending, startTestTransition] = useTransition();
-
- const { fields, append, remove } = useFieldArray({
- name: "data.webhook.headers",
- control: form.control,
- });
-
- const watchUrl = form.watch("data.webhook.endpoint");
- const watchHeaders = form.watch("data.webhook.headers");
-
- async function sendTestAlert() {
- if (!watchUrl) return;
- startTestTransition(async () => {
- const isSuccessful = await sendWebhookTestAlert({
- url: watchUrl,
- headers: watchHeaders,
- });
- if (isSuccessful) {
- toastAction("test-success");
- } else {
- toastAction("test-error");
- }
- });
- }
-
- return (
- <>
- <FormField
- control={form.control}
- name="data.webhook.endpoint"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>URL</FormLabel>
- <FormControl>
- <Input
- type="url"
- placeholder="https://your-webhook-url"
- {...field}
- />
- </FormControl>
- <FormMessage />
- </FormItem>
- )}
- />
-
- <div className="space-y-2 sm:col-span-full">
- <FormLabel>Request Header</FormLabel>
- {fields.map((field, index) => (
- <div key={field.id} className="grid grid-cols-6 gap-4">
- <FormField
- control={form.control}
- name={`data.webhook.headers.${index}.key`}
- render={({ field }) => (
- <FormItem className="col-span-2">
- <FormControl>
- <Input placeholder="key" {...field} />
- </FormControl>
- </FormItem>
- )}
- />
- <div className="col-span-4 flex items-center space-x-2">
- <FormField
- control={form.control}
- name={`data.webhook.headers.${index}.value`}
- render={({ field }) => (
- <FormItem className="w-full">
- <FormControl>
- <Input placeholder="value" {...field} />
- </FormControl>
- </FormItem>
- )}
- />
- <Button
- size="icon"
- variant="ghost"
- type="button"
- onClick={() => remove(index)}
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
- </div>
- ))}
- <div>
- <Button
- type="button"
- variant="outline"
- onClick={() => append({ key: "", value: "" })}
- >
- Add Custom Header
- </Button>
- </div>
- </div>
-
- <div className="col-span-full text-right">
- <Button
- type="button"
- variant="secondary"
- className="w-full sm:w-auto"
- disabled={isTestPending}
- onClick={sendTestAlert}
- >
- {!isTestPending ? (
- "Test Webhook"
- ) : (
- <LoadingAnimation variant="inverse" />
- )}
- </Button>
- </div>
- </>
- );
-}
diff --git a/apps/web/src/components/forms/notification/section-connect.tsx b/apps/web/src/components/forms/notification/section-connect.tsx
deleted file mode 100644
index d870e0303..000000000
--- a/apps/web/src/components/forms/notification/section-connect.tsx
+++ /dev/null
@@ -1,89 +0,0 @@
-"use client";
-import type { UseFormReturn } from "react-hook-form";
-
-import type {
- InsertNotificationWithData,
- Monitor,
-} from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@openstatus/ui";
-
-import { CheckboxLabel } from "../shared/checkbox-label";
-
-interface Props {
- form: UseFormReturn<InsertNotificationWithData>;
- monitors?: Monitor[];
-}
-
-export function SectionConnect({ form, monitors }: Props) {
- return (
- <div className="grid w-full gap-4">
- <div className="flex flex-col gap-3">
- <FormField
- control={form.control}
- name="monitors"
- render={() => (
- <FormItem>
- <div className="mb-4">
- <FormLabel>Monitors</FormLabel>
- <FormDescription>
- Attach the notification to specific monitors.
- </FormDescription>
- </div>
- <div className="grid grid-cols-1 grid-rows-1 gap-6 sm:grid-cols-2 md:grid-cols-3">
- {monitors?.map((item) => (
- <FormField
- key={item.id}
- control={form.control}
- name="monitors"
- render={({ field }) => {
- return (
- <FormItem key={item.id} className="h-full w-full">
- <FormControl className="w-full">
- <CheckboxLabel
- id={String(item.id)}
- name="monitor"
- checked={field.value?.includes(item.id)}
- onCheckedChange={(checked) => {
- return checked
- ? field.onChange([
- ...(field.value || []),
- item.id,
- ])
- : field.onChange(
- field.value?.filter(
- (value) => value !== item.id,
- ),
- );
- }}
- className="flex-col items-start truncate"
- >
- <span>{item.name}</span>
- <span className="font-normal text-muted-foreground text-sm">
- {item.url}
- </span>
- </CheckboxLabel>
- </FormControl>
- </FormItem>
- );
- }}
- />
- ))}
- </div>
- {!monitors || monitors.length === 0 ? (
- <FormDescription>Missing monitors.</FormDescription>
- ) : null}
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/skeleton-form.tsx b/apps/web/src/components/forms/skeleton-form.tsx
deleted file mode 100644
index f68f8265d..000000000
--- a/apps/web/src/components/forms/skeleton-form.tsx
+++ /dev/null
@@ -1,35 +0,0 @@
-import { Skeleton } from "@openstatus/ui";
-
-export function SkeletonForm() {
- return (
- <div className="grid w-full gap-6">
- <div className="col-span-full grid gap-4 sm:grid-cols-3">
- <div className="flex flex-col gap-2">
- <Skeleton className="h-6 w-24" />
- <Skeleton className="h-6 w-40" />
- </div>
- <div className="grid w-full gap-6 sm:col-span-2">
- <div className="space-y-2">
- <Skeleton className="h-6 w-24" />
- <Skeleton className="h-9 w-full" />
- <Skeleton className="h-5 w-64" />
- </div>
- <div className="space-y-2">
- <Skeleton className="h-6 w-24" />
- <Skeleton className="h-9 w-full" />
- <Skeleton className="h-5 w-64" />
- </div>
- <div className="space-y-2">
- <Skeleton className="h-6 w-24" />
- <Skeleton className="h-9 w-full" />
- <Skeleton className="h-5 w-64" />
- </div>
- </div>
- </div>
- <Skeleton className="h-9 w-full" />
- <div className="flex space-y-2 sm:col-span-full sm:justify-end">
- <Skeleton className="h-9 w-full sm:w-28" />
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/status-page/form.tsx b/apps/web/src/components/forms/status-page/form.tsx
deleted file mode 100644
index 99255fa2e..000000000
--- a/apps/web/src/components/forms/status-page/form.tsx
+++ /dev/null
@@ -1,213 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { usePathname, useRouter } from "next/navigation";
-import { useCallback, useEffect, useTransition } from "react";
-import { useForm } from "react-hook-form";
-
-import { insertPageSchema } from "@openstatus/db/src/schema";
-import type {
- InsertPage,
- Monitor,
- WorkspacePlan,
-} from "@openstatus/db/src/schema";
-import { Badge, Form } from "@openstatus/ui";
-
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@/components/dashboard/tabs";
-import { useDebounce } from "@/hooks/use-debounce";
-import { toast, toastAction } from "@/lib/toast";
-import { slugify } from "@/lib/utils";
-import { api } from "@/trpc/client";
-import { SaveButton } from "../shared/save-button";
-import { General } from "./general";
-import { SectionAdvanced } from "./section-advanced";
-import { SectionDanger } from "./section-danger";
-import { SectionMonitor } from "./section-monitor";
-import { SectionVisibility } from "./section-visibility";
-
-interface Props {
- defaultSection?: string;
- defaultValues?: Omit<InsertPage, "configuration">;
- allMonitors?: Monitor[];
- /**
- * gives the possibility to check all the monitors
- */
- checkAllMonitors?: boolean;
- /**
- * on submit, allows to push a url
- */
- nextUrl?: string;
- plan: WorkspacePlan;
- workspaceSlug: string;
-}
-
-export function StatusPageForm({
- defaultSection,
- defaultValues,
- allMonitors,
- checkAllMonitors,
- nextUrl,
- plan,
- workspaceSlug,
-}: Props) {
- const form = useForm<Omit<InsertPage, "configuration">>({
- resolver: zodResolver(insertPageSchema),
- defaultValues: {
- title: defaultValues?.title || "", // FIXME: you can save a page without title, causing unexpected slug behavior
- slug: defaultValues?.slug || "",
- description: defaultValues?.description || "",
- workspaceId: defaultValues?.workspaceId || 0,
- id: defaultValues?.id || 0,
- customDomain: defaultValues?.customDomain || "",
- icon: defaultValues?.icon || "",
- password: defaultValues?.password || "",
- passwordProtected: defaultValues?.passwordProtected || false,
- showMonitorValues: defaultValues?.showMonitorValues || true,
- monitors:
- checkAllMonitors && allMonitors
- ? allMonitors.map(({ id }) => ({ monitorId: id, order: 0 }))
- : defaultValues?.monitors ?? [],
- },
- });
- const pathname = usePathname();
- const router = useRouter();
- const [isPending, startTransition] = useTransition();
- const watchSlug = form.watch("slug");
- const watchTitle = form.watch("title");
- const debouncedSlug = useDebounce(watchSlug, 1000); // using debounce to not exhaust the server
-
- const checkUniqueSlug = useCallback(async () => {
- const isUnique = await api.page.getSlugUniqueness.query({
- slug: debouncedSlug,
- });
- return (
- isUnique ||
- debouncedSlug.toLowerCase() === defaultValues?.slug.toLowerCase()
- );
- }, [debouncedSlug, defaultValues?.slug]);
-
- useEffect(() => {
- async function watchSlugChanges() {
- const isUnique = await checkUniqueSlug();
- if (!isUnique) {
- form.setError("slug", {
- message: "Already taken. Please select another slug.",
- });
- } else {
- form.clearErrors("slug");
- }
- }
-
- void watchSlugChanges();
- // eslint-disable-next-line react-hooks/exhaustive-deps
- }, [checkUniqueSlug, form.clearErrors, form.setError]);
-
- useEffect(() => {
- if (!defaultValues?.title) {
- form.setValue("slug", slugify(watchTitle));
- }
- }, [watchTitle, form, defaultValues?.title]);
-
- const onSubmit = async ({ ...props }: InsertPage) => {
- startTransition(async () => {
- try {
- const isUnique = await checkUniqueSlug();
- if (!isUnique) {
- // the user will already have the "error" message - we include a toast as well
- toastAction("unique-slug");
- } else {
- if (defaultValues) {
- await api.page.update.mutate(props);
- } else {
- await api.page.create.mutate(props);
- }
-
- toast.success("Saved successfully.", {
- description: "Your status page is ready to go.",
- action: {
- label: "Visit",
- onClick: () =>
- window.open(`https://${props.slug}.openstatus.dev`, "_blank")
- ?.location,
- },
- });
- // otherwise, the form will stay dirty - keepValues is used to keep the current values in the form
- form.reset({}, { keepValues: true });
- if (nextUrl) {
- router.push(nextUrl);
- }
- router.refresh();
- }
- } catch {
- toastAction("error");
- }
- });
- };
-
- function onValueChange(value: string) {
- // REMINDER: we are not merging the searchParams here
- // we are just setting the section to allow refreshing the page
- const params = new URLSearchParams();
- params.set("section", value);
- router.push(`${pathname}?${params.toString()}`);
- }
-
- return (
- <Form {...form}>
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- void form.handleSubmit(onSubmit)(e);
- }}
- className="grid w-full gap-6"
- >
- <General form={form} />
- <Tabs
- defaultValue={defaultSection}
- className="w-full"
- onValueChange={onValueChange}
- >
- <TabsList>
- <TabsTrigger value="monitors">
- Monitors{" "}
- {defaultValues?.monitors?.length ? (
- <Badge variant="secondary" className="ml-1">
- {defaultValues.monitors.length}
- </Badge>
- ) : null}
- </TabsTrigger>
- <TabsTrigger value="advanced">Advanced</TabsTrigger>
- <TabsTrigger value="visibility">Visibility</TabsTrigger>
- {defaultValues?.id ? (
- <TabsTrigger value="danger">Danger</TabsTrigger>
- ) : null}
- </TabsList>
- <TabsContent value="monitors">
- <SectionMonitor form={form} monitors={allMonitors} />
- </TabsContent>
- <TabsContent value="advanced">
- <SectionAdvanced {...{ form }} />
- </TabsContent>
- <TabsContent value="visibility">
- <SectionVisibility {...{ form, plan, workspaceSlug }} />
- </TabsContent>
- {defaultValues?.id ? (
- <TabsContent value="danger">
- <SectionDanger pageId={defaultValues.id} />
- </TabsContent>
- ) : null}
- </Tabs>
- <SaveButton
- isPending={isPending}
- isDirty={form.formState.isDirty}
- onSubmit={form.handleSubmit(onSubmit)}
- />
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/forms/status-page/general.tsx b/apps/web/src/components/forms/status-page/general.tsx
deleted file mode 100644
index e8b567774..000000000
--- a/apps/web/src/components/forms/status-page/general.tsx
+++ /dev/null
@@ -1,67 +0,0 @@
-"use client";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertPage } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
- InputWithAddons,
-} from "@openstatus/ui";
-
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- form: UseFormReturn<InsertPage>;
-}
-
-export function General({ form }: Props) {
- return (
- <div className="grid gap-4 sm:grid-cols-3 sm:gap-6">
- <SectionHeader
- title="Basic information"
- description="The public status page to update your users on service uptime."
- />
- <div className="grid gap-4 sm:col-span-2">
- <FormField
- control={form.control}
- name="title"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Title</FormLabel>
- <FormControl>
- <Input placeholder="Documenso Status" {...field} />
- </FormControl>
- <FormDescription>The title of your page.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="slug"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Slug</FormLabel>
- <FormControl>
- <InputWithAddons
- placeholder="documenso"
- trailing={".openstatus.dev"}
- {...field}
- />
- </FormControl>
- <FormDescription>
- The subdomain for your status page. At least 3 chars.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/status-page/section-advanced.tsx b/apps/web/src/components/forms/status-page/section-advanced.tsx
deleted file mode 100644
index 48920fb70..000000000
--- a/apps/web/src/components/forms/status-page/section-advanced.tsx
+++ /dev/null
@@ -1,238 +0,0 @@
-"use client";
-
-import type { PutBlobResult } from "@vercel/blob";
-import Image from "next/image";
-import * as React from "react";
-import { useRef } from "react";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertPage } from "@openstatus/db/src/schema";
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- Button,
- Checkbox,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { BarDescription } from "@/components/tracker/tracker";
-import { MousePointer2 } from "lucide-react";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- form: UseFormReturn<InsertPage>;
-}
-
-export function SectionAdvanced({ form }: Props) {
- const inputFileRef = useRef<HTMLInputElement>(null);
- const [open, setOpen] = React.useState(false);
- const [file, setFile] = React.useState<File | null>(null);
-
- /**
- * Determine the width and height of the uploaded image - it ideally is a square
- */
- const getFileDimensions = async (file: File) => {
- const img = document.createElement("img");
- img.src = URL.createObjectURL(file);
- await img.decode();
- return { width: img.naturalWidth, height: img.naturalHeight };
- };
-
- const handleChange = async (file: FileList | null) => {
- if (!file || file.length === 0) {
- return;
- }
-
- const { height, width } = await getFileDimensions(file[0]);
-
- // remove rounding issues from transformations
- if (!(Math.abs(height - width) <= 1)) {
- setOpen(true);
- setFile(file[0]);
- return;
- }
-
- const newblob = await handleUpload(file[0]);
- form.setValue("icon", newblob.url);
- };
-
- const handleUpload = async (file: File) => {
- const response = await fetch(`/api/upload?filename=${file.name}`, {
- method: "POST",
- body: file,
- });
-
- const newblob = (await response.json()) as PutBlobResult;
- return newblob;
- };
-
- const handleCancel = () => {
- // biome-ignore lint/suspicious/noAssignInExpressions: <explanation>
- inputFileRef.current?.value && (inputFileRef.current.value = "");
- };
-
- const handleConfirm = async () => {
- if (file) {
- const newblob = await handleUpload(file);
- form.setValue("icon", newblob.url);
- setFile(null);
- }
- setOpen(false);
- };
-
- return (
- <div className="grid w-full gap-4 md:grid-cols-3">
- <SectionHeader
- title="Advanced Settings"
- description="Provide informations about what your status page is for. A favicon can be uploaded to customize your status page. It will be used as an icon on the header as well."
- className="md:col-span-full"
- />
- <FormField
- control={form.control}
- name="description"
- render={({ field }) => (
- <FormItem className="md:col-span-full">
- <FormLabel>Description</FormLabel>
- <FormControl>
- <Input
- placeholder="Stay informed about our api and website health."
- {...field}
- />
- </FormControl>
- <FormDescription>
- Provide your users informations about it.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="icon"
- render={({ field }) => (
- <FormItem className="col-span-full md:col-span-1">
- <FormLabel>Favicon</FormLabel>
- <FormControl>
- <>
- {!field.value && (
- <Input
- type="file"
- accept="image/x-icon,image/png"
- ref={inputFileRef}
- onChange={(e) => handleChange(e.target.files)}
- />
- )}
- {field.value && (
- <div className="flex items-center">
- <div className="h-10 w-10 rounded-sm border border-border p-1">
- <Image
- src={field.value}
- width={64}
- height={64}
- alt="Favicon"
- />
- </div>
- <Button
- variant="link"
- onClick={() => {
- form.setValue("icon", "");
- }}
- >
- Remove
- </Button>
- </div>
- )}
- </>
- </FormControl>
- <FormDescription>Your status page favicon</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="grid w-full gap-4 md:col-span-full md:grid-cols-3 md:grid-rows-2">
- <SectionHeader
- title="Monitor Values Visibility"
- description={
- <>
- Toggle the visibility of the values on the status page. Share your{" "}
- <span className="font-medium text-foreground">uptime</span> and
- the{" "}
- <span className="font-medium text-foreground">
- number of request
- </span>{" "}
- to your endpoint.
- </>
- }
- className="md:col-span-2"
- />
- <div className="group flex flex-col justify-center gap-1 rounded-md border border-dashed p-3 md:row-span-2">
- <div className="flex flex-row items-center justify-center gap-2 text-muted-foreground group-hover:text-foreground">
- <MousePointer2 className="h-3 w-3" />
- <p className="text-sm">Hover State</p>
- </div>
- <div className="mx-auto max-w-60">
- <BarDescription
- label="Operational"
- day={new Date().toISOString()}
- count={5600}
- ok={5569}
- showValues={!!form.getValues("showMonitorValues")}
- barClassName="bg-status-operational"
- className="rounded-md border bg-popover p-2 text-popover-foreground shadow-md md:col-span-1"
- />
- </div>
- </div>
- <FormField
- control={form.control}
- name="showMonitorValues"
- render={({ field }) => (
- <FormItem className="flex flex-row items-start space-x-3 space-y-0 md:col-span-2">
- <FormControl>
- <Checkbox
- disabled={field.disabled}
- checked={field.value ?? false}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- <div className="space-y-1 leading-none">
- <FormLabel>Show values</FormLabel>
- <FormDescription>
- Share the numbers to your users.
- </FormDescription>
- </div>
- </FormItem>
- )}
- />
- </div>
- <AlertDialog open={open} onOpenChange={(value) => setOpen(value)}>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Incorrect image size</AlertDialogTitle>
- <AlertDialogDescription>
- For the best result, the image should be a square. You can still
- upload it, but it will be cropped.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel onClick={handleCancel}>Cancel</AlertDialogCancel>
- <AlertDialogAction onClick={handleConfirm}>
- Continue
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/status-page/section-danger.tsx b/apps/web/src/components/forms/status-page/section-danger.tsx
deleted file mode 100644
index 3762faeac..000000000
--- a/apps/web/src/components/forms/status-page/section-danger.tsx
+++ /dev/null
@@ -1,92 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
- Button,
- FormDescription,
-} from "@openstatus/ui";
-
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-import React from "react";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- pageId: number;
-}
-
-export function SectionDanger({ pageId }: Props) {
- const router = useRouter();
- const [open, setOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- await api.page.delete.mutate({ id: pageId });
- toastAction("deleted");
- setOpen(false);
- router.push("../");
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <div className="grid w-full gap-4">
- <SectionHeader
- title="Danger Zone"
- description="Be aware of the changes you are about to make."
- />
- <div className="grid gap-4 sm:grid-cols-3">
- <div className="col-start-1 flex flex-col items-center gap-4 sm:col-span-2 sm:flex-row">
- <AlertDialog open={open} onOpenChange={setOpen}>
- <AlertDialogTrigger asChild>
- <Button variant="destructive" className="w-full sm:w-auto">
- Delete
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- status page.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- <FormDescription className="order-1 text-red-500 sm:order-2">
- This action cannot be undone. This will permanently delete the
- status page.
- </FormDescription>
- </div>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/status-page/section-monitor.tsx b/apps/web/src/components/forms/status-page/section-monitor.tsx
deleted file mode 100644
index 2efaa0b28..000000000
--- a/apps/web/src/components/forms/status-page/section-monitor.tsx
+++ /dev/null
@@ -1,161 +0,0 @@
-"use client";
-
-import { CheckIcon, ChevronsUpDown, GripVertical } from "lucide-react";
-import { useState } from "react";
-import type { UseFormReturn } from "react-hook-form";
-import { useFieldArray } from "react-hook-form";
-
-import type { InsertPage, Monitor } from "@openstatus/db/src/schema";
-import {
- Button,
- Command,
- CommandEmpty,
- CommandGroup,
- CommandInput,
- CommandItem,
- CommandList,
- Popover,
- PopoverContent,
- PopoverTrigger,
- Sortable,
- SortableDragHandle,
- SortableItem,
-} from "@openstatus/ui";
-
-import { StatusDot } from "@/components/monitor/status-dot";
-import { cn } from "@/lib/utils";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- monitors?: Monitor[];
- form: UseFormReturn<InsertPage>;
-}
-
-export function SectionMonitor({ form, monitors }: Props) {
- const [open, setOpen] = useState(false);
- const { fields, append, move, remove } = useFieldArray({
- control: form.control,
- name: "monitors",
- });
- const watchMonitors = form.watch("monitors");
-
- return (
- <div className="grid w-full gap-4">
- <SectionHeader
- title="Connected Monitors"
- description="Select the monitors you want to display on your status page. Change the order by using the right-side handle. Inactive monitors will not be shown."
- />
- <Popover open={open} onOpenChange={setOpen}>
- <PopoverTrigger asChild>
- <Button
- variant="outline"
- role="combobox"
- aria-expanded={open}
- className="w-[240px] justify-between"
- >
- {watchMonitors.length > 0
- ? `${watchMonitors.length} monitor${
- watchMonitors.length > 1 ? "s" : ""
- } selected`
- : "Select monitors..."}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </PopoverTrigger>
- <PopoverContent side="bottom" className="w-[240px] p-0">
- <Command>
- <CommandInput placeholder="Select monitors..." className="h-9" />
- <CommandList>
- <CommandEmpty>No monitors found.</CommandEmpty>
- <CommandGroup>
- {monitors?.map((monitor) => (
- <CommandItem
- key={monitor.id}
- value={`${monitor.name}-${String(monitor.id)}`}
- keywords={[monitor.name]}
- onSelect={(currentValue) => {
- const splitValue = currentValue.split("-");
- const id = splitValue?.[splitValue.length - 1];
- const monitorIndex = watchMonitors.findIndex(
- (m) => m.monitorId === Number.parseInt(id),
- );
- if (monitorIndex !== -1) {
- remove(monitorIndex);
- } else {
- append({
- monitorId: monitor.id,
- order: fields.length + 1,
- });
- }
- }}
- >
- <div className="truncate">
- <p>{monitor.name}</p>
- {/* <p className="text-muted-foreground truncate text-xs">
- {monitor.url}
- </p> */}
- </div>
- <CheckIcon
- className={cn(
- "ml-auto h-4 w-4 shrink-0",
- watchMonitors.some((m) => m.monitorId === monitor.id)
- ? "opacity-100"
- : "opacity-0",
- )}
- />
- </CommandItem>
- ))}
- </CommandGroup>
- </CommandList>
- </Command>
- </PopoverContent>
- </Popover>
- <div className="h-full w-full">
- {/* FIXME: if we wanna use `overlay` we need to fix the scrollable/position-fixed issues */}
- <Sortable
- value={fields}
- onMove={({ activeIndex, overIndex }) => move(activeIndex, overIndex)}
- // overlay={
- // <div className="grid grid-cols-[0.5fr_1fr_auto] items-center gap-2">
- // <Skeleton className="h-8 w-full rounded-sm" />
- // <Skeleton className="h-8 w-full rounded-sm" />
- // <Skeleton className="size-8 shrink-0 rounded-sm" />
- // </div>
- // }
- >
- <div className="w-full space-y-2">
- {fields.map((field) => {
- const monitor = monitors?.find(
- ({ id }) => field.monitorId === id,
- );
- if (!monitor) return null;
- return (
- <SortableItem key={field.id} value={field.id} asChild>
- <div className="grid grid-cols-[0.5fr_1fr_auto] items-center gap-2">
- <div className="flex items-center gap-2 truncate">
- <StatusDot
- active={monitor.active}
- status={monitor.status}
- />{" "}
- <span className="truncate">{monitor.name}</span>
- </div>
- <div className="truncate text-muted-foreground">
- {monitor?.url}
- </div>
- <SortableDragHandle
- variant="outline"
- size="icon"
- className="size-8 shrink-0"
- type="button"
- >
- <GripVertical className="size-4" aria-hidden="true" />
- </SortableDragHandle>
- </div>
- </SortableItem>
- );
- })}
- </div>
- </Sortable>
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/status-page/section-visibility.tsx b/apps/web/src/components/forms/status-page/section-visibility.tsx
deleted file mode 100644
index 1e781186e..000000000
--- a/apps/web/src/components/forms/status-page/section-visibility.tsx
+++ /dev/null
@@ -1,131 +0,0 @@
-"use client";
-
-import { X } from "lucide-react";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertPage, WorkspacePlan } from "@openstatus/db/src/schema";
-import {
- Button,
- Checkbox,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { getBaseUrl } from "@/app/status-page/[domain]/utils";
-import { ProFeatureHoverCard } from "@/components/billing/pro-feature-hover-card";
-import { CopyToClipboardButton } from "@/components/dashboard/copy-to-clipboard-button";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- form: UseFormReturn<InsertPage>;
- plan: WorkspacePlan;
- workspaceSlug: string;
-}
-
-export function SectionVisibility({ form, plan, workspaceSlug }: Props) {
- const watchPasswordProtected = form.watch("passwordProtected");
- const watchPassword = form.watch("password");
-
- const baseUrl = getBaseUrl({
- slug: form.getValues("slug"),
- customDomain: form.getValues("customDomain"),
- });
- const link = `${baseUrl}?authorize=${watchPassword}`;
-
- const hasFreePlan = plan === "free";
-
- return (
- <div className="grid w-full gap-4 md:grid-cols-2">
- <SectionHeader
- title="Visibility"
- description="Hide your page from the public by setting a password."
- className="md:col-span-full"
- />
- <ProFeatureHoverCard
- workspaceSlug={workspaceSlug}
- plan={plan}
- minRequiredPlan="starter"
- >
- <div className="grid w-full gap-4 md:col-span-full md:grid-cols-2">
- <FormField
- control={form.control}
- name="passwordProtected"
- disabled={hasFreePlan}
- render={({ field }) => (
- <FormItem className="flex flex-row items-start space-x-3 space-y-0 md:col-span-full">
- <FormControl>
- <Checkbox
- disabled={field.disabled}
- checked={field.value ?? false}
- onCheckedChange={field.onChange}
- />
- </FormControl>
- <div className="space-y-1 leading-none">
- <FormLabel>Protect with password</FormLabel>
- <FormDescription>
- Hide the page from the public
- </FormDescription>
- </div>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="password"
- disabled={hasFreePlan}
- render={({ field }) => (
- <FormItem className="md:col-span-1">
- <FormLabel>Password</FormLabel>
- <div className="flex items-center gap-2">
- <FormControl>
- <Input
- {...field}
- placeholder="top-secret"
- disabled={!watchPasswordProtected}
- value={field.value ?? ""} // REMINDER: remove nullish coalescing from db schema
- />
- </FormControl>
- <Button
- size="icon"
- variant="ghost"
- type="button"
- onClick={() => form.setValue("password", "")}
- disabled={!field.value || !watchPasswordProtected}
- >
- <X className="h-4 w-4" />
- </Button>
- </div>
- <FormDescription>
- No restriction on the password. It&apos;s just a simple
- password you define.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- {watchPasswordProtected ? (
- <div className="text-sm md:col-span-full">
- <p className="text-muted-foreground">
- If you want to share the page without the need to enter the
- password, you can share the following link:
- </p>
- <div className="flex flex-wrap items-center gap-2">
- <p className="text-foreground">{link} </p>
- {/* TODO: think of building a better shadcn like "CopyToClipboardButton" */}
- <CopyToClipboardButton
- text={link}
- tooltipText="Copy to clipboard"
- />
- </div>
- </div>
- ) : null}
- </div>
- </ProFeatureHoverCard>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/status-report-form.tsx b/apps/web/src/components/forms/status-report-form.tsx
deleted file mode 100644
index c7ab0a185..000000000
--- a/apps/web/src/components/forms/status-report-form.tsx
+++ /dev/null
@@ -1,346 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-import { useForm } from "react-hook-form";
-
-import {
- insertStatusReportSchema,
- statusReportStatus,
- statusReportStatusSchema,
-} from "@openstatus/db/src/schema";
-import type { InsertStatusReport, Monitor } from "@openstatus/db/src/schema";
-import {
- Accordion,
- AccordionContent,
- AccordionItem,
- AccordionTrigger,
- Button,
- Checkbox,
- DateTimePickerPopover,
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
- RadioGroup,
- RadioGroupItem,
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
- Textarea,
-} from "@openstatus/ui";
-
-import { Preview } from "@/components/content/preview";
-import { Icons } from "@/components/icons";
-import { LoadingAnimation } from "@/components/loading-animation";
-import { statusDict } from "@/data/incidents-dictionary";
-import { toastAction } from "@/lib/toast";
-import { cn } from "@/lib/utils";
-import { api } from "@/trpc/client";
-
-interface Props {
- defaultValues?: InsertStatusReport;
- monitors?: Monitor[];
- nextUrl?: string;
- pageId: number;
-}
-
-export function StatusReportForm({
- defaultValues,
- monitors,
- nextUrl,
- pageId,
-}: Props) {
- const form = useForm<InsertStatusReport>({
- resolver: zodResolver(insertStatusReportSchema),
- defaultValues: defaultValues
- ? {
- id: defaultValues.id,
- title: defaultValues.title,
- status: defaultValues.status,
- monitors: defaultValues.monitors,
- // include update on creation
- message: defaultValues.message,
- date: defaultValues.date,
- }
- : {
- status: "investigating",
- date: new Date(),
- },
- });
- const router = useRouter();
- const [isPending, startTransition] = React.useTransition();
-
- const onSubmit = ({ ...props }: InsertStatusReport) => {
- startTransition(async () => {
- try {
- if (defaultValues) {
- await api.statusReport.updateStatusReport.mutate({
- pageId,
- ...props,
- });
- } else {
- const { message, date, status, ...rest } = props;
- const statusReport = await api.statusReport.createStatusReport.mutate(
- {
- status,
- message,
- pageId,
- ...rest,
- },
- );
- // include update on creation
- if (statusReport?.id) {
- await api.statusReport.createStatusReportUpdate.mutate({
- message,
- date,
- status,
- statusReportId: statusReport.id,
- });
- }
- }
- if (nextUrl) {
- router.push(nextUrl);
- }
- router.refresh();
- toastAction("saved");
- } catch {
- toastAction("error");
- }
- });
- };
-
- return (
- <Form {...form}>
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- form.handleSubmit(onSubmit)(e);
- }}
- className="grid w-full gap-6"
- >
- <div className="grid gap-4 sm:grid-cols-3">
- <div className="my-1.5 flex flex-col gap-2">
- <p className="font-semibold text-sm leading-none">Inform</p>
- <p className="text-muted-foreground text-sm">
- Keep your users informed about what just happened.
- </p>
- </div>
- <div className="grid gap-6 sm:col-span-2 sm:grid-cols-3">
- <FormField
- control={form.control}
- name="title"
- render={({ field }) => (
- <FormItem className="sm:col-span-4">
- <FormLabel>Title</FormLabel>
- <FormControl>
- <Input placeholder="Downtime..." {...field} />
- </FormControl>
- <FormDescription>The title of your outage.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="status"
- render={({ field }) => (
- <FormItem className="col-span-full space-y-1">
- <FormLabel>Status</FormLabel>
- <FormDescription>Select the current status.</FormDescription>
- <FormMessage />
- <RadioGroup
- onValueChange={(value) =>
- field.onChange(statusReportStatusSchema.parse(value))
- } // value is a string
- defaultValue={field.value}
- className="grid grid-cols-2 gap-4 sm:grid-cols-4"
- >
- {statusReportStatus.map((status) => {
- const { value, label, icon } = statusDict[status];
- const Icon = Icons[icon];
- return (
- <FormItem key={value}>
- <FormLabel className="[&:has([data-state=checked])>div]:border-primary [&:has([data-state=checked])>div]:text-foreground">
- <FormControl>
- <RadioGroupItem
- value={value}
- className="sr-only"
- />
- </FormControl>
- <div className="flex w-full items-center justify-center rounded-lg border border-border px-3 py-2 text-center text-muted-foreground text-sm">
- <Icon className="mr-2 h-4 w-4 shrink-0" />
- <span className="truncate">{label}</span>
- </div>
- </FormLabel>
- </FormItem>
- );
- })}
- </RadioGroup>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="monitors"
- render={() => (
- <FormItem className="sm:col-span-full">
- <div className="mb-4">
- <FormLabel>Monitors</FormLabel>
- {/* TODO: second phrase can be set inside of a (?) tooltip */}
- <FormDescription>
- Select the monitors that you want to refer the incident
- to. It will be displayed on the status page they are
- attached to.
- </FormDescription>
- </div>
- <div className="grid grid-cols-2 gap-4 sm:grid-cols-4">
- {monitors?.map((item) => (
- <FormField
- key={item.id}
- control={form.control}
- name="monitors"
- render={({ field }) => {
- return (
- <FormItem
- key={item.id}
- className="flex flex-row items-start space-x-3 space-y-0"
- >
- <FormControl>
- <Checkbox
- checked={field.value?.includes(item.id)}
- onCheckedChange={(checked) => {
- return checked
- ? field.onChange([
- ...(field.value || []),
- item.id,
- ])
- : field.onChange(
- field.value?.filter(
- (value) => value !== item.id,
- ),
- );
- }}
- />
- </FormControl>
- <div className="grid gap-1.5 leading-none">
- <div className="flex items-center gap-2">
- <FormLabel className="font-normal">
- {item.name}
- </FormLabel>
- <span
- className={cn(
- "rounded-full p-1",
- item.active
- ? "bg-green-500"
- : "bg-red-500",
- )}
- />
- </div>
- <p className="truncate text-muted-foreground text-sm">
- {item.description}
- </p>
- </div>
- </FormItem>
- );
- }}
- />
- ))}
- </div>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- {/* include update on creation */}
- {!defaultValues ? (
- <Accordion type="single" defaultValue="message" collapsible>
- <AccordionItem value="message">
- <AccordionTrigger>Message</AccordionTrigger>
- <AccordionContent>
- <div className="grid gap-4 sm:grid-cols-3">
- <div className="my-1.5 flex flex-col gap-2">
- <p className="font-semibold text-sm leading-none">
- Status Update
- </p>
- <p className="text-muted-foreground text-sm">
- What is actually going wrong?
- </p>
- </div>
- <div className="grid gap-6 sm:col-span-2 sm:grid-cols-2">
- <FormField
- control={form.control}
- name="message"
- render={({ field }) => (
- <FormItem className="sm:col-span-4">
- <FormLabel>Message</FormLabel>
- <Tabs defaultValue="write">
- <TabsList>
- <TabsTrigger value="write">Write</TabsTrigger>
- <TabsTrigger value="preview">Preview</TabsTrigger>
- </TabsList>
- <TabsContent value="write">
- <FormControl>
- <Textarea
- placeholder="We are encountering..."
- className="h-auto w-full resize-none"
- rows={9}
- {...field}
- />
- </FormControl>
- </TabsContent>
- <TabsContent value="preview">
- <Preview md={form.getValues("message")} />
- </TabsContent>
- </Tabs>
- <FormDescription>
- Tell your user what&apos;s happening. Supports
- markdown.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="date"
- render={({ field }) => (
- <FormItem className="flex flex-col sm:col-span-full">
- <FormLabel>Date</FormLabel>
- <DateTimePickerPopover
- date={
- field.value ? new Date(field.value) : new Date()
- }
- setDate={(date) => {
- field.onChange(date);
- }}
- />
- <FormDescription>
- The date and time when the incident took place.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- </AccordionContent>
- </AccordionItem>
- </Accordion>
- ) : null}
- <div className="flex sm:justify-end">
- <Button className="w-full sm:w-auto" size="lg">
- {!isPending ? "Confirm" : <LoadingAnimation />}
- </Button>
- </div>
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/forms/status-report-update-form.tsx b/apps/web/src/components/forms/status-report-update-form.tsx
deleted file mode 100644
index d6f9bc57d..000000000
--- a/apps/web/src/components/forms/status-report-update-form.tsx
+++ /dev/null
@@ -1,199 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-import { useForm } from "react-hook-form";
-
-import type { InsertStatusReportUpdate } from "@openstatus/db/src/schema";
-import {
- insertStatusReportUpdateSchema,
- statusReportStatus,
- statusReportStatusSchema,
-} from "@openstatus/db/src/schema";
-import {
- Button,
- DateTimePicker,
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- RadioGroup,
- RadioGroupItem,
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
- Textarea,
-} from "@openstatus/ui";
-
-import { Preview } from "@/components/content/preview";
-import { Icons } from "@/components/icons";
-import { LoadingAnimation } from "@/components/loading-animation";
-import { statusDict } from "@/data/incidents-dictionary";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-interface Props {
- defaultValues?: InsertStatusReportUpdate;
- statusReportId: number;
- onSubmit?: () => void;
-}
-
-export function StatusReportUpdateForm({
- defaultValues,
- statusReportId,
- onSubmit,
-}: Props) {
- const form = useForm<InsertStatusReportUpdate>({
- resolver: zodResolver(insertStatusReportUpdateSchema),
- defaultValues: {
- id: defaultValues?.id || 0,
- status: defaultValues?.status || "investigating",
- message: defaultValues?.message,
- date: defaultValues?.date || new Date(),
- statusReportId,
- },
- });
- const router = useRouter();
- const [isPending, startTransition] = React.useTransition();
-
- const handleSubmit = ({ ...props }: InsertStatusReportUpdate) => {
- startTransition(async () => {
- try {
- if (defaultValues) {
- await api.statusReport.updateStatusReportUpdate.mutate({ ...props });
- } else {
- await api.statusReport.createStatusReportUpdate.mutate({ ...props });
- }
- toastAction("saved");
- onSubmit?.();
- router.refresh();
- } catch {
- toastAction("error");
- }
- });
- };
-
- return (
- <Form {...form}>
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- form.handleSubmit(handleSubmit)(e);
- }}
- className="grid w-full gap-6"
- >
- <div className="grid gap-4 sm:grid-cols-3">
- <div className="my-1.5 flex flex-col gap-2">
- <p className="font-semibold text-sm leading-none">Inform</p>
- <p className="text-muted-foreground text-sm">
- Keep your users informed about what just happened.
- </p>
- </div>
- <div className="grid gap-6 sm:col-span-2 sm:grid-cols-3">
- <FormField
- control={form.control}
- name="status"
- render={({ field }) => (
- <FormItem className="space-y-1 sm:col-span-full">
- <FormLabel>Status</FormLabel>
- <FormDescription>Select the current status.</FormDescription>
- <FormMessage />
- <RadioGroup
- onValueChange={(value) =>
- field.onChange(statusReportStatusSchema.parse(value))
- } // value is a string
- defaultValue={field.value}
- className="grid grid-cols-2 gap-4 sm:grid-cols-4"
- >
- {statusReportStatus.map((status) => {
- const { value, label, icon } = statusDict[status];
- const Icon = Icons[icon];
- return (
- <FormItem key={value}>
- <FormLabel className="[&:has([data-state=checked])>div]:border-primary [&:has([data-state=checked])>div]:text-foreground">
- <FormControl>
- <RadioGroupItem
- value={value}
- className="sr-only"
- />
- </FormControl>
- <div className="flex w-full items-center justify-center rounded-lg border border-border px-3 py-2 text-center text-muted-foreground text-sm">
- <Icon className="mr-2 h-4 w-4 shrink-0" />
- <span className="truncate">{label}</span>
- </div>
- </FormLabel>
- </FormItem>
- );
- })}
- </RadioGroup>
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="message"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Message</FormLabel>
- <Tabs defaultValue="write">
- <TabsList>
- <TabsTrigger value="write">Write</TabsTrigger>
- <TabsTrigger value="preview">Preview</TabsTrigger>
- </TabsList>
- <TabsContent value="write">
- <FormControl>
- <Textarea
- placeholder="We are encountering..."
- className="h-auto w-full resize-none"
- rows={9}
- {...field}
- />
- </FormControl>
- </TabsContent>
- <TabsContent value="preview">
- <Preview md={form.getValues("message")} />
- </TabsContent>
- </Tabs>
- <FormDescription>
- Tell your user what&apos;s happening. Supports markdown.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="date"
- render={({ field }) => (
- <FormItem className="flex flex-col sm:col-span-2">
- <FormLabel>Date</FormLabel>
- <DateTimePicker
- className="w-full"
- date={new Date(field.value)}
- setDate={(date) => {
- field.onChange(date);
- }}
- />
- <FormDescription>
- The date and time when the incident took place.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- <div className="flex sm:justify-end">
- <Button className="w-full sm:w-auto" size="lg">
- {!isPending ? "Confirm" : <LoadingAnimation />}
- </Button>
- </div>
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/forms/status-report-update/form.tsx b/apps/web/src/components/forms/status-report-update/form.tsx
deleted file mode 100644
index 5d72d95f8..000000000
--- a/apps/web/src/components/forms/status-report-update/form.tsx
+++ /dev/null
@@ -1,103 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useRouter } from "next/navigation";
-import * as React from "react";
-import { useForm } from "react-hook-form";
-
-import type { InsertStatusReportUpdate } from "@openstatus/db/src/schema";
-import { insertStatusReportUpdateSchema } from "@openstatus/db/src/schema";
-import { Button, Form } from "@openstatus/ui";
-
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@/components/dashboard/tabs";
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-import { General } from "./general";
-import { SectionDate } from "./section-date";
-import { SectionMessage } from "./section-message";
-
-interface Props {
- defaultValues?: InsertStatusReportUpdate;
- statusReportId: number;
- onSubmit?: () => void;
-}
-
-export function StatusReportUpdateForm({
- defaultValues,
- statusReportId,
- onSubmit,
-}: Props) {
- const form = useForm<InsertStatusReportUpdate>({
- resolver: zodResolver(insertStatusReportUpdateSchema),
- defaultValues: {
- id: defaultValues?.id || 0,
- status: defaultValues?.status || "investigating",
- message: defaultValues?.message,
- date: defaultValues?.date || new Date(),
- statusReportId,
- },
- });
- const router = useRouter();
- const [isPending, startTransition] = React.useTransition();
-
- const handleSubmit = ({ ...props }: InsertStatusReportUpdate) => {
- startTransition(async () => {
- try {
- if (defaultValues) {
- await api.statusReport.updateStatusReportUpdate.mutate({
- ...props,
- });
- } else {
- const statusReportUpdate =
- await api.statusReport.createStatusReportUpdate.mutate({
- ...props,
- });
- if (!statusReportUpdate) return;
- await api.emailRouter.sendStatusReport.mutate({
- id: statusReportUpdate.id,
- });
- }
- toastAction("saved");
- onSubmit?.();
- router.refresh();
- } catch {
- toastAction("error");
- }
- });
- };
-
- return (
- <Form {...form}>
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- form.handleSubmit(handleSubmit)(e);
- }}
- className="grid w-full gap-6"
- >
- <General form={form} />
- <Tabs defaultValue="message">
- <TabsList>
- <TabsTrigger value="message">Message</TabsTrigger>
- <TabsTrigger value="date">Date & Time</TabsTrigger>
- </TabsList>
- <TabsContent value="message">
- <SectionMessage form={form} />
- </TabsContent>
- <TabsContent value="date">
- <SectionDate form={form} />
- </TabsContent>
- </Tabs>
- <Button className="w-full sm:w-auto" size="lg">
- {!isPending ? "Confirm" : <LoadingAnimation />}
- </Button>
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/forms/status-report-update/general.tsx b/apps/web/src/components/forms/status-report-update/general.tsx
deleted file mode 100644
index f70959276..000000000
--- a/apps/web/src/components/forms/status-report-update/general.tsx
+++ /dev/null
@@ -1,64 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import {
- statusReportStatus,
- statusReportStatusSchema,
-} from "@openstatus/db/src/schema";
-import type { InsertStatusReportUpdate } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- RadioGroup,
- RadioGroupItem,
-} from "@openstatus/ui";
-
-import { Icons } from "@/components/icons";
-import { statusDict } from "@/data/incidents-dictionary";
-
-interface Props {
- form: UseFormReturn<InsertStatusReportUpdate>;
-}
-export function General({ form }: Props) {
- return (
- <FormField
- control={form.control}
- name="status"
- render={({ field }) => (
- <FormItem className="space-y-1 sm:col-span-full">
- <FormLabel>Status</FormLabel>
- <FormMessage />
- <RadioGroup
- onValueChange={(value) =>
- field.onChange(statusReportStatusSchema.parse(value))
- } // value is a string
- defaultValue={field.value}
- className="grid grid-cols-2 gap-4 sm:grid-cols-4"
- >
- {statusReportStatus.map((status) => {
- const { value, label, icon } = statusDict[status];
- const Icon = Icons[icon];
- return (
- <FormItem key={value}>
- <FormLabel className="[&:has([data-state=checked])>div]:border-primary [&:has([data-state=checked])>div]:text-foreground">
- <FormControl>
- <RadioGroupItem value={value} className="sr-only" />
- </FormControl>
- <div className="flex w-full items-center justify-center rounded-lg border border-border px-3 py-2 text-center text-muted-foreground text-sm">
- <Icon className="mr-2 h-4 w-4 shrink-0" />
- <span className="truncate">{label}</span>
- </div>
- </FormLabel>
- </FormItem>
- );
- })}
- </RadioGroup>
- </FormItem>
- )}
- />
- );
-}
diff --git a/apps/web/src/components/forms/status-report-update/section-date.tsx b/apps/web/src/components/forms/status-report-update/section-date.tsx
deleted file mode 100644
index 95d96c5f7..000000000
--- a/apps/web/src/components/forms/status-report-update/section-date.tsx
+++ /dev/null
@@ -1,41 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertStatusReportUpdate } from "@openstatus/db/src/schema";
-import {
- DateTimePicker,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@openstatus/ui";
-
-interface Props {
- form: UseFormReturn<InsertStatusReportUpdate>;
-}
-export function SectionDate({ form }: Props) {
- return (
- <FormField
- control={form.control}
- name="date"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Date</FormLabel>
- <DateTimePicker
- className="max-w-min rounded-md border"
- date={new Date(field.value)}
- setDate={(date) => {
- field.onChange(date);
- }}
- />
- <FormDescription>
- The date and time when the incident took place.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- );
-}
diff --git a/apps/web/src/components/forms/status-report-update/section-message.tsx b/apps/web/src/components/forms/status-report-update/section-message.tsx
deleted file mode 100644
index 3fb735313..000000000
--- a/apps/web/src/components/forms/status-report-update/section-message.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-"use client";
-
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertStatusReportUpdate } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
- Textarea,
-} from "@openstatus/ui";
-
-import { Preview } from "@/components/content/preview";
-
-interface Props {
- form: UseFormReturn<InsertStatusReportUpdate>;
-}
-export function SectionMessage({ form }: Props) {
- return (
- <FormField
- control={form.control}
- name="message"
- render={({ field }) => (
- <FormItem className="sm:col-span-full">
- <FormLabel>Message</FormLabel>
- <Tabs defaultValue="write">
- <TabsList>
- <TabsTrigger value="write">Write</TabsTrigger>
- <TabsTrigger value="preview">Preview</TabsTrigger>
- </TabsList>
- <TabsContent value="write">
- <FormControl>
- <Textarea
- placeholder="We are encountering..."
- className="h-auto w-full resize-none"
- rows={9}
- {...field}
- />
- </FormControl>
- </TabsContent>
- <TabsContent value="preview">
- <Preview md={form.getValues("message")} />
- </TabsContent>
- </Tabs>
- <FormDescription>
- Tell your user what&apos;s happening. Supports markdown.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- );
-}
diff --git a/apps/web/src/components/forms/status-report/form.tsx b/apps/web/src/components/forms/status-report/form.tsx
deleted file mode 100644
index 24d7c96d5..000000000
--- a/apps/web/src/components/forms/status-report/form.tsx
+++ /dev/null
@@ -1,153 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { usePathname, useRouter } from "next/navigation";
-import * as React from "react";
-import { useForm } from "react-hook-form";
-
-import { insertStatusReportSchema } from "@openstatus/db/src/schema";
-import type { InsertStatusReport, Monitor } from "@openstatus/db/src/schema";
-import { Form } from "@openstatus/ui";
-
-import {
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
-} from "@/components/dashboard/tabs";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-import { SaveButton } from "../shared/save-button";
-import { General } from "./general";
-import { SectionConnect } from "./section-connect";
-import { SectionUpdateMessage } from "./section-update-message";
-
-interface Props {
- defaultSection?: string;
- defaultValues?: InsertStatusReport;
- monitors?: Monitor[];
- nextUrl?: string;
- pageId: number;
-}
-
-export function StatusReportForm({
- defaultSection,
- defaultValues,
- monitors,
- nextUrl,
- pageId,
-}: Props) {
- const form = useForm<InsertStatusReport>({
- resolver: zodResolver(insertStatusReportSchema),
- defaultValues: defaultValues
- ? {
- id: defaultValues.id,
- title: defaultValues.title,
- status: defaultValues.status,
- monitors: defaultValues.monitors,
- // include update on creation
- message: defaultValues.message,
- date: defaultValues.date,
- }
- : {
- status: "investigating",
- date: new Date(),
- },
- });
- const pathname = usePathname();
- const router = useRouter();
- const [isPending, startTransition] = React.useTransition();
-
- const onSubmit = ({ ...props }: InsertStatusReport) => {
- startTransition(async () => {
- try {
- if (defaultValues) {
- await api.statusReport.updateStatusReport.mutate({
- pageId,
- ...props,
- });
- } else {
- const { message, date, status, ...rest } = props;
- const statusReport = await api.statusReport.createStatusReport.mutate(
- {
- status,
- message,
- pageId,
- ...rest,
- },
- );
- // include update on creation
- if (statusReport?.id) {
- const statusReportUpdate =
- await api.statusReport.createStatusReportUpdate.mutate({
- message,
- date,
- status,
- statusReportId: statusReport.id,
- });
-
- if (statusReportUpdate) {
- await api.emailRouter.sendStatusReport.mutate({
- id: statusReportUpdate.id,
- });
- }
- }
- }
- if (nextUrl) {
- router.push(nextUrl);
- }
- router.refresh();
- toastAction("saved");
- } catch {
- toastAction("error");
- }
- });
- };
-
- function onValueChange(value: string) {
- // REMINDER: we are not merging the searchParams here
- // we are just setting the section to allow refreshing the page
- const params = new URLSearchParams();
- params.set("section", value);
- router.push(`${pathname}?${params.toString()}`);
- }
-
- return (
- <Form {...form}>
- <form
- onSubmit={async (e) => {
- e.preventDefault();
- form.handleSubmit(onSubmit)(e);
- }}
- className="grid w-full gap-6"
- >
- <General form={form} />
- <Tabs
- defaultValue={defaultSection}
- className="w-full"
- onValueChange={onValueChange}
- >
- <TabsList>
- {!defaultValues ? (
- <TabsTrigger value="update-message">Message</TabsTrigger>
- ) : null}
- <TabsTrigger value="connect">Connect</TabsTrigger>
- </TabsList>
- {!defaultValues ? (
- <TabsContent value="update-message">
- <SectionUpdateMessage form={form} />
- </TabsContent>
- ) : null}
- <TabsContent value="connect">
- <SectionConnect form={form} monitors={monitors} />
- </TabsContent>
- </Tabs>
- <SaveButton
- isPending={isPending}
- isDirty={form.formState.isDirty}
- onSubmit={form.handleSubmit(onSubmit)}
- />
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/forms/status-report/general.tsx b/apps/web/src/components/forms/status-report/general.tsx
deleted file mode 100644
index 1883ccd40..000000000
--- a/apps/web/src/components/forms/status-report/general.tsx
+++ /dev/null
@@ -1,90 +0,0 @@
-"use client";
-import type { UseFormReturn } from "react-hook-form";
-
-import {
- statusReportStatus,
- statusReportStatusSchema,
-} from "@openstatus/db/src/schema";
-import type { InsertStatusReport } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
- RadioGroup,
- RadioGroupItem,
-} from "@openstatus/ui";
-
-import { Icons } from "@/components/icons";
-import { statusDict } from "@/data/incidents-dictionary";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- form: UseFormReturn<InsertStatusReport>;
-}
-
-export function General({ form }: Props) {
- return (
- <div className="grid gap-4 sm:grid-cols-3 sm:gap-6">
- <SectionHeader
- title="Inform"
- description="Keep your users informed about what just happened."
- />
- <div className="grid gap-4 sm:col-span-2">
- <FormField
- control={form.control}
- name="title"
- render={({ field }) => (
- <FormItem>
- <FormLabel>Title</FormLabel>
- <FormControl>
- <Input placeholder="Downtime..." {...field} />
- </FormControl>
- <FormDescription>The title of your outage.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="status"
- render={({ field }) => (
- <FormItem className="space-y-1">
- <FormLabel>Status</FormLabel>
- <FormDescription>Select the current status.</FormDescription>
- <FormMessage />
- <RadioGroup
- onValueChange={(value) =>
- field.onChange(statusReportStatusSchema.parse(value))
- } // value is a string
- defaultValue={field.value}
- className="grid grid-cols-2 gap-4 sm:grid-cols-4"
- >
- {statusReportStatus.map((status) => {
- const { value, label, icon } = statusDict[status];
- const Icon = Icons[icon];
- return (
- <FormItem key={value}>
- <FormLabel className="[&:has([data-state=checked])>div]:border-primary [&:has([data-state=checked])>div]:text-foreground">
- <FormControl>
- <RadioGroupItem value={value} className="sr-only" />
- </FormControl>
- <div className="flex w-full items-center justify-center rounded-lg border border-border px-3 py-2 text-center text-muted-foreground text-sm">
- <Icon className="mr-2 h-4 w-4 shrink-0" />
- <span className="truncate">{label}</span>
- </div>
- </FormLabel>
- </FormItem>
- );
- })}
- </RadioGroup>
- </FormItem>
- )}
- />
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/status-report/section-connect.tsx b/apps/web/src/components/forms/status-report/section-connect.tsx
deleted file mode 100644
index d301a6851..000000000
--- a/apps/web/src/components/forms/status-report/section-connect.tsx
+++ /dev/null
@@ -1,84 +0,0 @@
-"use client";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertStatusReport, Monitor } from "@openstatus/db/src/schema";
-import {
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
-} from "@openstatus/ui";
-
-import { CheckboxLabel } from "../shared/checkbox-label";
-
-interface Props {
- form: UseFormReturn<InsertStatusReport>;
- monitors?: Monitor[];
-}
-
-export function SectionConnect({ form, monitors }: Props) {
- return (
- <div className="grid w-full gap-4">
- <div className="flex flex-col gap-3">
- <FormField
- control={form.control}
- name="monitors"
- render={() => (
- <FormItem>
- <div className="mb-4">
- <FormLabel>Monitors</FormLabel>
- {/* TODO: second phrase can be set inside of a (?) tooltip */}
- <FormDescription>
- Select the monitors that you want to refer the incident to. It
- will be displayed on the status page they are attached to.
- </FormDescription>
- </div>
- <div className="grid grid-cols-1 grid-rows-1 gap-6 sm:grid-cols-2 md:grid-cols-3">
- {monitors?.map((item) => (
- <FormField
- key={item.id}
- control={form.control}
- name="monitors"
- render={({ field }) => {
- return (
- <FormItem key={item.id} className="h-full w-full">
- <FormControl className="w-full">
- <CheckboxLabel
- id={String(item.id)}
- name="monitor"
- checked={field.value?.includes(item.id)}
- onCheckedChange={(checked) => {
- return checked
- ? field.onChange([
- ...(field.value || []),
- item.id,
- ])
- : field.onChange(
- field.value?.filter(
- (value) => value !== item.id,
- ),
- );
- }}
- >
- {item.name}
- </CheckboxLabel>
- </FormControl>
- </FormItem>
- );
- }}
- />
- ))}
- </div>
- {!monitors || monitors.length === 0 ? (
- <FormDescription>Missing monitors.</FormDescription>
- ) : null}
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/status-report/section-update-message.tsx b/apps/web/src/components/forms/status-report/section-update-message.tsx
deleted file mode 100644
index 42082ba6e..000000000
--- a/apps/web/src/components/forms/status-report/section-update-message.tsx
+++ /dev/null
@@ -1,87 +0,0 @@
-"use client";
-import type { UseFormReturn } from "react-hook-form";
-
-import type { InsertStatusReport } from "@openstatus/db/src/schema";
-import {
- DateTimePickerPopover,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Tabs,
- TabsContent,
- TabsList,
- TabsTrigger,
- Textarea,
-} from "@openstatus/ui";
-
-import { Preview } from "@/components/content/preview";
-import { SectionHeader } from "../shared/section-header";
-
-interface Props {
- form: UseFormReturn<InsertStatusReport>;
-}
-
-export function SectionUpdateMessage({ form }: Props) {
- return (
- <div className="grid w-full gap-4">
- <SectionHeader
- title="Status Update Message"
- description="Describe the current status of the incident."
- />
- <FormField
- control={form.control}
- name="message"
- render={({ field }) => (
- <FormItem className="sm:col-span-4">
- <FormLabel>Message</FormLabel>
- <Tabs defaultValue="write">
- <TabsList>
- <TabsTrigger value="write">Write</TabsTrigger>
- <TabsTrigger value="preview">Preview</TabsTrigger>
- </TabsList>
- <TabsContent value="write">
- <FormControl>
- <Textarea
- placeholder="We are encountering..."
- className="h-auto w-full resize-none"
- rows={9}
- {...field}
- />
- </FormControl>
- </TabsContent>
- <TabsContent value="preview">
- <Preview md={form.getValues("message")} />
- </TabsContent>
- </Tabs>
- <FormDescription>
- Tell your user what&apos;s happening. Supports markdown.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <FormField
- control={form.control}
- name="date"
- render={({ field }) => (
- <FormItem className="flex flex-col sm:col-span-full">
- <FormLabel>Date</FormLabel>
- <DateTimePickerPopover
- date={field.value ? new Date(field.value) : new Date()}
- setDate={(date) => {
- field.onChange(date);
- }}
- />
- <FormDescription>
- The date and time when the incident took place.
- </FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- </div>
- );
-}
diff --git a/apps/web/src/components/forms/workspace-form.tsx b/apps/web/src/components/forms/workspace-form.tsx
deleted file mode 100644
index dbae2b042..000000000
--- a/apps/web/src/components/forms/workspace-form.tsx
+++ /dev/null
@@ -1,79 +0,0 @@
-"use client";
-
-import { zodResolver } from "@hookform/resolvers/zod";
-import { useRouter } from "next/navigation";
-import { useTransition } from "react";
-import { useForm } from "react-hook-form";
-import * as z from "zod";
-
-import {
- Button,
- Form,
- FormControl,
- FormDescription,
- FormField,
- FormItem,
- FormLabel,
- FormMessage,
- Input,
-} from "@openstatus/ui";
-
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-import { LoadingAnimation } from "../loading-animation";
-
-// or insertWorkspaceSchema.pick({ name: true }) and updating name to not be nullable
-const schema = z.object({
- name: z.string().min(3, "workspace names must contain at least 3 characters"),
-});
-type Schema = z.infer<typeof schema>;
-
-export function WorkspaceForm({ defaultValues }: { defaultValues: Schema }) {
- const form = useForm<Schema>({
- resolver: zodResolver(schema),
- defaultValues,
- });
- const router = useRouter();
- const [isPending, startTransition] = useTransition();
-
- async function onSubmit(data: Schema) {
- startTransition(async () => {
- try {
- await api.workspace.updateWorkspace.mutate(data);
- toastAction("saved");
- router.refresh();
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <Form {...form}>
- <form
- onSubmit={form.handleSubmit(onSubmit)}
- className="grid w-full grid-cols-1 items-center gap-6 sm:grid-cols-6"
- >
- <FormField
- control={form.control}
- name="name"
- render={({ field }) => (
- <FormItem className="sm:col-span-4">
- <FormLabel>Name</FormLabel>
- <FormControl>
- <Input placeholder="Documenso" {...field} />
- </FormControl>
- <FormDescription>The name of your workspace.</FormDescription>
- <FormMessage />
- </FormItem>
- )}
- />
- <div className="sm:col-span-full">
- <Button className="w-full sm:w-auto" size="lg">
- {!isPending ? "Confirm" : <LoadingAnimation />}
- </Button>
- </div>
- </form>
- </Form>
- );
-}
diff --git a/apps/web/src/components/layout/app-footer.tsx b/apps/web/src/components/layout/app-footer.tsx
deleted file mode 100644
index 963e76cb4..000000000
--- a/apps/web/src/components/layout/app-footer.tsx
+++ /dev/null
@@ -1,30 +0,0 @@
-import Link from "next/link";
-
-import { Shell } from "../dashboard/shell";
-
-export function AppFooter() {
- return (
- <footer className="w-full">
- <Shell className="flex items-center justify-between">
- <div className="font-light text-muted-foreground text-xs">
- All rights reserved &copy;
- </div>
- <div className="text-right text-xs">
- <Link
- href="/legal/terms"
- className="text-foreground underline underline-offset-4 hover:no-underline"
- >
- Terms
- </Link>
- <span className="mx-1 text-muted-foreground/70">&bull;</span>
- <Link
- href="/legal/privacy"
- className="text-foreground underline underline-offset-4 hover:no-underline"
- >
- Privacy
- </Link>
- </div>
- </Shell>
- </footer>
- );
-}
diff --git a/apps/web/src/components/layout/app-menu.tsx b/apps/web/src/components/layout/app-menu.tsx
deleted file mode 100644
index 3409121c4..000000000
--- a/apps/web/src/components/layout/app-menu.tsx
+++ /dev/null
@@ -1,42 +0,0 @@
-"use client";
-
-import { ChevronsUpDown } from "lucide-react";
-import { useSelectedLayoutSegment } from "next/navigation";
-import * as React from "react";
-
-import {
- Collapsible,
- CollapsibleContent,
- CollapsibleTrigger,
-} from "@openstatus/ui/src/components/collapsible";
-
-import type { Page } from "@/config/pages";
-import { AppSidebar } from "./app-sidebar";
-
-export function AppMenu({ page }: { page?: Page }) {
- const [open, setOpen] = React.useState(false);
-
- const selectedSegment = useSelectedLayoutSegment();
-
- if (!page) return null;
-
- const activeChild = page?.children?.find(
- ({ segment }) => segment === selectedSegment,
- );
-
- return (
- <Collapsible open={open} onOpenChange={(value) => setOpen(value)}>
- <CollapsibleTrigger className="flex w-full items-center justify-between">
- <span className="font-medium text-foreground">
- {activeChild?.title}
- </span>
- <span className="inline-flex h-9 w-9 items-center justify-center rounded-md font-medium text-sm transition-colors hover:bg-accent hover:text-accent-foreground focus-visible:outline-hidden focus-visible:ring-1 focus-visible:ring-ring disabled:pointer-events-none disabled:opacity-50">
- <ChevronsUpDown className="h-4 w-4" />
- </span>
- </CollapsibleTrigger>
- <CollapsibleContent className="mt-2">
- <AppSidebar page={page} />
- </CollapsibleContent>
- </Collapsible>
- );
-}
diff --git a/apps/web/src/components/layout/app-page-layout.tsx b/apps/web/src/components/layout/app-page-layout.tsx
deleted file mode 100644
index b7f61f397..000000000
--- a/apps/web/src/components/layout/app-page-layout.tsx
+++ /dev/null
@@ -1,20 +0,0 @@
-import { Shell } from "@/components/dashboard/shell";
-import { cn } from "@/lib/utils";
-
-export default function AppPageLayout({
- children,
- className,
-}: {
- children: React.ReactNode;
- className?: string;
-}) {
- return (
- <Shell className="relative flex flex-1 flex-col overflow-x-hidden">
- <div
- className={cn("flex h-full flex-1 flex-col gap-6 md:gap-8", className)}
- >
- {children}
- </div>
- </Shell>
- );
-}
diff --git a/apps/web/src/components/layout/app-page-with-sidebar-layout.tsx b/apps/web/src/components/layout/app-page-with-sidebar-layout.tsx
deleted file mode 100644
index 296877e41..000000000
--- a/apps/web/src/components/layout/app-page-with-sidebar-layout.tsx
+++ /dev/null
@@ -1,39 +0,0 @@
-import { Shell } from "@/components/dashboard/shell";
-import type { PageId } from "@/config/pages";
-import { pagesConfig } from "@/config/pages";
-import { cn } from "@/lib/utils";
-import { AppMenu } from "./app-menu";
-import { AppSidebar } from "./app-sidebar";
-
-export default function AppPageWithSidebarLayout({
- id,
- className,
- children,
-}: {
- id?: PageId;
- className?: string;
- children: React.ReactNode;
-}) {
- const page = pagesConfig.find((page) => page.segment === id);
-
- return (
- <div className="flex w-full flex-1 flex-col gap-6 lg:flex-row lg:gap-8">
- <Shell className="block py-3 md:py-3 lg:hidden">
- <AppMenu page={page} />
- </Shell>
- <Shell className="hidden max-h-[calc(100vh-8rem)] max-w-min shrink-0 lg:sticky lg:top-28 lg:block">
- <AppSidebar page={page} />
- </Shell>
- <Shell className="relative flex-1 overflow-hidden">
- <div
- className={cn(
- "flex h-full flex-1 flex-col gap-6 md:gap-8",
- className,
- )}
- >
- {children}
- </div>
- </Shell>
- </div>
- );
-}
diff --git a/apps/web/src/components/layout/app-sidebar.tsx b/apps/web/src/components/layout/app-sidebar.tsx
deleted file mode 100644
index 8a5ad308e..000000000
--- a/apps/web/src/components/layout/app-sidebar.tsx
+++ /dev/null
@@ -1,52 +0,0 @@
-"use client";
-
-import { useParams, useSelectedLayoutSegment } from "next/navigation";
-
-import type { Page } from "@/config/pages";
-import { ProBanner } from "../billing/pro-banner";
-import { AppLink } from "./app-link";
-
-function replacePlaceholders(
- template: string,
- values: { [key: string]: string },
-): string {
- return template.replace(/\[([^\]]+)\]/g, (_, key) => {
- return values[key] || `[${key}]`;
- });
-}
-
-export function AppSidebar({ page }: { page?: Page }) {
- const params = useParams<Record<string, string>>();
- const selectedSegment = useSelectedLayoutSegment();
-
- if (!page) return null;
-
- return (
- <div className="flex h-full flex-col justify-between gap-2">
- <div className="grid gap-2">
- <p className="hidden px-3 font-medium text-foreground text-lg lg:block">
- {page?.title}
- </p>
- <ul className="grid gap-2">
- {page?.children?.map(({ title, segment, icon, disabled, href }) => {
- const prefix = `/app/${params.workspaceSlug}`;
- return (
- <li key={title} className="w-full">
- <AppLink
- label={title}
- href={`${prefix}${replacePlaceholders(href, params)}`}
- disabled={disabled}
- active={segment === selectedSegment}
- icon={icon}
- />
- </li>
- );
- })}
- </ul>
- </div>
- <div className="hidden lg:block">
- <ProBanner />
- </div>
- </div>
- );
-}
diff --git a/apps/web/src/components/layout/header/app-header.tsx b/apps/web/src/components/layout/header/app-header.tsx
deleted file mode 100644
index 43e929b47..000000000
--- a/apps/web/src/components/layout/header/app-header.tsx
+++ /dev/null
@@ -1,78 +0,0 @@
-"use client";
-
-import { allChangelogs } from "content-collections";
-import { ArrowUpRight } from "lucide-react";
-import Link from "next/link";
-
-import { Button, Skeleton } from "@openstatus/ui";
-
-import { Shell } from "@/components/dashboard/shell";
-import { useCookieState } from "@/hooks/use-cookie-state";
-import { AppTabs } from "./app-tabs";
-import { Breadcrumbs } from "./breadcrumbs";
-import { UserNav } from "./user-nav";
-
-const lastChangelog = allChangelogs
- .sort(
- (a, b) =>
- new Date(a.publishedAt).getTime() - new Date(b.publishedAt).getTime(),
- )
- .pop();
-
-export function AppHeader() {
- const [lastViewed, setLastViewed] = useCookieState(
- "last-viewed-changelog",
- new Date(0).toISOString(),
- );
-
- const show =
- lastChangelog && lastViewed
- ? new Date(lastViewed) < new Date(lastChangelog.publishedAt)
- : false;
-
- return (
- // TODO: discuss amount of top-3 and top-6
- <header className="sticky top-2 z-50 w-full border-border">
- <Shell className="bg-background/70 px-3 py-3 backdrop-blur-lg md:px-6 md:py-3">
- <div className="flex w-full items-center justify-between">
- <Breadcrumbs />
- {/* */}
- <div className="flex items-center gap-1">
- <ul className="hidden gap-1 sm:flex">
- <li className="w-full">
- <Button variant="link" asChild>
- <Link
- href="/changelog"
- target="_blank"
- onClick={() => setLastViewed(new Date().toISOString())}
- className="relative"
- >
- Changelog
- {show ? (
- <span className="absolute top-1 right-1 h-2 w-2 rounded-full bg-green-500" />
- ) : null}
- </Link>
- </Button>
- </li>
- <li className="w-full">
- <Button variant="link" asChild>
- <Link href="/docs" target="_blank" className="group">
- Docs
- <ArrowUpRight className="ml-1 h-4 w-4 shrink-0 text-muted-foreground group-hover:text-foreground" />
- </Link>
- </Button>
- </li>
- </ul>
- <div className="relative">
- <Skeleton className="h-8 w-8 rounded-full" />
- <div className="absolute inset-0">
- <UserNav />
- </div>
- </div>
- </div>
- </div>
- <AppTabs />
- </Shell>
- </header>
- );
-}
diff --git a/apps/web/src/components/layout/header/app-tabs.tsx b/apps/web/src/components/layout/header/app-tabs.tsx
deleted file mode 100644
index 7eacaf7d4..000000000
--- a/apps/web/src/components/layout/header/app-tabs.tsx
+++ /dev/null
@@ -1,60 +0,0 @@
-"use client";
-
-import { useParams, useSelectedLayoutSegment } from "next/navigation";
-
-import { TabsContainer, TabsLink } from "@/components/dashboard/tabs-link";
-import { StatusDot } from "@/components/monitor/status-dot";
-import { pagesConfig } from "@/config/pages";
-import { api } from "@/trpc/client";
-import { useEffect, useState } from "react";
-
-export function AppTabs() {
- const params = useParams();
- const selectedSegment = useSelectedLayoutSegment();
-
- if (!params?.workspaceSlug) return null;
-
- return (
- <div className="-mb-3">
- <TabsContainer>
- {pagesConfig.map(({ title, segment, href }) => {
- const active = segment === selectedSegment;
- return (
- <TabsLink
- key={segment}
- active={active}
- href={`/app/${params?.workspaceSlug}${href}`}
- prefetch={false}
- className="relative"
- >
- {title}
- {/* {segment === "incidents" ? <IncidentsDot /> : null} */}
- </TabsLink>
- );
- })}
- </TabsContainer>
- </div>
- );
-}
-
-// FIXME: use react-query - once the user resolves the incident, the dot should disappear without refresh
-export function IncidentsDot() {
- const [open, setOpen] = useState(false);
-
- useEffect(() => {
- async function checkOpenIncidents() {
- const incidents = await api.incident.getOpenIncidents.query();
- if (incidents.length) setOpen(true);
- }
-
- checkOpenIncidents();
- }, []);
-
- if (!open) return null;
-
- return (
- <div className="absolute top-1 right-1">
- <StatusDot status="error" active />
- </div>
- );
-}
diff --git a/apps/web/src/components/layout/header/breadcrumbs.tsx b/apps/web/src/components/layout/header/breadcrumbs.tsx
deleted file mode 100644
index a6edfe9d0..000000000
--- a/apps/web/src/components/layout/header/breadcrumbs.tsx
+++ /dev/null
@@ -1,107 +0,0 @@
-"use client";
-
-import { Slash } from "lucide-react";
-import Image from "next/image";
-import Link from "next/link";
-import {
- useParams,
- useSelectedLayoutSegment,
- useSelectedLayoutSegments,
-} from "next/navigation";
-import { Fragment, useEffect, useState } from "react";
-
-import { SelectWorkspace } from "@/components/workspace/select-workspace";
-import { notEmpty } from "@/lib/utils";
-import { api } from "@/trpc/client";
-
-export function Breadcrumbs() {
- const params = useParams();
- // const selectedSegment = useSelectedLayoutSegment();
- // const selectedSegments = useSelectedLayoutSegments();
- // const label = useIdLabel();
-
- // // remove route groups like '(overview)' from the segments
- // const segmentsWithoutRouteGroup = selectedSegments.filter(
- // (segment) => !segment.startsWith("("),
- // );
-
- // const isRoot = segmentsWithoutRouteGroup.length <= 1;
-
- // const page = pagesConfig.find(({ segment }) => segment === selectedSegment);
- const breadcrumbs = [
- // !isRoot ? page?.title : null,
- // label,
- ].filter(notEmpty);
-
- const _isWorkspaceSlug = params.workspaceSlug;
-
- return (
- <div className="flex items-center">
- <Link href="/app" className="shrink-0">
- <Image
- src="/icon.png"
- alt="OpenStatus"
- height={30}
- width={30}
- className="rounded-full border border-border"
- />
- </Link>
- <Slash className="-rotate-12 mr-0.5 ml-2.5 h-4 w-4 text-muted-foreground" />
- {params.workspaceSlug ? (
- <div className="w-40">
- <SelectWorkspace />
- </div>
- ) : null}
- {breadcrumbs.map((breadcrumb) => (
- <Fragment key={breadcrumb}>
- <Slash className="-rotate-12 mr-2.5 ml-0.5 h-4 w-4 text-muted-foreground" />
- <p className="rounded-md font-medium text-primary text-sm">
- {breadcrumb}
- </p>
- </Fragment>
- ))}
- </div>
- );
-}
-
-// This is a custom hook that returns the label of the current id
-// biome-ignore lint/correctness/noUnusedVariables: <explanation>
-function useIdLabel() {
- const params = useParams();
- const selectedSegment = useSelectedLayoutSegment();
- const selectedSegments = useSelectedLayoutSegments();
- const [label, setLabel] = useState<string>();
-
- // remove route groups like '(overview)' from the segments
- const segmentsWithoutRouteGroup = selectedSegments.filter(
- (segment) => !segment.startsWith("("),
- );
-
- const isRoot = segmentsWithoutRouteGroup.length <= 1;
-
- useEffect(() => {
- async function getInfos() {
- const { id } = params;
- if (!isRoot && id) {
- if (selectedSegment === "monitors") {
- const monitor = await api.monitor.getMonitorById.query({
- id: Number(id),
- });
- if (monitor) setLabel(monitor.name);
- }
- if (selectedSegment === "status-pages") {
- const statusPage = await api.page.getPageById.query({
- id: Number(id),
- });
- if (statusPage) setLabel(statusPage.title);
- }
- }
- if (isRoot && label) {
- setLabel(undefined);
- }
- }
- getInfos();
- }, [params, selectedSegment, isRoot, label]);
-
- return label;
-}
diff --git a/apps/web/src/components/status-update/delete-status-update.tsx b/apps/web/src/components/status-update/delete-status-update.tsx
deleted file mode 100644
index a1d01b9cd..000000000
--- a/apps/web/src/components/status-update/delete-status-update.tsx
+++ /dev/null
@@ -1,77 +0,0 @@
-"use client";
-
-import { useRouter } from "next/navigation";
-import * as React from "react";
-
-import {
- AlertDialog,
- AlertDialogAction,
- AlertDialogCancel,
- AlertDialogContent,
- AlertDialogDescription,
- AlertDialogFooter,
- AlertDialogHeader,
- AlertDialogTitle,
- AlertDialogTrigger,
-} from "@openstatus/ui/src/components/alert-dialog";
-import { Button } from "@openstatus/ui/src/components/button";
-
-import { Icons } from "@/components/icons";
-import { LoadingAnimation } from "@/components/loading-animation";
-import { toastAction } from "@/lib/toast";
-import { api } from "@/trpc/client";
-
-export function DeleteStatusReportUpdateButtonIcon({ id }: { id: number }) {
- const router = useRouter();
- const [alertOpen, setAlertOpen] = React.useState(false);
- const [isPending, startTransition] = React.useTransition();
-
- async function onDelete() {
- startTransition(async () => {
- try {
- await api.statusReport.deleteStatusReportUpdate.mutate({ id });
- toastAction("deleted");
- router.refresh();
- setAlertOpen(false);
- } catch {
- toastAction("error");
- }
- });
- }
-
- return (
- <AlertDialog open={alertOpen} onOpenChange={(value) => setAlertOpen(value)}>
- <AlertDialogTrigger asChild>
- <Button
- size="icon"
- variant="outline"
- className="border-destructive/50 text-destructive/80 hover:bg-destructive/10 hover:text-destructive"
- >
- <Icons.trash className="h-4 w-4" />
- </Button>
- </AlertDialogTrigger>
- <AlertDialogContent>
- <AlertDialogHeader>
- <AlertDialogTitle>Are you absolutely sure?</AlertDialogTitle>
- <AlertDialogDescription>
- This action cannot be undone. This will permanently delete the
- status report update.
- </AlertDialogDescription>
- </AlertDialogHeader>
- <AlertDialogFooter>
- <AlertDialogCancel>Cancel</AlertDialogCancel>
- <AlertDialogAction
- onClick={(e) => {
- e.preventDefault();
- onDelete();
- }}
- disabled={isPending}
- className="bg-destructive text-destructive-foreground hover:bg-destructive/90"
- >
- {!isPending ? "Delete" : <LoadingAnimation />}
- </AlertDialogAction>
- </AlertDialogFooter>
- </AlertDialogContent>
- </AlertDialog>
- );
-}
diff --git a/apps/web/src/components/status-update/edit-status-update.tsx b/apps/web/src/components/status-update/edit-status-update.tsx
deleted file mode 100644
index 6aa2468b5..000000000
--- a/apps/web/src/components/status-update/edit-status-update.tsx
+++ /dev/null
@@ -1,49 +0,0 @@
-"use client";
-
-import { useState } from "react";
-
-import type { InsertStatusReportUpdate } from "@openstatus/db/src/schema";
-import { Button } from "@openstatus/ui/src/components/button";
-import {
- Dialog,
- DialogContent,
- DialogDescription,
- DialogHeader,
- DialogTitle,
- DialogTrigger,
-} from "@openstatus/ui/src/components/dialog";
-
-import { StatusReportUpdateForm } from "../forms/status-report-update/form";
-import { Icons } from "../icons";
-
-export function EditStatusReportUpdateIconButton({
- statusReportId,
- statusReportUpdate,
-}: {
- statusReportId: number;
- statusReportUpdate?: InsertStatusReportUpdate;
-}) {
- const [open, setOpen] = useState(false);
- return (
- <Dialog open={open} onOpenChange={setOpen}>
- <DialogTrigger asChild>
- <Button size="icon" variant="outline">
- <Icons.pencil className="h-4 w-4" />
- </Button>
- </DialogTrigger>
- <DialogContent className="max-h-screen overflow-y-scroll sm:max-w-[650px]">
- <DialogHeader>
- <DialogTitle>Edit Status Report</DialogTitle>
- <DialogDescription>
- Update your status report with new information.
- </DialogDescription>
- </DialogHeader>
- <StatusReportUpdateForm
- statusReportId={statusReportId}
- defaultValues={statusReportUpdate}
- onSubmit={() => setOpen(false)}
- />
- </DialogContent>
- </Dialog>
- );
-}
diff --git a/apps/web/src/components/status-update/events.tsx b/apps/web/src/components/status-update/events.tsx
deleted file mode 100644
index ca7b8c17f..000000000
--- a/apps/web/src/components/status-update/events.tsx
+++ /dev/null
@@ -1,113 +0,0 @@
-"use client";
-
-import { format } from "date-fns";
-import * as React from "react";
-
-import type { StatusReportUpdate } from "@openstatus/db/src/schema";
-import { Button } from "@openstatus/ui/src/components/button";
-
-import { Icons } from "@/components/icons";
-import { statusDict } from "@/data/incidents-dictionary";
-import { useProcessor } from "@/hooks/use-preprocessor";
-import { cn } from "@/lib/utils";
-import { DeleteStatusReportUpdateButtonIcon } from "./delete-status-update";
-import { EditStatusReportUpdateIconButton } from "./edit-status-update";
-
-export function Events({
- statusReportUpdates,
- editable = false,
- collabsible = false,
-}: {
- statusReportUpdates: StatusReportUpdate[];
- editable?: boolean;
- collabsible?: boolean;
-}) {
- const [open, toggle] = React.useReducer((open) => !open, false);
-
- const sortedArray = statusReportUpdates.sort((a, b) => {
- return b.date.getTime() - a.date.getTime();
- });
-
- const slicedArray =
- open || !collabsible
- ? sortedArray
- : sortedArray.length > 0
- ? [sortedArray[0]]
- : [];
- //
-
- return (
- <div className="grid gap-3">
- {slicedArray?.map((update, i) => {
- const { icon, label } = statusDict[update.status];
- const StatusIcon = Icons[icon];
- return (
- <div
- key={update.id}
- className={cn(
- "group -m-2 relative flex gap-4 border border-transparent p-2",
- editable && "hover:rounded-lg hover:bg-accent/40",
- )}
- >
- <div className="relative">
- <div className="rounded-full border border-border bg-background p-2">
- <StatusIcon className="h-4 w-4" />
- </div>
- {i !== sortedArray.length - 1 ? (
- <div className="absolute inset-x-0 mx-auto h-full w-[2px] bg-muted" />
- ) : null}
- </div>
- <div className="mt-1 grid flex-1">
- {editable ? (
- <div className="absolute top-2 right-2 hidden gap-2 group-hover:flex group-active:flex">
- <EditStatusReportUpdateIconButton
- statusReportId={update.statusReportId}
- statusReportUpdate={update}
- />
- <DeleteStatusReportUpdateButtonIcon id={update.id} />
- </div>
- ) : undefined}
- <div className="flex items-center gap-2">
- <p className="font-medium text-sm">{label}</p>
- <p className="mt-px text-muted-foreground text-xs">
- <code>
- {format(new Date(update.date), "LLL dd, y HH:mm")}
- </code>
- </p>
- </div>
- {/* <p className="max-w-3xl text-sm">{update.message}</p> */}
- <EventMessage message={update.message} />
- </div>
- </div>
- );
- })}
- {collabsible && statusReportUpdates.length > 1 ? (
- <div className="text-center">
- <Button variant="ghost" onClick={toggle}>
- {open ? "Close" : "More"}
- </Button>
- </div>
- ) : null}
- </div>
- );
-}
-
-function EventMessage({
- message,
- className,
-}: {
- message: string;
- className?: string;
-}) {
- const Component = useProcessor(message); // FIXME: make it work with markdown without hook!
- return (
- <div
- className={cn(
- "prose dark:prose-invert prose-sm overflow-hidden text-ellipsis prose-headings:font-cal", // fixes very long words
- className,
- )}
- >
- {Component}
- </div>
- );
-}
diff --git a/apps/web/src/components/status-update/status-badge.tsx b/apps/web/src/components/status-update/status-badge.tsx
deleted file mode 100644
index 4020e6dd7..000000000
--- a/apps/web/src/components/status-update/status-badge.tsx
+++ /dev/null
@@ -1,23 +0,0 @@
-import type { StatusReport } from "@openstatus/db/src/schema";
-import { Badge } from "@openstatus/ui/src/components/badge";
-
-import { statusDict } from "@/data/incidents-dictionary";
-import { cn } from "@/lib/utils";
-import { Icons } from "../icons";
-
-export function StatusBadge({
- status,
- className,
-}: {
- status: StatusReport["status"];
- className?: string;
-}) {
- const { label, icon, color } = statusDict[status];
- const Icon = Icons[icon];
- return (
- <Badge variant="outline" className={cn("font-normal", color, className)}>
- <Icon className="mr-1 h-3 w-3" />
- {label}
- </Badge>
- );
-}
diff --git a/apps/web/src/components/status-update/summary.tsx b/apps/web/src/components/status-update/summary.tsx
deleted file mode 100644
index 161c53030..000000000
--- a/apps/web/src/components/status-update/summary.tsx
+++ /dev/null
@@ -1,54 +0,0 @@
-import { format, formatDistanceStrict } from "date-fns";
-
-import type {
- Monitor,
- StatusReport,
- StatusReportUpdate,
-} from "@openstatus/db/src/schema";
-import { Badge } from "@openstatus/ui/src/components/badge";
-
-import { StatusBadge } from "./status-badge";
-
-export function Summary({
- report,
- monitors,
-}: {
- report: StatusReport & { statusReportUpdates: StatusReportUpdate[] };
- monitors: Pick<Monitor, "name" | "id">[];
-}) {
- const firstUpdate = report.statusReportUpdates?.[0];
- const lastUpdate =
- report.statusReportUpdates?.[report.statusReportUpdates.length - 1];
-
- return (
- <div className="grid grid-cols-5 gap-3 text-sm">
- <p className="col-start-1 text-muted-foreground">Started</p>
- <p className="col-span-4">
- {firstUpdate ? (
- <code>{format(new Date(firstUpdate.date), "LLL dd, y HH:mm")}</code>
- ) : null}
- </p>
- <p className="col-start-1 text-muted-foreground">Status</p>
- <div className="col-span-4 flex items-center gap-2">
- <StatusBadge status={report.status} />
- {firstUpdate && lastUpdate && report.status === "resolved" ? (
- <span className="text-muted-foreground text-xs">
- after {formatDistanceStrict(firstUpdate.date, lastUpdate.date)}
- </span>
- ) : null}
- </div>
- <p className="col-start-1 text-muted-foreground">Affected</p>
- <ul className="col-span-4 flex gap-2">
- {monitors.length > 0 ? (
- monitors.map(({ name, id }) => (
- <li key={id} className="text-xs">
- <Badge variant="outline">{name}</Badge>
- </li>
- ))
- ) : (
- <li>-</li>
- )}
- </ul>
- </div>
- );
-}
diff --git a/apps/web/src/components/workspace/select-workspace.tsx b/apps/web/src/components/workspace/select-workspace.tsx
deleted file mode 100644
index 631a88fe3..000000000
--- a/apps/web/src/components/workspace/select-workspace.tsx
+++ /dev/null
@@ -1,116 +0,0 @@
-"use client";
-
-import { Check, ChevronsUpDown, Copy, CopyCheck, Plus } from "lucide-react";
-import Link from "next/link";
-import { usePathname } from "next/navigation";
-import * as React from "react";
-
-import type { Workspace } from "@openstatus/db/src/schema";
-import { Button } from "@openstatus/ui/src/components/button";
-import {
- DropdownMenu,
- DropdownMenuContent,
- DropdownMenuItem,
- DropdownMenuLabel,
- DropdownMenuSeparator,
- DropdownMenuTrigger,
-} from "@openstatus/ui/src/components/dropdown-menu";
-import { Skeleton } from "@openstatus/ui/src/components/skeleton";
-
-import { copyToClipboard } from "@/lib/utils";
-import { api } from "@/trpc/client";
-
-export function SelectWorkspace() {
- const [workspaces, setWorkspaces] = React.useState<Workspace[]>([]);
- const [active, setActive] = React.useState<string>();
- const pathname = usePathname();
- const [hasCopied, setHasCopied] = React.useState(false);
-
- React.useEffect(() => {
- if (hasCopied) {
- setTimeout(() => {
- setHasCopied(false);
- }, 2000);
- }
- }, [hasCopied]);
-
- React.useEffect(() => {
- if (pathname?.split("/")?.[2] && workspaces.length > 0) {
- setActive(pathname?.split("/")?.[2]);
- }
- }, [pathname, workspaces]);
-
- React.useEffect(() => {
- // REMINDER: avoid prop drilling to get data from the layout.tsx component. instead use client trpc
- async function fetchWorkspaces() {
- const _workspaces = await api.workspace.getUserWorkspaces.query();
- setWorkspaces(_workspaces);
- }
- fetchWorkspaces();
- }, []);
-
- return (
- <DropdownMenu>
- <DropdownMenuTrigger asChild>
- <Button
- variant="ghost"
- className="flex w-full items-center justify-between"
- >
- {active ? (
- <span className="truncate">{active}</span>
- ) : (
- <Skeleton className="h-5 w-full" />
- )}
- <ChevronsUpDown className="ml-2 h-4 w-4 shrink-0 opacity-50" />
- </Button>
- </DropdownMenuTrigger>
- <DropdownMenuContent
- style={{ width: "var(--radix-dropdown-menu-trigger-width)" }}
- >
- <DropdownMenuLabel>Workspaces</DropdownMenuLabel>
- <DropdownMenuSeparator />
- {workspaces.map((workspace) => (
- <DropdownMenuItem key={workspace.id} asChild>
- <a
- href={`/app/${workspace.slug}/monitors`}
- className="group justify-between"
- >
- <span className="truncate">{workspace.slug}</span>
- <Button
- type="button"
- variant="ghost"
- size="icon"
- className="mx-0.5 hidden h-5 w-5 group-hover:block"
- onClick={(e) => {
- e.stopPropagation();
- e.preventDefault();
- copyToClipboard(workspace.slug);
- setHasCopied(true);
- }}
- >
- {!hasCopied ? (
- <Copy className="h-3 w-3" />
- ) : (
- <CopyCheck className="h-3 w-3" />
- )}
- </Button>
- {active === workspace.slug ? (
- <Check className="ml-2 h-4 w-4 shrink-0" />
- ) : null}
- </a>
- </DropdownMenuItem>
- ))}
- <DropdownMenuSeparator />
- <DropdownMenuItem asChild>
- <Link
- href={`/app/${active}/settings/team`}
- className="flex items-center justify-between"
- >
- Invite Members
- <Plus className="ml-2 h-4 w-4" />
- </Link>
- </DropdownMenuItem>
- </DropdownMenuContent>
- </DropdownMenu>
- );
-}