Files
supabase/apps/studio/components/layouts/Tabs/Tabs.utils.ts
Joshen Lim 4ed3627d72 Joshenlim/fe 3891 improve handling of partition tables in (#53268)
## Context

The Table Editor doesn't really handle partitioned tables well given the
following issues:
- Partitioned tables are rendered as a flat list in the Table Editor
side menu, so the menu could get very long and noisy - this was the
primary motivation for this PR
- Child partitioned tables are not indicated with a proper icon, they're
treated as regular tables in the Table Editor which is incorrect

## Changes involved
- Table Editor side menu now only lists parent partitioned tables, omits
all child partitioned tables
- Child partitioned tables can be viewed by clicking on the button
tooltip here or drilling down via "View partitions"
<img width="300" alt="image"
src="https://github.com/user-attachments/assets/e3cfbe4b-21ff-47df-8fcd-81d0c9f68d94"
/><br />
<img width="400" alt="image"
src="https://github.com/user-attachments/assets/5d0747cb-fb52-4301-ad9e-c7be504f43c9"
/>

  - Selecting that will then render a nested nav as such
<img width="291" height="323" alt="image"
src="https://github.com/user-attachments/assets/bff0a42b-4265-4317-8299-537d82544388"
/>

- Sub partitioned tables can be drilled into the same way, and the back
CTA steps up one level
<img width="485" height="306" alt="image"
src="https://github.com/user-attachments/assets/66f6f6cb-8b7d-46c5-8ea3-4ee4fd57aa84"
/>

- Parent partition tables have the following actions (Previously was
only copy name and schema)
<img width="465" height="257" alt="image"
src="https://github.com/user-attachments/assets/2aa90995-7c30-4bcf-a446-d01ab52c1ede"
/>

- Deleting a parent partition table will also delete the child partition
table, and that's highlighted in the confirmation modal
<img width="418" height="316" alt="image"
src="https://github.com/user-attachments/assets/0d61984b-f85e-4c93-84d0-549d300838c9"
/>

- Child partition tables have the following actions (Edit + duplicate
removed since they aren't supported via the UI)
<img width="482" height="229" alt="image"
src="https://github.com/user-attachments/assets/e028b13d-2e92-4491-b05c-7a6cb0a129d6"
/>


## To test
In general, just verify the viewing UX of partitioned tables to see if
it all feels alright, can use the following SQL to quickly set up
partitioned tables
```sql
   create schema if not exists tint;
   create table public.nest_demo (id int, hue int not null, primary key (id, hue))
     partition by range (hue);
   create table public.nest_demo_blue partition of public.nest_demo
     for values from (200) to (300) partition by range (hue);
   create table public.nest_demo_blue_light partition of public.nest_demo_blue
     for values from (200) to (250);
   create table tint.nest_demo_blue_deep partition of public.nest_demo_blue
     for values from (250) to (300);
   create table public.nest_demo_other partition of public.nest_demo
     for values from (0) to (200);
   ```
2026-11-16 17:23:59 +07:00

237 lines
8.7 KiB
TypeScript

import { useCallback, useEffect, useRef } from 'react'
import { Entity } from '@/data/entity-types/entity-types-infinite-query'
import { useLatest } from '@/hooks/misc/useLatest'
import { wasNeverPersisted } from '@/state/sql-editor/sql-editor-lifecycle'
import { getSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
import { createTabId, editorEntityTypes, useTabsStateSnapshot } from '@/state/tabs'
export function useTableEditorTabsCleanUp() {
const tabs = useTabsStateSnapshot()
const tabMapRef = useLatest(tabs.tabsMap)
const recentItemsRef = useLatest(tabs.recentItems)
const openTabsRef = useLatest(tabs.openTabs)
return useCallback(
async ({
schemas,
entities: listedEntities,
resolveEntities,
}: {
schemas: string[]
entities: Entity[]
// Confirms tabs missing from `entities` (e.g. hidden child partitions) still exist before
// pruning them. If it rejects, nothing is pruned.
resolveEntities?: (ids: number[]) => Promise<Entity[]>
}) => {
// Snapshot the candidates up front: tabs opened while the lookup below is pending
// haven't been checked against anything, so they must not be pruned
const recentItemsFilteredToSchemas: string[] = []
for (const schema of schemas) {
recentItemsFilteredToSchemas.push(
...recentItemsRef.current.filter((x) => x.metadata?.schema === schema).map((x) => x.id)
)
}
const tabsFilteredToSchemas: string[] = []
for (const schema of schemas) {
tabsFilteredToSchemas.push(
...openTabsRef.current.filter((tabId) => {
const tab = tabMapRef.current[tabId]
return tab?.metadata?.schema === schema
})
)
}
const listedTabIds = new Set(listedEntities.map((x) => createTabId(x.type, { id: x.id })))
const unlistedEntityIds = getUnlistedEntityIds({
tabIds: [...tabsFilteredToSchemas, ...recentItemsFilteredToSchemas],
listedTabIds,
})
const resolvedEntities =
resolveEntities && unlistedEntityIds.length > 0
? await resolveEntities(unlistedEntityIds)
: []
const entities = [...listedEntities, ...resolvedEntities]
// Identity all entities by tab ID
const entitiesById: string[] = entities.map((x: Entity) => createTabId(x.type, { id: x.id }))
const recentItemsToRemove = [
...recentItemsFilteredToSchemas.filter((entityId) => !entitiesById.includes(entityId)),
]
tabs.removeRecentItems(recentItemsToRemove)
const tableEditorTabsToBeCleaned = [
...tabsFilteredToSchemas.filter(
(id) => !id.startsWith('sql') && !id.startsWith('schema') && !entitiesById.includes(id)
),
]
// perform tabs cleanup
tabs.removeTabs(tableEditorTabsToBeCleaned)
// [Joshen] Validate for opened tabs, if their label matches the entity's name - update label if not
// As the entity could've been renamed outside of the table editor
// e.g Using the SQL editor to rename the entity
const openTabs = openTabsRef.current
.map((id) => tabMapRef.current[id])
.filter((tab) => !!tab && editorEntityTypes['table']?.includes(tab.type))
openTabs.forEach((tab) => {
const entity = entities?.find((x) => tab.metadata?.tableId === x.id)
if (!!entity && entity.name !== tab.label) tabs.updateTab(tab.id, { label: entity.name })
})
},
[]
)
}
const ENTITY_TAB_ID = /^[rvmfp]-(\d+)$/
function getUnlistedEntityIds({
tabIds,
listedTabIds,
}: {
tabIds: string[]
listedTabIds: Set<string>
}) {
const ids = new Set<number>()
for (const tabId of tabIds) {
const match = ENTITY_TAB_ID.exec(tabId)
if (match && !listedTabIds.has(tabId)) ids.add(Number(match[1]))
}
return [...ids]
}
export function useSqlEditorTabsCleanup() {
const tabs = useTabsStateSnapshot()
const tabMapRef = useLatest(tabs.tabsMap)
const openTabsRef = useLatest(tabs.openTabs)
return useCallback(
({
snippets,
canPruneLogsTabs = true,
}: {
snippets: { id: string; type: string; name: string }[]
// Whether `log_sql` snippets in `snippets` are authoritative. When false (the
// logs section is disabled or its query errored) we can't know which logs
// snippets exist, so logs tabs are preserved rather than pruned as stale.
canPruneLogsTabs?: boolean
}) => {
// these are tabs that are static content
// these canot be removed from localstorage based on this query request
const IGNORED_TAB_IDS = ['sql-templates', 'sql-quickstarts']
// Identify all SQL snippets / content by their tab ids. Both database (`sql`) and
// logs (`log_sql`) snippets live in the `sql-` tab id space, so both are counted as
// live. Anything not in this set is treated as removed outside the session and pruned.
const currentContentIds = [
...snippets
.filter((content) => content.type === 'sql' || content.type === 'log_sql')
.map((content) => createTabId('sql', { id: content.id })),
// append ignored tab IDs
...IGNORED_TAB_IDS,
]
// A snippet created during this session (by typing in a new tab) exists only
// in the local store until its first save lands, so the server-fetched list
// legitimately doesn't contain it yet. Without this, invalidating the snippet
// lists on that first keystroke prunes the tab that was just opened — the URL
// and editor stay on the new snippet while the tab bar falls back to whichever
// tab was open before, making it look like the previous tab is being edited.
const localSnippets = getSqlEditorV2StateSnapshot().snippets
const isUnpersistedLocalSnippet = (sqlId: string | undefined) =>
sqlId !== undefined && wasNeverPersisted(localSnippets[sqlId]?.snippet.status)
const isPrunable = (id: string) =>
id.startsWith('sql') &&
!currentContentIds.includes(id) &&
!isUnpersistedLocalSnippet(tabMapRef.current[id]?.metadata?.sqlId) &&
(canPruneLogsTabs || tabMapRef.current[id]?.metadata?.sqlSource !== 'logs')
// Remove any snippet tabs that might no longer be existing (removed outside of the dashboard session)
const snippetTabsToBeCleaned = openTabsRef.current.filter(isPrunable)
tabs.removeTabs(snippetTabsToBeCleaned)
// Remove any recent items that might no longer be existing (removed outside of the dashboard session)
const recentItems = tabs.getRecentItemsByType('sql')
tabs.removeRecentItems(
recentItems
? recentItems
.filter(
(item) =>
!currentContentIds.includes(item.id) &&
!isUnpersistedLocalSnippet(item.metadata?.sqlId) &&
(canPruneLogsTabs || item.metadata?.sqlSource !== 'logs')
)
.map((item) => item.id)
: []
)
// [Joshen] Validate for opened tabs, if their label matches the snippet's name - update label if not
// As the snippets name could've been updated outside of the SQL Editor session
// e.g for a shared snippet, the owner could've updated the name of the snippet
const openSqlTabs = openTabsRef.current
.map((id) => tabMapRef.current[id])
.filter((tab) => !!tab && editorEntityTypes['sql']?.includes(tab.type))
openSqlTabs.forEach((tab) => {
const snippet = snippets?.find((x) => tab.metadata?.sqlId === x.id)
if (!!snippet && snippet.name !== tab.label) tabs.updateTab(tab.id, { label: snippet.name })
})
},
[]
)
}
interface UseTabsScrollOptions {
activeTab: string | null | undefined
tabCount: number
}
export function useTabsScroll({ activeTab, tabCount }: UseTabsScrollOptions) {
const tabsListRef = useRef<HTMLDivElement>(null)
const prevTabCountRef = useRef<number>(tabCount)
const isInitialMount = useRef(true)
useEffect(() => {
if (tabsListRef.current) {
tabsListRef.current.scrollLeft = tabsListRef.current.scrollWidth
}
}, [])
useEffect(() => {
if (isInitialMount.current) {
isInitialMount.current = false
return
}
if (!tabsListRef.current) return
const tabCountIncreased = tabCount > prevTabCountRef.current
if (tabCountIncreased) {
tabsListRef.current.scrollLeft = tabsListRef.current.scrollWidth
} else if (activeTab) {
const activeTabElement = tabsListRef.current.querySelector(
`[data-state="active"]`
) as HTMLElement
if (activeTabElement) {
activeTabElement.scrollIntoView({
behavior: 'smooth',
block: 'nearest',
inline: 'nearest',
})
}
}
prevTabCountRef.current = tabCount
}, [activeTab, tabCount])
return { tabsListRef }
}