"use client" import * as React from "react" import { Plus, Trash2, Cog, X, ChevronDown, ChevronUp, GripVertical, Lock, AlertTriangle } from "lucide-react" import { Button } from "@/components/ui/button" import { Input } from "@/components/ui/input" import { Label } from "@/components/ui/label" import { Badge } from "@/components/ui/badge" import { Drawer, DrawerContent, DrawerDescription, DrawerFooter, DrawerHeader, DrawerTitle, } from "@/components/ui/drawer" import { AlertDialog, AlertDialogAction, AlertDialogCancel, AlertDialogContent, AlertDialogDescription, AlertDialogFooter, AlertDialogHeader, AlertDialogTitle, } from "@/components/ui/alert-dialog" import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select" import { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs" import { ScrollArea } from "@/components/ui/scroll-area" import { Textarea } from "@/components/ui/textarea" import { Collapsible, CollapsibleContent, CollapsibleTrigger } from "@/components/ui/collapsible" import { Checkbox } from "@/components/ui/checkbox" import { Switch } from "@/components/ui/switch" import type { ApiClient, AuthMethods, TableMetadata, ForeignKeyConfig } from "@/lib/api" import { authMethodLabel, getApiClientError, normalizeAuthMethods } from "@/lib/api" import { dataTypes, intPrecisions, DEFAULT_INT_PRECISION } from "@/lib/constants" import { appendPrecisionToFieldPayload, applyFieldTypeChange, normalizeFieldTypeForEditor, schemaFieldsNeedMigration, } from "@/lib/field-types" import { migrateSchemaFieldsIfNeeded } from "@/lib/schema-migration" import { OAuthEntityPanel } from "@/components/oauth/oauth-entity-panel" import { useToast } from "@/hooks/use-toast" import { useNavigate } from "react-router-dom" import { ROUTES } from "@/lib/routes" import { cn } from "@/lib/utils" import { formatConstraintDefaultForInput, normalizeConstraintsForFieldType } from "@/lib/schema-constraints" interface TableConfigDrawerProps { table: TableMetadata apiClient: ApiClient open: boolean onClose: () => void onTableUpdate: (table: TableMetadata) => void onTablesUpdate?: (tables: TableMetadata[]) => void tables?: TableMetadata[] // List of existing tables for foreign key entity selection } // The update structure for tables is a s follows /* { name: "", // can be different from existing one has_api: , addRule: "", getRule: "", listRule: "", updateRule: "", deleteRule: "", deletedFields: [], // List of column names to delete fields: [], array of fields, changes to particular fields will be effected, new fields will be created } */ function transformFieldsForEditor(fields: TableMetadata["schema"]["fields"] | undefined) { return ( fields?.map((col) => { const normalized = normalizeFieldTypeForEditor(col) return { ...col, type: normalized.type, precision: normalized.precision, old_name: col.name, // Flatten constraints for UI primaryKey: col.primary_key || false, minValue: col.constraints?.min_value || null, maxValue: col.constraints?.max_value || null, defaultValue: col.constraints?.default_value || null, validator: col.constraints?.validator || null, foreign_key: col.foreign_key, } }) || [] ) } function normalizeRuleMode(mode: string | undefined) { // Convert empty string to "admin" for UI (Select doesn't allow empty string values) return mode === "" || !mode ? "admin" : mode } // NOTE: We don't support changing of field names yet! export function TableConfigDrawer({ table, apiClient, open, onClose, onTableUpdate, onTablesUpdate, tables = [] }: TableConfigDrawerProps) { const [columns, setColumns] = React.useState([]) const [rules, setRules] = React.useState<{ list: { mode: string; expr: string } get: { mode: string; expr: string } add: { mode: string; expr: string } update: { mode: string; expr: string } delete: { mode: string; expr: string } }>({ list: { mode: "admin", expr: "" }, get: { mode: "admin", expr: "" }, add: { mode: "admin", expr: "" }, update: { mode: "admin", expr: "" }, delete: { mode: "admin", expr: "" }, }) const [isLoading, setIsLoading] = React.useState(false) const [activeTab, setActiveTab] = React.useState("schema") const [hasUnsavedChanges, setHasUnsavedChanges] = React.useState(false) const [expandedFields, setExpandedFields] = React.useState>(new Set()) const [deletedColumns, setDeletedColumns] = React.useState([]) // Track deleted field IDs const [deleteDialogOpen, setDeleteDialogOpen] = React.useState(false) const [isDeleting, setIsDeleting] = React.useState(false) const [authMethods, setAuthMethods] = React.useState(() => normalizeAuthMethods(table.schema.auth), ) const [savingAuthMethod, setSavingAuthMethod] = React.useState(null) const wasOpenRef = React.useRef(false) const { toast } = useToast() const navigate = useNavigate() const isAuthEntity = table.schema.type === "auth" // Get unique key for field (use id if exists, otherwise generate one) const getFieldKey = (field: any, index: number) => field.id || `temp-${index}` // Only hydrate drawer state when it opens. Parent table updates (auth toggles, // schema saves) must not reset the active tab or feel like a close/reopen. React.useEffect(() => { const justOpened = open && !wasOpenRef.current wasOpenRef.current = open if (!justOpened) { return } setColumns(transformFieldsForEditor(table.schema?.fields)) setRules({ list: { mode: normalizeRuleMode(table.schema.rules?.list?.mode), expr: table.schema.rules?.list?.expr || "", }, get: { mode: normalizeRuleMode(table.schema.rules?.get?.mode), expr: table.schema.rules?.get?.expr || "", }, add: { mode: normalizeRuleMode(table.schema.rules?.add?.mode), expr: table.schema.rules?.add?.expr || "", }, update: { mode: normalizeRuleMode(table.schema.rules?.update?.mode), expr: table.schema.rules?.update?.expr || "", }, delete: { mode: normalizeRuleMode(table.schema.rules?.delete?.mode), expr: table.schema.rules?.delete?.expr || "", }, }) setAuthMethods(normalizeAuthMethods(table.schema.auth)) setActiveTab("schema") setHasUnsavedChanges(false) setExpandedFields(new Set()) setDeletedColumns([]) void (async () => { try { const fresh = await apiClient.call(`/api/v1/schemas/${table.schema.name}`) if ((fresh as { error?: unknown[] })?.error?.length) { return } if (!schemaFieldsNeedMigration(fresh.schema?.fields ?? [])) { return } const migrated = await migrateSchemaFieldsIfNeeded(apiClient, fresh) if (migrated) { setColumns(transformFieldsForEditor(migrated.schema?.fields)) onTableUpdate(migrated) } else { setHasUnsavedChanges(true) } } catch (error) { console.error("Failed to migrate legacy field types:", error) setHasUnsavedChanges(true) } })() }, [open, table, apiClient, onTableUpdate]) const addColumn = () => { setColumns([...columns, { id: `field-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`, name: "", type: "string", precision: null, primary_key: false, primaryKey: false, // UI format required: true, system: false, unique: false, constraints: { default_value: null, max_value: null, min_value: null, validator: null, }, minValue: null, // UI format maxValue: null, // UI format defaultValue: null, // UI format validator: null, // UI format old_name: null }]) setHasUnsavedChanges(true) } // Remove existing column by ID const removeColumn = (index: number) => { const column = columns[index] const isSystemColumn = column.system if (!(columns.length > 1 && !isSystemColumn)) return // Ensure the field we are deleting existed/exists in the table already if (isAnExistingField(index)) { // Find the original field from the table schema to get its ID const originalField = table.schema.fields.find((f: any) => f.name === column.old_name || f.name === column.name) if (originalField?.id && !deletedColumns.includes(originalField.id)) { // Add the field ID to the delete array setDeletedColumns([...deletedColumns, originalField.id]); } } setColumns(columns.filter((_, i) => i !== index)) } const isAnExistingField = (index: number) => { const col_old_name = columns[index]?.old_name if (!col_old_name) return false; for (const f of table.schema.fields) { if (f.name === col_old_name) return true; } return false; } // Update existing column data const updateColumn = (index: number, field: string, value: any) => { const updatedColumns = columns.map((col, i) => { if (i !== index) { return col } if (field === "type") { const typeUpdate = applyFieldTypeChange(col.type, value, col.precision) return { ...col, type: typeUpdate.type, precision: typeUpdate.precision, } } return { ...col, [field]: value } }) setColumns(updatedColumns) setHasUnsavedChanges(true) } // Get fields for a selected entity (for foreign key field selector) const getEntityFields = (entityName: string): any[] => { const entity = tables.find(t => t.schema.name === entityName) return entity?.schema.fields || [] } const handleSaveSchema = async () => { setIsLoading(true) try { // Transform UI format (camelCase flat) to API format (with constraints and snake_case) const transformedFields: any[] = [] for (const col of columns) { const rawConstraints = { default_value: col.defaultValue !== undefined ? col.defaultValue : col.constraints?.default_value, min_value: col.minValue !== undefined ? col.minValue : col.constraints?.min_value, max_value: col.maxValue !== undefined ? col.maxValue : col.constraints?.max_value, validator: col.validator !== undefined ? col.validator : (col.constraints?.validator ?? null), } const normalized = normalizeConstraintsForFieldType(col.type, rawConstraints, col.precision) if (!normalized.ok) { toast({ variant: "destructive", title: "Invalid constraints", description: `${col.name || "Field"}: ${normalized.message}`, duration: 5000, }) setIsLoading(false) return } if (col.type === "int" && !col.precision) { toast({ variant: "destructive", title: "Invalid field", description: `${col.name || "Field"}: integer fields require a precision.`, duration: 5000, }) setIsLoading(false) return } const fieldData: any = { id: col.id, name: col.name, type: col.type, primary_key: col.primaryKey !== undefined ? col.primaryKey : col.primary_key, required: col.required, system: col.system || false, unique: col.unique || false, constraints: normalized.constraints, ...(col.old_name && { old_name: col.old_name }), } appendPrecisionToFieldPayload(fieldData, col) if (col.foreign_key && col.foreign_key.entity && col.foreign_key.field) { fieldData.foreign_key = col.foreign_key } transformedFields.push(fieldData) } // Add deleted fields to the fields array with op: "delete" const deletedFields = deletedColumns.map((fieldId: string) => ({ id: fieldId, op: "delete" })) // Combine regular fields and deleted fields in the fields array const allFields = [...transformedFields, ...deletedFields] const body = { fields: allFields }; console.log(body) // return const updatedTable = await apiClient.call(`/api/v1/schemas/${table.schema.name}`, { method: "PATCH", body: JSON.stringify(body), }) // If the request failed, throw the error here if ((updatedTable as any)?.error?.length > 0) throw (updatedTable as any).error onTableUpdate(updatedTable) setColumns(transformFieldsForEditor(updatedTable.schema?.fields)) setDeletedColumns([]) setHasUnsavedChanges(false) toast({ title: "Table Updated", description: "Table fields updated successfully.", duration: 3000, }) } catch (error) { console.error("Failed to update schema:", error) } finally { setIsLoading(false) } } // Update rule changes const handleSaveRules = async () => { setIsLoading(true) try { const updatedTable = await apiClient.call(`/api/v1/schemas/${table.schema.name}`, { method: "PATCH", body: JSON.stringify({ rules: { list: { mode: rules.list.mode === "admin" ? "" : (rules.list.mode || ""), expr: rules.list.expr || "", }, get: { mode: rules.get.mode === "admin" ? "" : (rules.get.mode || ""), expr: rules.get.expr || "", }, add: { mode: rules.add.mode === "admin" ? "" : (rules.add.mode || ""), expr: rules.add.expr || "", }, update: { mode: rules.update.mode === "admin" ? "" : (rules.update.mode || ""), expr: rules.update.expr || "", }, delete: { mode: rules.delete.mode === "admin" ? "" : (rules.delete.mode || ""), expr: rules.delete.expr || "", }, }, }), }) // If the request failed, throw the error here if ((updatedTable as any)?.error?.length > 0) throw (updatedTable as any).error onTableUpdate(updatedTable) toast({ title: "Table Updated", description: "Table access rules updated successfully!", duration: 3000, }) setHasUnsavedChanges(false) } catch (error) { console.error("Failed to update rules:", error) toast({ title: "Error", description: error instanceof Error ? error.message : "Failed to update access rules", variant: "destructive", duration: 5000, }) } finally { setIsLoading(false) } } // Helper to update a specific rule const updateRule = (ruleKey: keyof typeof rules, field: "mode" | "expr", value: string) => { setRules({ ...rules, [ruleKey]: { ...rules[ruleKey], [field]: value, }, }) setHasUnsavedChanges(true) } const handleAuthMethodToggle = async (method: keyof AuthMethods, enabled: boolean) => { const previous = authMethods setAuthMethods({ ...authMethods, [method]: enabled }) setSavingAuthMethod(method) try { const updatedTable = await apiClient.call(`/api/v1/schemas/${table.schema.name}`, { method: "PATCH", body: JSON.stringify({ auth: { [method]: enabled }, }), }) const apiError = getApiClientError(updatedTable) if (apiError) { throw new Error(apiError) } const nextMethods = normalizeAuthMethods(updatedTable.schema?.auth ?? { ...previous, [method]: enabled }) setAuthMethods(nextMethods) onTableUpdate({ ...updatedTable, schema: { ...updatedTable.schema, auth: nextMethods, }, }) toast({ title: enabled ? "Setting Enabled" : "Setting Disabled", description: `${authMethodLabel(method)} ${enabled ? "enabled" : "disabled"} for ${table.schema.name}.`, duration: 3000, }) } catch (error) { console.error("Failed to update auth methods:", error) setAuthMethods(previous) toast({ title: "Error", description: error instanceof Error ? error.message : "Failed to update auth methods", variant: "destructive", duration: 5000, }) } finally { setSavingAuthMethod(null) } } const isSystemColumn = (column: any) => { return column.system } const handleClose = () => { if (hasUnsavedChanges) { if (confirm("You have unsaved changes. Are you sure you want to close?")) { setHasUnsavedChanges(false) setDeletedColumns([]) onClose() } } else { onClose() } } const handleDeleteSchema = async () => { setIsDeleting(true) try { const res: any = await apiClient.call(`/api/v1/schemas/${table.schema.name}`, { method: "DELETE", }) if (res?.error?.length > 0) throw res.error // Fetch updated tables list if (onTablesUpdate) { const response: any = await apiClient.call("/api/v1/schemas") if (response?.error?.length > 0) throw response.error let updatedTables: TableMetadata[] = [] if (Array.isArray(response)) { updatedTables = response } else if (response?.data && Array.isArray(response.data)) { updatedTables = response.data } onTablesUpdate(updatedTables) } toast({ title: "Entity Deleted", description: `The entity '${table.schema.name}' has been deleted successfully.`, duration: 3000, }) // Navigate to entities list or another entity navigate(ROUTES.entities) onClose() } catch (error: any) { toast({ variant: "destructive", title: "Error", description: error?.message || "Failed to delete entity", duration: 5000, }) } finally { setIsDeleting(false) setDeleteDialogOpen(false) } } const toggleFieldExpanded = (fieldKey: string) => { setExpandedFields((prev) => { const next = new Set(prev) if (next.has(fieldKey)) { next.delete(fieldKey) } else { next.add(fieldKey) } return next }) } return (
Configure {table.schema.name} Table
{isAuthEntity ? "Manage fields, login methods, OAuth providers, and access rules" : "Manage entity fields and access control rules"}
Fields {isAuthEntity && Auth} Access Rules

Define the fields for your entity

{table.schema.type === "view" ? (
SQL Query
                          {table.schema?.sql}
                        
) : (
{columns.map((column, index) => { const fieldKey = getFieldKey(column, index) const isSystem = isSystemColumn(column) return (
{/* Field Header - Name and Type */}
{isSystem && ( )}
updateColumn(index, "name", e.target.value)} disabled={isSystem} className={isSystem ? "bg-muted" : ""} />
{column.type === "int" && ( )}
{!isSystem && ( )} {isSystem && ( System )}
{/* Collapsible Advanced Options */} {!isSystem && ( toggleFieldExpanded(fieldKey)}>
updateColumn(index, "primaryKey", checked as boolean)} />
updateColumn(index, "unique", checked as boolean)} />
updateColumn(index, "required", checked as boolean)} />
updateColumn(index, "minValue", e.target.value ? Number.parseFloat(e.target.value) : null) } className="h-8 text-xs" />
updateColumn(index, "maxValue", e.target.value ? Number.parseFloat(e.target.value) : null) } className="h-8 text-xs" />
updateColumn(index, "defaultValue", e.target.value)} className="h-8 text-xs" />
updateColumn(index, "validator", e.target.value || null)} className="h-8 text-xs" />
{/* Foreign Key Configuration */}
)}
) })} {/* Add Field Button */}
)} {table.schema.type !== "view" && (
System System columns are automatically managed and cannot be modified.
Table Type Once a table is created, we dont support changing table field types.
)}
{isAuthEntity && (

Control which sign-in options are available for this auth entity. Changes save immediately and only affect new logins.

Email/identity and password via /login

handleAuthMethodToggle("password", checked)} aria-label="Enable password login" />

Send a 6-digit code to the user's email. Requires SMTP in application settings.

handleAuthMethodToggle("otp", checked)} aria-label="Enable email sign-in codes" />

Third-party providers. After enabling, configure and enable providers below.

handleAuthMethodToggle("oauth", checked)} aria-label="Enable OAuth login" />

Require users to verify their email before a new login. Existing sessions keep working.

When on, password, OTP, and OAuth logins return{" "} 403 until{" "} email_verified is true. Needs SMTP and Site Domain for verification emails.

handleAuthMethodToggle("requireEmailVerification", checked)} aria-label="Require email verification before login" />
{(authMethods.otp || authMethods.requireEmailVerification) && (
{authMethods.otp && (

OTP requires SMTP (host and{" "} from) under Settings.

)} {authMethods.requireEmailVerification && (

Verification emails also need Site Domain set under Settings (General).

)}
)} {authMethods.oauth ? (
) : (
Enable OAuth above to register providers and turn them on for this entity.
)}
)}

Access Control Rules

Configure who can access and modify records in this entity

{/* List Rule */}

Controls who can list all records

{rules.list.mode === "custom" && (