Files
supabase/apps/studio/components/interfaces/SQLEditor/useSnippetIdentity.ts
Charis cdc843dadd refactor(sql-editor): extract deriveSnippetIdentity, debug/completion/diff-key helpers (#48014)
## Summary
Pure-fn extraction pass across the SQL editor hooks.

- Extracts `deriveSnippetIdentity` out of `useSnippetIdentity`'s inline
id + `isLoading` derivation into `SQLEditor.utils.ts`.
- Extracts `extractDebugContext` (shared snippet/result/error
extraction) and `buildDebugChatArgs` (the `aiSnap.newChat(...)` payload
builder) out of `useSqlEditorAi`'s `buildDebugPrompt`/`onDebug` into
`SQLEditor.utils.ts`.
- Extracts `buildCompletionRequestBody` (the AI completion endpoint's
request body builder) and `planDiffRequestApplication` (the
pending-diff-request application decision: replace vs. open a diff,
depending on whether the editor is currently empty) out of
`useSqlEditorAi` into `SQLEditor.utils.ts`. The `drainDiffRequest`
effect now just applies the plan instead of branching inline.
- Extracts `resolveDiffKeyAction` out of `useSqlEditorShortcuts`'s
window-keydown Enter/Escape branch into `SQLEditor.utils.ts`.

## Test plan
- [x] `pnpm --filter studio typecheck`
- [x] `pnpm test:studio -- SQLEditor` (265 tests passing)
- [x] `pnpm --filter studio run lint:ratchet`
2026-07-21 13:47:40 -04:00

35 lines
1.3 KiB
TypeScript

import { useParams } from 'common'
import { useMemo } from 'react'
import { generateSnippetTitle } from './SQLEditor.constants'
import { deriveSnippetIdentity } from './SQLEditor.utils'
import { generateUuid } from '@/lib/api/snippets.browser'
import { useSqlEditorV2StateSnapshot } from '@/state/sql-editor/sql-editor-state'
/**
* Derives the stable snippet id + display name for the editor from the URL.
*
* For `/sql/new` (or no id) a fresh name + uuid are generated; otherwise the URL
* id is used. `isLoading` is true while an existing snippet's content is still
* being fetched.
*/
export function useSnippetIdentity() {
const { id: urlId } = useParams()
const snapV2 = useSqlEditorV2StateSnapshot()
// generate a new snippet title and an id to be used for new snippets. The dependency on urlId is to avoid a bug which
// shows up when clicking on the SQL Editor while being in the SQL editor on a random snippet.
const [generatedNewSnippetName, generatedId] = useMemo(() => {
const name = generateSnippetTitle()
return [name, generateUuid([`${name}.sql`])]
}, [urlId])
const { id, isLoading } = deriveSnippetIdentity({
urlId,
generatedId,
snippets: snapV2.snippets,
})
return { id, urlId, generatedNewSnippetName, isLoading }
}