editor-panel-state.tsx 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. import { safeSql, type DisplayableSqlFragment } from '@supabase/pg-meta'
  2. import { proxy, snapshot, useSnapshot } from 'valtio'
  3. type Template = {
  4. name: string
  5. description: string
  6. content: string
  7. }
  8. export type SqlError = {
  9. error?: string
  10. formattedError?: string
  11. message?: string
  12. }
  13. type EditorPanelState = {
  14. value: DisplayableSqlFragment
  15. templates: Template[]
  16. results: Record<string, unknown>[] | undefined
  17. error: SqlError | undefined
  18. initialPrompt: string
  19. onChange: ((value: DisplayableSqlFragment) => void) | undefined
  20. activeSnippetId: string | null
  21. pendingReset: boolean
  22. }
  23. const initialState: EditorPanelState = {
  24. value: safeSql``,
  25. templates: [],
  26. results: undefined,
  27. error: undefined,
  28. initialPrompt: '',
  29. onChange: undefined,
  30. activeSnippetId: null,
  31. pendingReset: false,
  32. }
  33. export const editorPanelState = proxy({
  34. ...initialState,
  35. setValue(value: DisplayableSqlFragment) {
  36. editorPanelState.value = value
  37. editorPanelState.onChange?.(value)
  38. editorPanelState.setResults(undefined)
  39. editorPanelState.setError(undefined)
  40. },
  41. setTemplates(templates: Template[]) {
  42. editorPanelState.templates = templates
  43. },
  44. setResults(results: Record<string, unknown>[] | undefined) {
  45. editorPanelState.results = results
  46. },
  47. setError(error: SqlError | undefined) {
  48. editorPanelState.error = error
  49. },
  50. setInitialPrompt(initialPrompt: string) {
  51. editorPanelState.initialPrompt = initialPrompt
  52. },
  53. setActiveSnippetId(id: string | null) {
  54. editorPanelState.activeSnippetId = id
  55. },
  56. openAsNew() {
  57. editorPanelState.value = safeSql``
  58. editorPanelState.results = undefined
  59. editorPanelState.error = undefined
  60. editorPanelState.pendingReset = true
  61. },
  62. reset() {
  63. Object.assign(editorPanelState, initialState)
  64. },
  65. })
  66. export const getEditorPanelStateSnapshot = () => snapshot(editorPanelState)
  67. export const useEditorPanelStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) =>
  68. useSnapshot(editorPanelState, options)