{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "onboarding-03",
  "description": "A searchable, filterable list of data sources to pick from, then follow through connecting to connected, with an error state.",
  "registryDependencies": [
    "button",
    "field",
    "input-group",
    "https://www.dashboardblocks.com/r/radix/option-select.json",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/choice-cards.json",
    "https://www.dashboardblocks.com/r/radix/link.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/onboarding/onboarding-03.tsx",
      "content": "'use client'\n\nimport {\n  BlockMessage,\n  BlockReady,\n  BlockStateProvider,\n  BlockStateRows,\n  type BlockStateProps,\n  getBlockState,\n} from '@/registry/components/dashboardblocks/block-state'\nimport {\n  type ChoiceCardOption,\n  ChoiceCards,\n} from '@/registry/components/dashboardblocks/choice-cards'\nimport { Link } from '@/registry/components/dashboardblocks/link'\nimport { OptionSelect } from '@/registry/components/dashboardblocks/option-select'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport {\n  type FormEvent,\n  type ReactNode,\n  startTransition,\n  useEffect,\n  useId,\n  useRef,\n  useState,\n} from 'react'\n\nimport { Button } from '@/components/ui/button'\nimport { FieldError } from '@/components/ui/field'\nimport { InputGroup, InputGroupAddon, InputGroupInput } from '@/components/ui/input-group'\n\ninterface DataSource {\n  category: string\n  description: string\n  id: string\n  logo?: ReactNode\n  name: string\n  popular?: boolean\n}\n\ninterface Onboarding3Props extends BlockStateProps {\n  onConnect?: (id: string) => Promise<void>\n  onContinue?: (id: string) => void\n  requestHref: string\n  /** Leave out, or pass none, to show the empty state. */\n  sources?: DataSource[]\n}\n\nconst exampleProps: Onboarding3Props = {\n  requestHref: '/sources/request',\n  sources: [\n    {\n      category: 'Databases',\n      description: 'Tables and views from Postgres 12 or later.',\n      id: 'postgres',\n      name: 'PostgreSQL',\n      popular: true,\n    },\n    {\n      category: 'Payments',\n      description: 'Charges, subscriptions, refunds and payouts.',\n      id: 'stripe',\n      name: 'Stripe',\n      popular: true,\n    },\n    {\n      category: 'Warehouses',\n      description: 'Datasets from any Google Cloud project.',\n      id: 'bigquery',\n      name: 'BigQuery',\n    },\n    {\n      category: 'Warehouses',\n      description: 'Databases and schemas through a key pair.',\n      id: 'snowflake',\n      name: 'Snowflake',\n    },\n    {\n      category: 'CRM',\n      description: 'Contacts, companies, deals and pipelines.',\n      id: 'hubspot',\n      name: 'HubSpot',\n    },\n    {\n      category: 'CRM',\n      description: 'Accounts, opportunities and custom objects.',\n      id: 'salesforce',\n      name: 'Salesforce',\n    },\n    {\n      category: 'E-commerce',\n      description: 'Orders, products, customers and inventory.',\n      id: 'shopify',\n      name: 'Shopify',\n    },\n    {\n      category: 'Marketing',\n      description: 'Sessions, events and conversions from GA4.',\n      id: 'ga4',\n      name: 'Google Analytics',\n    },\n    {\n      category: 'Spreadsheets',\n      description: 'Any sheet you can open, synced every hour.',\n      id: 'sheets',\n      name: 'Google Sheets',\n    },\n  ],\n}\n\nasync function connectSource(id: string) {\n  await new Promise((resolve) => setTimeout(resolve, 1500))\n  if (id === 'snowflake') {\n    throw new Error(\n      'Snowflake rejected the key pair. Check the user has USAGE on the warehouse.',\n    )\n  }\n}\n\ntype Status =\n  | { state: 'picking' }\n  | { id: string; state: 'connecting' | 'connected' }\n  | { id: string; message: string; state: 'failed' }\n\nfunction toOption(source: DataSource): ChoiceCardOption {\n  return {\n    badge: source.popular ? 'Popular' : undefined,\n    description: source.description,\n    icon: source.logo ?? <span className='text-sm font-semibold'>{source.name[0]}</span>,\n    title: source.name,\n    value: source.id,\n  }\n}\n\nconst Onboarding3 = (props: Onboarding3Props) => {\n  const {\n    onConnect = connectSource,\n    onContinue,\n    requestHref,\n    sources = [],\n    errorMessage,\n    status: blockStatus,\n  } = props\n  const blockState = getBlockState(blockStatus, sources)\n  const id = useId()\n  const [query, setQuery] = useState('')\n  const [category, setCategory] = useState('')\n  const [selected, setSelected] = useState('')\n  const [error, setError] = useState<string>()\n  const [status, setStatus] = useState<Status>({ state: 'picking' })\n  const attempt = useRef(0)\n  const messageRef = useRef<HTMLDivElement>(null)\n  const shownState = useRef(status.state)\n\n  const categories = [...new Set(sources.map((source) => source.category))]\n  const search = query.trim().toLowerCase()\n  const visible = sources.filter(\n    (source) =>\n      (!category || source.category === category) &&\n      (!search ||\n        `${source.name} ${source.category} ${source.description}`\n          .toLowerCase()\n          .includes(search)),\n  )\n  const source = sources.find(\n    (item) => item.id === (status.state === 'picking' ? selected : status.id),\n  )\n\n  useEffect(() => {\n    const from = shownState.current\n    shownState.current = status.state\n    if (from === status.state) return\n    const message = messageRef.current\n    if (status.state === 'picking') document.getElementById(`${id}-search`)?.focus()\n    else if (message && !message.contains(document.activeElement)) message.focus()\n  }, [id, status.state])\n\n  async function connect(sourceId: string) {\n    attempt.current += 1\n    const current = attempt.current\n    setStatus({ id: sourceId, state: 'connecting' })\n    try {\n      await onConnect(sourceId)\n      if (current === attempt.current)\n        startTransition(() => setStatus({ id: sourceId, state: 'connected' }))\n    } catch (caught) {\n      if (current !== attempt.current) return\n      startTransition(() =>\n        setStatus({\n          id: sourceId,\n          message:\n            caught instanceof Error ? caught.message : 'Something went wrong. Try again.',\n          state: 'failed',\n        }),\n      )\n    }\n  }\n\n  function onSubmit(event: FormEvent<HTMLFormElement>) {\n    event.preventDefault()\n    if (!selected) {\n      setError('Pick a source to connect.')\n      document.getElementById(`${id}-sources`)?.focus()\n      return\n    }\n    void connect(selected)\n  }\n\n  function cancelPendingConnection() {\n    attempt.current += 1\n  }\n\n  function backToSources() {\n    cancelPendingConnection()\n    setStatus({ state: 'picking' })\n  }\n\n  const announcement =\n    status.state === 'connecting'\n      ? `Connecting to ${source?.name}`\n      : status.state === 'connected'\n        ? `${source?.name} is connected`\n        : status.state === 'failed'\n          ? `Couldn't connect to ${source?.name}`\n          : ''\n\n  return (\n    <BlockStateProvider errorMessage={errorMessage} state={blockState}>\n      <section className='@container flex flex-col gap-4'>\n        <header className='flex flex-col gap-0.5'>\n          <h2 id={`${id}-title`} className='font-semibold tracking-tight'>\n            Connect a data source\n          </h2>\n          <BlockReady className='text-sm'>\n            <p className='text-muted-foreground text-sm'>\n              Pick one of {sources.length} sources to start. You can add more later.\n            </p>\n          </BlockReady>\n        </header>\n        <p role='status' className='sr-only'>\n          {announcement}\n        </p>\n        {status.state === 'picking' ? (\n          <form\n            method='post'\n            noValidate\n            onSubmit={onSubmit}\n            className='flex flex-col gap-4'\n          >\n            <div className='flex flex-col gap-4'>\n              <div className='flex flex-col gap-2 @md:flex-row'>\n                <InputGroup className='@md:flex-1'>\n                  <InputGroupAddon>\n                    <IconPlaceholder\n                      lucide='SearchIcon'\n                      tabler='IconSearch'\n                      hugeicons='SearchIcon'\n                      phosphor='MagnifyingGlassIcon'\n                      remixicon='RiSearchLine'\n                    />\n                  </InputGroupAddon>\n                  <InputGroupInput\n                    id={`${id}-search`}\n                    type='search'\n                    aria-label='Search sources'\n                    aria-controls={`${id}-results`}\n                    placeholder='Search sources'\n                    disabled={blockState !== undefined}\n                    value={query}\n                    onChange={(event) => setQuery(event.target.value)}\n                  />\n                </InputGroup>\n                <OptionSelect\n                  aria-label='Category'\n                  className='w-full @md:w-44'\n                  disabled={blockState !== undefined}\n                  value={category || 'all'}\n                  options={[\n                    { label: 'All categories', value: 'all' },\n                    ...categories.map((item) => ({ label: item, value: item })),\n                  ]}\n                  onValueChange={(value) => setCategory(value === 'all' ? '' : value)}\n                />\n              </div>\n              <p role='status' className='sr-only'>\n                {blockState\n                  ? ''\n                  : visible.length === 1\n                    ? '1 source'\n                    : `${visible.length} sources`}\n              </p>\n              <div id={`${id}-results`}>\n                {blockState ? (\n                  <BlockStateRows className='border-t' rows={6} />\n                ) : visible.length > 0 ? (\n                  <ChoiceCards\n                    id={`${id}-sources`}\n                    aria-labelledby={`${id}-title`}\n                    aria-invalid={error ? true : undefined}\n                    aria-describedby={error ? `${id}-error` : undefined}\n                    className='@lg:grid-cols-2 @3xl:grid-cols-3'\n                    options={visible.map(toOption)}\n                    value={selected}\n                    onValueChange={(value) => {\n                      setSelected(value)\n                      setError(undefined)\n                    }}\n                  />\n                ) : (\n                  <BlockMessage\n                    className='rounded-lg border border-dashed'\n                    icon={\n                      <IconPlaceholder\n                        lucide='SearchXIcon'\n                        tabler='IconZoomCancel'\n                        hugeicons='SearchRemoveIcon'\n                        phosphor='MagnifyingGlassMinusIcon'\n                        remixicon='RiSearchLine'\n                      />\n                    }\n                    title='No sources match'\n                    description='Check the spelling or try another category.'\n                    action={\n                      <Button\n                        type='button'\n                        variant='outline'\n                        size='sm'\n                        onClick={() => {\n                          setQuery('')\n                          setCategory('')\n                          document.getElementById(`${id}-search`)?.focus()\n                        }}\n                      >\n                        Clear filters\n                      </Button>\n                    }\n                  />\n                )}\n              </div>\n              <FieldError id={`${id}-error`}>{error}</FieldError>\n            </div>\n            <div className='flex flex-col items-stretch gap-3 border-t pt-4 @md:flex-row @md:items-center @md:justify-between'>\n              <p className='text-muted-foreground text-sm'>\n                Can&apos;t find yours?{' '}\n                <Link\n                  href={requestHref}\n                  className='text-foreground font-medium underline underline-offset-4'\n                >\n                  Request a source\n                </Link>\n              </p>\n              <Button type='submit' disabled={blockState !== undefined}>\n                {source ? `Connect ${source.name}` : 'Connect'}\n              </Button>\n            </div>\n          </form>\n        ) : (\n          <div className='border-t pt-4'>\n            <div ref={messageRef} tabIndex={-1} className='outline-none'>\n              {status.state === 'connecting' && (\n                <BlockMessage\n                  icon={\n                    <IconPlaceholder\n                      lucide='LoaderCircleIcon'\n                      tabler='IconLoader2'\n                      hugeicons='Loading03Icon'\n                      phosphor='CircleNotchIcon'\n                      remixicon='RiLoader4Line'\n                      className='animate-spin motion-reduce:animate-none'\n                    />\n                  }\n                  title={`Connecting to ${source?.name}…`}\n                  description='Approve access in the window that opened. It usually takes less than a minute.'\n                  action={\n                    <Button variant='ghost' size='sm' onClick={backToSources}>\n                      Cancel\n                    </Button>\n                  }\n                />\n              )}\n              {status.state === 'connected' && (\n                <BlockMessage\n                  icon={\n                    <IconPlaceholder\n                      lucide='CircleCheckIcon'\n                      tabler='IconCircleCheck'\n                      hugeicons='CheckmarkCircle02Icon'\n                      phosphor='CheckCircleIcon'\n                      remixicon='RiCheckboxCircleLine'\n                      className='text-emerald-700 dark:text-emerald-400'\n                    />\n                  }\n                  title={`${source?.name} is connected`}\n                  description=\"We're importing the last 90 days. Your first dashboard will be ready in a few minutes.\"\n                  action={\n                    <div className='flex flex-wrap justify-center gap-2'>\n                      <Button onClick={() => onContinue?.(status.id)}>Continue</Button>\n                      <Button variant='outline' onClick={backToSources}>\n                        <IconPlaceholder\n                          lucide='PlugIcon'\n                          tabler='IconPlugConnected'\n                          hugeicons='Plug01Icon'\n                          phosphor='PlugsConnectedIcon'\n                          remixicon='RiPlugLine'\n                          data-icon='inline-start'\n                        />\n                        Connect another\n                      </Button>\n                    </div>\n                  }\n                />\n              )}\n              {status.state === 'failed' && (\n                <BlockMessage\n                  tone='error'\n                  icon={\n                    <IconPlaceholder\n                      lucide='TriangleAlertIcon'\n                      tabler='IconAlertTriangle'\n                      hugeicons='Alert02Icon'\n                      phosphor='WarningIcon'\n                      remixicon='RiErrorWarningLine'\n                    />\n                  }\n                  title={`Couldn't connect to ${source?.name}`}\n                  description={status.message}\n                  action={\n                    <div className='flex flex-wrap justify-center gap-2'>\n                      <Button onClick={() => void connect(status.id)}>\n                        <IconPlaceholder\n                          lucide='RefreshCwIcon'\n                          tabler='IconRefresh'\n                          hugeicons='RefreshIcon'\n                          phosphor='ArrowClockwiseIcon'\n                          remixicon='RiRefreshLine'\n                          data-icon='inline-start'\n                        />\n                        Try again\n                      </Button>\n                      <Button variant='outline' onClick={backToSources}>\n                        Pick another source\n                      </Button>\n                    </div>\n                  }\n                />\n              )}\n            </div>\n          </div>\n        )}\n      </section>\n    </BlockStateProvider>\n  )\n}\n\nexport { Onboarding3, exampleProps as onboarding3ExampleProps, type Onboarding3Props }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/onboarding/onboarding-03.tsx"
    }
  ],
  "meta": {
    "shows": "A searchable, filterable list of data sources to pick from, then follow through connecting to connected, with an error state.",
    "size": "full",
    "usedWith": [
      "onboarding-04",
      "checklist-01"
    ],
    "component": "Onboarding3",
    "props": "{ onConnect?: (id: string) => Promise<void>; onContinue?: (id: string) => void; requestHref: string; sources?: { category: string; description: string; id: string; logo?: ReactNode; name: string; popular?: boolean }[]; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:component"
}
