{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "settings-03",
  "description": "Each notification against each channel, grouped by topic, with a switch for each one and a switch for the whole channel.",
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/attempt.json",
    "https://www.dashboardblocks.com/r/radix/announcements.json",
    "switch",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/table.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/settings/settings-03.tsx",
      "content": "'use client'\n\nimport {\n  Announcements,\n  useAnnouncements,\n} from '@/registry/components/dashboardblocks/announcements'\nimport {\n  BlockStateProvider,\n  type BlockStateProps,\n  getBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  DataTable,\n  DataTableBody,\n  DataTableCell,\n  DataTableGroupHead,\n  DataTableHead,\n  DataTableHeader,\n  DataTableRow,\n  DataTableRowHead,\n  DataTableStateRows,\n} from '@/registry/components/dashboardblocks/table'\nimport { attempt } from '@/registry/lib/dashboardblocks/attempt'\nimport { type ReactNode, startTransition, useId, useState } from 'react'\n\nimport { Switch } from '@/components/ui/switch'\n\ninterface NotificationChannel {\n  id: string\n  label: string\n  /** Why the channel can't send right now, such as \"Slack isn't connected. Ask an admin to connect it.\" Shown above the table; the channel's switches turn off until it can, and the saved choices come back then. */\n  unavailable?: ReactNode\n}\n\ninterface NotificationEvent {\n  description?: string\n  id: string\n  label: string\n}\n\ninterface NotificationGroup {\n  events: NotificationEvent[]\n  id: string\n  label: string\n}\n\n/** `preferences[eventId]` lists the channel ids that event is sent to. */\ntype NotificationPreferences = Record<string, string[]>\n\ntype NotificationChangeResult = void | { status: 'error'; message: string }\n\ninterface Settings3Props extends BlockStateProps {\n  channels: NotificationChannel[]\n  description: string\n  /** Leave out, or pass none, to show the empty state. */\n  groups?: NotificationGroup[]\n  /** Saves the new preferences; resolve to an error, or throw, to put the switches it changed back and say why. */\n  onChange?: (\n    preferences: NotificationPreferences,\n  ) => NotificationChangeResult | Promise<NotificationChangeResult>\n  preferences?: NotificationPreferences\n  title: string\n}\n\nconst exampleProps: Settings3Props = {\n  channels: [\n    { id: 'email', label: 'Email' },\n    { id: 'push', label: 'Push' },\n    { id: 'slack', label: 'Slack' },\n  ],\n  description: 'Choose where each notification is sent.',\n  groups: [\n    {\n      events: [\n        {\n          description: 'When a metric crosses a threshold you set',\n          id: 'alert-triggered',\n          label: 'Alert triggered',\n        },\n        {\n          description: 'When an alert clears',\n          id: 'alert-resolved',\n          label: 'Alert resolved',\n        },\n      ],\n      id: 'alerts',\n      label: 'Alerts',\n    },\n    {\n      events: [\n        { id: 'weekly-summary', label: 'Weekly summary' },\n        { id: 'report-ready', label: 'Scheduled report ready' },\n      ],\n      id: 'reports',\n      label: 'Reports',\n    },\n    {\n      events: [\n        { id: 'invoice-paid', label: 'Invoice paid' },\n        {\n          description: 'When a payment fails or a card is about to expire',\n          id: 'payment-issue',\n          label: 'Payment issue',\n        },\n      ],\n      id: 'billing',\n      label: 'Billing',\n    },\n    {\n      events: [\n        { id: 'mention', label: 'Mentioned in a comment' },\n        { id: 'member-joined', label: 'Member joined' },\n      ],\n      id: 'workspace',\n      label: 'Workspace',\n    },\n  ],\n  preferences: {\n    'alert-resolved': ['slack'],\n    'alert-triggered': ['email', 'push', 'slack'],\n    'invoice-paid': ['email'],\n    mention: ['email', 'push'],\n    'member-joined': [],\n    'payment-issue': ['email', 'push'],\n    'report-ready': ['email'],\n    'weekly-summary': ['email'],\n  },\n  title: 'Notifications',\n}\n\nfunction revert(\n  current: NotificationPreferences,\n  previous: NotificationPreferences,\n  next: NotificationPreferences,\n) {\n  const reverted = { ...current }\n  for (const eventId of new Set([...Object.keys(previous), ...Object.keys(next)])) {\n    const was = previous[eventId] ?? []\n    const sent = next[eventId] ?? []\n    for (const channelId of new Set([...was, ...sent])) {\n      if (was.includes(channelId) === sent.includes(channelId)) continue\n      const without = (reverted[eventId] ?? []).filter((channel) => channel !== channelId)\n      reverted[eventId] = was.includes(channelId) ? [...without, channelId] : without\n    }\n  }\n  return reverted\n}\n\nconst Settings3 = (props: Settings3Props) => {\n  const {\n    channels,\n    description,\n    groups = [],\n    onChange,\n    errorMessage,\n    status,\n    title,\n  } = props\n  const [preferences, setPreferences] = useState(props.preferences ?? {})\n  const [error, setError] = useState<string | null>(null)\n  const [said, announce] = useAnnouncements()\n  const noteId = useId()\n  const ready = !status && groups.length > 0\n  const unavailable = channels.filter((channel) => channel.unavailable)\n\n  const update = async (next: NotificationPreferences) => {\n    const previous = preferences\n    setPreferences(next)\n    setError(null)\n    const result: NotificationChangeResult = await attempt(\n      () => onChange?.(next),\n      'Couldn’t save your notifications. Try again.',\n    )\n    if (!result) return\n    const { message } = result\n    startTransition(() => {\n      setPreferences((current) => revert(current, previous, next))\n      setError(message)\n      announce(message)\n    })\n  }\n\n  const isOn = (eventId: string, channel: NotificationChannel) =>\n    !channel.unavailable && (preferences[eventId]?.includes(channel.id) ?? false)\n\n  const noteFor = (channel: NotificationChannel) =>\n    channel.unavailable ? `${noteId}-${channel.id}` : undefined\n\n  const toggle = (eventId: string, channelId: string, on: boolean) => {\n    const current = preferences[eventId] ?? []\n    return update({\n      ...preferences,\n      [eventId]: on\n        ? [...current, channelId]\n        : current.filter((channel) => channel !== channelId),\n    })\n  }\n\n  const allEvents = groups.flatMap((group) => group.events)\n\n  const setChannel = (channelId: string, on: boolean) =>\n    update(\n      Object.fromEntries(\n        allEvents.map((event) => {\n          const current = preferences[event.id] ?? []\n          const without = current.filter((channel) => channel !== channelId)\n          return [event.id, on ? [...without, channelId] : without]\n        }),\n      ),\n    )\n\n  return (\n    <BlockStateProvider errorMessage={errorMessage} state={getBlockState(status, groups)}>\n      <section className='@container flex flex-col gap-3'>\n        <header className='flex flex-col gap-0.5'>\n          <h2 className='font-semibold tracking-tight'>{title}</h2>\n          <p className='text-muted-foreground text-sm'>{description}</p>\n        </header>\n        {ready &&\n          unavailable.map((channel) => (\n            <p\n              key={channel.id}\n              id={noteFor(channel)}\n              className='text-muted-foreground text-sm text-pretty'\n            >\n              {channel.unavailable}\n            </p>\n          ))}\n        <DataTable className='border-t' caption={title}>\n          <DataTableHeader>\n            <DataTableRow>\n              <DataTableHead className='min-w-40'>\n                <span className='sr-only'>Notification</span>\n              </DataTableHead>\n              {channels.map((channel) => {\n                const count = allEvents.filter((event) => isOn(event.id, channel)).length\n                return (\n                  <DataTableHead key={channel.id} align='center' className='w-20 py-2.5'>\n                    <div className='flex flex-col items-center gap-2'>\n                      <span className='text-foreground text-sm'>{channel.label}</span>\n                      <Switch\n                        size='sm'\n                        aria-label={`All ${channel.label} notifications`}\n                        aria-describedby={noteFor(channel)}\n                        checked={ready && count === allEvents.length}\n                        disabled={!ready || Boolean(channel.unavailable)}\n                        onCheckedChange={(on) => void setChannel(channel.id, on)}\n                      />\n                    </div>\n                  </DataTableHead>\n                )\n              })}\n            </DataTableRow>\n          </DataTableHeader>\n          {!ready && (\n            <DataTableBody>\n              <DataTableStateRows colSpan={channels.length + 1} rows={4} />\n            </DataTableBody>\n          )}\n          {ready &&\n            groups.map((group) => (\n              <DataTableBody key={group.id}>\n                <DataTableRow>\n                  <DataTableGroupHead colSpan={channels.length + 1}>\n                    {group.label}\n                  </DataTableGroupHead>\n                </DataTableRow>\n                {group.events.map((event) => (\n                  <DataTableRow key={event.id}>\n                    <DataTableRowHead>\n                      <span className='block'>{event.label}</span>\n                      {event.description && (\n                        <span className='text-muted-foreground block text-xs'>\n                          {event.description}\n                        </span>\n                      )}\n                    </DataTableRowHead>\n                    {channels.map((channel) => (\n                      <DataTableCell key={channel.id} align='center'>\n                        <Switch\n                          aria-label={`${event.label} by ${channel.label}`}\n                          aria-describedby={noteFor(channel)}\n                          checked={isOn(event.id, channel)}\n                          disabled={Boolean(channel.unavailable)}\n                          onCheckedChange={(on) => void toggle(event.id, channel.id, on)}\n                        />\n                      </DataTableCell>\n                    ))}\n                  </DataTableRow>\n                ))}\n              </DataTableBody>\n            ))}\n        </DataTable>\n        {error && <p className='text-destructive text-sm'>{error}</p>}\n        <Announcements said={said} />\n      </section>\n    </BlockStateProvider>\n  )\n}\n\nexport {\n  Settings3,\n  exampleProps as settings3ExampleProps,\n  type NotificationChangeResult,\n  type NotificationChannel,\n  type NotificationEvent,\n  type NotificationGroup,\n  type NotificationPreferences,\n  type Settings3Props,\n}\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/settings/settings-03.tsx"
    }
  ],
  "meta": {
    "shows": "Each notification against each channel, grouped by topic, with a switch for each one and a switch for the whole channel.",
    "size": "full",
    "usedWith": [
      "notifications-01",
      "settings-07"
    ],
    "component": "Settings3",
    "props": "{ channels: { id: string; label: string; unavailable?: ReactNode }[]; description: string; groups?: { events: { description?: string; id: string; label: string }[]; id: string; label: string }[]; onChange?: (preferences: {  }) => void | { status: \"error\"; message: string } | Promise<void | { status: \"error\"; message: string }>; preferences?: {  }; title: string; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:component"
}
