The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
chore: remove new CMD+K. added Clippy modal back into docs
Jonathan Summers-Muir53aab94dd4ff
diff --git a/apps/docs/components/Navigation/NavigationMenu/TopNavBarRef.tsx b/apps/docs/components/Navigation/NavigationMenu/TopNavBarRef.tsxindex 7501f116c2a..0a2bdb7a696 100644--- a/apps/docs/components/Navigation/NavigationMenu/TopNavBarRef.tsx+++ b/apps/docs/components/Navigation/NavigationMenu/TopNavBarRef.tsx@@ -3,11 +3,13 @@ import Image from 'next/image'import Link from 'next/link'import { useRouter } from 'next/router'import { FC, useEffect, useState } from 'react'-import { Button, IconCommand, IconGitHub, IconMoon, IconSearch, IconSun, SearchButton } from 'ui'+import { Button, IconCommand, IconGitHub, IconMoon, IconSearch, IconSun } from 'ui'import { REFERENCES } from '~/components/Navigation/Navigation.constants'import { getPageType } from '~/lib/helpers'+import SearchButton from '~/components/Search/SearchButton'+const TopNavBarRef: FC = () => {const { isDarkMode, toggleTheme } = useTheme()const [mounted, setMounted] = useState(false)diff --git a/apps/docs/components/Search/SearchButton.tsx b/apps/docs/components/Search/SearchButton.tsxnew file mode 100644index 00000000000..94da639a526--- /dev/null+++ b/apps/docs/components/Search/SearchButton.tsx@@ -0,0 +1,40 @@+import {+ ButtonHTMLAttributes,+ DetailedHTMLProps,+ FC,+ PropsWithChildren,+ useEffect,+ useRef,+} from 'react'+import { useActionKey } from '~/hooks/useActionKey'+import { useSearch } from './SearchProvider'++const SearchButton: FC<+ PropsWithChildren<DetailedHTMLProps<ButtonHTMLAttributes<HTMLButtonElement>, HTMLButtonElement>>+> = ({ children, ...props }) => {+ const searchButtonRef = useRef<HTMLButtonElement>()+ const { open, setQuery } = useSearch()++ useEffect(() => {+ function onKeyDown(event: KeyboardEvent) {+ if (searchButtonRef.current === document.activeElement) {+ if (/[a-zA-Z0-9]/.test(String.fromCharCode(event.keyCode))) {+ open()+ setQuery?.(event.key)+ }+ }+ }+ window.addEventListener('keydown', onKeyDown)+ return () => {+ window.removeEventListener('keydown', onKeyDown)+ }+ }, [open, setQuery])++ return (+ <button type="button" ref={searchButtonRef} onClick={open} {...props}>+ {children}+ </button>+ )+}++export default SearchButtondiff --git a/apps/docs/components/Search/SearchModal.tsx b/apps/docs/components/Search/SearchModal.tsxnew file mode 100644index 00000000000..213035540b1--- /dev/null+++ b/apps/docs/components/Search/SearchModal.tsx@@ -0,0 +1,423 @@+import type { CreateCompletionResponse } from 'openai'+import { FC, useCallback, useRef, useState } from 'react'+import ReactMarkdown from 'react-markdown'+import remarkGfm from 'remark-gfm'+import { SSE } from 'sse.js'+import clippyImageDark from '../../public/img/clippy-dark.png'+import clippyImage from '../../public/img/clippy.png'++import { useSupabaseClient } from '@supabase/auth-helpers-react'+import { useTheme } from 'common/Providers'+import Image from 'next/image'+import {+ Button,+ IconAlertCircle,+ IconAlertTriangle,+ IconLoader,+ IconSearch,+ Input,+ Loading,+ Modal,+ Tabs,+} from 'ui'+import components from '~/components'+import { IS_PLATFORM } from '~/lib/constants'+import { useSearch } from './SearchProvider'+import SearchResult, { SearchResultType } from './SearchResult'++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?',+]++function getEdgeFunctionUrl() {+ const supabaseUrl = process.env.NEXT_PUBLIC_SUPABASE_URL?.replace(/\/$/, '')++ if (IS_PLATFORM) {+ const [schemeAndProjectId, domain, tld] = supabaseUrl.split('.')+ return `${schemeAndProjectId}.functions.${domain}.${tld}`+ } else {+ return `${supabaseUrl}/functions/v1`+ }+}++const edgeFunctionUrl = getEdgeFunctionUrl()++const SearchModal: FC = () => {+ const { isDarkMode } = useTheme()+ const { close, query, setQuery } = useSearch()+ const [answer, setAnswer] = useState('')+ const [results, setResults] = useState<any[]>()+ const [isLoading, setIsLoading] = useState(false)+ const [isResponding, setIsResponding] = useState(false)+ const [hasClippyError, setHasClippyError] = useState(false)+ const [hasSearchError, setHasSearchError] = useState(false)+ const [selectedTab, setSelectedTab] = useState('search-panel')+ const eventSourceRef = useRef<SSE>()+ const supabaseClient = useSupabaseClient()++ const cantHelp = answer?.trim() === "Sorry, I don't know how to help with that."+ const status = isLoading+ ? 'Clippy is searching...'+ : isResponding+ ? 'Clippy is responding...'+ : cantHelp || hasClippyError+ ? 'Clippy has failed you'+ : undefined++ const handleSearchConfirm = useCallback(+ async (query: string) => {+ setResults(undefined)+ setAnswer(undefined)+ setIsResponding(false)+ setHasClippyError(false)+ setHasSearchError(false)+ setIsLoading(true)++ const { error, data: pageSections } = await supabaseClient.functions.invoke('search', {+ body: { query },+ })++ setIsLoading(false)++ if (error) {+ setIsLoading(false)+ setIsResponding(false)+ setHasSearchError(true)+ console.error(error)+ return+ }++ if (!Array.isArray(pageSections)) {+ setIsLoading(false)+ setIsResponding(false)+ setHasSearchError(true)+ console.error('Malformed response')+ return+ }++ setResults(pageSections)+ },+ [supabaseClient]+ )++ const handleClippyConfirm = useCallback(async (query: string) => {+ setResults(undefined)+ setAnswer(undefined)+ setIsResponding(false)+ setHasClippyError(false)+ setHasSearchError(false)+ setIsLoading(true)++ const eventSource = new SSE(`${edgeFunctionUrl}/clippy-search`, {+ 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({ query }),+ })++ function handleError<T>(err: T) {+ setIsLoading(false)+ setIsResponding(false)+ setHasClippyError(true)+ console.error(err)+ }++ eventSource.addEventListener('error', handleError)+ eventSource.addEventListener('message', (e) => {+ try {+ setIsLoading(false)++ if (e.data === '[DONE]') {+ setIsResponding(false)+ return+ }++ setIsResponding(true)++ const completionResponse: CreateCompletionResponse = JSON.parse(e.data)+ const [{ text }] = completionResponse.choices++ setAnswer((answer) => {+ return (answer ?? '') + text+ })+ } catch (err) {+ handleError(err)+ }+ })++ eventSource.stream()++ eventSourceRef.current = eventSource++ setIsLoading(true)+ }, [])++ const handleConfirm = useCallback(+ (selectedTab: string, query: string) => {+ switch (selectedTab) {+ case 'search-panel':+ return handleSearchConfirm(query)+ case 'clippy-panel':+ return handleClippyConfirm(query)+ }+ },+ [handleSearchConfirm, handleClippyConfirm]+ )++ function handleResetPrompt() {+ eventSourceRef.current?.close()+ eventSourceRef.current = undefined+ setQuery('')+ setResults(undefined)+ setAnswer(undefined)+ setIsResponding(false)+ setHasClippyError(false)+ setHasSearchError(false)+ }+ return (+ <Modal size="xlarge" visible={true} onCancel={close} closable={false} hideFooter>+ <div+ className={`mx-auto max-h-[90vh] lg:max-h-[75vh] flex flex-col gap-4 rounded-lg p-4 md:pt-6 md:px-6 pb-2 w-full shadow-2xl overflow-hidden border text-left border-scale-500 bg-scale-100 dark:bg-scale-300 cursor-auto relative min-w-[340px]`}+ onClick={(e) => e.stopPropagation()}+ >+ <div className="relative">+ <Input+ className="w-full"+ size="xlarge"+ autoFocus+ placeholder={selectedTab === 'search-panel' ? 'Search documentation' : 'Ask a question'}+ value={query}+ onChange={(e) => setQuery(e.target.value)}+ icon={<IconSearch size="small" />}+ onKeyDown={(e) => {+ switch (e.key) {+ case 'Enter':+ if (!query) {+ return+ }+ handleConfirm(selectedTab, query)+ return+ default:+ return+ }+ }}+ />+ <div className="absolute right-0 top-0 mt-3 mr-4 hidden md:block">+ <Button type="default" size="tiny" onClick={close}>+ esc+ </Button>+ </div>+ {!isLoading && answer && (+ <div className="absolute right-0 top-0 mt-3 mr-16 hidden md:block">+ <Button type="text" size="tiny" onClick={handleResetPrompt}>+ Try again+ </Button>+ </div>+ )}+ </div>+ <Tabs+ activeId={selectedTab}+ onChange={(tabId) => {+ setSelectedTab(tabId)+ if (!query) {+ handleResetPrompt()+ return+ }+ handleConfirm(tabId, query)+ }}+ >+ <Tabs.Panel id="search-panel" label="Guides & Reference">+ <div className="mb-6">+ {!isLoading && !hasSearchError && !results && (+ <div className="p-10 grid">+ <h2 className="text-lg text-center text-scale-1100">+ Search Supabase guides & reference docs+ </h2>+ </div>+ )}+ {results && results.length > 0 && (+ <div className="flex flex-col gap-3 max-h-[70vh] lg:max-h-[50vh] overflow-y-auto px-4 py-4 rounded-lg bg-scale-200">+ {results.map((page) => {+ const pageSections = page.sections.filter((section) => !!section.heading)+ return (+ <div key={page.id} className="flex flex-col gap-3">+ <SearchResult+ href={page.path}+ type={SearchResultType.Document}+ title={page.meta.title}+ />+ {pageSections.length > 0 && (+ <div className="flex flex-row">+ <div className="border bg-scale-300 rounded-xl self-stretch p-[1px] ml-4 mr-4"></div>+ <div className="flex flex-col gap-3 items-stretch grow">+ {pageSections.map((section) => (+ <SearchResult+ key={section.id}+ href={`${page.path}${page.type === 'reference' ? '/' : '#'}${+ section.slug+ }`}+ type={SearchResultType.Section}+ title={section.heading}+ chip={page.meta.title}+ />+ ))}+ </div>+ </div>+ )}+ </div>+ )+ })}+ </div>+ )}+ {isLoading && (+ <div className="p-6 grid gap-6 mt-4">+ <Loading active>{}</Loading>+ <p className="text-lg text-center">Searching for results</p>+ </div>+ )}+ {results && results.length === 0 && (+ <div className="p-6 flex flex-col items-center gap-6 mt-4">+ <IconAlertTriangle strokeWidth={1.5} size={40} />+ <p className="text-lg text-center">No results found.</p>+ <Button size="tiny" type="secondary" onClick={handleResetPrompt}>+ Try again?+ </Button>+ </div>+ )}+ {hasSearchError && (+ <div className="p-6 flex flex-col items-center gap-6 mt-4">+ <IconAlertTriangle strokeWidth={1.5} size={40} />+ <p className="text-lg text-center">+ Sorry, looks like we're having some issues with search!+ </p>+ <p className="text-sm text-center">Please try again in a bit.</p>+ <Button size="tiny" type="secondary" onClick={handleResetPrompt}>+ Try again?+ </Button>+ </div>+ )}+ </div>+ </Tabs.Panel>+ <Tabs.Panel id="clippy-panel" label="Ask Clippy">+ {!isLoading && !answer && !hasClippyError && (+ <div className="">+ <div className="mt-2">+ <h2 className="text-sm text-scale-1100">Not sure where to start?</h2>++ <ul className="text-sm mt-4 text-scale-1100 grid md:flex gap-4 flex-wrap max-w-3xl">+ {questions.map((question) => {+ const key = question.replace(/\s+/g, '_')+ return (+ <li key={key}>+ <button+ className="hover:bg-slate-400 hover:dark:bg-slate-400 px-4 py-2 bg-slate-300 dark:bg-slate-200 rounded-lg transition-colors"+ onClick={() => {+ setQuery(question)+ handleClippyConfirm(question)+ }}+ >+ {question}+ </button>+ </li>+ )+ })}+ </ul>+ </div>+ </div>+ )}+ {answer && (+ <div className="px-4 py-4 rounded-lg overflow-y-auto bg-scale-200 max-h-[70vh] lg:max-h-[50vh]">+ {cantHelp ? (+ <p className="flex flex-col gap-4 items-center p-4">+ <div className="grid md:flex items-center gap-2 mt-4 text-center justify-items-center">+ <IconAlertCircle />+ <p>Sorry, I don't know how to help with that.</p>+ </div>+ <Button size="tiny" type="secondary" onClick={handleResetPrompt}>+ Try again?+ </Button>+ </p>+ ) : (+ <div className="prose dark:prose-dark">+ <ReactMarkdown+ linkTarget="_blank"+ remarkPlugins={[remarkGfm]}+ transformLinkUri={(href) => {+ const supabaseUrl = new URL('https://supabase.com')+ const linkUrl = new URL(href, 'https://supabase.com')++ if (linkUrl.origin === supabaseUrl.origin) {+ return linkUrl.toString()+ }++ return href+ }}+ components={components}+ >+ {answer}+ </ReactMarkdown>+ </div>+ )}+ </div>+ )}+ {isLoading && (+ <div className="p-6 grid gap-6 mt-4">+ <Loading active>{}</Loading>+ <p className="text-lg text-center">Searching for results</p>+ </div>+ )}+ {hasClippyError && (+ <div className="p-6 flex flex-col items-center gap-6 mt-4">+ <IconAlertTriangle strokeWidth={1.5} size={40} />+ <p className="text-lg text-center">+ Sorry, looks like Clippy is having a hard time!+ </p>+ <p className="text-sm text-center">Please try again in a bit.</p>+ <Button size="tiny" type="secondary" onClick={handleResetPrompt}>+ Try again?+ </Button>+ </div>+ )}+ <div className="border-t border-scale-600 mt-4 text-scale-1100">+ <div className="flex justify-between items-center py-2 text-xs">+ <div className="flex items-centerp gap-1 pt-3 pb-1">+ <span>Powered by OpenAI.</span>+ <a href="/blog/chatgpt-supabase-docs" className="underline">+ Read the blog post+ </a>+ </div>+ <div className="flex items-center gap-6 py-1">+ {status ? (+ <span className="bg-scale-400 rounded-lg py-1 px-2 items-center gap-2 hidden md:flex">+ {(isLoading || isResponding) && (+ <IconLoader size={14} className="animate-spin" />+ )}+ {status}+ </span>+ ) : (+ <></>+ )}+ <Image+ width={30}+ height={34}+ src={isDarkMode ? clippyImageDark : clippyImage}+ alt="Clippy"+ />+ </div>+ </div>+ </div>+ </Tabs.Panel>+ </Tabs>+ </div>+ </Modal>+ )+}++export default SearchModaldiff --git a/apps/docs/components/Search/SearchProvider.tsx b/apps/docs/components/Search/SearchProvider.tsxnew file mode 100644index 00000000000..4175c159c29--- /dev/null+++ b/apps/docs/components/Search/SearchProvider.tsx@@ -0,0 +1,80 @@+import {+ createContext,+ FC,+ PropsWithChildren,+ useCallback,+ useContext,+ useEffect,+ useState,+} from 'react'+import { createPortal } from 'react-dom'+import SearchModal from './SearchModal'++export type SearchContextValue = {+ isOpen: boolean+ open: () => void+ close: () => void+ query: string+ setQuery: (query: string) => void+}++export const SearchContext = createContext<SearchContextValue>(null)++export const useSearch = () => {+ const { isOpen, open, close, query, setQuery } = useContext(SearchContext)++ return { isOpen, open, close, query, setQuery }+}++const SearchProvider: FC<PropsWithChildren<{}>> = ({ children }) => {+ const [isOpen, setIsOpen] = useState(false)+ const [query, setQuery] = useState('')++ const open = useCallback(() => {+ setIsOpen(true)+ document.body.classList.add('DocSearch--active')+ }, [])++ const close = useCallback(() => {+ setIsOpen(false)+ document.body.classList.remove('DocSearch--active')+ }, [])++ useSearchKeyboardEvents({+ open,+ close,+ })++ return (+ <SearchContext.Provider value={{ isOpen, open, close, query, setQuery }}>+ {children}+ {isOpen && createPortal(<SearchModal />, document.body)}+ </SearchContext.Provider>+ )+}++function useSearchKeyboardEvents({ open, close }) {+ useEffect(() => {+ function onKeyDown(event: KeyboardEvent) {+ switch (event.key) {+ case 'Escape':+ close()+ return+ case 'k':+ case '/':+ if (event.metaKey || event.ctrlKey) {+ open()+ }+ return+ }+ }++ window.addEventListener('keydown', onKeyDown)++ return () => {+ window.removeEventListener('keydown', onKeyDown)+ }+ }, [open, close])+}++export default SearchProviderdiff --git a/apps/docs/components/Search/SearchResult.tsx b/apps/docs/components/Search/SearchResult.tsxnew file mode 100644index 00000000000..d3689024ec5--- /dev/null+++ b/apps/docs/components/Search/SearchResult.tsx@@ -0,0 +1,54 @@+import Link from 'next/link'+import { FC } from 'react'+import { IconBookOpen, IconHash } from '~/../../packages/ui'+import { useSearch } from './SearchProvider'++export enum SearchResultType {+ Document = 'document',+ Section = 'section',+}++type Props = {+ href: string+ type: SearchResultType+ title: string+ chip?: string+}++const SearchResult: FC<Props> = ({ href, type, title, chip }) => {+ const { close } = useSearch()++ return (+ <Link href={href}>+ <a+ className="flex flex-row items-center bg-scale-400 hover:bg-scale-600 transition p-4 rounded-md border border-scale-600 text-sm cursor-pointer"+ onClick={close}+ >+ <div className="w-6 h-6 p-1 flex items-center justify-center mr-4 text-brand-1100 rounded-md bg-scale-700">+ {getIconByType(type)}+ </div>+ <div className="flex flex-col gap-2 items-start">+ {chip && (+ <div className="rounded-xl bg-scale-700 pl-3 pr-3 pt-0.5 pb-0.5 text-xs text-scale-1100">+ {chip}+ </div>+ )}+ <div>{title}</div>+ </div>+ </a>+ </Link>+ )+}++function getIconByType(type: SearchResultType) {+ switch (type) {+ case SearchResultType.Document:+ return <IconBookOpen />+ case SearchResultType.Section:+ return <IconHash />+ default:+ throw new Error(`Unknown search result type '${type}'`)+ }+}++export default SearchResultdiff --git a/apps/docs/pages/_app.tsx b/apps/docs/pages/_app.tsxindex f26400c6502..1557f8ec9d7 100644--- a/apps/docs/pages/_app.tsx+++ b/apps/docs/pages/_app.tsx@@ -4,8 +4,9 @@ import { ThemeProvider } from 'common/Providers'import { useRouter } from 'next/router'import { useEffect, useState } from 'react'import { AppPropsWithLayout } from 'types'-import { CommandMenuProvider } from 'ui'+// import { CommandMenuProvider } from 'ui'import Favicons from '~/components/Favicons'+import SearchProvider from '~/components/Search/SearchProvider'import SiteLayout from '~/layouts/SiteLayout'import { IS_PLATFORM, LOCAL_SUPABASE } from '~/lib/constants'import { post } from '~/lib/fetchWrappers'@@ -66,20 +67,24 @@ function MyApp({ Component, pageProps }: AppPropsWithLayout) {{IS_PLATFORM || LOCAL_SUPABASE ? (<SessionContextProvider supabaseClient={supabase}><ThemeProvider>- <CommandMenuProvider site="docs">+ <SearchProvider>+ {/* <CommandMenuProvider site="docs"> */}<SiteLayout><Component {...pageProps} /></SiteLayout>- </CommandMenuProvider>+ {/* </CommandMenuProvider> */}+ </SearchProvider></ThemeProvider></SessionContextProvider>) : (<ThemeProvider>- <CommandMenuProvider site="docs">+ <SearchProvider>+ {/* <CommandMenuProvider site="docs"> */}<SiteLayout><Component {...pageProps} /></SiteLayout>- </CommandMenuProvider>+ {/* </CommandMenuProvider> */}+ </SearchProvider></ThemeProvider>)}</>diff --git a/studio/pages/_app.tsx b/studio/pages/_app.tsxindex f9c80b2081a..054c4fe8cfa 100644--- a/studio/pages/_app.tsx+++ b/studio/pages/_app.tsx@@ -40,7 +40,7 @@ import { PortalToast, RouteValidationWrapper, AppBannerWrapper } from 'componentimport PageTelemetry from 'components/ui/PageTelemetry'import FlagProvider from 'components/ui/Flag/FlagProvider'import useAutoAuthRedirect from 'hooks/misc/useAutoAuthRedirect'-import CommandMenuProvider from 'ui/src/components/Command/CommandMenuProvider'+// import CommandMenuProvider from 'ui/src/components/Command/CommandMenuProvider'import { TooltipProvider } from '@radix-ui/react-tooltip'dayjs.extend(customParseFormat)@@ -118,9 +118,9 @@ function CustomApp({ Component, pageProps }: AppPropsWithLayout) {<TooltipProvider><RouteValidationWrapper><AppBannerWrapper>- <CommandMenuProvider site="studio">- {getLayout(<Component {...pageProps} />)}- </CommandMenuProvider>+ {/* <CommandMenuProvider site="studio"> */}+ {getLayout(<Component {...pageProps} />)}+ {/* </CommandMenuProvider> */}</AppBannerWrapper></RouteValidationWrapper></TooltipProvider>