Skip to content

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

Update SQL editor search to return a flat list (#33064)

Joshen Lim4425e05f04d3
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
index 5e20b846c21..3b91c2bcc71 100644
--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorMenu.tsx
@@ -1,9 +1,10 @@
import { PermissionAction } from '@supabase/shared-types/out/constants'
-import { FilePlus, FolderPlus, Plus } from 'lucide-react'
+import { FilePlus, FolderPlus, Plus, X } from 'lucide-react'
import { useRouter } from 'next/router'
-import { useState } from 'react'
+import { useEffect, useState } from 'react'
import { toast } from 'sonner'
+import { useDebounce } from '@uidotdev/usehooks'
import { useParams } from 'common'
import { useCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useLocalStorage } from 'hooks/misc/useLocalStorage'
@@ -16,15 +17,19 @@ import {
DropdownMenuContent,
DropdownMenuItem,
DropdownMenuTrigger,
+ Tooltip,
+ TooltipContent,
+ TooltipTrigger,
} from 'ui'
import {
+ InnerSideBarFilters,
InnerSideBarFilterSearchInput,
InnerSideBarFilterSortDropdown,
InnerSideBarFilterSortDropdownItem,
- InnerSideBarFilters,
InnerSideMenuItem,
} from 'ui-patterns/InnerSideMenu'
-import { SQLEditorNav as SQLEditorNavV2 } from './SQLEditorNavV2/SQLEditorNav'
+import { SQLEditorNav } from './SQLEditorNavV2/SQLEditorNav'
+import { SearchList } from './SQLEditorNavV2/SearchList'
interface SQLEditorMenuProps {
onViewOngoingQueries: () => void
@@ -37,10 +42,12 @@ export const SQLEditorMenu = ({ onViewOngoingQueries }: SQLEditorMenuProps) => {
const { ref } = useParams()
const snapV2 = useSqlEditorV2StateSnapshot()
- const [searchText, setSearchText] = useState('')
- const [isSearching, setIsSearching] = useState(false)
+ const [search, setSearch] = useState('')
+ const [showSearch, setShowSearch] = useState(false)
const [sort, setSort] = useLocalStorage<'name' | 'inserted_at'>('sql-editor-sort', 'inserted_at')
+ const debouncedSearch = useDebounce(search, 500)
+
const canCreateSQLSnippet = useCheckPermissions(PermissionAction.CREATE, 'user_content', {
resource: { type: 'sql', owner_id: profile?.id },
subject: { id: profile?.id },
@@ -48,6 +55,8 @@ export const SQLEditorMenu = ({ onViewOngoingQueries }: SQLEditorMenuProps) => {
const createNewFolder = () => {
if (!ref) return console.error('Project ref is required')
+ setSearch('')
+ setShowSearch(false)
snapV2.addNewFolder({ projectRef: ref })
}
@@ -60,36 +69,65 @@ export const SQLEditorMenu = ({ onViewOngoingQueries }: SQLEditorMenuProps) => {
}
try {
router.push(`/project/${ref}/sql/new?skip=true`)
- setSearchText('')
+ setSearch('')
+ setShowSearch(false)
} catch (error: any) {
toast.error(`Failed to create new query: ${error.message}`)
}
}
+ useEffect(() => {
+ setShowSearch(debouncedSearch.length > 0)
+ }, [debouncedSearch])
+
return (
<div className="h-full flex flex-col justify-between">
- <div className="mt-4 mb-2 flex flex-col gap-y-4">
- <div className="mx-4 flex items-center justify-between gap-x-2">
+ <div className="flex flex-col gap-y-4 flex-grow">
+ <div className="mt-4 mx-4 flex items-center justify-between gap-x-2">
<InnerSideBarFilters className="w-full p-0 gap-0">
<InnerSideBarFilterSearchInput
name="search-queries"
placeholder="Search queries..."
aria-labelledby="Search queries"
- value={searchText}
- onChange={(e) => setSearchText(e.target.value)}
- isLoading={isSearching}
+ value={search}
+ onChange={(e) => {
+ const value = e.target.value
+ setSearch(value)
+ if (value.length === 0) setShowSearch(false)
+ }}
+ onKeyDown={(e) => {
+ if (e.code === 'Escape') {
+ setSearch('')
+ setShowSearch(false)
+ }
+ }}
>
- <InnerSideBarFilterSortDropdown
- value={sort}
- onValueChange={(value: any) => setSort(value)}
- >
- <InnerSideBarFilterSortDropdownItem key="name" value="name">
- Alphabetical
- </InnerSideBarFilterSortDropdownItem>
- <InnerSideBarFilterSortDropdownItem key="inserted_at" value="inserted_at">
- Created At
- </InnerSideBarFilterSortDropdownItem>
- </InnerSideBarFilterSortDropdown>
+ {showSearch ? (
+ <Tooltip>
+ <TooltipTrigger
+ className="absolute right-1 top-[.4rem] md:top-[.3rem] transition-colors text-foreground-light hover:text-foreground"
+ onClick={() => {
+ setSearch('')
+ setShowSearch(false)
+ }}
+ >
+ <X size={18} />
+ </TooltipTrigger>
+ <TooltipContent>Clear search</TooltipContent>
+ </Tooltip>
+ ) : (
+ <InnerSideBarFilterSortDropdown
+ value={sort}
+ onValueChange={(value: any) => setSort(value)}
+ >
+ <InnerSideBarFilterSortDropdownItem key="name" value="name">
+ Alphabetical
+ </InnerSideBarFilterSortDropdownItem>
+ <InnerSideBarFilterSortDropdownItem key="inserted_at" value="inserted_at">
+ Created At
+ </InnerSideBarFilterSortDropdownItem>
+ </InnerSideBarFilterSortDropdown>
+ )}
</InnerSideBarFilterSearchInput>
</InnerSideBarFilters>
<DropdownMenu>
@@ -113,24 +151,36 @@ export const SQLEditorMenu = ({ onViewOngoingQueries }: SQLEditorMenuProps) => {
</DropdownMenu>
</div>
- <div className="px-2">
- <InnerSideMenuItem
- title="Templates"
- isActive={router.asPath === `/project/${ref}/sql/templates`}
- href={`/project/${ref}/sql/templates`}
- >
- Templates
- </InnerSideMenuItem>
- <InnerSideMenuItem
- title="Quickstarts"
- isActive={router.asPath === `/project/${ref}/sql/quickstarts`}
- href={`/project/${ref}/sql/quickstarts`}
- >
- Quickstarts
- </InnerSideMenuItem>
- </div>
+ {showSearch ? (
+ <SearchList
+ search={debouncedSearch}
+ onSelectSnippet={() => {
+ setSearch('')
+ setShowSearch(false)
+ }}
+ />
+ ) : (
+ <>
+ <div className="px-2">
+ <InnerSideMenuItem
+ title="Templates"
+ isActive={router.asPath === `/project/${ref}/sql/templates`}
+ href={`/project/${ref}/sql/templates`}
+ >
+ Templates
+ </InnerSideMenuItem>
+ <InnerSideMenuItem
+ title="Quickstarts"
+ isActive={router.asPath === `/project/${ref}/sql/quickstarts`}
+ href={`/project/${ref}/sql/quickstarts`}
+ >
+ Quickstarts
+ </InnerSideMenuItem>
+ </div>
- <SQLEditorNavV2 searchText={searchText} sort={sort} setIsSearching={setIsSearching} />
+ <SQLEditorNav sort={sort} />
+ </>
+ )}
</div>
<div className="p-4 border-t sticky bottom-0 bg-studio">
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
index 5e33a98986a..d4a1ada1b19 100644
--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorNav.tsx
@@ -1,7 +1,6 @@
-import { useDebounce } from '@uidotdev/usehooks'
import { Eye, EyeOffIcon, Heart, Unlock } from 'lucide-react'
import { useRouter } from 'next/router'
-import { Dispatch, SetStateAction, useEffect, useMemo, useState } from 'react'
+import { useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
@@ -26,7 +25,7 @@ import {
useSqlEditorV2StateSnapshot,
} from 'state/sql-editor-v2'
import { SqlSnippets } from 'types'
-import { cn, Separator, TreeView } from 'ui'
+import { Separator, TreeView } from 'ui'
import {
InnerSideBarEmptyPanel,
InnerSideMenuCollapsible,
@@ -40,27 +39,16 @@ import { formatFolderResponseForTreeView, getLastItemIds, ROOT_NODE } from './SQ
import { SQLEditorTreeViewItem } from './SQLEditorTreeViewItem'
interface SQLEditorNavProps {
- searchText: string
sort?: 'inserted_at' | 'name'
- setIsSearching?: Dispatch<SetStateAction<boolean>>
}
-export const SQLEditorNav = ({
- searchText: _searchText,
- sort = 'inserted_at',
- setIsSearching,
-}: SQLEditorNavProps) => {
- const searchText = _searchText.trim()
- const debouncedSearchText = useDebounce(searchText, 250)
- const isSearching = searchText.length > 0
-
+export const SQLEditorNav = ({ sort = 'inserted_at' }: SQLEditorNavProps) => {
const router = useRouter()
const { profile } = useProfile()
const project = useSelectedProject()
const { ref: projectRef, id } = useParams()
const snapV2 = useSqlEditorV2StateSnapshot()
- const [mountedId, setMountedId] = useState(false)
const [showMoveModal, setShowMoveModal] = useState(false)
const [showDeleteModal, setShowDeleteModal] = useState(false)
const [showRenameModal, setShowRenameModal] = useState(false)
@@ -68,7 +56,7 @@ export const SQLEditorNav = ({
const [showSharedSnippets, setShowSharedSnippets] = useState(false)
const [showPrivateSnippets, setShowPrivateSnippets] = useState(true)
- const [defaultExpandedFolderIds, setDefaultExpandedFolderIds] = useState<string[]>()
+ const [expandedFolderIds, setExpandedFolderIds] = useState<string[]>([])
const [selectedSnippets, setSelectedSnippets] = useState<Snippet[]>([])
const [selectedSnippetToShare, setSelectedSnippetToShare] = useState<Snippet>()
const [selectedSnippetToUnshare, setSelectedSnippetToUnshare] = useState<Snippet>()
@@ -83,33 +71,14 @@ export const SQLEditorNav = ({
// ==========================
const {
data: privateSnippetsPages,
+ isSuccess,
isLoading,
isPreviousData,
isFetching,
hasNextPage,
fetchNextPage,
isFetchingNextPage,
- } = useSQLSnippetFoldersQuery(
- { projectRef, name: debouncedSearchText, sort },
- { keepPreviousData: true }
- )
-
- useEffect(() => {
- if (projectRef && privateSnippetsPages) {
- privateSnippetsPages.pages.forEach((page) => {
- page.contents?.forEach((snippet) => {
- snapV2.addSnippet({
- projectRef,
- snippet,
- })
- })
-
- page.folders?.forEach((folder) => {
- snapV2.addFolder({ projectRef, folder })
- })
- })
- }
- }, [projectRef, privateSnippetsPages?.pages])
+ } = useSQLSnippetFoldersQuery({ projectRef, sort }, { keepPreviousData: true })
const [subResults, setSubResults] = useState<{
[id: string]: { snippets?: Snippet[]; isLoading: boolean }
@@ -169,7 +138,6 @@ export const SQLEditorNav = ({
const { data: snippetCountData } = useContentCountQuery({
projectRef,
type: 'sql',
- name: debouncedSearchText,
})
const numPrivateSnippets = snippetCountData?.private ?? 0
@@ -200,25 +168,11 @@ export const SQLEditorNav = ({
{
projectRef,
favorite: true,
- name: debouncedSearchText,
sort,
},
{ enabled: showFavoriteSnippets, keepPreviousData: true }
)
- useEffect(() => {
- if (projectRef === undefined || !isFavoriteSnippetsSuccess) return
-
- favoriteSqlSnippetsData.pages.forEach((page) => {
- page.contents?.forEach((snippet) => {
- snapV2.addSnippet({
- projectRef,
- snippet,
- })
- })
- })
- }, [projectRef, privateSnippetsPages?.pages])
-
const favoriteSnippets = useMemo(() => {
let snippets = favoriteSqlSnippetsData?.pages.flatMap((page) => page.contents ?? []) ?? []
@@ -265,25 +219,11 @@ export const SQLEditorNav = ({
{
projectRef,
visibility: 'project',
- name: debouncedSearchText,
sort,
},
{ enabled: showSharedSnippets, keepPreviousData: true }
)
- useEffect(() => {
- if (projectRef === undefined || !isSharedSqlSnippetsSuccess) return
-
- sharedSqlSnippetsData.pages.forEach((page) => {
- page.contents?.forEach((snippet) => {
- snapV2.addSnippet({
- projectRef,
- snippet,
- })
- })
- })
- }, [projectRef, privateSnippetsPages?.pages])
-
const sharedSnippets = useMemo(() => {
let snippets = sharedSqlSnippetsData?.pages.flatMap((page) => page.contents ?? []) ?? []
@@ -516,26 +456,60 @@ export const SQLEditorNav = ({
// ===============
useEffect(() => {
- setIsSearching?.(filteredSnippets.isLoading)
- }, [filteredSnippets.isLoading, setIsSearching])
-
- useEffect(() => {
- if (snippet !== undefined && !mountedId) {
+ if (snippet !== undefined && isSuccess) {
if (snippet.visibility === 'project') setShowSharedSnippets(true)
- if (snippet.folder_id) {
- setDefaultExpandedFolderIds([snippet.folder_id])
+ if (snippet.folder_id && !expandedFolderIds.includes(snippet.folder_id)) {
+ setExpandedFolderIds([...expandedFolderIds, snippet.folder_id])
}
-
- // Only want to run this once when loading sql/[id] route
- setMountedId(true)
}
- }, [snippet, mountedId, sort, debouncedSearchText])
+ }, [snippet, sort, isSuccess])
useEffect(() => {
// Unselect all snippets whenever opening another snippet
setSelectedSnippets([])
}, [id])
+ useEffect(() => {
+ if (projectRef && privateSnippetsPages) {
+ privateSnippetsPages.pages.forEach((page) => {
+ page.contents?.forEach((snippet) => {
+ snapV2.addSnippet({
+ projectRef,
+ snippet,
+ })
+ })
+
+ page.folders?.forEach((folder) => snapV2.addFolder({ projectRef, folder }))
+ })
+ }
+ }, [projectRef, privateSnippetsPages?.pages])
+
+ useEffect(() => {
+ if (projectRef === undefined || !isFavoriteSnippetsSuccess) return
+
+ favoriteSqlSnippetsData.pages.forEach((page) => {
+ page.contents?.forEach((snippet) => {
+ snapV2.addSnippet({
+ projectRef,
+ snippet,
+ })
+ })
+ })
+ }, [projectRef, privateSnippetsPages?.pages])
+
+ useEffect(() => {
+ if (projectRef === undefined || !isSharedSqlSnippetsSuccess) return
+
+ sharedSqlSnippetsData.pages.forEach((page) => {
+ page.contents?.forEach((snippet) => {
+ snapV2.addSnippet({
+ projectRef,
+ snippet,
+ })
+ })
+ })
+ }, [projectRef, privateSnippetsPages?.pages])
+
return (
<>
<InnerSideMenuSeparator />
@@ -552,13 +526,9 @@ export const SQLEditorNav = ({
<SQLEditorLoadingSnippets />
) : numProjectSnippets === 0 ? (
<InnerSideBarEmptyPanel
- className={cn('mx-2 px-3', isSearching ? '[&>div>p]:text-foreground-lighter' : '')}
- title={isSearching ? 'No results found based on your search' : 'No shared queries'}
- description={
- isSearching
- ? undefined
- : 'Share queries with your team by right-clicking on the query'
- }
+ className="mx-2 px-3"
+ title="No shared queries"
+ description="Share queries with your team by right-clicking on the query"
/>
) : (
<TreeView
@@ -610,16 +580,14 @@ export const SQLEditorNav = ({
<SQLEditorLoadingSnippets />
) : numFavoriteSnippets === 0 ? (
<InnerSideBarEmptyPanel
- title={isSearching ? 'No results found based on your search' : 'No favorite queries'}
- className={cn('mx-2 px-3', isSearching ? '[&>div>p]:text-foreground-lighter' : '')}
+ title="No favorite queries"
+ className="mx-2 px-3"
description={
- isSearching ? null : (
- <>
- Save a query to favorites for easy accessibility by clicking the{' '}
- <Heart size={12} className="inline-block relative align-center -top-[1px]" />{' '}
- icon.
- </>
- )
+ <>
+ Save a query to favorites for easy accessibility by clicking the{' '}
+ <Heart size={12} className="inline-block relative align-center -top-[1px]" />{' '}
+ icon.
+ </>
}
/>
) : (
@@ -686,7 +654,16 @@ export const SQLEditorNav = ({
data={privateSnippetsTreeState}
selectedIds={selectedSnippets.map((x) => x.id)}
aria-label="private-snippets"
- expandedIds={defaultExpandedFolderIds}
+ onExpand={(props) => {
+ const folderId = props.element.id.toString()
+ if (props.isExpanded && !expandedFolderIds.includes(folderId)) {
+ setExpandedFolderIds([...expandedFolderIds, folderId])
+ }
+ if (!props.isExpanded && expandedFolderIds.includes(folderId)) {
+ setExpandedFolderIds(expandedFolderIds.filter((x) => x !== folderId))
+ }
+ }}
+ expandedIds={expandedFolderIds}
nodeRenderer={({ element, ...props }) => (
<SQLEditorTreeViewItem
{...props}
@@ -747,7 +724,6 @@ export const SQLEditorNav = ({
fetchNextPage={fetchNextPage}
isFetchingNextPage={isFetchingNextPage}
sort={sort}
- name={debouncedSearchText}
onFolderContentsChange={({ isLoading, snippets }) => {
setSubResults((prev) => ({
...prev,
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
new file mode 100644
index 00000000000..104d8f911bc
--- /dev/null
+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SearchList.tsx
@@ -0,0 +1,152 @@
+import { Loader2 } from 'lucide-react'
+import Link from 'next/link'
+import { useMemo } from 'react'
+
+import { useParams } from 'common'
+import InfiniteList from 'components/ui/InfiniteList'
+import { useContentCountQuery } from 'data/content/content-count-query'
+import { useContentIdQuery } from 'data/content/content-id-query'
+import { useContentInfiniteQuery } from 'data/content/content-infinite-query'
+import { Content } from 'data/content/content-query'
+import { SNIPPET_PAGE_LIMIT } from 'data/content/sql-folders-query'
+import { SqlSnippets } from 'types'
+import {
+ cn,
+ CodeBlock,
+ HoverCard_Shadcn_,
+ HoverCardContent_Shadcn_,
+ HoverCardTrigger_Shadcn_,
+ ScrollArea,
+ SQL_ICON,
+} from 'ui'
+import ShimmeringLoader from 'ui-patterns/ShimmeringLoader'
+
+interface SearchListProps {
+ search: string
+ onSelectSnippet: () => void
+}
+
+export const SearchList = ({ search, onSelectSnippet }: SearchListProps) => {
+ const { ref: projectRef } = useParams()
+
+ const { data, isLoading, hasNextPage, fetchNextPage, isFetchingNextPage } =
+ useContentInfiniteQuery(
+ {
+ projectRef,
+ type: 'sql',
+ limit: SNIPPET_PAGE_LIMIT,
+ name: search.length === 0 ? undefined : search,
+ },
+ { keepPreviousData: true }
+ )
+
+ const { data: count, isLoading: isLoadingCount } = useContentCountQuery(
+ {
+ projectRef,
+ cumulative: true,
+ type: 'sql',
+ name: search,
+ },
+ { keepPreviousData: true }
+ )
+ const totalNumber = (count as unknown as { count: number })?.count ?? 0
+
+ const snippets = useMemo(() => data?.pages.flatMap((page) => page.content), [data?.pages])
+
+ return (
+ <div className="flex flex-col flex-grow">
+ {isLoading ? (
+ <div className="px-4 py-1 pb-2.5">
+ <Loader2 className="animate-spin" size={14} />
+ </div>
+ ) : !!count ? (
+ <p className="px-4 pb-2 text-sm text-foreground-lighter">
+ {totalNumber} result{totalNumber > 1 ? 's' : ''} found
+ </p>
+ ) : null}
+ {isLoading ? (
+ <div className="px-4 flex flex-col gap-y-1">
+ <ShimmeringLoader className="py-2.5" />
+ <ShimmeringLoader className="py-2.5 w-5/6" />
+ <ShimmeringLoader className="py-2.5 w-3/4" />
+ </div>
+ ) : (
+ <InfiniteList
+ items={snippets}
+ ItemComponent={(props) => (
+ <SearchListItem snippet={props.item} onSelectSnippet={onSelectSnippet} />
+ )}
+ itemProps={{}}
+ getItemSize={() => 28}
+ hasNextPage={hasNextPage}
+ isLoadingNextPage={isFetchingNextPage}
+ onLoadNextPage={() => fetchNextPage()}
+ />
+ )}
+ </div>
+ )
+}
+
+const SearchListItem = ({
+ snippet,
+ onSelectSnippet,
+}: {
+ snippet: Content
+ onSelectSnippet: () => void
+}) => {
+ const { ref } = useParams()
+ return (
+ <HoverCard_Shadcn_ openDelay={500} closeDelay={100}>
+ <HoverCardTrigger_Shadcn_>
+ <Link
+ className="h-full flex items-center gap-x-3 pl-4 hover:bg-control"
+ href={`/project/${ref}/sql/${snippet.id}`}
+ onClick={() => onSelectSnippet()}
+ >
+ <SQL_ICON
+ size={16}
+ strokeWidth={1.5}
+ className="w-5 h-5 -ml-0.5 transition-colors fill-foreground-muted group-aria-selected:fill-foreground"
+ />
+ <p className="text-sm text-foreground-light truncate">{snippet.name}</p>
+ </Link>
+ </HoverCardTrigger_Shadcn_>
+ <HoverCardContent_Shadcn_ side="right" className="p-0 w-[300px]">
+ <SearchItemListHover id={snippet.id} />
+ </HoverCardContent_Shadcn_>
+ </HoverCard_Shadcn_>
+ )
+}
+
+const SearchItemListHover = ({ id }: { id: string }) => {
+ const { ref } = useParams()
+ const { data, isLoading } = useContentIdQuery({ projectRef: ref, id })
+ const sql = (data?.content as SqlSnippets.Content)?.sql ?? ''
+ const newLines = (sql.match(new RegExp('\n', 'g')) || []).length
+
+ return (
+ <div>
+ {isLoading ? (
+ <div className="p-2">
+ <ShimmeringLoader />
+ </div>
+ ) : sql.length === 0 ? (
+ <div className="px-4 py-2">
+ <p className="text-xs text-foreground-lighter">Snippet is empty</p>
+ </div>
+ ) : (
+ <ScrollArea className={cn(newLines > 6 ? 'h-[140px]' : '')}>
+ <CodeBlock
+ hideLineNumbers
+ language="sql"
+ value={sql}
+ className={cn(
+ 'border-0 py-0 px-3 max-w-full prose dark:prose-dark text-xs',
+ '[&>code]:m-0 [&>code>span]:flex [&>code>span]:flex-wrap'
+ )}
+ />
+ </ScrollArea>
+ )}
+ </div>
+ )
+}
diff --git a/apps/studio/data/content/content-count-query.ts b/apps/studio/data/content/content-count-query.ts
index 513e42b54f8..d6201e01f69 100644
--- a/apps/studio/data/content/content-count-query.ts
+++ b/apps/studio/data/content/content-count-query.ts
@@ -8,10 +8,11 @@ import { contentKeys } from './keys'
type GetContentCountVariables =
operations['ContentController_getContentCountV2']['parameters']['query'] & {
projectRef?: string
+ cumulative?: boolean
}
export async function getContentCount(
- { projectRef, type, name }: GetContentCountVariables,
+ { projectRef, cumulative, type, name }: GetContentCountVariables,
signal?: AbortSignal
) {
if (typeof projectRef === 'undefined') throw new Error('projectRef is required')
@@ -24,7 +25,7 @@ export async function getContentCount(
...(name && { name }),
},
},
- headers: { Version: '2' },
+ ...(cumulative ? {} : { headers: { Version: '2' } }),
signal,
})
@@ -36,14 +37,15 @@ export type ContentIdData = Awaited<ReturnType<typeof getContentCount>>
export type ContentIdError = ResponseError
export const useContentCountQuery = <TData = ContentIdData>(
- { projectRef, type, name }: GetContentCountVariables,
+ { projectRef, cumulative, type, name }: GetContentCountVariables,
{ enabled = true, ...options }: UseQueryOptions<ContentIdData, ContentIdError, TData> = {}
) =>
useQuery<ContentIdData, ContentIdError, TData>(
contentKeys.count(projectRef, type, {
+ cumulative,
name,
}),
- ({ signal }) => getContentCount({ projectRef, type, name }, signal),
+ ({ signal }) => getContentCount({ projectRef, cumulative, type, name }, signal),
{
enabled: enabled && typeof projectRef !== 'undefined',
...options,
diff --git a/apps/studio/data/content/content-infinite-query.ts b/apps/studio/data/content/content-infinite-query.ts
new file mode 100644
index 00000000000..00c77b1e11d
--- /dev/null
+++ b/apps/studio/data/content/content-infinite-query.ts
@@ -0,0 +1,63 @@
+import { useInfiniteQuery, UseInfiniteQueryOptions } from '@tanstack/react-query'
+
+import { get, handleError } from 'data/fetchers'
+import { Content, ContentType } from './content-query'
+import { contentKeys } from './keys'
+
+interface GetContentVariables {
+ projectRef?: string
+ cursor?: string
+ type: ContentType
+ name?: string
+ limit?: number
+ sort?: 'name' | 'inserted_at'
+}
+
+export async function getContent(
+ { projectRef, type, name, limit = 10, sort, cursor }: GetContentVariables,
+ signal?: AbortSignal
+) {
+ if (typeof projectRef === 'undefined') {
+ throw new Error('projectRef is required for getContent')
+ }
+
+ const { data, error } = await get('/platform/projects/{ref}/content', {
+ params: {
+ path: { ref: projectRef },
+ query: {
+ type,
+ name,
+ sort_by: sort,
+ limit: limit.toString(),
+ cursor,
+ },
+ },
+ signal,
+ })
+
+ if (error) handleError(error)
+
+ return {
+ cursor: data.cursor,
+ content: data.data as unknown as Content[],
+ }
+}
+
+export type ContentData = Awaited<ReturnType<typeof getContent>>
+export type ContentError = unknown
+
+export const useContentInfiniteQuery = <TData = ContentData>(
+ { projectRef, type, name, limit, sort }: GetContentVariables,
+ { enabled = true, ...options }: UseInfiniteQueryOptions<ContentData, ContentError, TData> = {}
+) => {
+ return useInfiniteQuery<ContentData, ContentError, TData>(
+ contentKeys.infiniteList(projectRef, { type, name, limit, sort }),
+ ({ signal, pageParam }) =>
+ getContent({ projectRef, type, name, limit, sort, cursor: pageParam }, signal),
+ {
+ enabled: enabled && typeof projectRef !== 'undefined',
+ getNextPageParam: (lastPage) => lastPage.cursor,
+ ...options,
+ }
+ )
+}
diff --git a/apps/studio/data/content/content-query.ts b/apps/studio/data/content/content-query.ts
index fbde6e51fd5..27c77c8ff9c 100644
--- a/apps/studio/data/content/content-query.ts
+++ b/apps/studio/data/content/content-query.ts
@@ -1,7 +1,7 @@
import { useQuery, UseQueryOptions } from '@tanstack/react-query'
import { components } from 'api-types'
-import { get } from 'data/fetchers'
+import { get, handleError } from 'data/fetchers'
import type { Dashboards, LogSqlSnippets, SqlSnippets } from 'types'
import { contentKeys } from './keys'
@@ -29,10 +29,11 @@ interface GetContentVariables {
projectRef?: string
type: ContentType
name?: string
+ limit?: number
}
export async function getContent(
- { projectRef, type, name }: GetContentVariables,
+ { projectRef, type, name, limit = 10 }: GetContentVariables,
signal?: AbortSignal
) {
if (typeof projectRef === 'undefined') {
@@ -40,13 +41,11 @@ export async function getContent(
}
const { data, error } = await get('/platform/projects/{ref}/content', {
- params: { path: { ref: projectRef }, query: { type, name } },
+ params: { path: { ref: projectRef }, query: { type, name, limit: limit.toString() } },
signal,
})
- if (error) {
- throw error
- }
+ if (error) handleError(error)
return {
cursor: data.cursor,
@@ -57,12 +56,13 @@ export async function getContent(
export type ContentData = Awaited<ReturnType<typeof getContent>>
export type ContentError = unknown
+/** @deprecated Use useContentInfiniteQuery from content-infinite-query instead */
export const useContentQuery = <TData = ContentData>(
- { projectRef, type, name }: GetContentVariables,
+ { projectRef, type, name, limit }: GetContentVariables,
{ enabled = true, ...options }: UseQueryOptions<ContentData, ContentError, TData> = {}
) =>
useQuery<ContentData, ContentError, TData>(
- contentKeys.list(projectRef, { type, name }),
- ({ signal }) => getContent({ projectRef, type, name }, signal),
+ contentKeys.list(projectRef, { type, name, limit }),
+ ({ signal }) => getContent({ projectRef, type, name, limit }, signal),
{ enabled: enabled && typeof projectRef !== 'undefined', ...options }
)
diff --git a/apps/studio/data/content/keys.ts b/apps/studio/data/content/keys.ts
index 7078bf75f73..bb13ee08472 100644
--- a/apps/studio/data/content/keys.ts
+++ b/apps/studio/data/content/keys.ts
@@ -3,9 +3,18 @@ import type { SqlSnippet } from './sql-snippets-query'
export const contentKeys = {
allContentLists: (projectRef: string | undefined) => ['projects', projectRef, 'content'] as const,
+ infiniteList: (
+ projectRef: string | undefined,
+ options: {
+ type: ContentType | undefined
+ name: string | undefined
+ limit?: number
+ sort?: string
+ }
+ ) => ['projects', projectRef, 'content-infinite', options] as const,
list: (
projectRef: string | undefined,
- options: { type: ContentType | undefined; name: string | undefined }
+ options: { type?: ContentType; name?: string; limit?: number }
) => ['projects', projectRef, 'content', options] as const,
sqlSnippets: (
projectRef: string | undefined,
@@ -30,6 +39,11 @@ export const contentKeys = {
count: (
projectRef: string | undefined,
type?: string,
- options?: { visibility?: SqlSnippet['visibility']; favorite?: boolean; name?: string }
+ options?: {
+ cumulative?: boolean
+ visibility?: SqlSnippet['visibility']
+ favorite?: boolean
+ name?: string
+ }
) => ['projects', projectRef, 'content', 'count', type, options].filter(Boolean),
}
diff --git a/apps/studio/data/content/sql-folder-contents-query.ts b/apps/studio/data/content/sql-folder-contents-query.ts
index ff3e4fe2019..a792caf3f11 100644
--- a/apps/studio/data/content/sql-folder-contents-query.ts
+++ b/apps/studio/data/content/sql-folder-contents-query.ts
@@ -36,7 +36,7 @@ export async function getSQLSnippetFolderContents(
signal,
})
- if (error) throw handleError(error)
+ if (error) handleError(error)
return {
...data.data,
cursor: data.cursor,
diff --git a/apps/studio/data/content/sql-folders-query.ts b/apps/studio/data/content/sql-folders-query.ts
index 4da5cf1cf89..ba881f36157 100644
--- a/apps/studio/data/content/sql-folders-query.ts
+++ b/apps/studio/data/content/sql-folders-query.ts
@@ -43,7 +43,7 @@ export async function getSQLSnippetFolders(
signal,
})
- if (error) throw handleError(error)
+ if (error) handleError(error)
return {
...data.data,
cursor: data.cursor,
diff --git a/packages/ui-patterns/InnerSideMenu/index.tsx b/packages/ui-patterns/InnerSideMenu/index.tsx
index 53b9afc688b..8dc98935f07 100644
--- a/packages/ui-patterns/InnerSideMenu/index.tsx
+++ b/packages/ui-patterns/InnerSideMenu/index.tsx
@@ -197,7 +197,7 @@ const InnerSideBarFilterSortDropdown = forwardRef<
asChild
className={cn(
'absolute right-1 top-[.4rem] md:top-[.3rem]',
- 'text-foreground-muted transition-colors hover:text-foreground data-[state=open]:text-foreground',
+ 'text-foreground transition-colors hover:text-foreground data-[state=open]:text-foreground',
triggerClassName
)}
>
diff --git a/packages/ui/src/components/shadcn/ui/context-menu.tsx b/packages/ui/src/components/shadcn/ui/context-menu.tsx
index 3b14e960011..e680e7959f2 100644
--- a/packages/ui/src/components/shadcn/ui/context-menu.tsx
+++ b/packages/ui/src/components/shadcn/ui/context-menu.tsx
@@ -1,8 +1,8 @@
'use client'
-import * as React from 'react'
import * as ContextMenuPrimitive from '@radix-ui/react-context-menu'
import { Check, ChevronRight, Circle } from 'lucide-react'
+import * as React from 'react'
import { cn } from '../../../lib/utils/cn'
@@ -172,18 +172,18 @@ ContextMenuShortcut.displayName = 'ContextMenuShortcut'
export {
ContextMenu,
- ContextMenuTrigger,
+ ContextMenuCheckboxItem,
ContextMenuContent,
+ ContextMenuGroup,
ContextMenuItem,
- ContextMenuCheckboxItem,
- ContextMenuRadioItem,
ContextMenuLabel,
+ ContextMenuPortal,
+ ContextMenuRadioGroup,
+ ContextMenuRadioItem,
ContextMenuSeparator,
ContextMenuShortcut,
- ContextMenuGroup,
- ContextMenuPortal,
ContextMenuSub,
ContextMenuSubContent,
ContextMenuSubTrigger,
- ContextMenuRadioGroup,
+ ContextMenuTrigger,
}
diff --git a/packages/ui/src/components/shadcn/ui/hover-card.tsx b/packages/ui/src/components/shadcn/ui/hover-card.tsx
index 450c73581ca..e898899d081 100644
--- a/packages/ui/src/components/shadcn/ui/hover-card.tsx
+++ b/packages/ui/src/components/shadcn/ui/hover-card.tsx
@@ -15,19 +15,21 @@ const HoverCardContent = React.forwardRef<
animate?: 'zoom-in' | 'slide-in'
}
>(({ className, align = 'center', animate = 'zoom-in', sideOffset = 4, ...props }, ref) => (
- <HoverCardPrimitive.Content
- ref={ref}
- align={align}
- sideOffset={sideOffset}
- className={cn(
- 'z-50 w-64 rounded-md border bg-overlay p-4 text-popover-foreground shadow-md outline-none',
- animate === 'zoom-in'
- ? 'animate-in zoom-in-[99%]'
- : 'animate-in fade-in-50 data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1',
- className
- )}
- {...props}
- />
+ <HoverCardPrimitive.Portal>
+ <HoverCardPrimitive.Content
+ ref={ref}
+ align={align}
+ sideOffset={sideOffset}
+ className={cn(
+ 'z-50 w-64 rounded-md border bg-overlay p-4 text-popover-foreground shadow-md outline-none',
+ animate === 'zoom-in'
+ ? 'animate-in zoom-in-[99%]'
+ : 'animate-in fade-in-50 data-[side=bottom]:slide-in-from-top-1 data-[side=left]:slide-in-from-right-1 data-[side=right]:slide-in-from-left-1 data-[side=top]:slide-in-from-bottom-1',
+ className
+ )}
+ {...props}
+ />
+ </HoverCardPrimitive.Portal>
))
HoverCardContent.displayName = HoverCardPrimitive.Content.displayName