Skip to content

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

Drag query to home (#39506)

Saxon Fletcher43b686e31a1c
diff --git a/apps/studio/components/interfaces/HomeNew/CustomReportSection.tsx b/apps/studio/components/interfaces/HomeNew/CustomReportSection.tsx
index 91a635f39aa..62e4c9fb4f5 100644
--- a/apps/studio/components/interfaces/HomeNew/CustomReportSection.tsx
+++ b/apps/studio/components/interfaces/HomeNew/CustomReportSection.tsx
@@ -9,14 +9,15 @@ import {
import { SortableContext, arrayMove, rectSortingStrategy, useSortable } from '@dnd-kit/sortable'
import { PermissionAction } from '@supabase/shared-types/out/constants'
import dayjs from 'dayjs'
+import type { CSSProperties, DragEvent, ReactNode } from 'react'
import { Plus, RefreshCw } from 'lucide-react'
-import type { CSSProperties, ReactNode } from 'react'
import { useCallback, useEffect, useMemo, useState } from 'react'
import { toast } from 'sonner'
import { useParams } from 'common'
import { SnippetDropdown } from 'components/interfaces/HomeNew/SnippetDropdown'
import { ReportBlock } from 'components/interfaces/Reports/ReportBlock/ReportBlock'
+import { createSqlSnippetSkeletonV2 } from 'components/interfaces/SQLEditor/SQLEditor.utils'
import type { ChartConfig } from 'components/interfaces/SQLEditor/UtilityPanel/ChartConfig'
import { ButtonTooltip } from 'components/ui/ButtonTooltip'
import { DEFAULT_CHART_CONFIG } from 'components/ui/QueryBlock/QueryBlock'
@@ -24,10 +25,14 @@ import { AnalyticsInterval } from 'data/analytics/constants'
import { useInvalidateAnalyticsQuery } from 'data/analytics/utils'
import { useContentInfiniteQuery } from 'data/content/content-infinite-query'
import { Content } from 'data/content/content-query'
-import { useContentUpsertMutation } from 'data/content/content-upsert-mutation'
+import {
+ UpsertContentPayload,
+ useContentUpsertMutation,
+} from 'data/content/content-upsert-mutation'
import { useSendEventMutation } from 'data/telemetry/send-event-mutation'
import { useAsyncCheckPermissions } from 'hooks/misc/useCheckPermissions'
import { useSelectedOrganizationQuery } from 'hooks/misc/useSelectedOrganization'
+import { useSelectedProjectQuery } from 'hooks/misc/useSelectedProject'
import { uuidv4 } from 'lib/helpers'
import { useProfile } from 'lib/profile'
import { useDatabaseSelectorStateSnapshot } from 'state/database-selector'
@@ -45,6 +50,7 @@ export function CustomReportSection() {
const { data: organization } = useSelectedOrganizationQuery()
const { mutate: sendEvent } = useSendEventMutation()
const { invalidateInfraMonitoringQuery } = useInvalidateAnalyticsQuery()
+ const { data: project } = useSelectedProjectQuery()
const [isRefreshing, setIsRefreshing] = useState<boolean>(false)
@@ -57,6 +63,7 @@ export function CustomReportSection() {
const [editableReport, setEditableReport] = useState<Dashboards.Content | undefined>(
reportContent
)
+ const [isDraggingOver, setIsDraggingOver] = useState(false)
const { can: canCreateReport } = useAsyncCheckPermissions(
PermissionAction.CREATE,
@@ -155,51 +162,74 @@ export function CustomReportSection() {
[]
)
- const addSnippetToReport = (snippet: { id: string; name: string }) => {
- if (
- editableReport?.layout?.some(
- (x) =>
- String(x.id) === String(snippet.id) || String(x.attribute) === `snippet_${snippet.id}`
- )
- ) {
- toast('This block is already in your report')
- return
- }
- // If the Home report doesn't exist yet, create it with the new block
- if (!editableReport || !homeReport) {
- if (!ref || !profile) return
-
- // Initial placement for first block
- const initialBlock = createSnippetChartBlock(snippet, { x: 0, y: 0 })
-
- const newReport: Dashboards.Content = {
- schema_version: 1,
- period_start: { time_period: '7d', date: '' },
- period_end: { time_period: 'today', date: '' },
- interval: '1d',
- layout: [initialBlock],
+ const addSnippetToReport = useCallback(
+ (snippet: { id: string; name: string }) => {
+ if (
+ editableReport?.layout?.some(
+ (x) =>
+ String(x.id) === String(snippet.id) || String(x.attribute) === `snippet_${snippet.id}`
+ )
+ ) {
+ toast('This block is already in your report')
+ return
}
+ // If the Home report doesn't exist yet, create it with the new block
+ if (!editableReport || !homeReport) {
+ if (!ref || !profile) return
+
+ // Initial placement for first block
+ const initialBlock = createSnippetChartBlock(snippet, { x: 0, y: 0 })
+
+ const newReport: Dashboards.Content = {
+ schema_version: 1,
+ period_start: { time_period: '7d', date: '' },
+ period_end: { time_period: 'today', date: '' },
+ interval: '1d',
+ layout: [initialBlock],
+ }
+
+ setEditableReport(newReport)
+ upsertContent({
+ projectRef: ref,
+ payload: {
+ id: uuidv4(),
+ type: 'report',
+ name: 'Home',
+ description: '',
+ visibility: 'project',
+ owner_id: profile.id,
+ content: newReport,
+ },
+ })
- setEditableReport(newReport)
- upsertContent({
- projectRef: ref,
- payload: {
- id: uuidv4(),
- type: 'report',
- name: 'Home',
- description: '',
- visibility: 'project',
- owner_id: profile.id,
- content: newReport,
- },
- })
+ if (ref && organization?.slug) {
+ sendEvent({
+ action: 'home_custom_report_block_added',
+ properties: {
+ block_id: snippet.id,
+ position: 0,
+ },
+ groups: {
+ project: ref,
+ organization: organization.slug,
+ },
+ })
+ }
+ return
+ }
+ const current = [...editableReport.layout]
+ const { x, y } = findNextPlacement(current)
+ current.push(createSnippetChartBlock(snippet, { x, y }))
+ const updated = { ...editableReport, layout: current }
+ setEditableReport(updated)
+ persistReport(updated)
if (ref && organization?.slug) {
sendEvent({
action: 'home_custom_report_block_added',
properties: {
block_id: snippet.id,
- position: 0,
+ position: current.length - 1,
},
groups: {
project: ref,
@@ -207,29 +237,20 @@ export function CustomReportSection() {
},
})
}
- return
- }
- const current = [...editableReport.layout]
- const { x, y } = findNextPlacement(current)
- current.push(createSnippetChartBlock(snippet, { x, y }))
- const updated = { ...editableReport, layout: current }
- setEditableReport(updated)
- persistReport(updated)
-
- if (ref && organization?.slug) {
- sendEvent({
- action: 'home_custom_report_block_added',
- properties: {
- block_id: snippet.id,
- position: current.length - 1,
- },
- groups: {
- project: ref,
- organization: organization.slug,
- },
- })
- }
- }
+ },
+ [
+ editableReport,
+ homeReport,
+ ref,
+ profile,
+ upsertContent,
+ organization,
+ sendEvent,
+ findNextPlacement,
+ createSnippetChartBlock,
+ persistReport,
+ ]
+ )
const handleRemoveChart = ({ metric }: { metric: { key: string } }) => {
if (!editableReport) return
@@ -277,6 +298,51 @@ export function CustomReportSection() {
persistReport(updated)
}
+ const handleDrop = useCallback(
+ async (e: DragEvent<HTMLDivElement>) => {
+ e.preventDefault()
+ setIsDraggingOver(false)
+ if (!ref || !profile || !project) return
+
+ const data = e.dataTransfer.getData('application/json')
+ if (!data) return
+
+ const { label, sql, config } = JSON.parse(data)
+ if (!label || !sql) return
+
+ const toastId = toast.loading(`Creating new query: ${label}`)
+ const id = uuidv4()
+
+ const payload = createSqlSnippetSkeletonV2({
+ id,
+ name: label,
+ sql,
+ owner_id: profile.id,
+ project_id: project.id,
+ }) as UpsertContentPayload
+
+ upsertContent({ projectRef: ref, payload })
+
+ // Handle success optimistically
+ toast.success(`Successfully created new query: ${label}`, { id: toastId })
+ addSnippetToReport({ id, name: label })
+ sendEvent({
+ action: 'custom_report_assistant_sql_block_added',
+ groups: { project: ref, organization: organization?.slug ?? 'Unknown' },
+ })
+ },
+ [ref, profile, project, upsertContent, addSnippetToReport, sendEvent, organization]
+ )
+
+ const handleDragOver = (e: DragEvent<HTMLDivElement>) => {
+ setIsDraggingOver(true)
+ e.preventDefault()
+ }
+
+ const handleDragLeave = () => {
+ setIsDraggingOver(false)
+ }
+
const onRefreshReport = () => {
if (!ref) return
@@ -334,8 +400,16 @@ export function CustomReportSection() {
</div>
</div>
<div className="relative">
+ {isDraggingOver && (
+ <div className="absolute inset-0 rounded bg-brand/10 pointer-events-none z-10" />
+ )}
{layout.length === 0 ? (
- <div className="h-64 flex flex-col items-center justify-center rounded border-2 border-dashed p-16 border-default">
+ <div
+ className="h-64 flex flex-col items-center justify-center rounded border-2 border-dashed p-16 transition-colors"
+ onDrop={handleDrop}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ >
<h4>Build a custom report</h4>
<p className="text-sm text-foreground-light mb-4">
Keep track of your most important metrics
@@ -368,7 +442,12 @@ export function CustomReportSection() {
items={(editableReport?.layout ?? []).map((x) => String(x.id))}
strategy={rectSortingStrategy}
>
- <Row columns={[3, 2, 1]}>
+ <Row
+ columns={[3, 2, 1]}
+ onDrop={handleDrop}
+ onDragOver={handleDragOver}
+ onDragLeave={handleDragLeave}
+ >
{layout.map((item) => (
<SortableReportBlock key={item.id} id={String(item.id)}>
<div className="h-64">
diff --git a/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlockContainer.tsx b/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlockContainer.tsx
index 74e43c73f4f..4cb1ef68da1 100644
--- a/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlockContainer.tsx
+++ b/apps/studio/components/interfaces/Reports/ReportBlock/ReportBlockContainer.tsx
@@ -47,20 +47,13 @@ export const ReportBlockContainer = ({
)}
>
{showDragHandle ? (
- <div className="absolute left-3 top-2.5 z-10 opacity-0 transition-opacity group-hover:opacity-100">
- <GripHorizontal size={16} strokeWidth={1.5} />
- </div>
+ <GripHorizontal size={16} strokeWidth={1.5} />
) : icon ? (
icon
) : (
<Code size={16} strokeWidth={1.5} className="text-foreground-muted" />
)}
- <div
- className={cn(
- 'flex items-center gap-2 flex-1 transition-opacity',
- showDragHandle && 'group-hover:opacity-25'
- )}
- >
+ <div className={cn('flex items-center gap-2 flex-1 transition-opacity')}>
<h3 className="heading-meta truncate">{label}</h3>
{badge && <div className="flex items-center shrink-0">{badge}</div>}
</div>
diff --git a/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx b/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx
index 9d360738a20..eb3f1e621ae 100644
--- a/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx
+++ b/apps/studio/components/ui/AIAssistantPanel/DisplayBlockRenderer.tsx
@@ -85,7 +85,9 @@ export const DisplayBlockRenderer = ({
const [rows, setRows] = useState<any[] | undefined>(
Array.isArray(initialResults) ? initialResults : undefined
)
- const isDraggableToReports = canCreateSQLSnippet && router.pathname.endsWith('/reports/[id]')
+ const isReportsPage = router.pathname.endsWith('/reports/[id]')
+ const isHomePage = router.pathname === '/project/[ref]'
+ const isDraggableToReports = canCreateSQLSnippet && (isReportsPage || isHomePage)
const label = initialArgs.label || 'SQL Results'
const [isWriteQuery, setIsWriteQuery] = useState<boolean>(initialArgs.isWriteQuery || false)
const sqlQuery = initialArgs.sql