The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat: replace docs command menu with v2 (#28048)
Charise3e8cd943c65
diff --git a/apps/docs/components/Navigation/Navigation.commands.tsx b/apps/docs/components/Navigation/Navigation.commands.tsxnew file mode 100644index 00000000000..77080e7fd30--- /dev/null+++ b/apps/docs/components/Navigation/Navigation.commands.tsx@@ -0,0 +1,153 @@+import { ArrowRight } from 'lucide-react'++import type { ICommand } from 'ui-patterns/CommandMenu'+import { useRegisterCommands } from 'ui-patterns/CommandMenu'++const navCommands = [+ {+ id: 'nav-getting-started',+ name: 'Go to Getting Started',+ route: '/guides/getting-started',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-database',+ name: 'Go to Database',+ route: '/guides/database/overview',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-auth',+ name: 'Go to Auth',+ route: '/guides/auth',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-storage',+ name: 'Go to Storage',+ route: '/guides/storage',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-functions',+ name: 'Go to Functions',+ route: '/guides/functions',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-realtime',+ name: 'Go to Realtime',+ route: '/guides/realtime',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-ai',+ name: 'Go to AI & Vectors',+ route: '/guides/ai',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-rest',+ name: 'Go to REST API',+ route: '/guides/api',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-graphql',+ name: 'Go to GraphQL',+ route: '/guides/graphql',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-local-cli',+ name: 'Go to Local Dev / CLI',+ route: '/guides/cli',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-platform',+ name: 'Go to Platform',+ route: '/guides/platform',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-self-hosting',+ name: 'Go to Self-Hosting',+ route: '/guides/self-hosting',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-ref-javascript',+ name: 'Go to JavaScript reference',+ value: 'Reference, API, SDK: Go to JavaScript reference (JS)',+ route: '/reference/javascript/introduction',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-ref-dart',+ name: 'Go to Dart reference',+ value: 'Reference, API, SDK: Go to Dart reference (Flutter)',+ route: '/reference/dart/introduction',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-ref-python',+ name: 'Go to Python reference',+ value: 'Reference, API, SDK: Go to Python reference',+ route: '/reference/python/introduction',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-ref-csharp',+ name: 'Go to C# reference',+ value: 'Reference, API, SDK: Go to C# reference',+ route: '/reference/csharp/introduction',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-ref-swift',+ name: 'Go to Swift reference',+ value: 'Reference, API, SDK: Go to Swift reference',+ route: '/reference/swift/introduction',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-ref-kotlin',+ name: 'Go to Kotlin reference',+ value: 'Reference, API, SDK: Go to Kotlin reference',+ route: '/reference/kotlin/introduction',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-ref-cli',+ name: 'Go to CLI reference',+ value: 'Reference, API, SDK: Go to CLI reference',+ route: '/reference/cli/introduction',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-ref-api',+ name: 'Go to Management API reference',+ value: 'Reference, API, SDK: Go to Management API reference',+ route: '/reference/api/introduction',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-resources',+ name: 'Go to Guides & Examples',+ route: '/guides/resources',+ icon: () => <ArrowRight />,+ },+ {+ id: 'nav-integrations',+ name: 'Go to Integrations',+ route: 'https://supabase.com/partners/integrations',+ icon: () => <ArrowRight />,+ },+] satisfies ICommand[]++const useDocsNavCommands = () => {+ useRegisterCommands('Go to', navCommands)+}++export { useDocsNavCommands }diff --git a/apps/docs/components/Navigation/NavigationMenu/TopNavBar.tsx b/apps/docs/components/Navigation/NavigationMenu/TopNavBar.tsxindex 0b72eeb9e57..6b9c1a73ab3 100644--- a/apps/docs/components/Navigation/NavigationMenu/TopNavBar.tsx+++ b/apps/docs/components/Navigation/NavigationMenu/TopNavBar.tsx@@ -1,13 +1,13 @@-import { FC, memo, useState } from 'react'-import Link from 'next/link'+import { Command, Search, Menu } from 'lucide-react'import dynamic from 'next/dynamic'+import Image from 'next/image'+import Link from 'next/link'+import type { FC } from 'react'+import { memo, useState } from 'react'import { useIsLoggedIn, useIsUserLoading } from 'common'-import { SearchButton } from 'ui-patterns/Cmdk'import { Button, buttonVariants, cn } from 'ui'-import { Command, Search, Menu } from 'lucide-react'--import Image from 'next/image'+import { CommandMenuTrigger, useSetCommandMenuOpen } from 'ui-patterns/CommandMenu'import GlobalNavigationMenu from './GlobalNavigationMenu'const GlobalMobileMenu = dynamic(() => import('./GlobalMobileMenu'))@@ -17,6 +17,7 @@ const TopNavBar: FC = () => {const isLoggedIn = useIsLoggedIn()const isUserLoading = useIsUserLoading()const [mobileMenuOpen, setMobileMenuOpen] = useState(false)+ const setCommandMenuOpen = useSetCommandMenuOpen()return (<>@@ -35,26 +36,18 @@ const TopNavBar: FC = () => {</div><div className="flex gap-2 items-center">- <SearchButton- className="flex-grow md:w-44 xl:w-56 h-[30px]- focus-visible:!outline-4- focus-visible:outline-offset-1- focus-visible:outline-brand-600"- >- <div- className="- flex- group- items-center- justify-between- bg-surface-100/75- hover:bg-opacity-100- hover:border-strong- border- transition- pl-1.5 md:pl-2 pr-1 w-full h-full rounded-md- text-foreground-lighter- "+ <CommandMenuTrigger>+ <button+ className={cn(+ 'group',+ 'flex-grow md:w-44 xl:w-56 h-[30px] rounded-md',+ 'pl-1.5 md:pl-2 pr-1',+ 'flex items-center justify-between',+ 'bg-surface-100/75 text-foreground-lighter border',+ 'hover:bg-opacity-100 hover:border-strong',+ 'focus-visible:!outline-4 focus-visible:outline-offset-1 focus-visible:outline-brand-600',+ 'transition'+ )}><div className="flex items-center space-x-2 text-foreground-muted"><Search size={18} strokeWidth={2} />@@ -71,8 +64,8 @@ const TopNavBar: FC = () => {<span className="text-[12px]">K</span></div></div>- </div>- </SearchButton>+ </button>+ </CommandMenuTrigger><buttontitle="Menu dropdown button"className={cn(diff --git a/apps/docs/features/app.providers.tsx b/apps/docs/features/app.providers.tsxindex 51e4b0cabe7..ccf1b127bec 100644--- a/apps/docs/features/app.providers.tsx+++ b/apps/docs/features/app.providers.tsx@@ -1,4 +1,4 @@-import { CommandMenuProvider } from '@ui-patterns/Cmdk'+import { CommandProvider } from '@ui-patterns/CommandMenu'import { ThemeProvider } from 'common'import { PortalToast } from 'ui'import { PromoToast } from 'ui-patterns'@@ -6,6 +6,7 @@ import { type PropsWithChildren } from 'react'import SiteLayout from '~/layouts/SiteLayout'import { AuthContainer } from './auth/auth.client'+import { DocsCommandMenu } from './command'import { QueryClientProvider } from './data/queryClient.client'import { ShortcutPreviewBuild } from './envs/staging.client'import { PageTelemetry } from './telemetry/telemetry.client'@@ -23,16 +24,17 @@ function GlobalProviders({ children }: PropsWithChildren) {<PageTelemetry /><ScrollRestoration /><ThemeProvider defaultTheme="system" enableSystem disableTransitionOnChange>- <CommandMenuProvider site="docs">+ <CommandProvider><div className="flex flex-col"><SiteLayout><PortalToast /><PromoToast />{children}+ <DocsCommandMenu /></SiteLayout><ThemeSandbox /></div>- </CommandMenuProvider>+ </CommandProvider></ThemeProvider></AuthContainer></QueryClientProvider>diff --git a/apps/docs/features/command/CommandMenu.tsx b/apps/docs/features/command/CommandMenu.tsxnew file mode 100644index 00000000000..e671cd76379--- /dev/null+++ b/apps/docs/features/command/CommandMenu.tsx@@ -0,0 +1,39 @@+import {+ Breadcrumb,+ CommandHeader,+ CommandInput,+ CommandList,+ CommandMenu,+} from 'ui-patterns/CommandMenu'+import { useChangelogCommand } from 'ui-patterns/CommandMenu/prepackaged/Changelog'+import { useDocsAiCommands } from 'ui-patterns/CommandMenu/prepackaged/DocsAi'+import { useDocsSearchCommands } from 'ui-patterns/CommandMenu/prepackaged/DocsSearch'+import { useSupportCommands } from 'ui-patterns/CommandMenu/prepackaged/Support'+import { useThemeSwitcherCommands } from 'ui-patterns/CommandMenu/prepackaged/ThemeSwitcher'++import { useQuickstartCommands } from './Quickstarts'+import { useDocsNavCommands } from '../../components/Navigation/Navigation.commands'++const DocsCommandMenu = () => {+ useDocsSearchCommands({+ modify: (command) => ({ ...command, forceMount: true }),+ options: { forceMountSection: true },+ })+ useDocsAiCommands({ modify: (command) => ({ ...command, forceMount: true }) })+ useDocsNavCommands()+ useQuickstartCommands()+ useSupportCommands()+ useChangelogCommand()+ useThemeSwitcherCommands()++ return (+ <CommandMenu>+ <CommandHeader>+ <CommandInput />+ </CommandHeader>+ <CommandList />+ </CommandMenu>+ )+}++export { DocsCommandMenu as default }diff --git a/apps/docs/features/command/Quickstarts.tsx b/apps/docs/features/command/Quickstarts.tsxnew file mode 100644index 00000000000..15cfa1812af--- /dev/null+++ b/apps/docs/features/command/Quickstarts.tsx@@ -0,0 +1,58 @@+import { ArrowRight } from 'lucide-react'+import { useRegisterCommands } from 'ui-patterns/CommandMenu'++interface Quickstart {+ label: string+ url: `/${string}`+}++const quickstarts = [+ {+ label: 'React',+ url: '/guides/getting-started/quickstarts/reactjs',+ },+ {+ label: 'Next.js',+ url: '/guides/getting-started/quickstarts/nextjs',+ },+ {+ label: 'Nuxt.js',+ url: '/guides/getting-started/quickstarts/nuxtjs',+ },+ {+ label: 'Flutter',+ url: '/guides/getting-started/quickstarts/flutter',+ },+ {+ label: 'Kotlin',+ url: '/guides/getting-started/quickstarts/android',+ },+ {+ label: 'SvelteKit',+ url: '/guides/getting-started/quickstarts/sveltekit',+ },+ {+ label: 'SolidJS',+ url: '/guides/getting-started/quickstarts/solidjs',+ },+ {+ label: 'Vue',+ url: '/guides/getting-started/quickstarts/vue',+ },+] as Quickstart[]++const useQuickstartCommands = () => {+ useRegisterCommands(+ 'Quick starts',+ quickstarts.map(({ label, url }) => ({+ id: label,+ name: `Get started with ${label}`,+ route: url,+ defaultHidden: true,+ value: `Quick starts: Get started with ${label}`,+ icon: () => <ArrowRight />,+ }))+ )+}++export { useQuickstartCommands }diff --git a/apps/docs/features/command/index.tsx b/apps/docs/features/command/index.tsxnew file mode 100644index 00000000000..198bba2b8ee--- /dev/null+++ b/apps/docs/features/command/index.tsx@@ -0,0 +1,14 @@+'use client'++import dynamic from 'next/dynamic'++import { useCommandMenuInitiated } from 'ui-patterns/CommandMenu'++const LazyCommandMenu = dynamic(() => import('./CommandMenu'), { ssr: false })++const DocsCommandMenu = () => {+ const isInitiated = useCommandMenuInitiated()+ return isInitiated && <LazyCommandMenu />+}++export { DocsCommandMenu }diff --git a/packages/ui-patterns/CommandMenu/api/CommandHeader.tsx b/packages/ui-patterns/CommandMenu/api/CommandHeader.tsxnew file mode 100644index 00000000000..7584675bcf0--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/CommandHeader.tsx@@ -0,0 +1,13 @@+import type { PropsWithChildren } from 'react'++import { useCommandMenuTouchGestures } from './hooks/viewHooks'++export function CommandHeader({ children }: PropsWithChildren) {+ const { handleTouchStart, handleTouchMove, handleTouchEnd } = useCommandMenuTouchGestures()++ return (+ <div onTouchStart={handleTouchStart} onTouchMove={handleTouchMove} onTouchEnd={handleTouchEnd}>+ {children}+ </div>+ )+}diff --git a/packages/ui-patterns/CommandMenu/api/CommandInput.tsx b/packages/ui-patterns/CommandMenu/api/CommandInput.tsxindex 80a0890c5df..fb0589bc5c0 100644--- a/packages/ui-patterns/CommandMenu/api/CommandInput.tsx+++ b/packages/ui-patterns/CommandMenu/api/CommandInput.tsx@@ -1,35 +1,65 @@'use client'-import { forwardRef } from 'react'+import React, { forwardRef, useEffect, useRef } from 'react'+import { useBreakpoint } from 'common'import { CommandInput_Shadcn_, cn } from 'ui'import { useQuery, useSetQuery } from './hooks/queryHooks'-import { useCommandMenuTouchGestures } from './hooks/viewHooks'++function useFocusInputOnWiderScreens(ref: React.ForwardedRef<HTMLInputElement>) {+ const isBelowSm = useBreakpoint('sm')+ const isBelowSmSynchronous = useRef(isBelowSm)+ isBelowSmSynchronous.current = isBelowSm++ const internalRef = useRef<HTMLInputElement>()+ const combinedRef = (element: HTMLInputElement) => {+ if (ref instanceof Function) {+ ref(element)+ } else if (!!ref) {+ ref.current = element+ }+ internalRef.current = element+ }++ useEffect(() => {+ // This will always be false in the first iteration (since isBelowSm+ // switches from false -> true on narrow screens). To avoid a preemptive+ // focus, we need to delay this. But then we need to access the current+ // value of isBelowSm, not the stale value, which explains the business+ // with syncing state into a ref above.+ setTimeout(() => {+ if (!isBelowSmSynchronous.current) {+ internalRef.current?.focus()+ }+ })+ }, [])++ return combinedRef+}const CommandInput = forwardRef<React.ElementRef<typeof CommandInput_Shadcn_>,React.ComponentPropsWithoutRef<typeof CommandInput_Shadcn_>>(({ className, ...props }, ref) => {+ const inputRef = useFocusInputOnWiderScreens(ref)+const query = useQuery()const setQuery = useSetQuery()- const { handleTouchStart, handleTouchMove, handleTouchEnd } = useCommandMenuTouchGestures()-return (<CommandInput_Shadcn_- autoFocus- ref={ref}+ // Focus needs to be manually handled to check breakpoint first, due to+ // delays from useEffect+ autoFocus={false}+ ref={inputRef}value={query}onValueChange={setQuery}placeholder="Type a command or search..."- onTouchStart={handleTouchStart}- onTouchMove={handleTouchMove}- onTouchEnd={handleTouchEnd}className={cn('flex h-11 w-full rounded-md bg-transparent px-4 py-7 outline-none','focus:shadow-none focus:ring-transparent',- 'text-foreground-light placeholder:text-foreground-muted disabled:cursor-not-allowed disabled:opacity-50 border-0',+ 'text-base text-foreground-light placeholder:text-foreground-muted disabled:cursor-not-allowed disabled:opacity-50 border-0',className)}{...props}diff --git a/packages/ui-patterns/CommandMenu/api/CommandList.tsx b/packages/ui-patterns/CommandMenu/api/CommandList.tsxindex 12c11f0bac8..61937144171 100644--- a/packages/ui-patterns/CommandMenu/api/CommandList.tsx+++ b/packages/ui-patterns/CommandMenu/api/CommandList.tsx@@ -29,7 +29,7 @@ const CommandList = forwardRef<return (<CommandList_Shadcn_ref={setRef}- className={cn('overflow-y-auto overflow-x-hidden bg-transparent', className)}+ className={cn('max-h-[initial] overflow-y-auto overflow-x-hidden bg-transparent', className)}{...props}><CommandEmpty listRef={innerRef}>No results found.</CommandEmpty>diff --git a/packages/ui-patterns/CommandMenu/api/CommandMenu.tsx b/packages/ui-patterns/CommandMenu/api/CommandMenu.tsxindex 3184889ae8e..ea7c045b9d8 100644--- a/packages/ui-patterns/CommandMenu/api/CommandMenu.tsx+++ b/packages/ui-patterns/CommandMenu/api/CommandMenu.tsx@@ -1,12 +1,13 @@'use client'import { AlertTriangle, ArrowLeft } from 'lucide-react'-import { type PropsWithChildren, type ReactNode, forwardRef, memo, useEffect, useMemo } from 'react'+import type { HTMLAttributes, MouseEvent, PropsWithChildren, ReactElement, ReactNode } from 'react'+import { Children, cloneElement, forwardRef, isValidElement, useEffect, useMemo } from 'react'import { ErrorBoundary } from 'react-error-boundary'import { useBreakpoint } from 'common'import useDragToClose from 'common/hooks/useDragToClose'-import { Button, Command_Shadcn_, Dialog, DialogContent, DialogTrigger, cn } from 'ui'+import { Button, Command_Shadcn_, Dialog, DialogContent, cn } from 'ui'import { useCurrentPage, usePageComponent, usePopPage } from './hooks/pagesHooks'import { useQuery, useSetQuery } from './hooks/queryHooks'@@ -16,7 +17,6 @@ import {useSetCommandMenuOpen,useSetupCommandMenuTouchEvents,} from './hooks/viewHooks'-import { PageType } from './utils'function Breadcrumb({ className }: { className?: string }) {const currPage = useCurrentPage()@@ -25,14 +25,16 @@ function Breadcrumb({ className }: { className?: string }) {if (!currPage) returnreturn (- <div- className={cn('flex items-center gap-2 mt-2 ml-2 text-xs text-foreground-muted', className)}+ <button+ className={cn(+ 'p-2 bg-overlay flex items-center gap-2 text-xs text-foreground-muted',+ className+ )}+ onClick={popPage}>- <button onClick={popPage}>- <ArrowLeft width={12} height={12} />- </button>+ <ArrowLeft width={12} height={12} />{currPage.name}- </div>+ </button>)}@@ -40,8 +42,6 @@ const CommandWrapper = forwardRef<React.ElementRef<typeof Command_Shadcn_>,React.ComponentPropsWithoutRef<typeof Command_Shadcn_>>(({ children, className, ...props }, ref) => {- const currPage = useCurrentPage()-return (<Command_Shadcn_ref={ref}@@ -59,7 +59,6 @@ const CommandWrapper = forwardRef<)}{...props}>- {currPage?.type === PageType.Commands && <Breadcrumb />}{children}</Command_Shadcn_>)@@ -106,7 +105,43 @@ function useTouchGestures({ toggleOpen }: { toggleOpen: () => void }) {return { ref }}-const CommandMenuTrigger = memo(DialogTrigger)+function CommandMenuTrigger({ children }: PropsWithChildren) {+ const open = useCommandMenuOpen()+ const setOpen = useSetCommandMenuOpen()++ const childFromProps = Children.only(children) as ReactElement<+ {+ onClick?: (event: MouseEvent) => void+ onOpen?: (open: boolean) => void+ } & HTMLAttributes<HTMLElement>+ >+ if (!childFromProps || !isValidElement(childFromProps)) return null++ const handleOpen = () => {+ setOpen(!open)+ childFromProps.props.onOpen?.(!open)+ }++ const childWithClickHandler = cloneElement(childFromProps, {+ onClick: handleOpen,+ 'aria-haspopup': 'dialog',+ 'aria-expanded': open,+ 'aria-controls': 'command-menu-dialog-content',+ className: cn(+ 'h-10 px-4 py-2',+ 'inline-flex items-center justify-center',+ 'whitespace-nowrap',+ 'rounded-md border border-input bg-background',+ 'text-sm font-medium',+ 'hover:bg-accent hover:text-accent-foreground',+ 'ring-offset-background focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring focus-visible:ring-offset-2',+ 'disabled:pointer-events-none disabled:opacity-50',+ 'transition-colors',+ childFromProps.props.className+ ),+ })+ return childWithClickHandler+}interface CommandMenuProps extends PropsWithChildren {trigger?: ReactNode@@ -116,7 +151,7 @@ function CommandMenu({ children, trigger }: CommandMenuProps) {const open = useCommandMenuOpen()const setOpen = useSetCommandMenuOpen()- const isMobile = useBreakpoint()+ const isMobile = useBreakpoint('sm')const size = useCommandMenuSize()@@ -132,6 +167,7 @@ function CommandMenu({ children, trigger }: CommandMenuProps) {<Dialog open={open} onOpenChange={setOpen}>{trigger}<DialogContent+ id="command-menu-dialog-content"hideCloseforceMountref={contentRef}@@ -143,15 +179,16 @@ function CommandMenu({ children, trigger }: CommandMenuProps) {}}size={size}className={cn(- 'relative my-0 mx-auto rounded-t-lg overflow-y-scroll',+ 'relative flex flex-col my-0 mx-auto rounded-t-lg overflow-y-scroll','h-[85dvh] mt-[15vh] md:max-h-[500px] md:mt-0 left-0 bottom-0 md:bottom-auto',- 'place-self-end md:place-self-auto',- open && '!animate-in !slide-in-from-bottom !duration-300',+ '!animate-in !slide-in-from-bottom-[85%] !duration-300','data-[state=closed]:!animate-out data-[state=closed]:!slide-out-to-bottom',- 'md:data-[state=open]:!animate-in md:data-[state=closed]:!animate-out',- 'md:data-[state=closed]:!zoom-out-95 md:data-[state=open]:!zoom-in-95',- 'md:data-[state=closed]:!slide-out-to-left-[0%] md:data-[state=closed]:!slide-out-to-top-[0%]',- 'md:data-[state=open]:!slide-in-from-left-[0%] md:data-[state=open]:!slide-in-from-top-[0%]'+ // Remove defaults set from primitive component+ '!slide-in-from-left-[0%] :!slide-in-from-top-[0%]',+ // Remove defaults set from primitive component+ '!slide-out-to-left-[0%] !slide-out-to-top-[0%]',+ 'md:data-[state=open]:!slide-in-from-bottom-[0%] md:data-[state=closed]:!slide-out-to-bottom-[0%]',+ 'md:data-[state=open]:!zoom-in-95 md:data-[state=closed]:!zoom-out-95')}dialogOverlayProps={{className: cn('overflow-hidden flex data-closed:delay-100'),diff --git a/packages/ui-patterns/CommandMenu/api/CommandProvider.tsx b/packages/ui-patterns/CommandMenu/api/CommandProvider.tsxindex 10f1f8edad9..6eb8fc5bf02 100644--- a/packages/ui-patterns/CommandMenu/api/CommandProvider.tsx+++ b/packages/ui-patterns/CommandMenu/api/CommandProvider.tsx@@ -1,14 +1,16 @@'use client'-import { useConstant } from 'common'+import { useRouter as useLegacyRouter } from 'next/compat/router'import { type PropsWithChildren, useEffect, useMemo, useCallback } from 'react'+import { useConstant } from 'common'+import { CommandContext } from '../internal/Context'import { initCommandsState } from '../internal/state/commandsState'import { initPagesState } from '../internal/state/pagesState'import { initQueryState } from '../internal/state/queryState'import { initViewState } from '../internal/state/viewState'-import { useCrossCompatRouter } from './hooks/useCrossCompatRouter'+import { CrossCompatRouterContext } from './hooks/useCrossCompatRouter'import { useSetCommandMenuOpen, useToggleCommandMenu } from './hooks/viewHooks'const CommandProviderInternal = ({ children }: PropsWithChildren) => {@@ -44,21 +46,33 @@ const CommandShortcut = ({ openKey }: { openKey: string }) => {return null}-// This is a component not a hook so it can access the wrapping context.-function CloseOnNavigation() {+function CloseOnNavigation({ children }: PropsWithChildren) {const setIsOpen = useSetCommandMenuOpen()- const router = useCrossCompatRouter()++ const legacyRouter = useLegacyRouter()+ const isUsingLegacyRouting = !!legacyRouterconst completeNavigation = useCallback(() => {setIsOpen(false)}, [setIsOpen])+ const ctx = useMemo(+ () => ({+ onPendingEnd: new Set([completeNavigation]),+ }),+ [completeNavigation]+ )+useEffect(() => {- router.events.onRouteChangeComplete(completeNavigation)- return () => router.events.offRouteChangeComplete(completeNavigation)- }, [router])+ if (!isUsingLegacyRouting) return- return null+ legacyRouter.events.on('routeChangeComplete', completeNavigation)+ return () => legacyRouter.events.off('routeChangeComplete', completeNavigation)+ }, [isUsingLegacyRouting, legacyRouter])++ return (+ <CrossCompatRouterContext.Provider value={ctx}>{children}</CrossCompatRouterContext.Provider>+ )}interface CommandProviderProps extends PropsWithChildren {@@ -74,8 +88,7 @@ interface CommandProviderProps extends PropsWithChildren {const CommandProvider = ({ children, openKey }: CommandProviderProps) => (<CommandProviderInternal><CommandShortcut openKey={openKey ?? 'k'} />- <CloseOnNavigation />- {children}+ <CloseOnNavigation>{children}</CloseOnNavigation></CommandProviderInternal>)diff --git a/packages/ui-patterns/CommandMenu/api/hooks/useCrossCompatRouter.ts b/packages/ui-patterns/CommandMenu/api/hooks/useCrossCompatRouter.tsdeleted file mode 100644index dec64423056..00000000000--- a/packages/ui-patterns/CommandMenu/api/hooks/useCrossCompatRouter.ts+++ /dev/null@@ -1,67 +0,0 @@-'use client'--import { useRouter as useLegacyRouter } from 'next/compat/router'-import { useRouter as useNextRouter } from 'next/navigation'-import { useEffect, useMemo, useRef, useTransition } from 'react'-import { usePrevious } from 'react-use'--type Handler = (...evts: any[]) => void--function useHasChanged<T>(value: T, { onlyTo }: { onlyTo?: T } = {}) {- const prev = usePrevious(value)-- if (prev === value) return false- if (onlyTo && value !== onlyTo) return false-- return true-}--function useCrossCompatRouter() {- const legacyRouter = useLegacyRouter()- const newRouter = useNextRouter()- const isUsingLegacyRouting = !!legacyRouter-- const [isPending, startTransition] = useTransition()- const hasPendingEnded = useHasChanged(isPending, { onlyTo: false })- const onPendingEnd = useRef(new Set<() => void>())- useEffect(() => {- if (!isUsingLegacyRouting && hasPendingEnded) {- onPendingEnd.current.forEach((fn) => fn())- }- }, [hasPendingEnded, isUsingLegacyRouting])-- const api = useMemo(- () => ({- events: {- onRouteChangeComplete: (fn: Handler) => {- if (isUsingLegacyRouting) {- legacyRouter.events.on('routeChangeComplete', fn)- } else {- onPendingEnd.current.add(fn)- }- },- offRouteChangeComplete: (fn: Handler) => {- if (isUsingLegacyRouting) {- legacyRouter.events.off('routeChangeComplete', fn)- } else {- onPendingEnd.current.delete(fn)- }- },- },- push: (path: string) => {- if (isUsingLegacyRouting) {- legacyRouter.push(path)- } else {- startTransition(() => {- newRouter.push(path)- })- }- },- }),- []- )-- return api-}--export { useCrossCompatRouter }diff --git a/packages/ui-patterns/CommandMenu/api/hooks/useCrossCompatRouter.tsx b/packages/ui-patterns/CommandMenu/api/hooks/useCrossCompatRouter.tsxnew file mode 100644index 00000000000..499507790e5--- /dev/null+++ b/packages/ui-patterns/CommandMenu/api/hooks/useCrossCompatRouter.tsx@@ -0,0 +1,65 @@+'use client'++import { useRouter as useLegacyRouter } from 'next/compat/router'+import { useRouter as useNextRouter } from 'next/navigation'+import { createContext, useContext, useEffect, useMemo, useRef, useTransition } from 'react'++type Handler = (...evts: any[]) => void++export const CrossCompatRouterContext = createContext<{ onPendingEnd: Set<Handler> } | undefined>(+ undefined+)++function useCrossCompatRouterContext() {+ const ctx = useContext(CrossCompatRouterContext)+ if (!ctx) {+ throw Error(+ 'useCrossCompatRouterContext must be used within a CrossCompatRouterContext.Provider'+ )+ }+ return ctx+}++function useHasChanged<T>(value: T, { onlyTo }: { onlyTo?: T } = {}) {+ const prev = useRef(value)++ let result = true++ if (prev.current === value) result = false+ if (onlyTo && value !== onlyTo) result = false++ prev.current = value++ return result+}++export function useCrossCompatRouter() {+ const { onPendingEnd } = useCrossCompatRouterContext()++ const legacyRouter = useLegacyRouter()+ const newRouter = useNextRouter()+ const isUsingLegacyRouting = !!legacyRouter++ const [isPending, startTransition] = useTransition()+ const hasPendingEnded = useHasChanged(isPending, { onlyTo: false })+ if (!isUsingLegacyRouting && hasPendingEnded) {+ onPendingEnd.forEach((fn) => fn())+ }++ const api = useMemo(+ () => ({+ push: (path: string) => {+ if (isUsingLegacyRouting) {+ legacyRouter.push(path)+ } else {+ startTransition(() => {+ newRouter.push(path)+ })+ }+ },+ }),+ [isUsingLegacyRouting, legacyRouter, newRouter]+ )++ return api+}diff --git a/packages/ui-patterns/CommandMenu/index.tsx b/packages/ui-patterns/CommandMenu/index.tsxindex d3653d6baf3..26e24efdee0 100644--- a/packages/ui-patterns/CommandMenu/index.tsx+++ b/packages/ui-patterns/CommandMenu/index.tsx@@ -1,4 +1,5 @@export * from './api/Badges'+export { CommandHeader } from './api/CommandHeader'export { CommandInput } from './api/CommandInput'export { CommandList } from './api/CommandList'export { Breadcrumb, CommandMenu, CommandMenuTrigger, CommandWrapper } from './api/CommandMenu'@@ -7,6 +8,7 @@ export { TextHighlighter, TextHighlighterBase } from './api/TextHighlighter'export * from './api/hooks/commandsHooks'export * from './api/hooks/pagesHooks'export * from './api/hooks/queryHooks'+export { useCrossCompatRouter } from './api/hooks/useCrossCompatRouter'export { useHistoryKeys } from './api/hooks/useHistoryKeys'export * from './api/hooks/viewHooks'export * from './api/utils'diff --git a/packages/ui-patterns/CommandMenu/internal/Command.tsx b/packages/ui-patterns/CommandMenu/internal/Command.tsxindex 8c7712a22e0..e672e207f55 100644--- a/packages/ui-patterns/CommandMenu/internal/Command.tsx+++ b/packages/ui-patterns/CommandMenu/internal/Command.tsx@@ -103,7 +103,11 @@ const CommandItem = forwardRef<}: () => {}}- value={command.forceMount ? `${query} ${command.value}` : command.value}+ value={+ command.forceMount+ ? `${query} ${command.value ?? command.name}`+ : command.value ?? command.name+ }className={cn(generateCommandClassNames(isRouteCommand(command)),className,diff --git a/packages/ui-patterns/CommandMenu/prepackaged/Changelog.tsx b/packages/ui-patterns/CommandMenu/prepackaged/Changelog.tsxnew file mode 100644index 00000000000..5b8f56fe44b--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/Changelog.tsx@@ -0,0 +1,17 @@+import { Inbox } from 'lucide-react'++import { useRegisterCommands } from '..'+import { BASE_PATH } from './shared/constants'++const useChangelogCommand = () => {+ useRegisterCommands('Updates', [+ {+ id: 'changelog',+ name: 'Changelog',+ route: BASE_PATH ? 'https://supabase.com/changelog' : '/changelog',+ icon: () => <Inbox />,+ },+ ])+}++export { useChangelogCommand }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/DocsAiPage.tsx b/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/DocsAiPage.tsxnew file mode 100644index 00000000000..996d103b595--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/DocsAiPage.tsx@@ -0,0 +1,313 @@+'use client'++import { User } from 'lucide-react'+import { Fragment, useCallback, useEffect, useState } from 'react'+import ReactMarkdown from 'react-markdown'+import remarkGfm from 'remark-gfm'++import { useBreakpoint } from 'common'+import {+ AiIconAnimation,+ Button,+ CommandGroup_Shadcn_,+ CommandItem_Shadcn_,+ cn,+ markdownComponents,+} from 'ui'++import { StatusIcon } from '../../../Icons/StatusIcons'+import {+ Breadcrumb,+ CommandHeader,+ CommandInput,+ CommandWrapper,+ generateCommandClassNames,+ useHistoryKeys,+ useQuery,+ useSetCommandMenuSize,+ useSetQuery,+} from '../..'+import { AiWarning, Message, MessageRole, MessageStatus, useAiChat } from '../ai'++const questions = [+ 'How do I get started with Supabase?',+ 'How do I run Supabase locally?',+ 'How do I connect to my database?',+ 'How do I run migrations? ',+ 'How do I listen to changes in a table?',+ 'How do I set up authentication?',+]++const DocsAiPage = () => {+ const query = useQuery()+ const setQuery = useSetQuery()++ const isBelowSm = useBreakpoint('sm')++ /**+ * Interface for AI interaction is larger to allow more reading space.+ */+ useSetCommandMenuSize('xlarge')++ const [isLoading, setIsLoading] = useState(false)++ const { submit, reset, messages, isResponding, hasError } = useAiChat({+ setIsLoading,+ })++ useHistoryKeys({+ enable: !isResponding,+ stack: messages.filter(({ role }) => role === MessageRole.User).map(({ content }) => content),+ })++ const handleSubmit = useCallback(+ (message: string) => {+ setQuery('')+ submit(message)+ },+ [submit]+ )++ const handleReset = useCallback(() => {+ setQuery('')+ reset()+ }, [reset])++ useEffect(() => {+ if (query) {+ handleSubmit(query)+ }+ }, [])++ return (+ <CommandWrapper+ className={cn(+ 'flex flex-col',+ !isBelowSm &&+ '[&_[cmdk-input-wrapper]]:border-b-0 [&_[cmdk-input-wrapper]]:border-t [&_[cmdk-input-wrapper]]:border-solid [&_[cmdk-input-wrapper]]:border-bg-control'+ )}+ >+ <CommandHeader>+ <Breadcrumb />+ {isBelowSm && (+ <PromptInput+ submit={submit}+ messages={messages}+ isLoading={isLoading}+ isResponding={isResponding}+ />+ )}+ </CommandHeader>+ <div className={cn('flex-grow min-h-0 overflow-auto p-4')}>+ {!hasError && messages.length > 0 && <AiMessages messages={messages} />}+ {!hasError && messages.length === 0 && <EmptyState handleSubmit={handleSubmit} />}+ {hasError && <ErrorState handleReset={handleReset} />}+ </div>+ {!isBelowSm && (+ <PromptInput+ submit={submit}+ messages={messages}+ isLoading={isLoading}+ isResponding={isResponding}+ />+ )}+ {messages.length > 0 && !hasError && (+ <AiWarning className={isBelowSm ? 'rounded-b-none' : 'rounded-t-none'} />+ )}+ </CommandWrapper>+ )+}++function PromptInput({+ submit,+ messages,+ isLoading,+ isResponding,+ className,+}: {+ submit: (query: string) => Promise<void>+ messages: Array<Message>+ isLoading: boolean+ isResponding: boolean+ className?: string+}) {+ const query = useQuery()+ const setQuery = useSetQuery()++ useHistoryKeys({+ enable: !isResponding,+ stack: messages.filter(({ role }) => role === MessageRole.User).map(({ content }) => content),+ })++ const handleSubmit = useCallback(+ (message: string) => {+ setQuery('')+ submit(message)+ },+ [submit]+ )++ useEffect(() => {+ if (query) {+ handleSubmit(query)+ }+ }, [])++ // Detect an IME composition (so that we can ignore Enter keypress)+ const [isImeComposing, setIsImeComposing] = useState(false)++ return (+ <CommandInput+ className={cn(+ 'w-full h-11',+ 'border-none outline-none bg-transparent rounded-none rounded-t-md px-4 py-7',+ 'flex',+ 'text-base text-foreground-light',+ 'focus:ring-0 focus:shadow-none focus:ring-transparent',+ 'focus-visible:ring-0 focus-visible:shadow-none focus-visible:ring-transparent',+ 'placeholder:text-foreground-muted',+ 'disabled:cursor-not-allowed disabled:opacity-50',+ className+ )}+ placeholder={+ isLoading || isResponding ? 'Waiting on an answer...' : 'Ask Supabase AI a question...'+ }+ value={query}+ onCompositionStart={() => setIsImeComposing(true)}+ onCompositionEnd={() => setIsImeComposing(false)}+ onKeyDown={(e) => {+ switch (e.key) {+ case 'Enter':+ if (!query || isLoading || isResponding || isImeComposing) {+ return+ }+ return handleSubmit(query)+ default:+ return+ }+ }}+ />+ )+}++function AiMessages({ messages }: { messages: Array<Message> }) {+ return (+ <div+ className={cn(+ 'flex-grow min-h-0 overflow-auto p-4',+ 'grid gap-6 md:grid-cols-[max-content,1fr] grid-rows-[max-content]'+ )}+ >+ {messages.map((message, index) => {+ switch (message.role) {+ case MessageRole.User:+ return (+ <Fragment key={index}>+ <div className="flex items-center gap-4">+ <div+ className={cn(+ 'w-7 h-7',+ 'border border-muted bg-background shadow-sm rounded-full',+ 'flex items-center justify-center',+ 'text-foreground-lighter'+ )}+ >+ <User strokeWidth={1.5} size={16} />+ </div>+ <span className="font-mono text-sm text-foreground-muted uppercase tracking-widest md:hidden">+ You+ </span>+ </div>+ <div className="prose text-foreground-lighter">{message.content}</div>+ </Fragment>+ )+ case MessageRole.Assistant:+ return (+ <Fragment key={index}>+ <div className="flex items-center md:items-start gap-4">+ <AiIconAnimation+ className="ml-0.5"+ loading={+ message.status === MessageStatus.Pending ||+ message.status === MessageStatus.InProgress+ }+ allowHoverEffect+ />+ <span className="font-mono text-sm text-foreground-muted uppercase tracking-widest md:hidden">+ Supabase AI+ </span>+ </div>+ <div>+ {message.status === MessageStatus.Pending && (+ <span className="inline-block h-[1lh] w-[0.8lh] mt-1 bg-border-strong animate-bounce" />+ )}+ <ReactMarkdown+ remarkPlugins={[remarkGfm]}+ components={{+ ...markdownComponents,+ a: (props) => <a {...props} target="_blank" rel="noopener noreferrer" />,+ }}+ className="prose dark:prose-dark break-words"+ >+ {message.content}+ </ReactMarkdown>+ </div>+ </Fragment>+ )+ }+ })}+ </div>+ )+}++function EmptyState({ handleSubmit }: { handleSubmit: (message: string) => void }) {+ const query = useQuery()++ return (+ <CommandGroup_Shadcn_+ heading="Examples"+ className={cn(+ // Double padding from command group primitive and container, remove the primitive one+ '!p-0',+ 'text-border-strong',+ '[&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:pb-1.5',+ '[&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-normal [&_[cmdk-group-heading]]:text-foreground-muted'+ )}+ >+ {questions.map((question) => {+ const key = question.replace(/\s+/g, '_')+ return (+ <CommandItem_Shadcn_+ className={generateCommandClassNames(false)}+ onSelect={() => {+ if (!query) {+ handleSubmit(question)+ }+ }}+ key={key}+ >+ <AiIconAnimation />+ {question}+ </CommandItem_Shadcn_>+ )+ })}+ </CommandGroup_Shadcn_>+ )+}++function ErrorState({ handleReset }: { handleReset: () => void }) {+ return (+ <div className="p-6 flex flex-col items-center gap-2 mt-4">+ <StatusIcon variant="warning" />+ <p className="text-sm text-foreground text-center">+ Sorry, looks like Supabase AI is having a hard time!+ </p>+ <p className="text-sm text-foreground-lighter text-center">Please try again in a bit.</p>+ <Button size="tiny" type="default" onClick={handleReset}>+ Try again?+ </Button>+ </div>+ )+}++export { DocsAiPage }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/index.tsx b/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/index.tsxnew file mode 100644index 00000000000..469a9b4d62d--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/DocsAi/index.tsx@@ -0,0 +1,41 @@+import { AiIconAnimation } from 'ui'++import { useRegisterCommands } from '../../api/hooks/commandsHooks'+import { useRegisterPage, useSetPage } from '../../api/hooks/pagesHooks'+import type { ICommand, CommandOptions } from '../../api/types'+import { PageType } from '../../api/utils'+import { DocsAiPage } from './DocsAiPage'++const DOCS_AI_COMMANDS = {+ PAGE_NAME: 'Ask Supabase AI',+ SECTION_NAME: 'Docs',+}++const identity = <T,>(x: T) => x++const useDocsAiCommands = ({+ modify = identity,+ options,+}: { modify?: (command: ICommand) => ICommand; options?: CommandOptions } = {}) => {+ const setCommandPage = useSetPage()++ useRegisterPage(DOCS_AI_COMMANDS.PAGE_NAME, { type: PageType.Component, component: DocsAiPage })++ useRegisterCommands(+ DOCS_AI_COMMANDS.SECTION_NAME,+ [+ {+ id: 'ai-docs',+ name: 'Ask Supabase AI',+ action: () => {+ setCommandPage(DOCS_AI_COMMANDS.PAGE_NAME, true)+ },+ icon: () => <AiIconAnimation />,+ className: 'text-brand',+ },+ ].map(modify),+ options+ )+}++export { useDocsAiCommands }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/DocsSearch/DocsSearchPage.tsx b/packages/ui-patterns/CommandMenu/prepackaged/DocsSearch/DocsSearchPage.tsxnew file mode 100644index 00000000000..0a4bfb7274c--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/DocsSearch/DocsSearchPage.tsx@@ -0,0 +1,339 @@+'use client'++import { useSupabaseClient } from '@supabase/auth-helpers-react'+import { Book, ChevronRight, Github, Hash, Loader2, MessageSquare, Search } from 'lucide-react'+import { useEffect, useRef } from 'react'++import {+ DocsSearchResultType as PageType,+ useDocsSearch,+ type DocsSearchResult as Page,+ type DocsSearchResultSection as PageSection,+} from 'common'+import { Button, CommandGroup_Shadcn_, CommandItem_Shadcn_, CommandList_Shadcn_, cn } from 'ui'++import { StatusIcon } from '../../../Icons/StatusIcons'+import {+ Breadcrumb,+ CommandHeader,+ CommandInput,+ CommandWrapper,+ TextHighlighter,+ escapeAttributeSelector,+ generateCommandClassNames,+ useCrossCompatRouter,+ useQuery,+ useSetCommandMenuOpen,+ useSetQuery,+} from '../..'+import { BASE_PATH } from '../shared/constants'++const questions = [+ 'How do I get started with Supabase?',+ 'How do I run Supabase locally?',+ 'How do I connect to my database?',+ 'How do I run migrations? ',+ 'How do I listen to changes in a table?',+ 'How do I set up authentication?',+]++const ChevronArrow = () => (+ <ChevronRight+ strokeWidth={1.5}+ className={cn(+ '-left-4',+ 'opacity-0',+ 'text-foreground-muted',+ 'group-aria-selected:scale-[101%] group-aria-selected:opacity-100 group-aria-selected:left-0',+ 'transition'+ )}+ />+)++const IconContainer = (+ props: React.DetailedHTMLProps<React.HTMLAttributes<HTMLDivElement>, HTMLDivElement>+) => (+ <div+ className={cn(+ 'w-6 h-6',+ 'bg-surface-100 border rounded',+ 'flex items-center justify-center',+ 'text-foreground-muted',+ 'group-aria-selected:bg-surface-200 group-aria-selected:text-foreground-lighter group-aria-selected:[&_svg]:scale-[103%]',+ 'transition'+ )}+ {...props}+ />+)++const DocsSearchPage = () => {+ const supabaseClient = useSupabaseClient()+ const {+ searchState: state,+ handleDocsSearch: handleSearch,+ handleDocsSearchDebounced: debouncedSearch,+ resetSearch,+ } = useDocsSearch(supabaseClient)+ const setIsOpen = useSetCommandMenuOpen()+ const setQuery = useSetQuery()+ const query = useQuery()++ const initialLoad = useRef(true)+ const inputRef = useRef<HTMLInputElement>(null)+ const router = useCrossCompatRouter()++ async function openLink(pageType: PageType, link: string) {+ switch (pageType) {+ case PageType.Markdown:+ case PageType.Reference:+ if (BASE_PATH === '/docs') {+ router.push(link)+ setIsOpen(false)+ } else if (!BASE_PATH) {+ router.push(`/docs${link}`)+ setIsOpen(false)+ } else {+ window.open(`https://supabase.com/docs${link}`, '_blank', 'noreferrer,noopener')+ setIsOpen(false)+ }+ break+ case PageType.Integration:+ if (!BASE_PATH) {+ router.push(link)+ setIsOpen(false)+ } else {+ window.open(`https://supabase.com${link}`, '_blank', 'noreferrer,noopener')+ setIsOpen(false)+ }+ break+ case PageType.GithubDiscussion:+ window.open(link, '_blank', 'noreferrer,noopener')+ setIsOpen(false)+ break+ default:+ throw new Error(`Unknown page type '${pageType}'`)+ }+ }++ const hasResults =+ state.status === 'fullResults' ||+ state.status === 'partialResults' ||+ (state.status === 'loading' && state.staleResults.length > 0)++ function handleResetPrompt() {+ setQuery('')+ resetSearch()+ }++ useEffect(() => {+ if (initialLoad.current) {+ // On first navigation into 'docs search' page, search immediately+ if (query) {+ handleSearch(query)+ }+ initialLoad.current = false+ } else if (query) {+ // Else if user is typing, debounce search+ debouncedSearch(query)+ } else {+ // If user clears search, reset results+ resetSearch()+ }+ }, [query, handleSearch, debouncedSearch])++ // Immediately run search if user presses enter+ // and abort any debounced searches that are waiting+ useEffect(() => {+ const handleEnter = (event: KeyboardEvent) => {+ if (+ event.key === 'Enter' &&+ document.activeElement === inputRef.current &&+ query &&+ // If there are results, cmdk menu will trigger navigation to the highlighted+ // result on Enter, even though the active element is the input+ !hasResults+ ) {+ event.preventDefault()+ debouncedSearch.cancel()+ handleSearch(query)+ }+ }++ inputRef.current?.addEventListener('keydown', handleEnter)+ return () => inputRef.current?.removeEventListener('keydown', handleEnter)+ }, [query, hasResults])++ return (+ <CommandWrapper>+ <CommandHeader>+ <Breadcrumb />+ <CommandInput placeholder="Search..." ref={inputRef} />+ </CommandHeader>+ <CommandList_Shadcn_ className="max-h-[initial]">+ {hasResults &&+ ('results' in state ? state.results : state.staleResults).map((page, i) => {+ return (+ <CommandGroup_Shadcn_+ heading=""+ key={`${page.path}-group`}+ value={`${escapeAttributeSelector(page.title)}-group-index-${i}`}+ forceMount={true}+ className="overflow-hidden py-3 px-2 text-border-strong [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:pb-1.5 [&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-normal [&_[cmdk-group-heading]]:text-foreground-muted"+ >+ <CommandItem_Shadcn_+ key={`${page.path}-item`}+ value={`${escapeAttributeSelector(page.title)}-item-index-${i}`}+ onSelect={() => {+ openLink(page.type, page.path)+ }}+ forceMount={true}+ className={cn(generateCommandClassNames(true), 'border border-overlay/90')}+ >+ <div className="grow flex gap-3 items-center">+ <IconContainer>{getPageIcon(page)}</IconContainer>+ <div className="flex flex-col gap-0">+ <TextHighlighter>{page.title}</TextHighlighter>+ {(page.description || page.subtitle) && (+ <div className="text-xs text-foreground-muted">+ {page.description || page.subtitle}+ </div>+ )}+ </div>+ </div>++ <ChevronArrow />+ </CommandItem_Shadcn_>+ {page.sections.length > 0 && (+ <div className="border-l border-muted ml-3 pt-3">+ {page.sections.map((section, i) => (+ <CommandItem_Shadcn_+ className={cn(+ generateCommandClassNames(true),+ 'border border-overlay/90',+ 'ml-3 mb-3'+ )}+ onSelect={() => {+ openLink(page.type, formatSectionUrl(page, section))+ }}+ key={`${page.path}__${section.heading}-item`}+ value={`${escapeAttributeSelector(page.title)}__${escapeAttributeSelector(section.heading)}-item-index-${i}`}+ forceMount={true}+ >+ <div className="grow flex gap-3 items-center">+ <IconContainer>{getPageSectionIcon(page)}</IconContainer>+ <div className="flex flex-col gap-0">+ <cite>+ <TextHighlighter className="not-italic text-[10px] rounded-full px-2 py-1 bg-surface-300 text-foreground-muted">+ {page.title}+ </TextHighlighter>+ </cite>+ {section.heading && (+ <TextHighlighter>{section.heading}</TextHighlighter>+ )}+ </div>+ </div>+ <ChevronArrow />+ </CommandItem_Shadcn_>+ ))}+ </div>+ )}+ </CommandGroup_Shadcn_>+ )+ })}+ {state.status === 'initial' && (+ <CommandGroup_Shadcn_ className="overflow-hidden py-3 px-2 text-border-strong [&_[cmdk-group-heading]]:px-2 [&_[cmdk-group-heading]]:pb-1.5 [&_[cmdk-group-heading]]:text-sm [&_[cmdk-group-heading]]:font-normal [&_[cmdk-group-heading]]:text-foreground-muted">+ {questions.map((question) => {+ const key = question.replace(/\s+/g, '_')+ return (+ <CommandItem_Shadcn_+ className={generateCommandClassNames(false)}+ disabled={hasResults}+ onSelect={() => {+ if (!query) {+ handleSearch(question)+ setQuery(question)+ }+ }}+ key={key}+ >+ <Search />+ {question}+ </CommandItem_Shadcn_>+ )+ })}+ </CommandGroup_Shadcn_>+ )}+ {state.status === 'loading' && state.staleResults.length === 0 && (+ <div className="flex items-center gap-3 my-4 justify-center">+ <Loader2 className="animate animate-spin text-foreground-muted" size={14} />+ <p className="text-sm text-foreground-muted text-center">Searching for results</p>+ </div>+ )}+ {state.status === 'noResults' && (+ <div className="p-6 flex flex-col items-center gap-6 mt-4 text-foreground-light">+ <StatusIcon variant="default" />+ <p className="text-sm text-foreground-light text-center">No results found.</p>+ <Button size="tiny" type="default" onClick={handleResetPrompt}>+ Try again?+ </Button>+ </div>+ )}+ {state.status === 'error' && (+ <div className="p-6 flex flex-col items-center gap-6 mt-4">+ <StatusIcon variant="warning" />+ <p className="text-lg text-foreground-light">+ Sorry, looks like we're having some issues with search!+ </p>+ <p className="text-sm text-foreground-lighter">Please try again in a bit.</p>+ <Button size="tiny" type="default" onClick={handleResetPrompt}>+ Try again?+ </Button>+ </div>+ )}+ </CommandList_Shadcn_>+ </CommandWrapper>+ )+}++export function formatSectionUrl(page: Page, section: PageSection) {+ switch (page.type) {+ case PageType.Markdown:+ case PageType.GithubDiscussion:+ return `${page.path}#${section.slug ?? ''}`+ case PageType.Reference:+ return `${page.path}/${section.slug ?? ''}`+ case PageType.Integration:+ // [Charis] Markdown headings on integrations pages don't have slugs yet+ return page.path+ default:+ throw new Error(`Unknown page type '${page.type}'`)+ }+}++export function getPageIcon(page: Page) {+ switch (page.type) {+ case PageType.Markdown:+ case PageType.Reference:+ case PageType.Integration:+ return <Book strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />+ case PageType.GithubDiscussion:+ return <Github strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />+ default:+ throw new Error(`Unknown page type '${page.type}'`)+ }+}++export function getPageSectionIcon(page: Page) {+ switch (page.type) {+ case PageType.Markdown:+ case PageType.Reference:+ case PageType.Integration:+ return <Hash strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />+ case PageType.GithubDiscussion:+ return <MessageSquare strokeWidth={1.5} className="!mr-0 !w-4 !h-4" />+ default:+ throw new Error(`Unknown page type '${page.type}'`)+ }+}++export { DocsSearchPage }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/DocsSearch/index.tsx b/packages/ui-patterns/CommandMenu/prepackaged/DocsSearch/index.tsxnew file mode 100644index 00000000000..d6a041fcad1--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/DocsSearch/index.tsx@@ -0,0 +1,46 @@+import { Book } from 'lucide-react'++import {+ PageType,+ useRegisterCommands,+ useRegisterPage,+ useSetPage,+ type CommandOptions,+ type ICommand,+} from '../..'+import { DocsSearchPage } from './DocsSearchPage'++const DOCS_SEARCH_COMMANDS = {+ PAGE_NAME: 'Docs search',+ SECTION_NAME: 'Docs',+}++const identity = <T,>(x: T) => x++const useDocsSearchCommands = ({+ modify = identity,+ options,+}: { modify?: (command: ICommand) => ICommand; options?: CommandOptions } = {}) => {+ const setCommandPage = useSetPage()+ useRegisterPage(DOCS_SEARCH_COMMANDS.PAGE_NAME, {+ type: PageType.Component,+ component: DocsSearchPage,+ })++ useRegisterCommands(+ DOCS_SEARCH_COMMANDS.SECTION_NAME,+ [+ {+ id: 'search-docs',+ name: 'Search the docs',+ action: () => {+ setCommandPage(DOCS_SEARCH_COMMANDS.PAGE_NAME, true)+ },+ icon: () => <Book />,+ },+ ].map(modify),+ options+ )+}++export { useDocsSearchCommands }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/Support.tsx b/packages/ui-patterns/CommandMenu/prepackaged/Support.tsxnew file mode 100644index 00000000000..119d7ac035c--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/Support.tsx@@ -0,0 +1,47 @@+import { LifeBuoy } from 'lucide-react'+import { useMemo } from 'react'++import { useRegisterCommands, useSetCommandMenuOpen, type ICommand } from '..'+import { BASE_PATH } from './shared/constants'++const useSupportCommands = () => {+ const setOpen = useSetCommandMenuOpen()++ const commands = useMemo(+ () =>+ [+ {+ id: 'support',+ name: 'Go to Support',+ value: 'Support: Go to Support',+ href: '/support',+ icon: () => <LifeBuoy />,+ },+ {+ id: 'system-status',+ name: 'Go to System Status',+ value: 'Support: Go to System Status',+ href: 'https://status.supabase.com',+ icon: () => <LifeBuoy />,+ },+ {+ id: 'github-discussions',+ name: 'Go to GitHub Discussions',+ value: 'Support: Go to GitHub Discussions',+ href: 'https://github.com/orgs/supabase/discussions',+ icon: () => <LifeBuoy />,+ },+ ].map((command) => ({+ ...command,+ route:+ BASE_PATH && command.href.startsWith('/')+ ? `https://supabase.com/${command.href}`+ : command.href,+ })) as ICommand[],+ [setOpen]+ )++ useRegisterCommands('Support', commands)+}++export { useSupportCommands }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/ThemeSwitcher.tsx b/packages/ui-patterns/CommandMenu/prepackaged/ThemeSwitcher.tsxnew file mode 100644index 00000000000..85a77c5571a--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/ThemeSwitcher.tsx@@ -0,0 +1,60 @@+import { Monitor, MonitorDot, Moon, Sun } from 'lucide-react'+import { useTheme } from 'next-themes'++import { themes } from 'ui/src/components/ThemeProvider/themes'++import {+ PageType,+ useRegisterCommands,+ useRegisterPage,+ useSetCommandMenuOpen,+ useSetPage,+ type CommandOptions,+} from '..'++const THEME_SWITCHER_PAGE_NAME = 'Switch theme'++const useThemeSwitcherCommands = ({ options }: { options?: CommandOptions } = {}) => {+ const setIsOpen = useSetCommandMenuOpen()+ const setPage = useSetPage()++ const { setTheme } = useTheme()++ useRegisterPage(THEME_SWITCHER_PAGE_NAME, {+ type: PageType.Commands,+ sections: [+ {+ id: 'switch-theme',+ name: 'Switch theme',+ commands: themes+ .filter(({ name }) => name === 'System' || name === 'Light' || name === 'Dark')+ .map((theme) => ({+ id: `switch-theme-${theme.value}`,+ name: theme.name,+ action: () => {+ setTheme(theme.value)+ setIsOpen(false)+ },+ icon: () =>+ theme.name === 'System' ? <Monitor /> : theme.name === 'Light' ? <Sun /> : <Moon />,+ })),+ },+ ],+ })++ useRegisterCommands(+ 'Theme',+ [+ {+ id: 'switch-theme',+ name: 'Switch theme',+ action: () => setPage(THEME_SWITCHER_PAGE_NAME),+ defaultHidden: true,+ icon: () => <MonitorDot />,+ },+ ],+ options+ )+}++export { useThemeSwitcherCommands }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/ai/AiWarning.tsx b/packages/ui-patterns/CommandMenu/prepackaged/ai/AiWarning.tsxnew file mode 100644index 00000000000..07d34ed05d5--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/ai/AiWarning.tsx@@ -0,0 +1,17 @@+import { Microscope } from 'lucide-react'++import { Alert_Shadcn_, AlertDescription_Shadcn_, AlertTitle_Shadcn_, cn } from 'ui'++const AiWarning = ({ className }: { className?: string }) => (+ <Alert_Shadcn_ className={cn('!m-0', className)} variant="warning">+ <Microscope strokeWidth={1.5} size={18} className="text-foreground-muted" />+ <AlertTitle_Shadcn_>+ Supabase AI is experimental and may produce incorrect answers.+ </AlertTitle_Shadcn_>+ <AlertDescription_Shadcn_>+ <p>Always verify the output before executing.</p>+ </AlertDescription_Shadcn_>+ </Alert_Shadcn_>+)++export { AiWarning }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/ai/index.tsx b/packages/ui-patterns/CommandMenu/prepackaged/ai/index.tsxnew file mode 100644index 00000000000..6131a97011c--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/ai/index.tsx@@ -0,0 +1,4 @@+export { AiWarning } from './AiWarning'+export { queryAi } from './queryAi'+export { type UseAiChatOptions, useAiChat } from './useAiChat'+export { type Message, MessageRole, MessageStatus } from './utils'diff --git a/packages/ui-patterns/CommandMenu/prepackaged/ai/queryAi.ts b/packages/ui-patterns/CommandMenu/prepackaged/ai/queryAi.tsnew file mode 100644index 00000000000..dbf9251df65--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/ai/queryAi.ts@@ -0,0 +1,69 @@+import type OpenAI from 'openai'+import { SSE } from 'sse.js'++import { type Message } from './utils'+import { BASE_PATH } from '../shared/constants'++/**+ * Perform a one-off query to AI based on a snapshot of messages+ */+export function queryAi(messages: Message[], timeout = 0) {+ return new Promise<string>((resolve, reject) => {+ const eventSource = new SSE(`${BASE_PATH}/api/ai/docs`, {+ headers: {+ apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',+ Authorization: `Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`,+ 'Content-Type': 'application/json',+ },+ payload: JSON.stringify({+ messages: messages.map(({ role, content }) => ({ role, content })),+ }),+ })++ let timeoutId: number | undefined++ function handleError<T>(err: T) {+ if (timeoutId) {+ clearTimeout(timeoutId)+ }+ console.error(err)+ reject(err)+ }++ if (timeout > 0) {+ timeoutId = window.setTimeout(() => {+ handleError(new Error('AI query timed out'))+ }, timeout)+ }++ let answer = ''++ eventSource.addEventListener('error', handleError)+ eventSource.addEventListener('message', (e: MessageEvent) => {+ try {+ if (e.data === '[DONE]') {+ if (timeoutId) {+ clearTimeout(timeoutId)+ }+ resolve(answer)+ return+ }++ const completionChunk: OpenAI.Chat.Completions.ChatCompletionChunk = JSON.parse(e.data)+ const [+ {+ delta: { content },+ },+ ] = completionChunk.choices++ if (content) {+ answer += content+ }+ } catch (err) {+ handleError(err)+ }+ })++ eventSource.stream()+ })+}diff --git a/packages/ui-patterns/CommandMenu/prepackaged/ai/useAiChat.ts b/packages/ui-patterns/CommandMenu/prepackaged/ai/useAiChat.tsnew file mode 100644index 00000000000..f2af9154855--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/ai/useAiChat.ts@@ -0,0 +1,190 @@+import type OpenAI from 'openai'+import type { Dispatch, SetStateAction } from 'react'+import { useCallback, useReducer, useRef, useState } from 'react'+import { SSE } from 'sse.js'++import { BASE_PATH } from '../shared/constants'+import type { Message, MessageAction } from './utils'+import { MessageRole, MessageStatus } from './utils'++const messageReducer = (state: Message[], messageAction: MessageAction) => {+ let current = [...state]+ const { type } = messageAction++ switch (type) {+ case 'new': {+ const { message } = messageAction+ current.push(message)+ break+ }+ case 'update': {+ const { index, message } = messageAction+ if (current[index]) {+ current[index] = Object.assign({}, current[index], message)+ }+ break+ }+ case 'append-content': {+ const { index, content, idempotencyKey } = messageAction++ const messageToEdit = current[index]+ if (!messageToEdit || messageToEdit.idempotencyKey === idempotencyKey) {+ break+ }+ messageToEdit.idempotencyKey = idempotencyKey++ current[index] = Object.assign({}, messageToEdit, {+ content: (messageToEdit.content += content),+ })+ break+ }+ case 'reset': {+ current = []+ break+ }+ default: {+ throw new Error(`Unknown message action '${type}'`)+ }+ }++ return current+}++interface UseAiChatOptions {+ messageTemplate?: (message: string) => string+ setIsLoading?: Dispatch<SetStateAction<boolean>>+}++const useAiChat = ({ messageTemplate = (message) => message, setIsLoading }: UseAiChatOptions) => {+ const eventSourceRef = useRef<SSE>()+ const messageIdempotencyKey = useRef(0)++ const [isResponding, setIsResponding] = useState(false)+ const [hasError, setHasError] = useState(false)++ const [currentMessageIndex, setCurrentMessageIndex] = useState(1)+ const [messages, dispatchMessage] = useReducer(messageReducer, [])++ const submit = useCallback(+ async (query: string) => {+ dispatchMessage({+ type: 'new',+ message: {+ status: MessageStatus.Complete,+ role: MessageRole.User,+ content: query,+ },+ })+ dispatchMessage({+ type: 'new',+ message: {+ status: MessageStatus.Pending,+ role: MessageRole.Assistant,+ content: '',+ },+ })+ setIsResponding(false)+ setHasError(false)+ setIsLoading?.(true)++ const eventSource = new SSE(`${BASE_PATH}/api/ai/docs`, {+ headers: {+ apikey: process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY ?? '',+ Authorization: `Bearer ${process.env.NEXT_PUBLIC_SUPABASE_ANON_KEY}`,+ 'Content-Type': 'application/json',+ },+ payload: JSON.stringify({+ messages: messages+ .filter(({ status }) => status === MessageStatus.Complete)+ .map(({ role, content }) => ({ role, content }))+ .concat({ role: MessageRole.User, content: messageTemplate(query) }),+ }),+ })++ function handleError<T>(err: T) {+ setIsLoading?.(false)+ setIsResponding(false)+ setHasError(true)+ console.error(err)+ }++ function handleMessage(e: MessageEvent) {+ try {+ setIsLoading?.(false)++ if (e.data === '[DONE]') {+ setIsResponding(false)+ dispatchMessage({+ type: 'update',+ index: currentMessageIndex,+ message: {+ status: MessageStatus.Complete,+ },+ })+ setCurrentMessageIndex((x) => x + 2)+ return+ }++ dispatchMessage({+ type: 'update',+ index: currentMessageIndex,+ message: {+ status: MessageStatus.InProgress,+ },+ })++ setIsResponding(true)++ const completionChunk: OpenAI.Chat.Completions.ChatCompletionChunk = JSON.parse(e.data)+ const [+ {+ delta: { content },+ },+ ] = completionChunk.choices++ if (content) {+ dispatchMessage({+ type: 'append-content',+ index: currentMessageIndex,+ idempotencyKey: messageIdempotencyKey.current++,+ content,+ })+ }+ } catch (err) {+ handleError(err)+ }+ }++ eventSource.addEventListener('error', handleError)+ eventSource.addEventListener('message', handleMessage)++ eventSource.stream()++ eventSourceRef.current = eventSource++ setIsLoading?.(true)+ },+ [currentMessageIndex, messages, messageTemplate]+ )++ function reset() {+ eventSourceRef.current?.close()+ eventSourceRef.current = undefined+ setIsResponding(false)+ setHasError(false)+ dispatchMessage({+ type: 'reset',+ })+ }++ return {+ submit,+ reset,+ messages,+ isResponding,+ hasError,+ }+}++export { useAiChat }+export type { Message, UseAiChatOptions }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/ai/utils.ts b/packages/ui-patterns/CommandMenu/prepackaged/ai/utils.tsnew file mode 100644index 00000000000..d264df891a8--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/ai/utils.ts@@ -0,0 +1,44 @@+enum MessageRole {+ User = 'user',+ Assistant = 'assistant',+}++enum MessageStatus {+ Pending = 'pending',+ InProgress = 'in-progress',+ Complete = 'complete',+}++interface Message {+ role: MessageRole+ content: string+ status: MessageStatus+ idempotencyKey?: number+}++interface NewMessageAction {+ type: 'new'+ message: Message+}++interface UpdateMessageAction {+ type: 'update'+ index: number+ message: Partial<Message>+}++interface AppendContentAction {+ type: 'append-content'+ index: number+ content: string+ idempotencyKey: number+}++interface ResetAction {+ type: 'reset'+}++type MessageAction = NewMessageAction | UpdateMessageAction | AppendContentAction | ResetAction++export { MessageRole, MessageStatus }+export type { Message, MessageAction }diff --git a/packages/ui-patterns/CommandMenu/prepackaged/shared/constants.ts b/packages/ui-patterns/CommandMenu/prepackaged/shared/constants.tsnew file mode 100644index 00000000000..feb7f5706b3--- /dev/null+++ b/packages/ui-patterns/CommandMenu/prepackaged/shared/constants.ts@@ -0,0 +1,3 @@+const BASE_PATH = process.env.NEXT_PUBLIC_BASE_PATH++export { BASE_PATH }diff --git a/packages/ui/src/layout/ai-icon-animation/ai-icon-animation.tsx b/packages/ui/src/layout/ai-icon-animation/ai-icon-animation.tsxindex e56009e4675..32e2e1fb3bd 100644--- a/packages/ui/src/layout/ai-icon-animation/ai-icon-animation.tsx+++ b/packages/ui/src/layout/ai-icon-animation/ai-icon-animation.tsx@@ -1,7 +1,5 @@'use client'-// make a function that returns a component-import styles from './ai-icon-animation-style.module.css'import { useEffect, useState } from 'react'import { cn } from '../../lib/utils/cn'