The Postgres development platform. Supabase gives you a dedicated Postgres database to build your web, mobile, and AI applications.
TypeScript aialternativeauthdatabasedenoembeddingsexamplefirebasenextjsoauth2pgvectorpostgispostgrespostgresqlpostgrestrealtimesupabasevectorswebsockets
joshen/fe 4149 explorer support adding removing cells in notebook (#49037)
Joshen Lim93d9d8053509
diff --git a/apps/studio/components/interfaces/Explorer/AddCellDropdown.tsx b/apps/studio/components/interfaces/Explorer/AddCellDropdown.tsxnew file mode 100644index 00000000000..f63f2b83a5d--- /dev/null+++ b/apps/studio/components/interfaces/Explorer/AddCellDropdown.tsx@@ -0,0 +1,47 @@+import { FileText, Plus, SquareCode } from 'lucide-react'+import { DropdownMenu, DropdownMenuContent, DropdownMenuItem, DropdownMenuTrigger } from 'ui'++import { createMarkdownCellSkeleton, createQueryCellSkeleton } from './utils'+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'+import { useCurrentNotebook, useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'++interface AddCellDropdownProps {+ cellId: string+}++export const AddCellDropdown = ({ cellId }: AddCellDropdownProps) => {+ const snap = useNotebooksStateSnapshot()+ const currentNotebook = useCurrentNotebook()++ const onSelectAddCell = (type: 'markdown' | 'query') => {+ const notebookId = currentNotebook?.notebook.id+ if (!notebookId) return++ const cell = type === 'markdown' ? createMarkdownCellSkeleton() : createQueryCellSkeleton()++ snap.insertCellAfter({ id: notebookId, cellId, cell })+ }++ return (+ <DropdownMenu>+ <DropdownMenuTrigger asChild>+ <ButtonTooltip+ variant="text"+ className="w-7"+ icon={<Plus />}+ tooltip={{ content: { side: 'bottom', text: 'Add cell' } }}+ />+ </DropdownMenuTrigger>+ <DropdownMenuContent align="start" className="w-40">+ <DropdownMenuItem className="gap-x-2" onClick={() => onSelectAddCell('query')}>+ <SquareCode size={14} />+ <span>Add query cell</span>+ </DropdownMenuItem>+ <DropdownMenuItem className="gap-x-2" onClick={() => onSelectAddCell('markdown')}>+ <FileText size={14} />+ <span>Add markdown cell</span>+ </DropdownMenuItem>+ </DropdownMenuContent>+ </DropdownMenu>+ )+}diff --git a/apps/studio/components/interfaces/Explorer/ExplorerToolbar.tsx b/apps/studio/components/interfaces/Explorer/ExplorerToolbar.tsxindex 14e434db488..0c99f82e52d 100644--- a/apps/studio/components/interfaces/Explorer/ExplorerToolbar.tsx+++ b/apps/studio/components/interfaces/Explorer/ExplorerToolbar.tsx@@ -100,9 +100,9 @@ const ExplorerToolbarTitle = ({) : onSaveTitle ? (<Buttonvariant="text"- className="group"+ className="group/title"onClick={handleStartEditing}- iconRight={<Edit className="opacity-0 group-hover:opacity-100 transition" />}+ iconRight={<Edit className="opacity-0 group-hover/title:opacity-100 transition" />}>{title}</Button>diff --git a/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx b/apps/studio/components/interfaces/Explorer/MarkdownCell.tsxindex b08550a4408..3cbf89238be 100644--- a/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx+++ b/apps/studio/components/interfaces/Explorer/MarkdownCell.tsx@@ -3,6 +3,8 @@ import { useState } from 'react'import { Button, cn } from 'ui'import { Markdown } from '../Markdown'+import { AddCellDropdown } from './AddCellDropdown'+import { MoveCellDropdownContent } from './MoveCellDropdownContent'import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { CodeEditor } from '@/components/ui/CodeEditor/CodeEditor'import { SortableSection } from '@/components/ui/SortableSection'@@ -14,6 +16,8 @@ interface MarkdownCellProps {cell: MarkdownCellSchema}+// [Joshen] handleUpdateMarkdown could be shifted into notebook-state as a updateCell action+export const MarkdownCell = ({ cell }: MarkdownCellProps) => {const snap = useNotebooksStateSnapshot()const currentNotebook = useCurrentNotebook()@@ -45,10 +49,15 @@ export const MarkdownCell = ({ cell }: MarkdownCellProps) => {const handleUpdateMarkdownRef = useLatest(handleUpdateMarkdown)return (- <SortableSection gripClassName="mt-2.5" id={cell.id}>+ <SortableSection+ id={cell.id}+ actions={<AddCellDropdown cellId={cell.id} />}+ gripDropdownContent={<MoveCellDropdownContent cellId={cell.id} />}+ gripClassName="mt-1.5 opacity-0 group-hover:opacity-100 has-[[data-state=open]]:opacity-100 transition"+ >{isEditing ? (<div- className={cn('w-full max-w-2xl mx-auto transition', 'overflow-hidden border rounded-md')}+ className={cn('w-full max-w-3xl mx-auto transition', 'overflow-hidden border rounded-md')}><CodeEditorhideLineNumbers@@ -93,7 +102,7 @@ export const MarkdownCell = ({ cell }: MarkdownCellProps) => {onMouseDown={(e) => e.preventDefault()}onClick={() => handleUpdateMarkdown(cell.id, value)}>- Save+ Done</Button></div></div>@@ -102,7 +111,7 @@ export const MarkdownCell = ({ cell }: MarkdownCellProps) => {<divonDoubleClick={handleStartEditing}className={cn(- 'group relative w-full max-w-2xl mx-auto px-3 py-2 transition',+ 'group/mdcell relative w-full max-w-3xl mx-auto px-3 py-2 transition','hover:bg-alternative/50','border border-transparent rounded-md hover:border-default')}@@ -111,26 +120,30 @@ export const MarkdownCell = ({ cell }: MarkdownCellProps) => {variant="text"className={cn('absolute right-1 top-1 px-1',- 'opacity-0 group-hover:opacity-100 focus-visible:opacity-100'+ 'opacity-0 group-hover/mdcell:opacity-100 focus-visible:opacity-100')}icon={<Edit size={14} />}onClick={handleStartEditing}tooltip={{ content: { side: 'bottom', text: 'Edit' } }}/>- <Markdown- className={cn(- 'prose prose-sm max-w-none text-muted-foreground prose-headings:text-foreground',- '[&>h1]:mb-2 [&>h2]:mb-2',- '[&_ol>li]:pl-3',- '[--tw-prose-body:var(--foreground-muted)]',- '[--tw-prose-headings:var(--foreground-default)]',- '[--tw-prose-links:var(--foreground-muted)]',- '[--tw-prose-bold:var(--foreground-muted)]',- '[--tw-prose-quotes:var(--foreground-muted)]'- )}- >- {cell.text}- </Markdown>+ {cell.text ? (+ <Markdown+ className={cn(+ 'prose prose-sm max-w-none text-muted-foreground prose-headings:text-foreground',+ '[&>h1]:mb-2 [&>h2]:mb-2',+ '[&_ol>li]:pl-3',+ '[--tw-prose-body:var(--foreground-muted)]',+ '[--tw-prose-headings:var(--foreground-default)]',+ '[--tw-prose-links:var(--foreground-muted)]',+ '[--tw-prose-bold:var(--foreground-muted)]',+ '[--tw-prose-quotes:var(--foreground-muted)]'+ )}+ >+ {cell.text}+ </Markdown>+ ) : (+ <p className="text-foreground-lighter text-sm italic">This cell has no content</p>+ )}</div>)}</SortableSection>diff --git a/apps/studio/components/interfaces/Explorer/MoveCellDropdownContent.tsx b/apps/studio/components/interfaces/Explorer/MoveCellDropdownContent.tsxnew file mode 100644index 00000000000..5fb0e392ba7--- /dev/null+++ b/apps/studio/components/interfaces/Explorer/MoveCellDropdownContent.tsx@@ -0,0 +1,57 @@+import { ArrowDown, ArrowUp, Trash } from 'lucide-react'+import { DropdownMenuContent, DropdownMenuItem, DropdownMenuSeparator } from 'ui'++import { useCurrentNotebook, useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'++interface MoveCellDropdownContentProps {+ cellId: string+}++export const MoveCellDropdownContent = ({ cellId }: MoveCellDropdownContentProps) => {+ const snap = useNotebooksStateSnapshot()+ const currentNotebook = useCurrentNotebook()++ const cells = currentNotebook?.notebook.content?.cells ?? []+ const currentIndex = cells.findIndex((c) => c.id === cellId)+ const isFirstCell = currentIndex <= 0+ const isLastCell = currentIndex === -1 || currentIndex === cells.length - 1++ const onSelectMoveCell = (direction: 'up' | 'down') => {+ const notebookId = currentNotebook?.notebook.id+ if (!notebookId) return++ snap.moveCell({ id: notebookId, cellId, direction })+ }++ const onSelectRemoveCell = () => {+ const notebookId = currentNotebook?.notebook.id+ if (!notebookId) return+ snap.removeCell({ id: notebookId, cellId })+ }++ return (+ <DropdownMenuContent align="start" className="w-40">+ <DropdownMenuItem+ className="gap-x-2"+ disabled={isFirstCell}+ onClick={() => onSelectMoveCell('up')}+ >+ <ArrowUp size={14} />+ <p>Move up</p>+ </DropdownMenuItem>+ <DropdownMenuItem+ className="gap-x-2"+ disabled={isLastCell}+ onClick={() => onSelectMoveCell('down')}+ >+ <ArrowDown size={14} />+ <p>Move down</p>+ </DropdownMenuItem>+ <DropdownMenuSeparator />+ <DropdownMenuItem className="gap-x-2" onClick={() => onSelectRemoveCell()}>+ <Trash size={14} />+ <p>Remove cell</p>+ </DropdownMenuItem>+ </DropdownMenuContent>+ )+}diff --git a/apps/studio/components/interfaces/Explorer/NotebookEditor.tsx b/apps/studio/components/interfaces/Explorer/NotebookEditor.tsxindex 6cc223ce9e2..0949b02db74 100644--- a/apps/studio/components/interfaces/Explorer/NotebookEditor.tsx+++ b/apps/studio/components/interfaces/Explorer/NotebookEditor.tsx@@ -7,13 +7,12 @@ import {useSensors,} from '@dnd-kit/core'import {- arrayMove,SortableContext,sortableKeyboardCoordinates,verticalListSortingStrategy,} from '@dnd-kit/sortable'import { useParams } from 'common'-import { Notebook, NotebookText, Play, Save } from 'lucide-react'+import { FileText, Notebook, NotebookText, Play, Save, SquareCode } from 'lucide-react'import { AiIconAnimation, Button } from 'ui'import { EmptyStatePresentational } from 'ui-patterns/EmptyStatePresentational'@@ -26,6 +25,8 @@ import {} from './ExplorerToolbar'import { MarkdownCell } from './MarkdownCell'import { QueryCell } from './QueryCell'+import { createMarkdownCellSkeleton, createQueryCellSkeleton } from './utils'+import { ButtonTooltip } from '@/components/ui/ButtonTooltip'import { useCurrentNotebook, useNotebooksStateSnapshot } from '@/state/notebooks/notebooks-state'import { createTabId, useTabsStateSnapshot } from '@/state/tabs'@@ -55,11 +56,17 @@ export const NotebookEditor = () => {const { active, over } = eventif (!id || !over || active.id === over.id) return- const oldIndex = cells.findIndex((cell) => cell.id === active.id)- const newIndex = cells.findIndex((cell) => cell.id === over.id)- if (oldIndex === -1 || newIndex === -1) return+ snap.reorderCells({ id, activeCellId: active.id, overCellId: over.id })+ }++ const onSelectAddCell = (type: 'markdown' | 'query') => {+ const notebookId = currentNotebook?.notebook.id+ if (!notebookId) return++ const cell = type === 'markdown' ? createMarkdownCellSkeleton() : createQueryCellSkeleton()+ const lastCellId = cells[cells.length - 1]?.id- snap.updateCells({ id, cells: arrayMove([...cells], oldIndex, newIndex) })+ snap.insertCellAfter({ id: notebookId, cellId: lastCellId, cell })}return (@@ -88,34 +95,57 @@ export const NotebookEditor = () => {contentClassName="[&>h3]:text-sm [&>p]:text-xs"><div className="flex items-center gap-x-2">- <Button variant="default">Add query cell</Button>- <Button variant="default">Add markdown cell</Button>+ <Button variant="default" onClick={() => onSelectAddCell('query')}>+ Add query cell+ </Button>+ <Button variant="default" onClick={() => onSelectAddCell('markdown')}>+ Add markdown cell+ </Button></div></EmptyStatePresentational>)}{cells.length > 0 && (- <DndContext sensors={sensors} onDragEnd={handleDragEnd}>- <SortableContext- items={cells.map((cell) => cell.id)}- strategy={verticalListSortingStrategy}- >- <div className="flex flex-col gap-y-3">- {cells.map((cell) => {- switch (cell._tag) {- case 'markdown_cell':- return <MarkdownCell key={cell.id} cell={cell} />+ <>+ <DndContext sensors={sensors} onDragEnd={handleDragEnd}>+ <SortableContext+ items={cells.map((cell) => cell.id)}+ strategy={verticalListSortingStrategy}+ >+ <div className="flex flex-col gap-y-4">+ {cells.map((cell) => {+ switch (cell._tag) {+ case 'markdown_cell':+ return <MarkdownCell key={cell.id} cell={cell} />- case 'database_cell':- return <QueryCell key={cell.id} cell={cell} />+ case 'database_cell':+ return <QueryCell key={cell.id} cell={cell} />- case 'log_cell':- // [Joshen] Will eventually hook it up- return null- }- })}- </div>- </SortableContext>- </DndContext>+ case 'log_cell':+ // [Joshen] Will eventually hook it up+ return null+ }+ })}+ </div>+ </SortableContext>+ </DndContext>++ <div className="flex items-center justify-center gap-x-2 mt-4">+ <ButtonTooltip+ variant="outline"+ icon={<SquareCode />}+ className="w-7"+ onClick={() => onSelectAddCell('query')}+ tooltip={{ content: { side: 'bottom', text: 'Add query cell' } }}+ />+ <ButtonTooltip+ variant="outline"+ icon={<FileText />}+ className="w-7"+ onClick={() => onSelectAddCell('markdown')}+ tooltip={{ content: { side: 'bottom', text: 'Add markdown cell' } }}+ />+ </div>+ </>)}</div></div>diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/DisplaySettingsButton.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/DisplaySettingsButton.tsxindex 70c07a3bae5..d826537d372 100644--- a/apps/studio/components/interfaces/Explorer/QueryCell/DisplaySettingsButton.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryCell/DisplaySettingsButton.tsx@@ -32,6 +32,8 @@ interface DisplaySettingsButtonProps {}// [Joshen] TODO support multiple y axis charts+// [Joshen] TODO onUpdateChartConfig can likely be shifted into the notebook-state+// so this component doesn't need to know about other cellsexport const DisplaySettingsButton = ({display,diff --git a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsxindex 9553fa64262..00f63c1c9d1 100644--- a/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx+++ b/apps/studio/components/interfaces/Explorer/QueryCell/index.tsx@@ -2,6 +2,8 @@ import { untrustedSql } from '@supabase/pg-meta'import { useState } from 'react'import { type Snapshot } from 'valtio'+import { AddCellDropdown } from '../AddCellDropdown'+import { MoveCellDropdownContent } from '../MoveCellDropdownContent'import { QueryEditor } from '../QueryEditor'import { type QueryDisplay, type QueryResult } from '../types'import { SortableSection } from '@/components/ui/SortableSection'@@ -12,6 +14,17 @@ interface QueryCellProps {cell: Snapshot<DatabaseCellSchema>}+/**+ * [Joshen] Aiming to keep PRs small so the following are deliberating missing for now:+ * - Auto limit logic+ * - Database selection logic+ *+ * QueryCell atm minimally supports running queries and rendering results+ *+ * [Joshen] TODO: handleUpdateCell might be able to shift into notebook-state, so component+ * doesn't need to have context of the other cells+ */+type QueryCellUpdate = { sql: string } | { title: string } | { display: QueryDisplay }/** Notebook adapter around the shared QueryEditor. */@@ -56,7 +69,12 @@ export const QueryCell = ({ cell }: QueryCellProps) => {}return (- <SortableSection gripClassName="mt-2.5" id={cell.id}>+ <SortableSection+ id={cell.id}+ actions={<AddCellDropdown cellId={cell.id} />}+ gripDropdownContent={<MoveCellDropdownContent cellId={cell.id} />}+ gripClassName="mt-2 opacity-0 group-hover:opacity-100 has-[[data-state=open]]:opacity-100 transition"+ ><QueryEditorid={cell.id}variant="embedded"diff --git a/apps/studio/components/interfaces/Explorer/hooks.ts b/apps/studio/components/interfaces/Explorer/hooks.tsindex 99e21109f2a..506236d2cf2 100644--- a/apps/studio/components/interfaces/Explorer/hooks.ts+++ b/apps/studio/components/interfaces/Explorer/hooks.ts@@ -1,6 +1,6 @@-import { untrustedSql } from '@supabase/pg-meta'import { useRouter } from 'next/router'+import { createMarkdownCellSkeleton, createQueryCellSkeleton } from './utils'import { useSelectedProjectQuery } from '@/hooks/misc/useSelectedProject'import { generateUuid } from '@/lib/api/snippets.browser'import { useProfile } from '@/lib/profile'@@ -23,35 +23,28 @@ export const useCreateNotebook = () => {if (!profile) return console.error('Profile is required')if (!project) return console.error('Project is required')- // [Joshen] Just adding sample data to play around with, keep for now - clean up at the end- const DEFAULT_CELLS = [- {- _tag: 'markdown_cell',- id: generateUuid(),- text: `+ const sampleMdCell1 = createMarkdownCellSkeleton({+ content: `# TitleA brief description on what this notebook is about- `.trim(),- },- {- _tag: 'markdown_cell',- id: generateUuid(),- text: `+`.trim(),+ })+ const sampleMdCell2 = createMarkdownCellSkeleton({+ content: `## SectionThis is a sample paragraph to demonstrate the Markdown cells1. List item 12. List item 23. List item 3- `,- },- {- _tag: 'database_cell',- id: generateUuid(),- view: 'table',- chart: undefined,- unchecked_sql: untrustedSql('select * from colors;'),- row_limit: 100,- },+`.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()diff --git a/apps/studio/components/interfaces/Explorer/utils.ts b/apps/studio/components/interfaces/Explorer/utils.tsnew file mode 100644index 00000000000..059c84784d4--- /dev/null+++ b/apps/studio/components/interfaces/Explorer/utils.ts@@ -0,0 +1,31 @@+import { untrustedSql } from '@supabase/pg-meta'++import { generateUuid } from '@/lib/api/snippets.browser'++export const createQueryCellSkeleton = ({ sql }: { sql?: string } = {}) => {+ return {+ _tag: 'database_cell' as const,+ id: generateUuid(),+ view: 'table' as const,+ chart: undefined,+ unchecked_sql: untrustedSql(sql ?? ''),+ row_limit: 100,+ }+}++const DEFAULT_MARKDOWN_CONTENT = `+ # New section+ Add notes about your queries and results+`.trim()++export const createMarkdownCellSkeleton = ({+ content = DEFAULT_MARKDOWN_CONTENT,+}: {+ content?: string+} = {}) => {+ return {+ _tag: 'markdown_cell' as const,+ id: generateUuid(),+ text: content,+ }+}diff --git a/apps/studio/components/ui/SortableSection.tsx b/apps/studio/components/ui/SortableSection.tsxindex 3484e61e49e..53e44256795 100644--- a/apps/studio/components/ui/SortableSection.tsx+++ b/apps/studio/components/ui/SortableSection.tsx@@ -1,17 +1,44 @@+import { useDndMonitor } from '@dnd-kit/core'import { useSortable } from '@dnd-kit/sortable'import { GripVertical } from 'lucide-react'-import type { CSSProperties, PropsWithChildren } from 'react'-import { Button, cn } from 'ui'+import type { CSSProperties, PropsWithChildren, ReactNode } from 'react'+import { useEffect, useRef, useState } from 'react'+import { Button, cn, DropdownMenu, DropdownMenuTrigger } from 'ui'export const SortableSection = ({id,children,+ actions,gripClassName,-}: PropsWithChildren<{ id: string; gripClassName?: string }>) => {+ gripDropdownContent,+}: PropsWithChildren<{+ id: string+ gripClassName?: string+ actions?: ReactNode+ gripDropdownContent?: ReactNode+}>) => {const { attributes, listeners, setNodeRef, transform, transition, isDragging } = useSortable({id,})+ const [menuOpen, setMenuOpen] = useState(false)+ const isDraggingRef = useRef(false)+ const openTimeoutRef = useRef<ReturnType<typeof setTimeout>>(undefined)++ useDndMonitor({+ onDragStart: (event) => {+ if (event.active.id === id) isDraggingRef.current = true+ },+ onDragEnd: (event) => {+ if (event.active.id === id) isDraggingRef.current = false+ },+ onDragCancel: (event) => {+ if (event.active.id === id) isDraggingRef.current = false+ },+ })++ useEffect(() => () => clearTimeout(openTimeoutRef.current), [])+const style: CSSProperties = {transform: transform? `translate3d(${Math.round(transform.x)}px, ${Math.round(transform.y)}px, 0)`@@ -23,22 +50,43 @@ export const SortableSection = ({<divref={setNodeRef}style={style}- className="relative will-change-transform flex items-start gap-x-4"+ className="group relative will-change-transform flex items-start gap-x-4">- <Button- type="button"- variant="text"- aria-label="Drag to reorder section"- className={cn(- 'w-6 text-foreground-muted hover:text-foreground cursor-grab active:cursor-grabbing',- 'rounded-sm focus-ring',- gripClassName- )}- {...attributes}- {...listeners}- tabIndex={0}- icon={<GripVertical />}- />+ <div className={cn('flex items-center', gripClassName)}>+ {actions}+ <DropdownMenu+ open={menuOpen}+ onOpenChange={(open) => {+ clearTimeout(openTimeoutRef.current)++ if (!open) {+ setMenuOpen(false)+ return+ }++ openTimeoutRef.current = setTimeout(() => {+ if (!isDraggingRef.current) setMenuOpen(true)+ }, 150)+ }}+ >+ <DropdownMenuTrigger asChild>+ <Button+ type="button"+ variant="text"+ aria-label="Drag to reorder section"+ className={cn(+ 'w-6 text-foreground-muted hover:text-foreground cursor-grab active:cursor-grabbing',+ 'rounded-sm focus-ring'+ )}+ {...attributes}+ {...listeners}+ tabIndex={0}+ icon={<GripVertical />}+ />+ </DropdownMenuTrigger>+ {gripDropdownContent}+ </DropdownMenu>+ </div><div className={cn('w-full', isDragging && 'opacity-70')}>{children}</div></div>)diff --git a/apps/studio/state/notebooks/notebooks-state.ts b/apps/studio/state/notebooks/notebooks-state.tsindex f9f3054d934..cd0c2829696 100644--- a/apps/studio/state/notebooks/notebooks-state.ts+++ b/apps/studio/state/notebooks/notebooks-state.ts@@ -1,3 +1,5 @@+import { type UniqueIdentifier } from '@dnd-kit/core'+import { arrayMove } from '@dnd-kit/sortable'import { useParams } from 'common'import { useMemo } from 'react'import { proxy, snapshot, useSnapshot, type Snapshot } from 'valtio'@@ -92,6 +94,94 @@ export const notebooksState = proxy({if (!skipSave) notebooksState.needsSaving.set(id, false)},+ /**+ * Insert a cell right after `cellId` in a notebook's cell array — or at the+ * end, if `cellId` is omitted or isn't found (e.g. an empty notebook has no+ * cell to insert after). The caller builds the cell to insert (e.g. via+ * `createMarkdownCellSkeleton`/`createQueryCellSkeleton`) since deciding+ * what kind of cell to create is a UI concern, not a state one.+ */+ insertCellAfter: ({+ id,+ cellId,+ cell,+ }: {+ id: string+ cellId?: string+ cell: Notebooks.Cell+ }) => {+ const stateNotebook = notebooksState.notebooks[id]+ if (!stateNotebook?.notebook.content) return++ const cells = stateNotebook.notebook.content.cells+ const insertAt = cellId ? cells.findIndex((c) => c.id === cellId) : -1+ const nextCells = [...cells]+ nextCells.splice(insertAt === -1 ? cells.length : insertAt + 1, 0, cell)++ notebooksState.updateCells({ id, cells: nextCells })+ },++ /**+ * Remove a single cell from a notebook's cell array.+ */+ removeCell: ({ id, cellId }: { id: string; cellId: string }) => {+ const stateNotebook = notebooksState.notebooks[id]+ if (!stateNotebook?.notebook.content) return++ const nextCells = stateNotebook.notebook.content.cells.filter((c) => c.id !== cellId)+ notebooksState.updateCells({ id, cells: nextCells })+ },++ /**+ * Shift a cell one position up or down in a notebook's cell array. No-ops if+ * the cell is already at that boundary (or isn't found).+ */+ moveCell: ({+ id,+ cellId,+ direction,+ }: {+ id: string+ cellId: string+ direction: 'up' | 'down'+ }) => {+ const stateNotebook = notebooksState.notebooks[id]+ if (!stateNotebook?.notebook.content) return++ const cells = stateNotebook.notebook.content.cells+ const currentIndex = cells.findIndex((c) => c.id === cellId)+ if (currentIndex === -1) return++ const nextIndex = direction === 'up' ? currentIndex - 1 : currentIndex + 1+ if (nextIndex < 0 || nextIndex >= cells.length) return++ notebooksState.updateCells({ id, cells: arrayMove([...cells], currentIndex, nextIndex) })+ },++ /**+ * Reorder a notebook's cell array by moving the cell at `activeCellId` to+ * where `overCellId` currently sits (dnd-kit's drag-end positions).+ */+ reorderCells: ({+ id,+ activeCellId,+ overCellId,+ }: {+ id: string+ activeCellId: UniqueIdentifier+ overCellId: UniqueIdentifier+ }) => {+ const stateNotebook = notebooksState.notebooks[id]+ if (!stateNotebook?.notebook.content) return++ const cells = stateNotebook.notebook.content.cells+ const oldIndex = cells.findIndex((c) => c.id === activeCellId)+ const newIndex = cells.findIndex((c) => c.id === overCellId)+ if (oldIndex === -1 || newIndex === -1) return++ notebooksState.updateCells({ id, cells: arrayMove([...cells], oldIndex, newIndex) })+ },+addNeedsSaving: (id: string) => notebooksState.needsSaving.set(id, true),})