table-editor.tsx 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381
  1. import * as Sentry from '@sentry/nextjs'
  2. import type { PGColumn } from '@supabase/pg-meta'
  3. import { useConstant } from 'common'
  4. import { createContext, PropsWithChildren, useContext } from 'react'
  5. import { proxy, useSnapshot } from 'valtio'
  6. import {
  7. NewQueuedOperation,
  8. QueuedOperationType,
  9. type OperationQueueState,
  10. type QueueStatus,
  11. } from './table-editor-operation-queue.types'
  12. import type { SupaRow } from '@/components/grid/types'
  13. import {
  14. resolveDeleteRowConflicts,
  15. resolveEditCellConflicts,
  16. upsertOperation,
  17. } from '@/components/grid/utils/queueConflictResolution'
  18. import { generateTableChangeKey } from '@/components/grid/utils/queueOperationUtils'
  19. import { ForeignKey } from '@/components/interfaces/TableGridEditor/SidePanelEditor/ForeignKeySelector/ForeignKeySelector.types'
  20. import type { EditValue } from '@/components/interfaces/TableGridEditor/SidePanelEditor/RowEditor/RowEditor.types'
  21. import type { TableField } from '@/components/interfaces/TableGridEditor/SidePanelEditor/TableEditor/TableEditor.types'
  22. import type { SafePostgresColumn } from '@/lib/postgres-types'
  23. import type { Dictionary } from '@/types'
  24. export const TABLE_EDITOR_DEFAULT_ROWS_PER_PAGE = 100
  25. type ForeignKeyState = {
  26. foreignKey: ForeignKey
  27. row: Dictionary<any>
  28. column: PGColumn
  29. }
  30. export type SidePanel =
  31. | { type: 'cell'; value?: { column: string; row: Dictionary<any> } }
  32. | { type: 'row'; row?: Dictionary<any> }
  33. | { type: 'column'; column?: SafePostgresColumn }
  34. | { type: 'table'; mode: 'new' | 'edit' | 'duplicate'; templateData?: Partial<TableField> }
  35. | { type: 'schema'; mode: 'new' | 'edit' }
  36. | { type: 'json'; jsonValue: EditValue }
  37. | {
  38. type: 'foreign-row-selector'
  39. foreignKey: ForeignKeyState
  40. }
  41. | { type: 'csv-import'; file?: File }
  42. | { type: 'operation-queue' }
  43. export type ConfirmationDialog =
  44. | { type: 'table'; isDeleteWithCascade: boolean }
  45. | { type: 'column'; column: SafePostgresColumn; isDeleteWithCascade: boolean }
  46. // [Joshen] Just FYI callback, numRows, allRowsSelected is a temp workaround so that
  47. // DeleteConfirmationDialog can trigger dispatch methods after the successful deletion of rows.
  48. // Once we deprecate react tracked and move things to valtio, we can remove this.
  49. | {
  50. type: 'row'
  51. rows: SupaRow[]
  52. numRows?: number
  53. allRowsSelected?: boolean
  54. callback?: () => void
  55. }
  56. export type UIState =
  57. | {
  58. open: 'none'
  59. }
  60. | {
  61. open: 'side-panel'
  62. sidePanel: SidePanel
  63. }
  64. | {
  65. open: 'confirmation-dialog'
  66. confirmationDialog: ConfirmationDialog
  67. }
  68. /**
  69. * Global table editor state for the table editor across multiple tables.
  70. * See ./table-editor-table.tsx for table specific state.
  71. */
  72. export const createTableEditorState = () => {
  73. const state = proxy({
  74. rowsPerPage: TABLE_EDITOR_DEFAULT_ROWS_PER_PAGE,
  75. setRowsPerPage: (rowsPerPage: number) => {
  76. state.rowsPerPage = rowsPerPage
  77. },
  78. ui: { open: 'none' } as UIState,
  79. get sidePanel() {
  80. return state.ui.open === 'side-panel' ? state.ui.sidePanel : undefined
  81. },
  82. get confirmationDialog() {
  83. return state.ui.open === 'confirmation-dialog' ? state.ui.confirmationDialog : undefined
  84. },
  85. closeSidePanel: () => {
  86. state.ui = { open: 'none' }
  87. },
  88. closeConfirmationDialog: () => {
  89. state.ui = { open: 'none' }
  90. },
  91. onAddSchema: () => {
  92. state.ui = {
  93. open: 'side-panel',
  94. sidePanel: { type: 'schema', mode: 'new' },
  95. }
  96. },
  97. /* Tables */
  98. onAddTable: (templateData?: Partial<TableField>) => {
  99. // Record that the table creator was opened
  100. Sentry.startSpan({ name: 'table_creator.opened', op: 'ui.action' }, (span) => {
  101. span.setAttribute('table_creator.opened', 1)
  102. })
  103. state.ui = {
  104. open: 'side-panel',
  105. sidePanel: { type: 'table', mode: 'new', templateData },
  106. }
  107. },
  108. onEditTable: () => {
  109. state.ui = {
  110. open: 'side-panel',
  111. sidePanel: { type: 'table', mode: 'edit' },
  112. }
  113. },
  114. onDuplicateTable: () => {
  115. state.ui = {
  116. open: 'side-panel',
  117. sidePanel: { type: 'table', mode: 'duplicate' },
  118. }
  119. },
  120. onDeleteTable: () => {
  121. state.ui = {
  122. open: 'confirmation-dialog',
  123. confirmationDialog: { type: 'table', isDeleteWithCascade: false },
  124. }
  125. },
  126. /* Columns */
  127. onAddColumn: () => {
  128. state.ui = {
  129. open: 'side-panel',
  130. sidePanel: { type: 'column' },
  131. }
  132. },
  133. onEditColumn: (column: SafePostgresColumn) => {
  134. state.ui = {
  135. open: 'side-panel',
  136. sidePanel: { type: 'column', column },
  137. }
  138. },
  139. onDeleteColumn: (column: SafePostgresColumn) => {
  140. state.ui = {
  141. open: 'confirmation-dialog',
  142. confirmationDialog: { type: 'column', column, isDeleteWithCascade: false },
  143. }
  144. },
  145. /* Rows */
  146. onAddRow: () => {
  147. state.ui = {
  148. open: 'side-panel',
  149. sidePanel: { type: 'row' },
  150. }
  151. },
  152. onEditRow: (row: Dictionary<any>) => {
  153. state.ui = {
  154. open: 'side-panel',
  155. sidePanel: { type: 'row', row },
  156. }
  157. },
  158. onDeleteRows: (
  159. rows: SupaRow[],
  160. meta: { numRows?: number; allRowsSelected: boolean; callback?: () => void } = {
  161. numRows: 0,
  162. allRowsSelected: false,
  163. callback: () => {},
  164. }
  165. ) => {
  166. const { numRows, allRowsSelected, callback } = meta
  167. state.ui = {
  168. open: 'confirmation-dialog',
  169. confirmationDialog: { type: 'row', rows, numRows, allRowsSelected, callback },
  170. }
  171. },
  172. /* Misc */
  173. onExpandJSONEditor: (jsonValue: EditValue) => {
  174. state.ui = {
  175. open: 'side-panel',
  176. sidePanel: { type: 'json', jsonValue },
  177. }
  178. },
  179. onExpandTextEditor: (column: string, row: Dictionary<any>) => {
  180. state.ui = {
  181. open: 'side-panel',
  182. sidePanel: { type: 'cell', value: { column, row } },
  183. }
  184. },
  185. onEditForeignKeyColumnValue: (foreignKey: ForeignKeyState) => {
  186. state.ui = {
  187. open: 'side-panel',
  188. sidePanel: { type: 'foreign-row-selector', foreignKey },
  189. }
  190. },
  191. onImportData: (file?: File) => {
  192. state.ui = {
  193. open: 'side-panel',
  194. sidePanel: { type: 'csv-import', file },
  195. }
  196. },
  197. toggleViewOperationQueue: () => {
  198. if (state.ui.open === 'side-panel' && state.ui.sidePanel.type === 'operation-queue') {
  199. state.closeSidePanel()
  200. } else {
  201. state.ui = {
  202. open: 'side-panel',
  203. sidePanel: { type: 'operation-queue' },
  204. }
  205. }
  206. },
  207. /* Utils */
  208. toggleConfirmationIsWithCascade: (overrideIsDeleteWithCascade?: boolean) => {
  209. if (
  210. state.ui.open === 'confirmation-dialog' &&
  211. (state.ui.confirmationDialog.type === 'column' ||
  212. state.ui.confirmationDialog.type === 'table')
  213. ) {
  214. state.ui.confirmationDialog.isDeleteWithCascade =
  215. overrideIsDeleteWithCascade ?? !state.ui.confirmationDialog.isDeleteWithCascade
  216. }
  217. },
  218. // ========================================================================
  219. // Operation Queue
  220. // ========================================================================
  221. operationQueue: {
  222. operations: [],
  223. status: 'idle',
  224. } as OperationQueueState,
  225. /**
  226. * Queue a new operation for later processing.
  227. * If an operation with the same key already exists, it will be overwritten.
  228. * Handles conflict resolution:
  229. * - DELETE_ROW on a row: remove any pending EDIT_CELL ops for that row
  230. * - EDIT_CELL on a row pending deletion: reject (console.warn)
  231. * - EDIT_CELL on a newly added row: merge edit into ADD_ROW's rowData
  232. * - DELETE_ROW on a newly added row: cancel both operations
  233. */
  234. queueOperation: (operation: NewQueuedOperation) => {
  235. const updateQueueStatus = () => {
  236. if (state.operationQueue.operations.length === 0) {
  237. state.operationQueue.status = 'idle'
  238. } else if (state.operationQueue.status === 'idle') {
  239. state.operationQueue.status = 'pending'
  240. }
  241. }
  242. // Handle DELETE_ROW conflicts
  243. if (operation.type === QueuedOperationType.DELETE_ROW) {
  244. const result = resolveDeleteRowConflicts(state.operationQueue.operations, operation)
  245. state.operationQueue.operations = result.filteredOperations
  246. if (result.action === 'skip') {
  247. updateQueueStatus()
  248. return
  249. }
  250. }
  251. // Handle EDIT_CELL_CONTENT conflicts
  252. if (operation.type === QueuedOperationType.EDIT_CELL_CONTENT) {
  253. const result = resolveEditCellConflicts(state.operationQueue.operations, operation)
  254. if (result.action === 'reject') {
  255. console.warn(result.reason)
  256. return
  257. }
  258. if (result.action === 'merge') {
  259. state.operationQueue.operations = result.updatedOperations
  260. updateQueueStatus()
  261. return
  262. }
  263. }
  264. // Normal upsert
  265. const { operations } = upsertOperation(state.operationQueue.operations, operation)
  266. state.operationQueue.operations = operations
  267. updateQueueStatus()
  268. },
  269. /**
  270. * Clear all operations from the queue
  271. */
  272. clearQueue: () => {
  273. state.operationQueue.operations = []
  274. state.operationQueue.status = 'idle'
  275. },
  276. /**
  277. * Remove a specific operation from the queue
  278. */
  279. removeOperation: (operationId: string) => {
  280. state.operationQueue.operations = state.operationQueue.operations.filter(
  281. (op) => op.id !== operationId
  282. )
  283. if (state.operationQueue.operations.length === 0) {
  284. state.operationQueue.status = 'idle'
  285. }
  286. },
  287. /**
  288. * Undo the latest operation from the queue
  289. */
  290. undoLatestOperation: () => {
  291. state.operationQueue.operations = state.operationQueue.operations.slice(0, -1)
  292. if (state.operationQueue.operations.length === 0) {
  293. state.operationQueue.status = 'idle'
  294. }
  295. },
  296. /**
  297. * Update the queue status
  298. */
  299. setQueueStatus: (status: QueueStatus) => {
  300. state.operationQueue.status = status
  301. },
  302. /**
  303. * Check if there are any pending operations in the queue
  304. */
  305. get hasPendingOperations(): boolean {
  306. return state.operationQueue.operations.length > 0
  307. },
  308. hasPendingCellChange: (
  309. tableId: number,
  310. rowIdentifiers: Dictionary<unknown>,
  311. columnName: string
  312. ): boolean => {
  313. const key = generateTableChangeKey({
  314. type: QueuedOperationType.EDIT_CELL_CONTENT,
  315. tableId,
  316. payload: {
  317. columnName,
  318. rowIdentifiers,
  319. },
  320. })
  321. return state.operationQueue.operations.some((op) => op.id === key)
  322. },
  323. /**
  324. * Toggle the preflight check behaviour for each table
  325. */
  326. tablesToIgnorePreflightCheck: [] as number[],
  327. setTableToIgnorePreflightCheck: (id: number) => {
  328. const set = new Set<number>(state.tablesToIgnorePreflightCheck)
  329. set.add(id)
  330. state.tablesToIgnorePreflightCheck = [...set]
  331. },
  332. })
  333. return state
  334. }
  335. export type TableEditorState = ReturnType<typeof createTableEditorState>
  336. export const TableEditorStateContext = createContext<TableEditorState>(createTableEditorState())
  337. export const TableEditorStateContextProvider = ({ children }: PropsWithChildren<{}>) => {
  338. const state = useConstant(createTableEditorState)
  339. return (
  340. <TableEditorStateContext.Provider value={state}>{children}</TableEditorStateContext.Provider>
  341. )
  342. }
  343. export const useTableEditorStateSnapshot = (options?: Parameters<typeof useSnapshot>[1]) => {
  344. const state = useContext(TableEditorStateContext)
  345. return useSnapshot(state, options)
  346. }