Files
supabase/apps/studio/state/app-state.ts
143f49414b Feat/tabs (#31071)
* init

* Update inner-side-menu.mdx

* chore: update SQL sidebar to use ui pattern components

* mor

* Update

* Update index.tsx

* init: merge table editor and sql editor and schema visualization together

* more

* move to valtio

* fix issue with Command+B shortcut

* now shows in treeviews if item is opened in tab

* Update ProjectLayout.tsx

* fix sidebar

* fix schema selector for non explorer version

* show schema name in tabs

* added schema names to tabs

* tabs have been updated to support preview tabs

* fix URL issue

* add empty state stuff

* Update SQLEditorNav.tsx

* preview tab works now

* more tabs stuff. 'new' tab also added

* new tab concept

* updates

* fix type errors

* remove unused files

* update test

* move back button, fix width issues on sidebar

* update sidebar logic

* Update ProjectLayout.tsx

* lots of updates. layouts now streamlined. localstorage for tabs in use

* moar

* bunch of new tab logic

* fix empty tab issue

* Update tabs.ts

* layouts switched

* new pages now have fixed layouts

* fix tabs

* fix code bg

* add tabs support for multiple project refs

* intialization issue

* update ID handling

* fixed isOpened state for SQL snippets

* remove old assistant because its bugging up panels

* preview style works in sql editor

* fix border

* removes preview tab if there is one

* fix background of loading skeleton

* lots of issues with types/icons/redirect

* new tab cards

* snippets in empty state now work

* moar stuff

* tabs now in feature flags

* Update tabs.ts

* Update tabs.ts

* moar

* add feature previews

* remove code not needed

* Update next-env.d.ts

* Delete FeaturePreviewModal.tsx

* fix typescript errors. remove more explorer stuff

* remove explorer files

* fixed issues with templates and quickstarts tab

* fixed active state when tabs are not opted in

* logic error

* fix open/highlight issue when opted out of tabs

* templates/quickstarts now displayed with new cards

* Update recent-items.tsx

* Update new-tab.tsx

* add icon back in

* add old empty state back in

* recent items updated to respect project ref

* localstorage cleanup on deletion

* moar

* overflow tabs now working

* correct tab names used for new sql templates/quickstarts

* ongoing queries fix

* cleanup

* update images

* Update RouteValidationWrapper.tsx

* Update AppLayout.tsx

* Update NavigationBar.tsx

* add headers back into side panels

* improve writing

* tabs now drag and drop a billion times better

* Update tabs.tsx

* Update tabs.tsx

* init issues on stores, which caused a race condition.

* fix hydration error

* fix new tab issue in sql

* Update ProjectLayout.tsx

* Update pnpm-lock.yaml

* Update new-tab.tsx

* move EditorMenuListSkeleton

* Fix type issues

* fixes: DESIGN-87

fixes: DESIGN-87

* refactor sort/filter components

* Update rules-set-button-text.tsx

* remove discussions for now

* small styling fixes

* Update FeaturePreviewModal.tsx

* Update FeaturePreviewModal.tsx

* Update RouteValidationWrapper.tsx

* revert

* revert

* revert

* revert

* revert

* more revert

* Update collapse-button.tsx

* Update SQLEditorTreeViewItem.tsx

* revert

* Update SchemaGraph.tsx

* Delete new-upcoming.tsx

* revert

* Update ProjectLayout.tsx

* fix home link

* Update table-editor.spec.ts

* test update

* Update table-editor.spec.ts

* Fix the playwright tests.

* layout fixes

* layout fix

* revert sort/filter

* Update LastSignInWrapper.tsx

* revert

* revert

* remove

* update file names

* revert

* revert

* revert

* Fix TreeView console error props

* Add guards in SQL Editor to ensure that feature preview tabs changes do not affect existing UI when flag is off

* Fix missing DefaultLayout in SQL editor templates + fix New tab

* Remove console log

* Remove DatabaseSelector for SQL editor on local

* Fix SQL editor shared favorites for local

* Fix test

* Ensure NewTab doesn't show up if flag is not toggled for SQL editor

* Decouple UI state changes from content-query and entity-types-infinite-query

* Fix tab closing unnecessary rerouting

* Beef up feature previews

* Fix create new table from table editor new tab

* Fix tabs getting incorrectly reset when going between table and SQL editors

* Fix last visited SQL snippet for both tabs and not tabs

* Fix last visited table for table editor tabs

* Clear dashboard history when closing last tab

* Fix loading dashboard history

* Add comment to refactor stores

* Ensure we only save up to 8 items for recent items for each type

* Remove unneccesary logic in tabs

* Smol style fix for DeleteAccountButton

* Smol fix

* Fix inability to close New tab

---------

Co-authored-by: Joshen Lim <joshenlimek@gmail.com>
Co-authored-by: Alaister Young <a@alaisteryoung.com>
Co-authored-by: Ivan Vasilov <vasilov.ivan@gmail.com>
2025-03-27 17:46:57 +08:00

304 lines
8.3 KiB
TypeScript

import type { Message as MessageType } from 'ai/react'
import { LOCAL_STORAGE_KEYS as COMMON_LOCAL_STORAGE_KEYS } from 'common'
import { SQL_TEMPLATES } from 'components/interfaces/SQLEditor/SQLEditor.queries'
import { SupportedAssistantEntities } from 'components/ui/AIAssistantPanel/AIAssistant.types'
import { LOCAL_STORAGE_KEYS } from 'lib/constants'
import { proxy, snapshot, subscribe, useSnapshot } from 'valtio'
export type CommonDatabaseEntity = {
id: number
name: string
schema: string
[key: string]: any
}
export type SuggestionsType = {
title: string
prompts?: string[]
}
export type Template = {
name: string
description: string
content: string
}
type AiAssistantPanelType = {
open: boolean
messages: MessageType[]
initialInput: string
sqlSnippets?: string[]
suggestions?: SuggestionsType
editor?: SupportedAssistantEntities | null
// Raw string content for the monaco editor, currently used to retain where the user left off when toggling off the panel
content?: string
// Mainly used for editing a database entity (e.g editing a function, RLS policy etc)
entity?: CommonDatabaseEntity
tables: { schema: string; name: string }[]
}
type EditorPanelType = {
open: boolean
initialValue?: string
label?: string
saveLabel?: string
onSave?: (value: string) => void
functionName?: string
templates?: Template[]
initialPrompt?: string
}
type DashboardHistoryType = {
sql?: string
editor?: string
}
const INITIAL_AI_ASSISTANT: AiAssistantPanelType = {
open: false,
messages: [],
sqlSnippets: undefined,
initialInput: '',
suggestions: undefined,
editor: null,
content: '',
entity: undefined,
tables: [],
}
const INITIAL_EDITOR_PANEL: EditorPanelType = {
open: false,
initialValue: '',
label: '',
saveLabel: '',
initialPrompt: '',
templates: SQL_TEMPLATES.filter((template) => template.type === 'template').map((template) => ({
name: template.title,
description: template.description,
content: template.sql,
})),
}
const EMPTY_DASHBOARD_HISTORY: DashboardHistoryType = {
sql: undefined,
editor: undefined,
}
const getInitialState = () => {
if (typeof window === 'undefined') {
return {
aiAssistantPanel: INITIAL_AI_ASSISTANT,
editorPanel: INITIAL_EDITOR_PANEL,
dashboardHistory: EMPTY_DASHBOARD_HISTORY,
activeDocsSection: ['introduction'],
docsLanguage: 'js',
showProjectApiDocs: false,
isOptedInTelemetry: false,
showEnableBranchingModal: false,
showFeaturePreviewModal: false,
selectedFeaturePreview: '',
showAiSettingsModal: false,
showGenerateSqlModal: false,
ongoingQueriesPanelOpen: false,
mobileMenuOpen: false,
showSidebar: true,
}
}
const stored = localStorage.getItem(LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE)
const storedEditor = localStorage.getItem(LOCAL_STORAGE_KEYS.EDITOR_PANEL_STATE)
const urlParams = new URLSearchParams(window.location.search)
const aiAssistantPanelOpenParam = urlParams.get('aiAssistantPanelOpen')
let parsedAiAssistant = INITIAL_AI_ASSISTANT
let parsedEditorPanel = INITIAL_EDITOR_PANEL
try {
if (stored) {
parsedAiAssistant = JSON.parse(stored, (key, value) => {
if (key === 'createdAt' && value) {
return new Date(value)
}
return value
})
}
if (storedEditor) {
parsedEditorPanel = JSON.parse(storedEditor)
}
} catch {
// Ignore parsing errors
}
return {
aiAssistantPanel: {
...parsedAiAssistant,
open:
aiAssistantPanelOpenParam !== null
? aiAssistantPanelOpenParam === 'true'
: parsedAiAssistant.open,
},
editorPanel: parsedEditorPanel,
dashboardHistory: EMPTY_DASHBOARD_HISTORY,
activeDocsSection: ['introduction'],
docsLanguage: 'js',
showProjectApiDocs: false,
isOptedInTelemetry: false,
showEnableBranchingModal: false,
showFeaturePreviewModal: false,
selectedFeaturePreview: '',
showAiSettingsModal: false,
showGenerateSqlModal: false,
ongoingQueriesPanelOpen: false,
mobileMenuOpen: false,
showSidebar: true,
}
}
export const appState = proxy({
...getInitialState(),
setDashboardHistory: (ref: string, key: 'sql' | 'editor', id: string | undefined) => {
if (appState.dashboardHistory[key] !== id) {
appState.dashboardHistory[key] = id
localStorage.setItem(
LOCAL_STORAGE_KEYS.DASHBOARD_HISTORY(ref),
JSON.stringify(appState.dashboardHistory)
)
}
},
activeDocsSection: ['introduction'],
docsLanguage: 'js' as 'js' | 'bash',
showProjectApiDocs: false,
setShowProjectApiDocs: (value: boolean) => {
appState.showProjectApiDocs = value
},
setActiveDocsSection: (value: string[]) => {
appState.activeDocsSection = value
},
setDocsLanguage: (value: 'js' | 'bash') => {
appState.docsLanguage = value
},
isOptedInTelemetry: false,
setIsOptedInTelemetry: (value: boolean | null) => {
appState.isOptedInTelemetry = value === null ? false : value
if (typeof window !== 'undefined' && value !== null) {
localStorage.setItem(COMMON_LOCAL_STORAGE_KEYS.TELEMETRY_CONSENT, value.toString())
}
},
showEnableBranchingModal: false,
setShowEnableBranchingModal: (value: boolean) => {
appState.showEnableBranchingModal = value
},
showFeaturePreviewModal: false,
setShowFeaturePreviewModal: (value: boolean) => {
appState.showFeaturePreviewModal = value
},
selectedFeaturePreview: '',
setSelectedFeaturePreview: (value: string) => {
appState.selectedFeaturePreview = value
},
showAiSettingsModal: false,
setShowAiSettingsModal: (value: boolean) => {
appState.showAiSettingsModal = value
},
showGenerateSqlModal: false,
setShowGenerateSqlModal: (value: boolean) => {
appState.showGenerateSqlModal = value
},
showSidebar: true,
setShowSidebar: (value: boolean) => {
appState.showSidebar = value
},
resetAiAssistantPanel: () => {
appState.aiAssistantPanel = {
...INITIAL_AI_ASSISTANT,
open: appState.aiAssistantPanel.open,
}
},
setAiAssistantPanel: (value: Partial<AiAssistantPanelType>) => {
// Close Editor panel if AI Assistant panel is being opened
if (value.open && appState.editorPanel.open) {
appState.editorPanel.open = false
}
const hasEntityChanged = value.entity?.id !== appState.aiAssistantPanel.entity?.id
appState.aiAssistantPanel = {
...appState.aiAssistantPanel,
content: hasEntityChanged ? '' : appState.aiAssistantPanel.content,
...value,
}
},
showOngoingQueriesPanelOpen: false,
setOnGoingQueriesPanelOpen: (value: boolean) => {
appState.ongoingQueriesPanelOpen = value
},
saveLatestMessage: (message: any) => {
appState.aiAssistantPanel = {
...appState.aiAssistantPanel,
messages: [...appState.aiAssistantPanel.messages, message],
}
},
setEditorPanel: (value: Partial<EditorPanelType>) => {
// Close AI Assistant panel if editor panel is being opened
if (value.open && appState.aiAssistantPanel.open) {
appState.aiAssistantPanel.open = false
}
// Reset templates to initial if initialValue is empty
if (value.initialValue === '') {
value.templates = INITIAL_EDITOR_PANEL.templates
}
if (!value.open) {
value.initialPrompt = INITIAL_EDITOR_PANEL.initialPrompt
}
appState.editorPanel = {
...appState.editorPanel,
...value,
}
},
mobileMenuOpen: false,
setMobileMenuOpen: (value: boolean) => {
appState.mobileMenuOpen = value
},
})
// Set up localStorage subscriptions
if (typeof window !== 'undefined') {
subscribe(appState, () => {
// Save AI assistant state with limited message history
const aiAssistantState = {
...appState.aiAssistantPanel,
// limit to 20 messages so as to not overflow the context window
messages: appState.aiAssistantPanel.messages?.slice(-20),
}
localStorage.setItem(LOCAL_STORAGE_KEYS.AI_ASSISTANT_STATE, JSON.stringify(aiAssistantState))
// Save editor panel state
localStorage.setItem(
LOCAL_STORAGE_KEYS.EDITOR_PANEL_STATE,
JSON.stringify(appState.editorPanel)
)
})
}
export const getAppStateSnapshot = () => snapshot(appState)
export const useAppStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>
useSnapshot(appState, options)