The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
feat(reports): add optimistic delete for custom reports (#46803)
Jordi Enric4c011cf9c000
diff --git a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.tsx b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.tsxindex a9087d161f9..bea6aa28bf5 100644--- a/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.tsx+++ b/apps/studio/components/layouts/ObservabilityLayout/ObservabilityMenu.tsx@@ -65,15 +65,10 @@ const ObservabilityMenu = () => {projectRef: ref,type: 'report',})- const { mutate: deleteReport, isPending: isDeleting } = useContentDeleteMutation({- onSuccess: () => {- setDeleteModalOpen(false)- toast.success('Successfully deleted report')- router.push(`/project/${ref}/observability`)- },- onError: (error) => {- toast.error(`Failed to delete report: ${error.message}`)- },+ const { mutateAsync: deleteReport } = useContentDeleteMutation({+ // Toasts are driven by toast.promise in onConfirmDeleteReport. This no-op keeps the hook+ // from showing its own default error toast, while its optimistic rollback still runs.+ onError: () => {},})const [deleteModalOpen, setDeleteModalOpen] = useState(false)@@ -87,7 +82,26 @@ const ObservabilityMenu = () => {const onConfirmDeleteReport = () => {if (ref === undefined) return console.error('Project ref is required')if (selectedReportToDelete?.id === undefined) return console.error('Report ID is required')- deleteReport({ projectRef: ref, ids: [selectedReportToDelete.id] })+ const reportId = selectedReportToDelete.id+ const isViewingDeletedReport = id === reportId+ setDeleteModalOpen(false)++ const deletion = deleteReport({ projectRef: ref, ids: [reportId] })+ toast.promise(deletion, {+ loading: 'Deleting report...',+ success: 'Report deleted',+ error: (err) => `Failed to delete report: ${err?.message ?? 'Unknown error'}`,+ })++ // Only navigate away when the open report is the one deleted, and only after it+ // succeeds so a failed delete (which rolls the cache back) doesn't strand the route.+ deletion+ .then(() => {+ if (isViewingDeletedReport) router.push(`/project/${ref}/observability`)+ })+ .catch(() => {+ // Error is already surfaced by toast.promise; keep the user on the current route.+ })}function isReportContent(c: Content): c is ContentBase & {@@ -255,9 +269,8 @@ const ObservabilityMenu = () => {<ConfirmationModaltitle="Delete custom report"confirmLabel="Delete report"- confirmLabelLoading="Deleting report"size="medium"- loading={isDeleting}+ loading={false}visible={deleteModalOpen}onCancel={() => setDeleteModalOpen(false)}onConfirm={onConfirmDeleteReport}diff --git a/apps/studio/components/layouts/ReportsLayout/ReportMenuItem.tsx b/apps/studio/components/layouts/ReportsLayout/ReportMenuItem.tsxdeleted file mode 100644index c1d9498d682..00000000000--- a/apps/studio/components/layouts/ReportsLayout/ReportMenuItem.tsx+++ /dev/null@@ -1,111 +0,0 @@-import { PermissionAction } from '@supabase/shared-types/out/constants'-import { ChevronDown, Edit2, Trash } from 'lucide-react'-import Link from 'next/link'-import {- Button,- DropdownMenu,- DropdownMenuContent,- DropdownMenuItem,- DropdownMenuSeparator,- DropdownMenuTrigger,- Menu,-} from 'ui'--import { ContentBase } from '@/data/content/content-query'-import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'-import { useProfile } from '@/lib/profile'-import type { Dashboards } from '@/types'--interface ReportMenuItemProps {- item: {- id?: string- name: string- description: string- key: string- url: string- hasDropdownActions: boolean- report: ContentBase & {- type: 'report'- content: Dashboards.Content- }- }- pageKey: string- onSelectEdit: () => void- onSelectDelete: () => void-}--export const ReportMenuItem = ({- item,- pageKey,- onSelectEdit,- onSelectDelete,-}: ReportMenuItemProps) => {- const { profile } = useProfile()- const { can: canUpdateCustomReport } = useAsyncCheckPermissions(- PermissionAction.UPDATE,- 'user_content',- {- resource: {- type: 'report',- visibility: item.report.visibility,- owner_id: item.report.owner_id,- },- subject: { id: profile?.id },- }- )-- const menuItem = (- <Menu.Item active={item.key === pageKey}>- <div className="flex w-full items-center justify-between gap-1">- <span className="truncate">{item.name}</span>-- {canUpdateCustomReport && (- <DropdownMenu>- <DropdownMenuTrigger asChild>- <Button- type="text"- className="px-1 opacity-50 hover:opacity-100"- icon={<ChevronDown size={12} strokeWidth={2} />}- onClick={(e) => {- e.preventDefault()- e.stopPropagation()- }}- />- </DropdownMenuTrigger>- <DropdownMenuContent align="start" className="w-32 *:gap-x-2">- <DropdownMenuItem- onClick={(e) => {- e.preventDefault()- e.stopPropagation()- if (!item.id) return- onSelectEdit()- }}- >- <Edit2 size={12} />- <div>Rename report</div>- </DropdownMenuItem>- <DropdownMenuSeparator />- <DropdownMenuItem- onClick={(e) => {- e.preventDefault()- e.stopPropagation()- if (!item.id) return- onSelectDelete()- }}- >- <Trash size={12} />- <div>Delete report</div>- </DropdownMenuItem>- </DropdownMenuContent>- </DropdownMenu>- )}- </div>- </Menu.Item>- )-- return (- <Link key={item.key + '-menukey'} href={item.url} className="block">- {menuItem}- </Link>- )-}diff --git a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx b/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsxdeleted file mode 100644index 0a03b22f9cf..00000000000--- a/apps/studio/components/layouts/ReportsLayout/ReportsMenu.tsx+++ /dev/null@@ -1,266 +0,0 @@-import { PermissionAction } from '@supabase/shared-types/out/constants'-import { useParams } from 'common'-import { Plus } from 'lucide-react'-import { useRouter } from 'next/router'-import { parseAsBoolean, useQueryState } from 'nuqs'-import { useMemo, useState } from 'react'-import { toast } from 'sonner'-import { Menu } from 'ui'-import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'-import { ShimmeringLoader } from 'ui-patterns/ShimmeringLoader'--import { ReportMenuItem } from './ReportMenuItem'-import { CreateReportModal } from '@/components/interfaces/Reports/CreateReportModal'-import { UpdateCustomReportModal } from '@/components/interfaces/Reports/UpdateModal'-import { ButtonTooltip } from '@/components/ui/ButtonTooltip'-import { ProductMenu } from '@/components/ui/ProductMenu'-import { useContentDeleteMutation } from '@/data/content/content-delete-mutation'-import { Content, useContentQuery } from '@/data/content/content-query'-import { useAsyncCheckPermissions } from '@/hooks/misc/useCheckPermissions'-import { useIsFeatureEnabled } from '@/hooks/misc/useIsFeatureEnabled'-import { useProfile } from '@/lib/profile'--const ReportsMenu = () => {- const router = useRouter()- const { profile } = useProfile()- const { ref, id } = useParams()- const pageKey = (id || router.pathname.split('/')[4]) as string-- const storageSupported = useIsFeatureEnabled('project_storage:all')-- const { can: canCreateCustomReport } = useAsyncCheckPermissions(- PermissionAction.CREATE,- 'user_content',- {- resource: { type: 'report', owner_id: profile?.id },- subject: { id: profile?.id },- }- )-- // Preserve date range query parameters when navigating- const preservedQueryParams = useMemo(() => {- const { its, ite, isHelper, helperText } = router.query- const params = new URLSearchParams()-- if (its && typeof its === 'string') params.set('its', its)- if (ite && typeof ite === 'string') params.set('ite', ite)- if (isHelper && typeof isHelper === 'string') params.set('isHelper', isHelper)- if (helperText && typeof helperText === 'string') params.set('helperText', helperText)-- const queryString = params.toString()- return queryString ? `?${queryString}` : ''- }, [router.query])-- const { data: content, isPending: isLoading } = useContentQuery({- projectRef: ref,- type: 'report',- })- const { mutate: deleteReport, isPending: isDeleting } = useContentDeleteMutation({- onSuccess: () => {- setDeleteModalOpen(false)- toast.success('Successfully deleted report')- router.push(`/project/${ref}/reports`)- },- onError: (error) => {- toast.error(`Failed to delete report: ${error.message}`)- },- })-- const [deleteModalOpen, setDeleteModalOpen] = useState(false)- const [showNewReportModal, setShowNewReportModal] = useQueryState(- 'newReport',- parseAsBoolean.withDefault(false).withOptions({ history: 'push', clearOnDefault: true })- )- const [selectedReportToDelete, setSelectedReportToDelete] = useState<Content>()- const [selectedReportToUpdate, setSelectedReportToUpdate] = useState<Content>()-- const onConfirmDeleteReport = () => {- if (ref === undefined) return console.error('Project ref is required')- if (selectedReportToDelete?.id === undefined) return console.error('Report ID is required')- deleteReport({ projectRef: ref, ids: [selectedReportToDelete.id] })- }-- function getReportMenuItems() {- if (!content) return []-- const reports = content?.content.filter((c) => c.type === 'report')-- const sortedReports = reports?.sort((a, b) => {- if (a.name < b.name) {- return -1- }- if (a.name > b.name) {- return 1- }- return 0- })-- const reportMenuItems = sortedReports.map((r, idx) => ({- id: r.id,- name: r.name,- description: r.description || '',- key: r.id || idx + '-report',- url: `/project/${ref}/reports/${r.id}${preservedQueryParams}`,- hasDropdownActions: true,- report: r,- }))-- return reportMenuItems- }-- const reportMenuItems = getReportMenuItems()-- const menuItems = [- {- title: 'Built-in reports',- key: 'builtin-reports',- items: [- {- name: 'API Gateway',- key: 'api-overview',- url: `/project/${ref}/reports/api-overview${preservedQueryParams}`,- },- {- name: 'Auth',- key: 'auth',- url: `/project/${ref}/reports/auth${preservedQueryParams}`,- },- {- name: 'Database',- key: 'database',- url: `/project/${ref}/reports/database${preservedQueryParams}`,- },- {- name: 'Edge Functions',- key: 'edge-functions',- url: `/project/${ref}/reports/edge-functions${preservedQueryParams}`,- },- {- name: 'Query Performance',- key: 'query-performance',- url: `/project/${ref}/reports/query-performance${preservedQueryParams}`,- },- {- name: 'PostgREST',- key: 'postgrest',- url: `/project/${ref}/reports/postgrest${preservedQueryParams}`,- },- {- name: 'Realtime',- key: 'realtime',- url: `/project/${ref}/reports/realtime${preservedQueryParams}`,- },- ...(storageSupported- ? [- {- name: 'Storage',- key: 'storage',- url: `/project/${ref}/reports/storage${preservedQueryParams}`,- },- ]- : []),- ],- },- ]-- return (- <div className="mt-6">- {isLoading ? (- <div className="px-5 my-4 space-y-2">- <ShimmeringLoader />- <ShimmeringLoader className="w-3/4" />- <ShimmeringLoader className="w-1/2" />- </div>- ) : (- <div className="flex flex-col px-2 gap-y-6">- <div className="px-2">- <ButtonTooltip- block- type="default"- icon={<Plus />}- disabled={!canCreateCustomReport}- className="justify-start grow"- onClick={() => {- setShowNewReportModal(true)- }}- tooltip={{- content: {- side: 'bottom',- text: !canCreateCustomReport- ? 'You need additional permissions to create custom reports'- : undefined,- },- }}- >- New custom report- </ButtonTooltip>- </div>-- {reportMenuItems.length > 0 ? (- <Menu type="pills">- <Menu.Group- title={<span className="uppercase font-mono">Your custom reports</span>}- />- {reportMenuItems.map((item) => (- <ReportMenuItem- key={item.id}- item={item as any}- pageKey={pageKey}- onSelectEdit={() => {- setSelectedReportToUpdate(item.report)- }}- onSelectDelete={() => {- setSelectedReportToDelete(item.report)- setDeleteModalOpen(true)- }}- />- ))}- </Menu>- ) : null}-- <ProductMenu- page={pageKey}- menu={menuItems.map((item) => ({- ...item,- items: item.items.map((subItem) => ({ ...subItem, items: [] })),- }))}- />-- <UpdateCustomReportModal- onCancel={() => setSelectedReportToUpdate(undefined)}- selectedReport={selectedReportToUpdate}- initialValues={{- name: selectedReportToUpdate?.name || '',- description: selectedReportToUpdate?.description || '',- }}- />-- <ConfirmationModal- title="Delete custom report"- confirmLabel="Delete report"- confirmLabelLoading="Deleting report"- size="medium"- loading={isDeleting}- visible={deleteModalOpen}- onCancel={() => setDeleteModalOpen(false)}- onConfirm={onConfirmDeleteReport}- >- <div className="text-sm text-foreground-light grid gap-4">- <div className="grid gap-1">- <p>Are you sure you want to delete '{selectedReportToDelete?.name}'?</p>- </div>- </div>- </ConfirmationModal>-- <CreateReportModal- visible={showNewReportModal}- onCancel={() => setShowNewReportModal(false)}- afterSubmit={() => setShowNewReportModal(false)}- />- </div>- )}- </div>- )-}--export default ReportsMenudiff --git a/apps/studio/data/content/content-delete-mutation.test.ts b/apps/studio/data/content/content-delete-mutation.test.tsnew file mode 100644index 00000000000..41541dc9090--- /dev/null+++ b/apps/studio/data/content/content-delete-mutation.test.ts@@ -0,0 +1,37 @@+import { describe, expect, it } from 'vitest'++import { removeContentFromList } from './content-delete-mutation'+import type { ContentData } from './content-query'++const makeListData = (ids: string[]): ContentData => ({+ cursor: 'next-cursor',+ content: ids.map((id) => ({ id, name: id, type: 'report' })) as ContentData['content'],+})++describe('removeContentFromList', () => {+ it('removes a single matching id', () => {+ const result = removeContentFromList(makeListData(['a', 'b', 'c']), ['b'])+ expect(result.content.map((item) => item.id)).toEqual(['a', 'c'])+ })++ it('removes multiple matching ids', () => {+ const result = removeContentFromList(makeListData(['a', 'b', 'c']), ['a', 'c'])+ expect(result.content.map((item) => item.id)).toEqual(['b'])+ })++ it('leaves the list unchanged when no ids match', () => {+ const result = removeContentFromList(makeListData(['a', 'b']), ['x'])+ expect(result.content.map((item) => item.id)).toEqual(['a', 'b'])+ })++ it('preserves sibling fields such as cursor', () => {+ const result = removeContentFromList(makeListData(['a']), ['a'])+ expect(result.cursor).toBe('next-cursor')+ })++ it('does not mutate the input data', () => {+ const input = makeListData(['a', 'b'])+ removeContentFromList(input, ['a'])+ expect(input.content.map((item) => item.id)).toEqual(['a', 'b'])+ })+})diff --git a/apps/studio/data/content/content-delete-mutation.ts b/apps/studio/data/content/content-delete-mutation.tsindex 7466cced8ca..dcd6f94f7aa 100644--- a/apps/studio/data/content/content-delete-mutation.ts+++ b/apps/studio/data/content/content-delete-mutation.ts@@ -1,11 +1,14 @@import { useMutation, useQueryClient } from '@tanstack/react-query'+import type { QueryKey } from '@tanstack/react-query'import { toast } from 'sonner'+import type { ContentData } from './content-query'import { contentKeys } from './keys'import { del, handleError } from '@/data/fetchers'import type { ResponseError, UseCustomMutationOptions } from '@/types'type DeleteContentVariables = { projectRef: string; ids: string[] }+type DeleteContext = { snapshots: [QueryKey, ContentData | undefined][] }export async function deleteContents({ projectRef, ids }: DeleteContentVariables,@@ -26,18 +29,40 @@ export async function deleteContents(type DeleteContentData = Awaited<ReturnType<typeof deleteContents>>+/** Returns a copy of a cached content list with the given ids removed. Exported for testing. */+export function removeContentFromList(data: ContentData, ids: string[]): ContentData {+ return { ...data, content: data.content.filter((item) => !ids.includes(item.id)) }+}+export const useContentDeleteMutation = ({onSuccess,onError,...options}: Omit<- UseCustomMutationOptions<DeleteContentData, ResponseError, DeleteContentVariables>,+ UseCustomMutationOptions<DeleteContentData, ResponseError, DeleteContentVariables, DeleteContext>,'mutationFn'> = {}) => {const queryClient = useQueryClient()- return useMutation<DeleteContentData, ResponseError, DeleteContentVariables>({+ return useMutation<DeleteContentData, ResponseError, DeleteContentVariables, DeleteContext>({mutationFn: (args) => deleteContents(args),+ async onMutate({ projectRef, ids }) {+ await queryClient.cancelQueries({ queryKey: contentKeys.allContentLists(projectRef) })++ const snapshots = queryClient.getQueriesData<ContentData>({+ queryKey: contentKeys.allContentLists(projectRef),+ })++ // allContentLists is a prefix of sibling caches (sql snippets, folders, counts) that+ // don't share the { content: [...] } shape, so only optimistically update entries that do.+ for (const [queryKey, data] of snapshots) {+ if (data && Array.isArray(data.content)) {+ queryClient.setQueryData<ContentData>(queryKey, removeContentFromList(data, ids))+ }+ }++ return { snapshots }+ },async onSuccess(data, variables, context) {const { projectRef } = variablesawait Promise.all([@@ -47,11 +72,18 @@ export const useContentDeleteMutation = ({await onSuccess?.(data, variables, context)},- async onError(data, variables, context) {+ async onError(error, variables, context) {+ // Restore the snapshots captured in onMutate before surfacing the error.+ if (context?.snapshots) {+ for (const [queryKey, data] of context.snapshots) {+ queryClient.setQueryData(queryKey, data)+ }+ }+if (onError === undefined) {- toast.error(`Failed to delete contents: ${data.message}`)+ toast.error(`Failed to delete contents: ${error.message}`)} else {- onError(data, variables, context)+ onError(error, variables, context)}},...options,