Skip to content

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

refactor(studio): static tab kind registry and tab id codec (PR 1/9) (#48718)

Charisffd6d6636ddf
diff --git a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx
index 615eecc6aad..8d9a35c3db7 100644
--- a/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx
+++ b/apps/studio/components/layouts/SQLEditorLayout/SQLEditorNavV2/SQLEditorTreeViewItem.tsx
@@ -30,7 +30,6 @@ import {
import { getSnippetSource } from '@/components/interfaces/SQLEditor/querySource'
import { createSqlSnippetSkeletonV2 } from '@/components/interfaces/SQLEditor/SQLEditor.utils'
-import { LogsSnippetIcon } from '@/components/ui/EntityTypeIcon'
import { getContentById, getSqlSnippetById } from '@/data/content/content-id-query'
import { useSQLSnippetFolderContentsQuery } from '@/data/content/sql-folder-contents-query'
import { Snippet } from '@/data/content/sql-folders-query'
@@ -44,6 +43,7 @@ import {
type FolderStatus,
} from '@/state/sql-editor/sql-editor-lifecycle'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
+import { LogsSnippetIcon } from '@/state/tabs/kinds.icons'
interface SQLEditorTreeViewItemProps extends Omit<
ComponentProps<typeof TreeViewItem>,
diff --git a/apps/studio/components/ui/EntityTypeIcon.tsx b/apps/studio/components/ui/EntityTypeIcon.tsx
index 2dc05a6df58..3427a1654a4 100644
--- a/apps/studio/components/ui/EntityTypeIcon.tsx
+++ b/apps/studio/components/ui/EntityTypeIcon.tsx
@@ -1,29 +1,8 @@
-import { Eye, GitBranch, ScrollText, Table2 } from 'lucide-react'
+import { GitBranch } from 'lucide-react'
import { cn, SQL_ICON } from 'ui'
import type { SqlSnippetSource } from '@/components/interfaces/SQLEditor/querySource'
-import { ENTITY_TYPE } from '@/data/entity-types/entity-type-constants'
-
-/**
- * The single icon representing a logs (`log_sql`) snippet — reused by the tabs
- * (via EntityTypeIcon) and the nav tree so the two can't drift. Callers pass the
- * context-appropriate size/className; the icon and stroke stay the same.
- */
-export const LogsSnippetIcon = ({
- size = 15,
- strokeWidth = 1.5,
- className,
-}: {
- size?: number
- strokeWidth?: number
- className?: string
-}) => (
- <ScrollText
- size={size}
- strokeWidth={strokeWidth}
- className={cn('transition-colors', className)}
- />
-)
+import { TAB_KIND_ICONS } from '@/state/tabs/kinds.icons'
interface EntityTypeIconProps {
type: 'sql' | 'schema' | 'new' | 'r' | 'v' | 'm' | 'f' | 'p'
@@ -33,6 +12,7 @@ interface EntityTypeIconProps {
sqlSource?: SqlSnippetSource
}
+/** Thin wrapper over the per-kind icons in `state/tabs/kinds.icons`, preserving this component's flexible prop-based API for callers without a whole `Tab` to hand. */
export const EntityTypeIcon = ({
type,
size = 15,
@@ -40,22 +20,11 @@ export const EntityTypeIcon = ({
isActive,
sqlSource,
}: EntityTypeIconProps) => {
- if (type === 'sql' && sqlSource === 'logs') {
- return (
- <LogsSnippetIcon
- size={size}
- strokeWidth={strokeWidth}
- className={cn(
- 'text-foreground-muted',
- 'group-aria-selected:text-foreground',
- 'w-4 h-4',
- '-ml-0.5'
- )}
- />
- )
+ if (type === 'schema') {
+ return <GitBranch size={size} strokeWidth={strokeWidth} />
}
- if (type === 'sql') {
+ if (type === 'new') {
return (
<SQL_ICON
size={size}
@@ -71,52 +40,13 @@ export const EntityTypeIcon = ({
)
}
- if (type === ENTITY_TYPE.TABLE) {
- return (
- <Table2
- size={size}
- strokeWidth={strokeWidth}
- className={cn(
- 'text-foreground-muted group-hover:text-foreground-lighter group-aria-selected:text-foreground',
- isActive && 'text-foreground-light',
- 'transition-colors'
- )}
- />
- )
- }
-
- if (type === 'schema') {
- return <GitBranch size={size} strokeWidth={strokeWidth} />
- }
-
- if (type === ENTITY_TYPE.VIEW) {
- return (
- <Eye
- size={size}
- strokeWidth={strokeWidth}
- className={cn(
- 'text-foreground-muted group-hover:text-foreground-lighter',
- isActive && 'text-foreground-lighter',
- 'transition-colors'
- )}
- />
- )
- }
-
+ const KindIcon = TAB_KIND_ICONS[type]
return (
- <div
- className={cn(
- 'flex items-center justify-center text-xs h-4 w-4 rounded-[2px] font-bold',
- type === ENTITY_TYPE.FOREIGN_TABLE &&
- 'text-warning-600/80 dark:text-yellow-900 bg-yellow-500',
- type === ENTITY_TYPE.MATERIALIZED_VIEW && 'text-purple-1100 bg-purple-500',
- type === ENTITY_TYPE.PARTITIONED_TABLE &&
- 'text-foreground-light bg-surface-400 dark:bg-border-stronger'
- )}
- >
- {Object.entries(ENTITY_TYPE)
- .find(([, value]) => value === type)?.[0]?.[0]
- ?.toUpperCase()}
- </div>
+ <KindIcon
+ tab={{ metadata: { sqlSource } }}
+ size={size}
+ strokeWidth={strokeWidth}
+ isActive={isActive}
+ />
)
}
diff --git a/apps/studio/state/tabs/kinds.icons.tsx b/apps/studio/state/tabs/kinds.icons.tsx
new file mode 100644
index 00000000000..04c49527786
--- /dev/null
+++ b/apps/studio/state/tabs/kinds.icons.tsx
@@ -0,0 +1,117 @@
+import { Eye, MessageSquare, NotebookPen, ScrollText, Table2 } from 'lucide-react'
+import type { ReactNode } from 'react'
+import { cn, SQL_ICON } from 'ui'
+
+import type { TabKind } from './kinds'
+
+export const LogsSnippetIcon = ({
+ size = 15,
+ strokeWidth = 1.5,
+ className,
+}: {
+ size?: number
+ strokeWidth?: number
+ className?: string
+}) => (
+ <ScrollText
+ size={size}
+ strokeWidth={strokeWidth}
+ className={cn('transition-colors', className)}
+ />
+)
+
+interface KindIconProps {
+ // Structurally compatible with `Tab` (`state/tabs.tsx`) without importing it, keeping this module a leaf (ui + lucide-react + `TabKind` only).
+ tab: { metadata?: { sqlSource?: 'database' | 'logs' } }
+ size?: number
+ strokeWidth?: number
+ isActive?: boolean
+}
+
+type KindIconComponent = (props: KindIconProps) => ReactNode
+
+const SqlKindIcon = ({ tab, size = 15, strokeWidth = 1.5 }: KindIconProps) => {
+ if (tab.metadata?.sqlSource === 'logs') {
+ return (
+ <LogsSnippetIcon
+ size={size}
+ strokeWidth={strokeWidth}
+ className="text-foreground-muted group-aria-selected:text-foreground w-4 h-4 -ml-0.5"
+ />
+ )
+ }
+
+ return (
+ <SQL_ICON
+ size={size}
+ strokeWidth={strokeWidth}
+ className="transition-colors fill-foreground-muted group-aria-selected:fill-foreground w-4 h-4 -ml-0.5"
+ />
+ )
+}
+
+const TableKindIcon = ({ size = 15, strokeWidth = 1.5, isActive }: KindIconProps) => (
+ <Table2
+ size={size}
+ strokeWidth={strokeWidth}
+ className={cn(
+ 'text-foreground-muted group-hover:text-foreground-lighter group-aria-selected:text-foreground transition-colors',
+ isActive && 'text-foreground-light'
+ )}
+ />
+)
+
+const ViewKindIcon = ({ size = 15, strokeWidth = 1.5, isActive }: KindIconProps) => (
+ <Eye
+ size={size}
+ strokeWidth={strokeWidth}
+ className={cn(
+ 'text-foreground-muted group-hover:text-foreground-lighter transition-colors',
+ isActive && 'text-foreground-lighter'
+ )}
+ />
+)
+
+const badgeKindIcon = (letter: string, colorClassName: string): KindIconComponent =>
+ function BadgeKindIcon() {
+ return (
+ <div
+ className={cn(
+ 'flex items-center justify-center text-xs h-4 w-4 rounded-[2px] font-bold',
+ colorClassName
+ )}
+ >
+ {letter}
+ </div>
+ )
+ }
+
+const MaterializedViewKindIcon = badgeKindIcon('M', 'text-purple-1100 bg-purple-500')
+const ForeignTableKindIcon = badgeKindIcon(
+ 'F',
+ 'text-warning-600/80 dark:text-yellow-900 bg-yellow-500'
+)
+const PartitionedTableKindIcon = badgeKindIcon(
+ 'P',
+ 'text-foreground-light bg-surface-400 dark:bg-border-stronger'
+)
+
+const NotebookKindIcon = ({ size = 15, strokeWidth = 1.5 }: KindIconProps) => (
+ <NotebookPen size={size} strokeWidth={strokeWidth} />
+)
+
+const ChatKindIcon = ({ size = 15, strokeWidth = 1.5 }: KindIconProps) => (
+ <MessageSquare size={size} strokeWidth={strokeWidth} />
+)
+
+/** Per-kind icon, keyed identically to `TAB_KINDS` — see `kinds.ts` for the descriptor table. */
+export const TAB_KIND_ICONS: Record<TabKind, KindIconComponent> = {
+ sql: SqlKindIcon,
+ notebook: NotebookKindIcon,
+ chat: ChatKindIcon,
+ r: TableKindIcon,
+ v: ViewKindIcon,
+ m: MaterializedViewKindIcon,
+ f: ForeignTableKindIcon,
+ p: PartitionedTableKindIcon,
+}
diff --git a/apps/studio/state/tabs/kinds.ts b/apps/studio/state/tabs/kinds.ts
new file mode 100644
index 00000000000..48ba307a799
--- /dev/null
+++ b/apps/studio/state/tabs/kinds.ts
@@ -0,0 +1,89 @@
+import type { ReactNode } from 'react'
+
+import { TAB_KIND_ICONS } from './kinds.icons'
+import type { Tab } from '@/state/tabs'
+
+/** Which tab strip / layout a kind renders in — strip filtering, bulk-close, and recents key off this instead of an id-prefix check. */
+export type TabSurface = 'sql' | 'table'
+
+/** `sql` covers both Postgres and logs snippets; `Tab.metadata.sqlSource` discriminates */
+export type TabKind = 'sql' | 'notebook' | 'chat' | 'r' | 'v' | 'm' | 'f' | 'p'
+
+interface TabKindDescriptor {
+ surface: TabSurface
+ /** URL segment prefix. `null` = bare segment — `sql` (legacy) and every table kind, since `/editor/<id>` is already bare and unprefixed today. */
+ urlPrefix: string | null
+ /** Singular noun for shared copy, e.g. a not-found message: "This <noun> could not be found." */
+ noun: string
+ supportsPreview: boolean
+ Icon: (props: { tab: Tab }) => ReactNode
+}
+
+export const TAB_KINDS: Record<TabKind, TabKindDescriptor> = {
+ sql: {
+ surface: 'sql',
+ urlPrefix: null,
+ noun: 'query',
+ supportsPreview: true,
+ Icon: TAB_KIND_ICONS.sql,
+ },
+ notebook: {
+ surface: 'sql',
+ urlPrefix: 'notebook',
+ noun: 'notebook',
+ supportsPreview: true,
+ Icon: TAB_KIND_ICONS.notebook,
+ },
+ chat: {
+ surface: 'sql',
+ urlPrefix: 'chat',
+ noun: 'chat',
+ supportsPreview: true,
+ Icon: TAB_KIND_ICONS.chat,
+ },
+ r: {
+ surface: 'table',
+ urlPrefix: null,
+ noun: 'table',
+ supportsPreview: true,
+ Icon: TAB_KIND_ICONS.r,
+ },
+ v: {
+ surface: 'table',
+ urlPrefix: null,
+ noun: 'view',
+ supportsPreview: true,
+ Icon: TAB_KIND_ICONS.v,
+ },
+ m: {
+ surface: 'table',
+ urlPrefix: null,
+ noun: 'materialized view',
+ supportsPreview: true,
+ Icon: TAB_KIND_ICONS.m,
+ },
+ f: {
+ surface: 'table',
+ urlPrefix: null,
+ noun: 'foreign table',
+ supportsPreview: true,
+ Icon: TAB_KIND_ICONS.f,
+ },
+ p: {
+ surface: 'table',
+ urlPrefix: null,
+ noun: 'partitioned table',
+ supportsPreview: true,
+ Icon: TAB_KIND_ICONS.p,
+ },
+}
+
+export const isTabKind = (value: string): value is TabKind =>
+ Object.prototype.hasOwnProperty.call(TAB_KINDS, value)
+
+const TAB_KIND_LIST = Object.keys(TAB_KINDS).filter(isTabKind)
+
+export const surfaceOf = (kind: TabKind): TabSurface => TAB_KINDS[kind].surface
+
+export const kindsOnSurface = (surface: TabSurface): Array<TabKind> =>
+ TAB_KIND_LIST.filter((kind) => TAB_KINDS[kind].surface === surface)
diff --git a/apps/studio/state/tabs/tab-id.test.ts b/apps/studio/state/tabs/tab-id.test.ts
new file mode 100644
index 00000000000..618499d0d63
--- /dev/null
+++ b/apps/studio/state/tabs/tab-id.test.ts
@@ -0,0 +1,112 @@
+import { describe, expect, it } from 'vitest'
+
+import { kindsOnSurface, TAB_KINDS, type TabKind } from './kinds'
+import { createTabId, parseTabId, parseUrlSegment, toUrlSegment } from './tab-id'
+
+const ALL_KINDS = Object.keys(TAB_KINDS) as Array<TabKind>
+
+/** Test-only narrowing: every call site below passes a known-non-empty literal. */
+function mustCreateTabId(kind: TabKind, contentId: string): string {
+ const tabId = createTabId(kind, contentId)
+ if (tabId === null) throw new Error(`createTabId unexpectedly returned null for ${kind}`)
+ return tabId
+}
+
+describe('createTabId / parseTabId round-trip', () => {
+ it.each(ALL_KINDS)('round-trips a uuid-like content id for kind %s', (kind) => {
+ const contentId = '3fa85f64-5717-4562-b3fc-2c963f66afa6'
+ const tabId = mustCreateTabId(kind, contentId)
+
+ expect(tabId).toBe(`${kind}-${contentId}`)
+ expect(parseTabId(tabId)).toEqual({ kind, contentId })
+ })
+
+ it('returns null for an empty content id, so createTabId/parseTabId never disagree', () => {
+ expect(createTabId('sql', '')).toBeNull()
+ })
+
+ it('rejects an id with an unknown kind', () => {
+ expect(parseTabId('bogus-123')).toBeNull()
+ })
+
+ it('rejects an id whose kind is an inherited Object property name', () => {
+ expect(parseTabId('constructor-123')).toBeNull()
+ expect(parseTabId('toString-123')).toBeNull()
+ })
+
+ it('rejects an id with no dash separator', () => {
+ expect(parseTabId('sql')).toBeNull()
+ })
+
+ it('rejects an id with an empty content id', () => {
+ expect(parseTabId('sql-')).toBeNull()
+ })
+
+ it('splits on the first dash only, so a dashed content id survives', () => {
+ expect(parseTabId('notebook-3fa85f64-5717-4562-b3fc-2c963f66afa6')).toEqual({
+ kind: 'notebook',
+ contentId: '3fa85f64-5717-4562-b3fc-2c963f66afa6',
+ })
+ })
+})
+
+describe('toUrlSegment: bare vs. prefixed', () => {
+ it.each(['sql', 'r', 'v', 'm', 'f', 'p'] as const)(
+ 'drops the prefix for the bare kind %s',
+ (kind) => {
+ expect(toUrlSegment(mustCreateTabId(kind, 'abc'))).toBe('abc')
+ }
+ )
+
+ it.each(['notebook', 'chat'] as const)('keeps the prefix for kind %s', (kind) => {
+ expect(toUrlSegment(mustCreateTabId(kind, 'abc'))).toBe(`${kind}-abc`)
+ })
+
+ it('returns null for a malformed tab id', () => {
+ expect(toUrlSegment('not-a-real-kind-abc')).toBeNull()
+ })
+
+ it('passes through a null tab id, so it composes directly with createTabId', () => {
+ expect(toUrlSegment(createTabId('sql', ''))).toBeNull()
+ })
+})
+
+describe('parseUrlSegment: surface scoping', () => {
+ it('resolves a bare segment to the sql kind on the sql surface', () => {
+ expect(parseUrlSegment('abc', 'sql')).toEqual({ kind: 'sql', contentId: 'abc' })
+ })
+
+ it('resolves a prefixed segment to its kind on the sql surface', () => {
+ expect(parseUrlSegment('notebook-abc', 'sql')).toEqual({ kind: 'notebook', contentId: 'abc' })
+ expect(parseUrlSegment('chat-abc', 'sql')).toEqual({ kind: 'chat', contentId: 'abc' })
+ })
+
+ it('falls back to the bare sql kind for a segment that looks table-prefixed, since sql has no other claim on it', () => {
+ // "r-123" isn't a `notebook-`/`chat-` segment, so on the sql surface it's just
+ // a raw (if odd-looking) content id — the table kind `r` is out of scope here.
+ expect(parseUrlSegment('r-123', 'sql')).toEqual({ kind: 'sql', contentId: 'r-123' })
+ })
+
+ it('does not resolve a sql-surface-only prefix on the table surface', () => {
+ expect(parseUrlSegment('notebook-abc', 'table')).toBeNull()
+ })
+
+ it.each(kindsOnSurface('table'))(
+ 'does not resolve a bare segment on the table surface, which has %s among several ambiguous bare kinds',
+ (kind) => {
+ expect(TAB_KINDS[kind].urlPrefix).toBeNull()
+ expect(parseUrlSegment('123', 'table')).toBeNull()
+ }
+ )
+
+ it('returns null for an empty segment', () => {
+ expect(parseUrlSegment('', 'sql')).toBeNull()
+ })
+
+ it.each(['templates', 'examples', 'new'])(
+ 'resolves the "%s" sentinel to the bare sql kind, not a UUID',
+ (sentinel) => {
+ expect(parseUrlSegment(sentinel, 'sql')).toEqual({ kind: 'sql', contentId: sentinel })
+ }
+ )
+})
diff --git a/apps/studio/state/tabs/tab-id.ts b/apps/studio/state/tabs/tab-id.ts
new file mode 100644
index 00000000000..f0408e6c73c
--- /dev/null
+++ b/apps/studio/state/tabs/tab-id.ts
@@ -0,0 +1,60 @@
+import { isTabKind, kindsOnSurface, TAB_KINDS, type TabKind, type TabSurface } from './kinds'
+
+export interface ParsedTabId {
+ kind: TabKind
+ contentId: string
+}
+
+/** A tab's id is always `${kind}-${contentId}` — kind names never contain a dash. Returns null for an empty contentId, since `parseTabId` can't invert it. */
+export function createTabId(kind: TabKind, contentId: string): string | null {
+ if (!contentId) return null
+ return `${kind}-${contentId}`
+}
+
+/** Inverse of `createTabId`. Returns null for a malformed id or an unknown kind. */
+export function parseTabId(tabId: string): ParsedTabId | null {
+ const dashIndex = tabId.indexOf('-')
+ if (dashIndex === -1) return null
+
+ const kind = tabId.slice(0, dashIndex)
+ const contentId = tabId.slice(dashIndex + 1)
+ if (!contentId || !isTabKind(kind)) return null
+
+ return { kind, contentId }
+}
+
+/** The URL segment a tab id renders as. Drops the prefix for a bare kind (`sql-<uuid>` → `<uuid>`, and every table kind); keeps it otherwise (`notebook-<uuid>` → `notebook-<uuid>`). Passes through a null `tabId`, so it composes directly with `createTabId`. */
+export function toUrlSegment(tabId: string | null): string | null {
+ if (tabId === null) return null
+
+ const parsed = parseTabId(tabId)
+ if (!parsed) return null
+
+ const { urlPrefix } = TAB_KINDS[parsed.kind]
+ return urlPrefix === null ? parsed.contentId : `${urlPrefix}-${parsed.contentId}`
+}
+
+/** Inverse of `toUrlSegment`, scoped to a surface. A bare segment resolves only when exactly one bare kind exists on the surface (`sql`); the table surface's five bare kinds have no URL disambiguator, matching `/editor/[id]`, which learns kind from the fetched entity rather than the URL. */
+export function parseUrlSegment(segment: string, surface: TabSurface): ParsedTabId | null {
+ if (!segment) return null
+
+ let bareKind: TabKind | null = null
+ let bareKindIsAmbiguous = false
+
+ for (const kind of kindsOnSurface(surface)) {
+ const { urlPrefix } = TAB_KINDS[kind]
+ if (urlPrefix === null) {
+ if (bareKind === null) bareKind = kind
+ else bareKindIsAmbiguous = true
+ continue
+ }
+
+ const prefix = `${urlPrefix}-`
+ if (segment.startsWith(prefix)) {
+ const contentId = segment.slice(prefix.length)
+ if (contentId) return { kind, contentId }
+ }
+ }
+
+ return bareKind && !bareKindIsAmbiguous ? { kind: bareKind, contentId: segment } : null
+}