Skip to content

The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.

2.6 KB
Raw Blame
'use client'

import { usePathname, useRouter } from 'next/navigation'
import { Select, SelectContent, SelectGroup, SelectItem, SelectTrigger, SelectValue } from 'ui'

import { componentPages, frameworkTitles, oauthBlocks } from '@/config/docs'
import { useFramework } from '@/context/framework-context'

const frameworks = Object.keys(frameworkTitles)

export function FrameworkSelector() {
  const pathname = usePathname()

  // Extract framework and docTitle from pathname
  // Example: /ui/docs/nextjs/password-based-auth
  const pathParts = pathname.split('/')
  const docTitle = pathParts[pathParts.length - 1]
  const framework = pathParts[pathParts.length - 2]

  const router = useRouter()
  const { setFramework: setPreferredFramework } = useFramework()
  const selectedFramework = frameworks.includes(framework) ? framework : 'nextjs'

  if (!framework) {
    return null
  }

  // Get the supported frameworks for this component
  const componentItem = [...componentPages.items, ...oauthBlocks.items].find(
    (item) => item.href?.split('/').pop() === docTitle.toLowerCase()
  )
  // Use the supportedFrameworks property if it exists, otherwise default to all frameworks
  const supportedFrameworks = componentItem?.supportedFrameworks

  if (!supportedFrameworks) {
    return null
  }

  // Don't show selector if component only supports one framework
  if (supportedFrameworks && supportedFrameworks.length <= 1) {
    return null
  }

  const onSelect = (value: string) => {
    // Get current path parts
    const currentPathParts = [...pathParts]
    // Replace the framework part (second to last) with the new framework
    currentPathParts[currentPathParts.length - 2] = value
    // Build the new path
    const newPath = currentPathParts.join('/')

    router.push(newPath)

    // Also update the context/localStorage for future use
    setPreferredFramework(value as keyof typeof frameworkTitles)
  }

  const options =
    supportedFrameworks?.map((f) => ({
      label: frameworkTitles[f],
      value: f,
    })) || []

  return (
    <Select value={selectedFramework} onValueChange={onSelect}>
      <SelectTrigger
        aria-label="Framework"
        className="h-7 w-auto min-w-28 gap-2 rounded-md bg-surface-75 px-2 text-xs"
      >
        <SelectValue>{frameworkTitles[selectedFramework]}</SelectValue>
      </SelectTrigger>
      <SelectContent>
        <SelectGroup>
          {options.map((f) => (
            <SelectItem key={f.value} value={f.value}>
              {f.label}
            </SelectItem>
          ))}
        </SelectGroup>
      </SelectContent>
    </Select>
  )
}