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