{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "settings-05",
  "description": "Webhook endpoints with the events they receive, a chart of recent deliveries with each one in a tooltip, the delivery rate, what’s wrong with a failing one, and a switch to pause each one.",
  "dependencies": [
    "recharts"
  ],
  "registryDependencies": [
    "button",
    "switch",
    "https://www.dashboardblocks.com/r/radix/announcements.json",
    "https://www.dashboardblocks.com/r/radix/attempt.json",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/chart.json",
    "https://www.dashboardblocks.com/r/radix/details.json",
    "https://www.dashboardblocks.com/r/radix/format.json",
    "https://www.dashboardblocks.com/r/radix/settings.json",
    "https://www.dashboardblocks.com/r/radix/table.json",
    "https://www.dashboardblocks.com/r/radix/tooltip-link.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/settings/settings-05.tsx",
      "content": "'use client'\n\nimport {\n  Announcements,\n  useAnnouncements,\n} from '@/registry/components/dashboardblocks/announcements'\nimport {\n  BlockReady,\n  BlockStateProvider,\n  BlockStateRows,\n  type BlockStateProps,\n  getBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  ChartTooltipFrame,\n  ChartTooltipItem,\n  chartBarCursor,\n} from '@/registry/components/dashboardblocks/chart'\nimport { Details } from '@/registry/components/dashboardblocks/details'\nimport {\n  type ConnectionStatus,\n  ConnectionStatusLabel,\n  CopyButton,\n} from '@/registry/components/dashboardblocks/settings'\nimport {\n  DataTableListItem,\n  DataTableRowLink,\n} from '@/registry/components/dashboardblocks/table'\nimport { ButtonLink } from '@/registry/components/dashboardblocks/tooltip-link'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport { attempt } from '@/registry/lib/dashboardblocks/attempt'\nimport {\n  formatList,\n  formatPercent,\n  formatRelativeTime,\n} from '@/registry/lib/dashboardblocks/format'\nimport { startTransition, useOptimistic, useState } from 'react'\nimport { Bar, BarChart, Cell, ResponsiveContainer, Tooltip, YAxis } from 'recharts'\n\nimport { Button } from '@/components/ui/button'\nimport { Switch } from '@/components/ui/switch'\n\nimport { cn } from '@/lib/utils'\n\ninterface Delivery {\n  at: Date\n  /** The HTTP status, or 0 for a timeout. */\n  status: number\n}\n\ninterface WebhookEndpoint {\n  /** Recent deliveries, oldest first. */\n  deliveries: Delivery[]\n  /** What people call it, shown as the row's name with the URL below. */\n  description?: string\n  enabled: boolean\n  events: string[]\n  /** The endpoint's own page: the whole row opens it. */\n  href?: string\n  id: string\n  /**\n   * What's wrong while it's failing, in a sentence, such as what the server last said. While it's\n   * set, the endpoint reads Failing, whatever its last deliveries were.\n   */\n  problem?: string\n  url: string\n}\n\n/** A change that was refused resolves with the reason; the switch goes back. */\ntype Settings5Result = { message: string; status: 'error' } | { status: 'success' } | void\n\ninterface Settings5Props extends BlockStateProps {\n  /** @default a sentence counting the endpoints and any failing ones */\n  description?: string\n  /** Leave out, or pass none, to show the empty state. */\n  endpoints?: WebhookEndpoint[]\n  /** Pass a fixed date, so the block renders the same on the server and in the browser. */\n  now: Date\n  /** Where Add endpoint goes, such as a page with the new endpoint's form. In place of `onAdd`. */\n  addHref?: string\n  onAdd?: () => void\n  /**\n   * Pauses or resumes an endpoint. Return nothing to keep the change in the block, or a promise\n   * that resolves once the change is saved and the endpoints you pass show it; the switch shows\n   * the change until then. Leave out to keep the change in the block.\n   */\n  onEnabledChange?: (id: string, enabled: boolean) => void | Promise<Settings5Result>\n  title: string\n}\n\nconst NOW = new Date(Date.UTC(2026, 8, 26, 16, 0))\n\nfunction exampleDeliveries(count: number, failEvery: number, failFrom = count) {\n  return Array.from({ length: count }, (_, index) => ({\n    at: new Date(NOW.getTime() - (count - index) * 37 * 60_000),\n    status:\n      index >= failFrom\n        ? index % 2\n          ? 500\n          : 0\n        : failEvery > 0 && index % failEvery === failEvery - 1\n          ? 502\n          : 200,\n  }))\n}\n\nconst exampleProps: Settings5Props = {\n  endpoints: [\n    {\n      deliveries: exampleDeliveries(30, 0),\n      enabled: true,\n      events: ['alert.triggered', 'alert.resolved'],\n      id: 'w1',\n      url: 'https://api.acme.co/hooks/alerts',\n    },\n    {\n      deliveries: exampleDeliveries(30, 9, 24),\n      enabled: true,\n      events: ['invoice.paid', 'invoice.failed', 'subscription.updated'],\n      id: 'w2',\n      problem:\n        'The last 6 deliveries timed out or got a 500 back, so billing.acme.co missed 6 events.',\n      url: 'https://billing.acme.co/webhooks/dashboardblocks',\n    },\n    {\n      deliveries: exampleDeliveries(12, 0),\n      enabled: false,\n      events: ['report.ready'],\n      id: 'w3',\n      url: 'https://hooks.zapier.com/hooks/catch/1234/abcd',\n    },\n  ],\n  now: NOW,\n  title: 'Webhooks',\n}\n\nconst isSuccess = (delivery: Delivery) => delivery.status >= 200 && delivery.status < 300\n\ntype EndpointStatus = Extract<ConnectionStatus, 'connected' | 'error' | 'paused'>\n\nfunction getEndpointStatus(endpoint: WebhookEndpoint): EndpointStatus {\n  if (!endpoint.enabled) return 'paused'\n  if (endpoint.problem) return 'error'\n  const recent = endpoint.deliveries.slice(-3)\n  if (recent.length > 0 && recent.every((delivery) => !isSuccess(delivery)))\n    return 'error'\n  return 'connected'\n}\n\nconst statusLabel: Record<EndpointStatus, string> = {\n  connected: 'Active',\n  error: 'Failing',\n  paused: 'Paused',\n}\n\nconst BAR_SLOT_PX = 10\nconst DELIVERED_COLOR = 'var(--color-emerald-500)'\nconst FAILED_COLOR = 'var(--color-red-500)'\n\nfunction describeStatus(status: number) {\n  return status === 0 ? 'Timed out' : String(status)\n}\n\nfunction DeliveryChart({\n  deliveries,\n  enabled,\n  now,\n}: {\n  deliveries: Delivery[]\n  enabled: boolean\n  now: Date\n}) {\n  const data = deliveries.map((delivery) => ({\n    ...delivery,\n    height: isSuccess(delivery) ? 0.6 : 1,\n  }))\n  return (\n    <div className='h-6 w-full' style={{ maxWidth: deliveries.length * BAR_SLOT_PX }}>\n      <ResponsiveContainer width='100%' height='100%'>\n        <BarChart\n          data={data}\n          barCategoryGap={1}\n          margin={{ top: 0, right: 0, bottom: 0, left: 0 }}\n          aria-label={`Last ${deliveries.length} deliveries`}\n        >\n          <YAxis hide domain={[0, 1]} />\n          <Tooltip\n            cursor={chartBarCursor}\n            content={({ active, payload }) => {\n              const delivery = payload?.[0]?.payload as Delivery | undefined\n              if (!active || !delivery) return null\n              return (\n                <ChartTooltipFrame>\n                  <span className='font-medium'>\n                    {formatRelativeTime(delivery.at, now, { style: 'long' })}\n                  </span>\n                  <ChartTooltipItem\n                    color={isSuccess(delivery) ? DELIVERED_COLOR : FAILED_COLOR}\n                    name={isSuccess(delivery) ? 'Delivered' : 'Failed'}\n                    value={describeStatus(delivery.status)}\n                  />\n                </ChartTooltipFrame>\n              )\n            }}\n          />\n          <Bar dataKey='height' radius={2} maxBarSize={8}>\n            {data.map((delivery, index) => (\n              <Cell\n                key={index}\n                fill={isSuccess(delivery) ? DELIVERED_COLOR : FAILED_COLOR}\n                fillOpacity={enabled ? 1 : 0.4}\n              />\n            ))}\n          </Bar>\n        </BarChart>\n      </ResponsiveContainer>\n    </div>\n  )\n}\n\nconst ADD_ICON = (\n  <IconPlaceholder\n    lucide='PlusIcon'\n    tabler='IconPlus'\n    hugeicons='PlusSignIcon'\n    phosphor='PlusIcon'\n    remixicon='RiAddLine'\n    data-icon='inline-start'\n  />\n)\n\nconst NO_ENDPOINTS: WebhookEndpoint[] = []\nconst NO_IDS: ReadonlySet<string> = new Set()\n\nconst Settings5 = (props: Settings5Props) => {\n  const {\n    addHref,\n    endpoints: given = NO_ENDPOINTS,\n    errorMessage,\n    now,\n    onAdd,\n    onEnabledChange,\n    status: blockStatus,\n    title,\n  } = props\n  const [own, setOwn] = useState<Readonly<Record<string, boolean>>>({})\n  const [refused, setRefused] = useState<Readonly<Record<string, string>>>({})\n  const [said, announce] = useAnnouncements()\n  const [endpoints, showEnabled] = useOptimistic(\n    given.map((endpoint) =>\n      endpoint.id in own ? { ...endpoint, enabled: own[endpoint.id] } : endpoint,\n    ),\n    (current, change: { enabled: boolean; id: string }) =>\n      current.map((endpoint) =>\n        endpoint.id === change.id ? { ...endpoint, enabled: change.enabled } : endpoint,\n      ),\n  )\n  const [pendingIds, markPending] = useOptimistic(\n    NO_IDS,\n    (current: ReadonlySet<string>, id: string) => new Set(current).add(id),\n  )\n  const failing = endpoints.filter(\n    (endpoint) => getEndpointStatus(endpoint) === 'error',\n  ).length\n  const paused = endpoints.filter((endpoint) => !endpoint.enabled).length\n  const extra = [\n    failing > 0 && `${failing} ${failing === 1 ? 'is' : 'are'} failing`,\n    paused > 0 && `${paused} ${paused === 1 ? 'is' : 'are'} paused`,\n  ].filter((part): part is string => typeof part === 'string')\n  const description =\n    props.description ??\n    (endpoints.length === 0\n      ? 'Endpoints get a JSON POST when their events happen.'\n      : `${endpoints.length === 1 ? '1 endpoint gets a JSON POST when its events happen' : `${endpoints.length} endpoints get a JSON POST when their events happen`}${extra.length > 0 ? `, and ${formatList(extra)}` : ''}.`)\n\n  function changeEnabled(endpoint: WebhookEndpoint, enabled: boolean) {\n    setRefused((current) => {\n      const next = { ...current }\n      delete next[endpoint.id]\n      return next\n    })\n    if (!onEnabledChange) {\n      setOwn((current) => ({ ...current, [endpoint.id]: enabled }))\n      return\n    }\n    startTransition(async () => {\n      showEnabled({ enabled, id: endpoint.id })\n      markPending(endpoint.id)\n      const result = await attempt(() => onEnabledChange(endpoint.id, enabled))\n      startTransition(() => {\n        if (result && result.status === 'error') {\n          setRefused((current) => ({\n            ...current,\n            [endpoint.id]: result.message,\n          }))\n          announce(result.message)\n          return\n        }\n        if (!result) setOwn((current) => ({ ...current, [endpoint.id]: enabled }))\n        announce(\n          `${enabled ? 'Resumed' : 'Paused'} ${endpoint.description ?? endpoint.url}.`,\n        )\n      })\n    })\n  }\n\n  return (\n    <BlockStateProvider\n      errorMessage={errorMessage}\n      state={getBlockState(blockStatus, endpoints)}\n    >\n      <section className='@container flex flex-col gap-3'>\n        <header className='flex items-start justify-between gap-3'>\n          <div className='flex min-w-0 flex-col gap-0.5'>\n            <h2 className='font-semibold tracking-tight'>{title}</h2>\n            <BlockReady className='text-sm'>\n              <p className='text-muted-foreground text-sm'>{description}</p>\n            </BlockReady>\n          </div>\n          {addHref && blockStatus === undefined ? (\n            <ButtonLink href={addHref} className='shrink-0'>\n              {ADD_ICON}\n              Add endpoint\n            </ButtonLink>\n          ) : (\n            <Button\n              variant='outline'\n              size='sm'\n              className='shrink-0'\n              disabled={blockStatus !== undefined}\n              onClick={onAdd}\n            >\n              {ADD_ICON}\n              Add endpoint\n            </Button>\n          )}\n        </header>\n        {(blockStatus || endpoints.length === 0) && (\n          <div className='border-t'>\n            <BlockStateRows\n              rows={3}\n              emptyMessage='No endpoints yet. Add one to get a POST when its events happen.'\n            />\n          </div>\n        )}\n        {!blockStatus && endpoints.length > 0 && (\n          <ul className='flex flex-col divide-y border-t'>\n            {endpoints.map((endpoint) => {\n              const status = getEndpointStatus(endpoint)\n              const succeeded = endpoint.deliveries.filter(isSuccess).length\n              const last = endpoint.deliveries.at(-1)\n              const pending = pendingIds.has(endpoint.id)\n              return (\n                <DataTableListItem key={endpoint.id} className='flex flex-col gap-2 py-3'>\n                  <div className='flex items-start gap-3'>\n                    <div className='flex min-w-0 flex-1 flex-col gap-0.5'>\n                      {endpoint.description &&\n                        (endpoint.href ? (\n                          <DataTableRowLink\n                            href={endpoint.href}\n                            className='text-sm font-medium'\n                          >\n                            {endpoint.description}\n                          </DataTableRowLink>\n                        ) : (\n                          <span className='truncate text-sm font-medium'>\n                            {endpoint.description}\n                          </span>\n                        ))}\n                      <div className='flex min-w-0 items-center gap-1'>\n                        {endpoint.href && !endpoint.description ? (\n                          <DataTableRowLink\n                            href={endpoint.href}\n                            className='font-mono text-sm'\n                          >\n                            {endpoint.url}\n                          </DataTableRowLink>\n                        ) : (\n                          <span\n                            className={cn(\n                              'truncate font-mono',\n                              endpoint.description\n                                ? 'text-muted-foreground text-xs'\n                                : 'text-sm',\n                            )}\n                          >\n                            {endpoint.url}\n                          </span>\n                        )}\n                        <CopyButton\n                          label={`Copy ${endpoint.url}`}\n                          value={endpoint.url}\n                          className='-my-1 shrink-0'\n                        />\n                      </div>\n                      <p className='text-muted-foreground text-xs'>\n                        <ConnectionStatusLabel\n                          status={status}\n                          label={statusLabel[status]}\n                          className='me-1.5 align-middle'\n                        />\n                        <span className='font-mono'>{endpoint.events.join(', ')}</span>\n                      </p>\n                    </div>\n                    <Switch\n                      aria-label={`Send to ${endpoint.description ?? endpoint.url}`}\n                      aria-disabled={pending || undefined}\n                      checked={endpoint.enabled}\n                      onCheckedChange={(enabled) => {\n                        if (!pending) changeEnabled(endpoint, enabled)\n                      }}\n                    />\n                  </div>\n                  {endpoint.problem && (\n                    <p\n                      className={cn(\n                        'text-sm text-pretty',\n                        status === 'error'\n                          ? 'text-red-700 dark:text-red-400'\n                          : 'text-muted-foreground',\n                      )}\n                    >\n                      {endpoint.problem}\n                    </p>\n                  )}\n                  {refused[endpoint.id] && (\n                    <p className='text-destructive text-sm text-pretty'>\n                      {refused[endpoint.id]}\n                    </p>\n                  )}\n                  {endpoint.deliveries.length > 0 && (\n                    <div className='flex flex-col gap-1 @md:flex-row @md:items-center @md:gap-4'>\n                      <DeliveryChart\n                        deliveries={endpoint.deliveries}\n                        enabled={endpoint.enabled}\n                        now={now}\n                      />\n                      <Details className='text-muted-foreground shrink-0 text-xs tabular-nums'>\n                        {`${formatPercent(succeeded / endpoint.deliveries.length, {\n                          maximumFractionDigits: 0,\n                        })} delivered`}\n                        {last && (\n                          <>\n                            last{' '}\n                            <time dateTime={last.at.toISOString()}>\n                              {formatRelativeTime(last.at, now, {\n                                style: 'long',\n                              })}\n                            </time>\n                            {!isSuccess(last) && (\n                              <span className='text-red-700 dark:text-red-400'>\n                                {' '}\n                                ({describeStatus(last.status).toLowerCase()})\n                              </span>\n                            )}\n                          </>\n                        )}\n                      </Details>\n                    </div>\n                  )}\n                </DataTableListItem>\n              )\n            })}\n          </ul>\n        )}\n        <Announcements said={said} />\n      </section>\n    </BlockStateProvider>\n  )\n}\n\nexport {\n  Settings5,\n  exampleProps as settings5ExampleProps,\n  getEndpointStatus,\n  type Delivery,\n  type Settings5Props,\n  type Settings5Result,\n  type WebhookEndpoint,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/settings/settings-05.tsx"
    }
  ],
  "meta": {
    "shows": "Webhook endpoints with the events they receive, a chart of recent deliveries with each one in a tooltip, the delivery rate, what’s wrong with a failing one, and a switch to pause each one.",
    "size": "full",
    "usedWith": [
      "settings-02",
      "settings-04",
      "status-01"
    ],
    "component": "Settings5",
    "props": "{ description?: string; endpoints?: { deliveries: { at: Date; status: number }[]; description?: string; enabled: boolean; events: string[]; href?: string; id: string; problem?: string; url: string }[]; now: Date; addHref?: string; onAdd?: () => void; onEnabledChange?: (id: string, enabled: boolean) => void | Promise<void | { message: string; status: \"error\" } | { status: \"success\" }>; title: string; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:component"
}
