Skip to content

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

Hook up APIs for Notebooks CRUD (#49254)

Joshen Lim2893c783d537
diff --git a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
index b0fb890f53a..696408859c2 100644
--- a/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
+++ b/apps/studio/components/interfaces/Explorer/ExplorerNotebookTab.tsx
@@ -11,10 +11,31 @@ import {
sortableKeyboardCoordinates,
verticalListSortingStrategy,
} from '@dnd-kit/sortable'
+import { acceptUntrustedSql } from '@supabase/pg-meta'
import { useParams } from 'common'
-import { FileText, Notebook, NotebookText, Play, Save, SquareCode } from 'lucide-react'
+import {
+ FileText,
+ Loader2,
+ MoreVertical,
+ Notebook,
+ NotebookText,
+ Play,
+ Save,
+ SquareCode,
+ Trash,
+} from 'lucide-react'
+import { useRouter } from 'next/router'
import { useRef, useState } from 'react'
-import { AiIconAnimation, Button } from 'ui'
+import { toast } from 'sonner'
+import {
+ AiIconAnimation,
+ Button,
+ DropdownMenu,
+ DropdownMenuContent,
+ DropdownMenuItem,
+ DropdownMenuTrigger,
+} from 'ui'
+import ConfirmationModal from 'ui-patterns/Dialogs/ConfirmationModal'
import { EmptyStatePresentational } from 'ui-patterns/EmptyStatePresentational'
import {
@@ -24,28 +45,55 @@ import {
ExplorerToolbarIcon,
ExplorerToolbarTitle,
} from './ExplorerToolbar'
+import { useLoadNotebook } from './hooks'
import { MarkdownCell } from './MarkdownCell'
import { QueryCell } from './QueryCell'
import { type QueryEditorHandle } from './QueryEditor'
import { createMarkdownCellSkeleton, createQueryCellSkeleton } from './utils'
import { ButtonTooltip } from '@/components/ui/ButtonTooltip'
-import { isQueryCell } from '@/data/content/notebooks/notebook-schema'
+import { useContentDeleteMutation } from '@/data/content/content-delete-mutation'
+import {
+ isQueryCell,
+ WritableCell,
+ WritableNotebook,
+} from '@/data/content/notebooks/notebook-schema'
+import { useUpsertNotebookMutation } from '@/data/content/notebooks/notebook-upsert-mutation'
+import { acceptUntrustedLogsSql } from '@/data/logs/safe-analytics-sql'
import { useCurrentNotebook, useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'
import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
export const ExplorerNotebookTab = () => {
- const { id } = useParams()
+ const router = useRouter()
+ const { id, ref } = useParams()
const tabs = useTabsStateSnapshot()
const snap = useNotebooksStateSnapshot()
const currentNotebook = useCurrentNotebook()
const { name, content } = currentNotebook?.notebook ?? {}
+ const { isNotFound } = useLoadNotebook({ id, projectRef: ref })
const cells = content?.cells ?? []
const queryCellIds = cells.filter(isQueryCell).map((cell) => cell._id)
const [isRunningNotebook, setIsRunningNotebook] = useState(false)
+ const [isDeleteModalOpen, setIsDeleteModalOpen] = useState(false)
const queryCellRefs = useRef(new Map<string, QueryEditorHandle>())
+ const { mutate: updateNotebook, isPending: isUpdating } = useUpsertNotebookMutation({
+ onSuccess: () => toast.success('Successfully saved notebook!'),
+ })
+ const { mutate: deleteNotebook, isPending: isDeleting } = useContentDeleteMutation({
+ onSuccess: () => {
+ toast.success('Successfully deleted notebook')
+ if (id) {
+ tabs.removeTab(createTabId('notebook', { id }))
+ snap.removeNotebook({ id })
+ }
+ setIsDeleteModalOpen(false)
+ router.push(`/project/${ref}/explorer`)
+ },
+ onError: (error) => toast.error(`Failed to delete notebook: ${error.message}`),
+ })
+
const sensors = useSensors(
useSensor(PointerSensor, { activationConstraint: { distance: 8 } }),
useSensor(KeyboardSensor, { coordinateGetter: sortableKeyboardCoordinates })
@@ -70,6 +118,50 @@ export const ExplorerNotebookTab = () => {
}
}
+ const handleSaveNotebook = () => {
+ const notebookId = currentNotebook?.notebook.id
+ if (!ref || !notebookId || !name || !content) return
+
+ const writableContent: WritableNotebook = {
+ schema_version: content.schema_version,
+ cells: content.cells.map((cell): WritableCell => {
+ switch (cell._tag) {
+ case 'markdown_cell':
+ return cell
+ case 'database_cell': {
+ const { unchecked_sql, chart, ...rest } = cell
+ return {
+ ...rest,
+ chart: chart ? { ...chart, y_series: [...chart.y_series] } : undefined,
+ sql: acceptUntrustedSql(unchecked_sql),
+ }
+ }
+ case 'log_cell': {
+ const { unchecked_sql, chart, ...rest } = cell
+ return {
+ ...rest,
+ chart: chart ? { ...chart, y_series: [...chart.y_series] } : undefined,
+ sql: acceptUntrustedLogsSql(unchecked_sql),
+ }
+ }
+ }
+ }),
+ }
+
+ updateNotebook({
+ projectRef: ref,
+ id: notebookId,
+ name,
+ description: currentNotebook?.notebook.description,
+ content: writableContent,
+ })
+ }
+
+ const handleConfirmDeleteNotebook = () => {
+ if (!ref || !id) return
+ deleteNotebook({ projectRef: ref, ids: [id] })
+ }
+
const handleDragEnd = (event: DragEndEvent) => {
const { active, over } = event
if (!id || !over || active.id === over.id) return
@@ -87,6 +179,27 @@ export const ExplorerNotebookTab = () => {
snap.insertCellAfter({ id: notebookId, cellId: lastCellId, cell })
}
+ if (isNotFound) {
+ return (
+ <div className="px-20 flex flex-col h-full items-center justify-center bg-surface-100">
+ <EmptyStatePresentational
+ icon={<Notebook className="text-foreground-lighter" />}
+ title="Notebook not found"
+ description="This notebook may have been deleted or does not exist."
+ contentClassName="[&>h3]:text-sm [&>p]:text-xs"
+ />
+ </div>
+ )
+ }
+
+ if (!content) {
+ return (
+ <div className="flex flex-col h-full items-center justify-center bg-surface-100">
+ <Loader2 className="animate-spin text-foreground-muted" />
+ </div>
+ )
+ }
+
return (
<div className="flex flex-col h-full bg-surface-100">
<ExplorerToolbar className="px-4">
@@ -103,10 +216,29 @@ export const ExplorerNotebookTab = () => {
icon={<Play />}
tooltip="Run notebook"
loading={isRunningNotebook}
- disabled={isRunningNotebook || queryCellIds.length === 0}
+ disabled={queryCellIds.length === 0}
onClick={handleRunNotebook}
/>
- <ExplorerToolbarAction icon={<Save />} tooltip="Save changes" />
+ <ExplorerToolbarAction
+ aria-label="Save changes"
+ icon={<Save />}
+ tooltip="Save changes"
+ loading={isUpdating}
+ onClick={handleSaveNotebook}
+ />
+ <ExplorerToolbarActions>
+ <DropdownMenu>
+ <DropdownMenuTrigger asChild>
+ <ExplorerToolbarAction aria-label="More options" icon={<MoreVertical />} />
+ </DropdownMenuTrigger>
+ <DropdownMenuContent align="end" className="w-44">
+ <DropdownMenuItem className="gap-x-2" onClick={() => setIsDeleteModalOpen(true)}>
+ <Trash size={14} />
+ <span>Delete notebook</span>
+ </DropdownMenuItem>
+ </DropdownMenuContent>
+ </DropdownMenu>
+ </ExplorerToolbarActions>
</ExplorerToolbarActions>
</ExplorerToolbar>
@@ -175,6 +307,22 @@ export const ExplorerNotebookTab = () => {
)}
</div>
</div>
+
+ <ConfirmationModal
+ size="small"
+ visible={isDeleteModalOpen}
+ title={`Confirm to delete notebook '${name ?? ''}'`}
+ confirmLabel="Delete notebook"
+ confirmLabelLoading="Deleting notebook"
+ variant="destructive"
+ loading={isDeleting}
+ onCancel={() => setIsDeleteModalOpen(false)}
+ onConfirm={handleConfirmDeleteNotebook}
+ >
+ <p className="text-sm">
+ This action cannot be undone. Are you sure you want to delete '{name}'?
+ </p>
+ </ConfirmationModal>
</div>
)
}
diff --git a/apps/studio/components/interfaces/Explorer/hooks.ts b/apps/studio/components/interfaces/Explorer/hooks.ts
index 61449136ffa..b5922c03ce7 100644
--- a/apps/studio/components/interfaces/Explorer/hooks.ts
+++ b/apps/studio/components/interfaces/Explorer/hooks.ts
@@ -1,6 +1,7 @@
import { useRouter } from 'next/router'
+import { useEffect, useEffectEvent } from 'react'
-import { createMarkdownCellSkeleton, createQueryCellSkeleton } from './utils'
+import { useNotebookQuery } from '@/data/content/notebooks/notebook-query'
import { useSelectedOrganizationQuery } from '@/hooks/misc/useSelectedOrganization'
import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'
import { generateUuid } from '@/lib/api/snippets.browser'
@@ -12,6 +13,39 @@ import { useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'
import { type Notebook } from '@/state/notebooks/types'
import { Notebooks } from '@/types'
+/**
+ * Fetches a notebook's content by id and merges it into the valtio store, so landing on
+ * a notebook any way other than creating it in this session (direct link, hard refresh,
+ * clicking it from the nav list) still hydrates `notebooksState`.
+ */
+export const useLoadNotebook = ({ id, projectRef }: { id?: string; projectRef?: string }) => {
+ const notebooksSnap = useNotebooksStateSnapshot()
+ const currentNotebook = id ? notebooksSnap.notebooks[id] : undefined
+
+ const isCurrentProjectNotebook = currentNotebook?.projectRef === projectRef
+ const isNewLocalNotebook = isCurrentProjectNotebook && currentNotebook?.status === 'new'
+ const hasLoadedNotebook =
+ isCurrentProjectNotebook && currentNotebook?.notebook.content !== undefined
+
+ const { data, error, isError } = useNotebookQuery(
+ { projectRef, id },
+ {
+ retry: false,
+ enabled: !isNewLocalNotebook && !hasLoadedNotebook,
+ }
+ )
+
+ const mergeNotebook = useEffectEvent(() => {
+ if (projectRef && data) notebooksSnap.setNotebook({ projectRef, notebook: data })
+ })
+
+ useEffect(() => {
+ mergeNotebook()
+ }, [projectRef, data])
+
+ return { isNotFound: isError && error.code === 404 }
+}
+
export const useCreateNotebook = () => {
const router = useRouter()
const { profile } = useProfile()
@@ -26,30 +60,6 @@ export const useCreateNotebook = () => {
if (!profile) return console.error('Profile is required')
if (!project) return console.error('Project is required')
- const sampleMdCell1 = createMarkdownCellSkeleton({
- content: `
-# Title
-A brief description on what this notebook is about
-`.trim(),
- })
- const sampleMdCell2 = createMarkdownCellSkeleton({
- content: `
-## Section
-This is a sample paragraph to demonstrate the Markdown cells
-1. List item 1
-2. List item 2
-3. List item 3
-`.trim(),
- })
- const sampleQueryCell = createQueryCellSkeleton({ sql: 'select * from colors;' })
-
- // [Joshen] Just adding sample data to play around with, keep for now - clean up at the end
- const DEFAULT_CELLS = [
- sampleMdCell1,
- sampleMdCell2,
- sampleQueryCell,
- ] as Notebooks.Content['cells']
-
const id = idOverride ?? generateUuid()
const notebook: Notebook = {
@@ -61,7 +71,7 @@ This is a sample paragraph to demonstrate the Markdown cells
favorite: false,
content: {
schema_version: 1,
- cells: cells ?? DEFAULT_CELLS,
+ cells: cells ?? [],
},
owner_id: profile.id,
project_id: project.id,
diff --git a/apps/studio/components/interfaces/Explorer/utils.ts b/apps/studio/components/interfaces/Explorer/utils.ts
index 92a4cc2dcdb..7c850990240 100644
--- a/apps/studio/components/interfaces/Explorer/utils.ts
+++ b/apps/studio/components/interfaces/Explorer/utils.ts
@@ -2,9 +2,12 @@ import { untrustedSql } from '@supabase/pg-meta'
import { DEFAULT_CELL_ROW_LIMIT } from './QueryCell/QueryCell.utils'
import { generateDraftId } from '@/data/content/notebooks/notebook-schema'
+import { untrustedLogSql } from '@/data/logs/safe-analytics-sql'
+import type { Notebooks } from '@/types'
-export const createQueryCellSkeleton = ({ sql }: { sql?: string } = {}) => {
+export const createQueryCellSkeleton = ({ title, sql }: { title?: string; sql?: string } = {}) => {
return {
+ title,
_tag: 'database_cell' as const,
_id: generateDraftId(),
view: 'table' as const,
@@ -14,6 +17,28 @@ export const createQueryCellSkeleton = ({ sql }: { sql?: string } = {}) => {
}
}
+const DEFAULT_LOG_TIME_RANGE: Notebooks.TimeRange = {
+ _tag: 'relative_time_range',
+ unit: 'hour',
+ amount: 1,
+}
+
+export const createLogCellSkeleton = ({
+ sql,
+ title,
+ time_range = DEFAULT_LOG_TIME_RANGE,
+}: { sql?: string; title?: string; time_range?: Notebooks.TimeRange } = {}) => {
+ return {
+ title,
+ _tag: 'log_cell' as const,
+ id: generateDraftId(),
+ view: 'table' as const,
+ chart: undefined,
+ unchecked_sql: untrustedLogSql(sql ?? ''),
+ time_range,
+ }
+}
+
const DEFAULT_MARKDOWN_CONTENT = `
# New section
Add notes about your queries and results
diff --git a/apps/studio/components/layouts/ExplorerLayout/ExplorerNavNotebooks.tsx b/apps/studio/components/layouts/ExplorerLayout/ExplorerNavNotebooks.tsx
index d465190d848..39646c4e2d0 100644
--- a/apps/studio/components/layouts/ExplorerLayout/ExplorerNavNotebooks.tsx
+++ b/apps/studio/components/layouts/ExplorerLayout/ExplorerNavNotebooks.tsx
@@ -1,11 +1,28 @@
-import { useState } from 'react'
+import { useParams } from 'common'
+import { NotebookText } from 'lucide-react'
+import Link from 'next/link'
+import { useRouter } from 'next/router'
+import { useMemo, useState } from 'react'
+import { cn } from 'ui'
+import { GenericSkeletonLoader } from 'ui-patterns/ShimmeringLoader'
-import { ExplorerNavResourceWrapper } from './ExplorerLayout.constants'
+import { ExplorerNavResourceWrapper, rowClassName } from './ExplorerLayout.constants'
+import { useNotebooksInfiniteQuery } from '@/data/content/notebooks/notebooks-infinite-query'
export const ExplorerNavNotebooks = ({ onBack }: { onBack: () => void }) => {
+ const router = useRouter()
+ const { ref, id } = useParams()
const [search, setSearch] = useState('')
- // [Joshen] Eventually will have data fetching for notebooks via RQ
+ const { data: notebooksData, isPending } = useNotebooksInfiniteQuery({
+ projectRef: ref,
+ limit: 100,
+ name: search,
+ })
+ const notebooks = useMemo(() => {
+ const items = notebooksData?.pages.flatMap((page) => page.content) ?? []
+ return items
+ }, [notebooksData?.pages])
return (
<ExplorerNavResourceWrapper
@@ -15,7 +32,28 @@ export const ExplorerNavNotebooks = ({ onBack }: { onBack: () => void }) => {
onBack={onBack}
>
<div className="flex flex-1 flex-col gap-px overflow-y-auto px-3 pb-3">
- <p className="px-2 py-2 text-xs text-foreground-lighter">No notebooks created yet</p>
+ {isPending ? (
+ <GenericSkeletonLoader />
+ ) : notebooks.length === 0 ? (
+ <p className="px-2 py-2 text-xs text-foreground-lighter">
+ {search ? 'No notebooks found' : 'No notebooks created yet'}
+ </p>
+ ) : (
+ notebooks.map((notebook) => {
+ const isActive = router.pathname.includes('/explorer/notebook/') && id === notebook.id
+
+ return (
+ <Link
+ key={notebook.id}
+ href={`/project/${ref}/explorer/notebook/${notebook.id}`}
+ className={rowClassName(isActive)}
+ >
+ <NotebookText size={14} className={cn('shrink-0', isActive && 'text-foreground')} />
+ <span className="truncate text-left">{notebook.name}</span>
+ </Link>
+ )
+ })
+ )}
</div>
</ExplorerNavResourceWrapper>
)
diff --git a/apps/studio/data/content/notebooks/notebook-query.ts b/apps/studio/data/content/notebooks/notebook-query.ts
index 3e64aef8f35..0850f3a77be 100644
--- a/apps/studio/data/content/notebooks/notebook-query.ts
+++ b/apps/studio/data/content/notebooks/notebook-query.ts
@@ -2,7 +2,8 @@ import { useQuery } from '@tanstack/react-query'
import { getContentById } from '../content-id-query'
import { contentKeys } from '../keys'
-import type { Notebooks, ResponseError, UseCustomQueryOptions } from '@/types'
+import type { Notebooks, UseCustomQueryOptions } from '@/types'
+import { ResponseError } from '@/types'
export type NotebookVariables = { projectRef?: string; id?: string }
export type NotebookError = ResponseError
@@ -18,7 +19,9 @@ export async function getNotebook(
throw new Error(`Content ${id} is not a notebook (got type: ${data.type})`)
}
- return data as Omit<typeof data, 'content'> & {
+ return data as Omit<typeof data, 'content' | 'type' | 'visibility'> & {
+ type: 'notebook'
+ visibility: 'project'
content: Notebooks.Content
}
}
diff --git a/apps/studio/data/content/notebooks/notebook-upsert-mutation.test.ts b/apps/studio/data/content/notebooks/notebook-upsert-mutation.test.ts
index 55f5a0eb1fd..df4e8ce5e12 100644
--- a/apps/studio/data/content/notebooks/notebook-upsert-mutation.test.ts
+++ b/apps/studio/data/content/notebooks/notebook-upsert-mutation.test.ts
@@ -3,7 +3,7 @@ import { HttpResponse } from 'msw'
import { describe, expect, it } from 'vitest'
import type { WritableNotebook } from './notebook-schema'
-import { createNotebook, updateNotebook } from './notebook-upsert-mutation'
+import { createNotebook, upsertNotebook } from './notebook-upsert-mutation'
import { safeSql as safeLogSql } from '@/data/logs/safe-analytics-sql'
import { addAPIMock } from '@/tests/lib/msw'
@@ -100,7 +100,7 @@ describe('createNotebook', () => {
})
})
-describe('updateNotebook', () => {
+describe('upsertNotebook', () => {
const NOTEBOOK_ID = 'd3aadd77-7c3c-4de7-aa5c-5aa8ac270b44'
it('PUTs with the given id, keeping the existing cell id and leaving the new cell without one', async () => {
@@ -114,7 +114,7 @@ describe('updateNotebook', () => {
},
})
- await updateNotebook({
+ await upsertNotebook({
projectRef: 'default',
id: NOTEBOOK_ID,
name: 'Signup funnel',
@@ -136,7 +136,7 @@ describe('updateNotebook', () => {
it('rejects malformed content without making a network request', async () => {
await expect(
- updateNotebook({
+ upsertNotebook({
projectRef: 'default',
id: NOTEBOOK_ID,
name: 'Bad notebook',
diff --git a/apps/studio/data/content/notebooks/notebook-upsert-mutation.ts b/apps/studio/data/content/notebooks/notebook-upsert-mutation.ts
index e234a2f505f..e6332ac260a 100644
--- a/apps/studio/data/content/notebooks/notebook-upsert-mutation.ts
+++ b/apps/studio/data/content/notebooks/notebook-upsert-mutation.ts
@@ -51,10 +51,16 @@ export async function createNotebook(
export type CreateNotebookData = Awaited<ReturnType<typeof createNotebook>>
-export type UpdateNotebookVariables = CreateNotebookVariables & { id: string }
+export type UpsertNotebookVariables = {
+ id: string
+ projectRef: string
+ name: string
+ description?: string
+ content: WritableNotebook
+}
-export async function updateNotebook(
- { projectRef, id, name, description, content }: UpdateNotebookVariables,
+export async function upsertNotebook(
+ { projectRef, id, name, description, content }: UpsertNotebookVariables,
signal?: AbortSignal,
headersInit?: HeadersInit
) {
@@ -63,51 +69,20 @@ export async function updateNotebook(
return upsertContent({ projectRef, payload }, signal, headersInit)
}
-export type UpdateNotebookData = Awaited<ReturnType<typeof updateNotebook>>
-
-export const useCreateNotebookMutation = ({
- onError,
- onSuccess,
- ...options
-}: Omit<
- UseCustomMutationOptions<CreateNotebookData, ResponseError, CreateNotebookVariables>,
- 'mutationFn'
-> = {}) => {
- const queryClient = useQueryClient()
-
- return useMutation<CreateNotebookData, ResponseError, CreateNotebookVariables>({
- mutationFn: (args) => createNotebook(args),
- async onSuccess(data, variables, context) {
- const { projectRef } = variables
- await Promise.all([
- queryClient.invalidateQueries({ queryKey: contentKeys.allContentLists(projectRef) }),
- queryClient.invalidateQueries({ queryKey: contentKeys.infiniteList(projectRef) }),
- ])
- await onSuccess?.(data, variables, context)
- },
- async onError(error, variables, context) {
- if (onError === undefined) {
- toast.error(`Failed to create notebook: ${error.message}`)
- } else {
- onError(error, variables, context)
- }
- },
- ...options,
- })
-}
+export type UpdateNotebookData = Awaited<ReturnType<typeof upsertNotebook>>
-export const useUpdateNotebookMutation = ({
+export const useUpsertNotebookMutation = ({
onError,
onSuccess,
...options
}: Omit<
- UseCustomMutationOptions<UpdateNotebookData, ResponseError, UpdateNotebookVariables>,
+ UseCustomMutationOptions<UpdateNotebookData, ResponseError, UpsertNotebookVariables>,
'mutationFn'
> = {}) => {
const queryClient = useQueryClient()
- return useMutation<UpdateNotebookData, ResponseError, UpdateNotebookVariables>({
- mutationFn: (args) => updateNotebook(args),
+ return useMutation<UpdateNotebookData, ResponseError, UpsertNotebookVariables>({
+ mutationFn: (args) => upsertNotebook(args),
async onSuccess(data, variables, context) {
const { projectRef, id } = variables
await Promise.all([
diff --git a/apps/studio/data/content/notebooks/notebooks-infinite-query.ts b/apps/studio/data/content/notebooks/notebooks-infinite-query.ts
index 8e7db98d784..2be4970049b 100644
--- a/apps/studio/data/content/notebooks/notebooks-infinite-query.ts
+++ b/apps/studio/data/content/notebooks/notebooks-infinite-query.ts
@@ -1,10 +1,6 @@
-import type { InfiniteData } from '@tanstack/react-query'
+import { type InfiniteData } from '@tanstack/react-query'
-import {
- useContentInfiniteQuery,
- type ContentData,
- type ContentError,
-} from '../content-infinite-query'
+import { ContentData, ContentError, useContentInfiniteQuery } from '../content-infinite-query'
import type { ContentOfType } from '../content-query'
import type { UseCustomInfiniteQueryOptions } from '@/types'
diff --git a/apps/studio/lib/ai/tools/notebook-tools.ts b/apps/studio/lib/ai/tools/notebook-tools.ts
index 3383816b4f7..1ec84bdb88d 100644
--- a/apps/studio/lib/ai/tools/notebook-tools.ts
+++ b/apps/studio/lib/ai/tools/notebook-tools.ts
@@ -15,7 +15,7 @@ import {
type WritableCell,
type WritableNotebook,
} from '@/data/content/notebooks/notebook-schema'
-import { createNotebook, updateNotebook } from '@/data/content/notebooks/notebook-upsert-mutation'
+import { createNotebook, upsertNotebook } from '@/data/content/notebooks/notebook-upsert-mutation'
import { acceptUntrustedLogsSql, untrustedLogSql } from '@/data/logs/safe-analytics-sql'
import type { Notebooks } from '@/types'
@@ -181,7 +181,7 @@ export const getNotebookTools = (ctx: NotebookToolsContext = {}) => {
}
})
- await updateNotebook(
+ await upsertNotebook(
{
projectRef: projectRef ?? '',
id,
diff --git a/apps/studio/pages/project/[ref]/explorer/notebook/[id].tsx b/apps/studio/pages/project/[ref]/explorer/notebook/[id].tsx
index e98dfde91b8..ad8503778ce 100644
--- a/apps/studio/pages/project/[ref]/explorer/notebook/[id].tsx
+++ b/apps/studio/pages/project/[ref]/explorer/notebook/[id].tsx
@@ -2,6 +2,7 @@ import { useParams } from 'common'
import { useEffect, useEffectEvent } from 'react'
import { ExplorerNotebookTab } from '@/components/interfaces/Explorer/ExplorerNotebookTab'
+import { useLoadNotebook } from '@/components/interfaces/Explorer/hooks'
import { DefaultLayout } from '@/components/layouts/DefaultLayout'
import { ExplorerLayout } from '@/components/layouts/ExplorerLayout/ExplorerLayout'
import { useCurrentNotebook } from '@/state/notebooks/notebooks-state'
@@ -9,14 +10,15 @@ import { createTabId, useTabsStateSnapshot } from '@/state/tabs'
import type { NextPageWithLayout } from '@/types'
const NotebookPage: NextPageWithLayout = () => {
- const { id } = useParams()
+ const { ref, id } = useParams()
const tabs = useTabsStateSnapshot()
const currentNotebook = useCurrentNotebook()
const { name } = currentNotebook?.notebook ?? {}
+ const { isNotFound } = useLoadNotebook({ id, projectRef: ref })
const registerTab = useEffectEvent(() => {
- if (!id) return
+ if (!id || isNotFound) return
tabs.addTab({
id: createTabId('notebook', { id }),
type: 'notebook',
@@ -26,8 +28,15 @@ const NotebookPage: NextPageWithLayout = () => {
})
})
+ const backfillTabLabel = useEffectEvent(() => {
+ if (!id || !name) return
+ tabs.updateTab(createTabId('notebook', { id }), { label: name })
+ })
+
useEffect(() => registerTab(), [id])
+ useEffect(() => backfillTabLabel(), [id, name])
+
return <ExplorerNotebookTab />
}
diff --git a/apps/studio/state/notebooks/notebooks-state.ts b/apps/studio/state/notebooks/notebooks-state.ts
index 486129e4607..8591de569a4 100644
--- a/apps/studio/state/notebooks/notebooks-state.ts
+++ b/apps/studio/state/notebooks/notebooks-state.ts
@@ -9,8 +9,6 @@ import type { Notebook, StateNotebook } from './types'
import type { SnippetStatus } from '@/data/content/snippet-status'
import type { Notebooks } from '@/types'
-// [Joshen] Deliberately copied from sql-editor-lifecycle cause we might deprecate
-// that in favor of notebooks in the long run
function statusOnEdit(status: SnippetStatus): SnippetStatus {
return status === 'saved' ? 'unsaved' : status
}
@@ -67,8 +65,6 @@ export const notebooksState = proxy({
const { [id]: notebook, ...otherNotebooks } = notebooksState.notebooks
notebooksState.notebooks = otherNotebooks
if (!skipSave) notebooksState.needsSaving.delete(id)
-
- // TODO: clear notebookSessionState once it exists
},
/**