@nestledjs/data-browser 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (35) hide show
  1. package/.babelrc +12 -0
  2. package/LICENSE +21 -0
  3. package/README.md +320 -0
  4. package/eslint.config.mjs +12 -0
  5. package/package.json +44 -0
  6. package/project.json +39 -0
  7. package/src/index.ts +28 -0
  8. package/src/lib/admin-data.spec.tsx +10 -0
  9. package/src/lib/admin-data.tsx +9 -0
  10. package/src/lib/components/filters/DateRangeFilter.tsx +88 -0
  11. package/src/lib/components/filters/NumberRangeFilter.tsx +111 -0
  12. package/src/lib/components/filters/RelationComponents.tsx +176 -0
  13. package/src/lib/components/filters/RelationFilterField.tsx +106 -0
  14. package/src/lib/components/filters/index.ts +5 -0
  15. package/src/lib/components/index.ts +2 -0
  16. package/src/lib/components/shared/AdminBreadcrumbs.tsx +88 -0
  17. package/src/lib/components/shared/AdminErrorStates.tsx +180 -0
  18. package/src/lib/components/shared/AdminStatusDisplay.tsx +292 -0
  19. package/src/lib/components/shared/index.ts +3 -0
  20. package/src/lib/context/AdminDataContext.tsx +74 -0
  21. package/src/lib/hooks/useAdminList.ts +42 -0
  22. package/src/lib/hooks/useClickOutside.ts +21 -0
  23. package/src/lib/hooks/useDebounce.ts +16 -0
  24. package/src/lib/hooks/useRelationData.ts +114 -0
  25. package/src/lib/layouts/AdminDataLayout.tsx +251 -0
  26. package/src/lib/pages/AdminDataCreatePage.tsx +415 -0
  27. package/src/lib/pages/AdminDataEditPage.tsx +777 -0
  28. package/src/lib/pages/AdminDataIndexPage.tsx +50 -0
  29. package/src/lib/pages/AdminDataListPage.tsx +921 -0
  30. package/src/lib/types/index.ts +51 -0
  31. package/src/lib/utils/graphql-utils.ts +538 -0
  32. package/src/lib/utils/secure-storage.ts +305 -0
  33. package/src/lib/utils/string-utils.ts +53 -0
  34. package/tsconfig.json +17 -0
  35. package/tsconfig.lib.json +20 -0
@@ -0,0 +1,251 @@
1
+ import { getPluralName } from '@nestledjs/helpers'
2
+ import { Outlet, useNavigate, useParams } from 'react-router'
3
+ import { useMemo, useState, useRef } from 'react'
4
+ import { AdminLocalStorage } from '../utils/secure-storage'
5
+ import { kebabCase, spacedWords } from '../utils/string-utils'
6
+ import { useAdminDataContext } from '../context/AdminDataContext'
7
+
8
+ /**
9
+ * Main layout component for admin data browser
10
+ * Provides model selector, fullscreen toggle, and preferences import/export
11
+ */
12
+ export function AdminDataLayout() {
13
+ const navigate = useNavigate()
14
+ const params = useParams()
15
+ const { databaseModels, basePath = '/admin/data' } = useAdminDataContext()
16
+
17
+ const [isFullscreen, setIsFullscreen] = useState(false)
18
+ const [notification, setNotification] = useState<{ type: 'success' | 'error'; message: string } | null>(null)
19
+ const fileInputRef = useRef<HTMLInputElement>(null)
20
+
21
+ // Sort models alphabetically by plural display name
22
+ const sortedModels = useMemo(
23
+ () =>
24
+ [...databaseModels].sort((a, b) =>
25
+ getPluralName(spacedWords(a.name)).localeCompare(getPluralName(spacedWords(b.name))),
26
+ ),
27
+ [databaseModels],
28
+ )
29
+
30
+ // Find the current model based on route params
31
+ const currentModel = useMemo(() => {
32
+ const pluralParam = params.dataTypePlural
33
+ if (!pluralParam) return null
34
+
35
+ return sortedModels.find(m => {
36
+ const modelUrlName = kebabCase(getPluralName(m.name))
37
+ return modelUrlName.toLowerCase() === pluralParam.toLowerCase()
38
+ })
39
+ }, [params.dataTypePlural, sortedModels])
40
+
41
+ // Handle model selection
42
+ const handleModelChange = (event: React.ChangeEvent<HTMLSelectElement>) => {
43
+ const selectedModelName = event.target.value
44
+ if (selectedModelName) {
45
+ const selectedModel = sortedModels.find(m => m.name === selectedModelName)
46
+ if (selectedModel) {
47
+ navigate(`${basePath}/${kebabCase(getPluralName(selectedModel.name))}`)
48
+ }
49
+ }
50
+ }
51
+
52
+ const toggleFullscreen = () => {
53
+ setIsFullscreen(!isFullscreen)
54
+ }
55
+
56
+ // Show notification with auto-dismiss
57
+ const showNotification = (type: 'success' | 'error', message: string) => {
58
+ setNotification({ type, message })
59
+ setTimeout(() => setNotification(null), 5000)
60
+ }
61
+
62
+ // Export preferences
63
+ const handleExport = () => {
64
+ const configJson = AdminLocalStorage.exportConfig()
65
+ if (!configJson) {
66
+ showNotification('error', 'Failed to export preferences')
67
+ return
68
+ }
69
+
70
+ // Create download
71
+ const blob = new Blob([configJson], { type: 'application/json' })
72
+ const url = URL.createObjectURL(blob)
73
+ const link = document.createElement('a')
74
+ link.href = url
75
+ link.download = `admin-data-preferences-${new Date().toISOString().split('T')[0]}.json`
76
+ document.body.appendChild(link)
77
+ link.click()
78
+ document.body.removeChild(link)
79
+ URL.revokeObjectURL(url)
80
+
81
+ showNotification('success', 'Preferences exported successfully')
82
+ }
83
+
84
+ // Import preferences
85
+ const handleImport = (event: React.ChangeEvent<HTMLInputElement>) => {
86
+ const file = event.target.files?.[0]
87
+ if (!file) return
88
+
89
+ const reader = new FileReader()
90
+ reader.onload = (e) => {
91
+ const content = e.target?.result as string
92
+ if (!content) {
93
+ showNotification('error', 'Failed to read file')
94
+ return
95
+ }
96
+
97
+ const success = AdminLocalStorage.importConfig(content)
98
+ if (success) {
99
+ showNotification('success', 'Preferences imported successfully. Refreshing...')
100
+ // Refresh the page to apply new preferences
101
+ setTimeout(() => window.location.reload(), 1500)
102
+ } else {
103
+ showNotification('error', 'Invalid preferences file')
104
+ }
105
+ }
106
+ reader.onerror = () => {
107
+ showNotification('error', 'Failed to read file')
108
+ }
109
+ reader.readAsText(file)
110
+
111
+ // Reset file input
112
+ if (fileInputRef.current) {
113
+ fileInputRef.current.value = ''
114
+ }
115
+ }
116
+
117
+ const triggerImport = () => {
118
+ fileInputRef.current?.click()
119
+ }
120
+
121
+ const content = (
122
+ <div className="max-w-full mx-auto h-full flex flex-col">
123
+ {/* Notification Toast */}
124
+ {notification && (
125
+ <div className={`mb-4 px-4 py-3 rounded-md border ${
126
+ notification.type === 'success'
127
+ ? 'bg-green-50 border-green-200 text-green-800 dark:bg-green-900/20 dark:border-green-800 dark:text-green-200'
128
+ : 'bg-red-50 border-red-200 text-red-800 dark:bg-red-900/20 dark:border-red-800 dark:text-red-200'
129
+ }`}>
130
+ <div className="flex items-center">
131
+ {notification.type === 'success' ? (
132
+ <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
133
+ <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.707-9.293a1 1 0 00-1.414-1.414L9 10.586 7.707 9.293a1 1 0 00-1.414 1.414l2 2a1 1 0 001.414 0l4-4z" clipRule="evenodd" />
134
+ </svg>
135
+ ) : (
136
+ <svg className="w-5 h-5 mr-2" fill="currentColor" viewBox="0 0 20 20">
137
+ <path fillRule="evenodd" d="M10 18a8 8 0 100-16 8 8 0 000 16zM8.707 7.293a1 1 0 00-1.414 1.414L8.586 10l-1.293 1.293a1 1 0 101.414 1.414L10 11.414l1.293 1.293a1 1 0 001.414-1.414L11.414 10l1.293-1.293a1 1 0 00-1.414-1.414L10 8.586 8.707 7.293z" clipRule="evenodd" />
138
+ </svg>
139
+ )}
140
+ <span className="text-sm font-medium">{notification.message}</span>
141
+ </div>
142
+ </div>
143
+ )}
144
+
145
+ {/* Model Selector and Controls */}
146
+ <div className="mb-6 space-y-3">
147
+ <div className="flex items-end gap-3">
148
+ <div className="flex-1">
149
+ <label htmlFor="model-selector" className="block text-sm font-medium text-gray-900 dark:text-gray-100 mb-2">
150
+ Select Model
151
+ </label>
152
+ <div className="relative">
153
+ <select
154
+ id="model-selector"
155
+ value={currentModel?.name || ''}
156
+ onChange={handleModelChange}
157
+ className="w-full h-[50px] pl-4 pr-10 py-3 bg-white dark:bg-gray-800 text-gray-900 dark:text-gray-100 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm focus:outline-none focus:ring-2 focus:ring-green-web focus:border-green-web text-base appearance-none cursor-pointer"
158
+ >
159
+ <option value="">Choose a model...</option>
160
+ {sortedModels.map(model => (
161
+ <option key={model.name} value={model.name}>
162
+ {getPluralName(spacedWords(model.name))}
163
+ </option>
164
+ ))}
165
+ </select>
166
+ {/* Custom chevron icon */}
167
+ <div className="pointer-events-none absolute inset-y-0 right-0 flex items-center pr-3">
168
+ <svg className="h-5 w-5 text-gray-400" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor">
169
+ <path fillRule="evenodd" d="M5.293 7.293a1 1 0 011.414 0L10 10.586l3.293-3.293a1 1 0 111.414 1.414l-4 4a1 1 0 01-1.414 0l-4-4a1 1 0 010-1.414z" clipRule="evenodd" />
170
+ </svg>
171
+ </div>
172
+ </div>
173
+ </div>
174
+
175
+ {/* Fullscreen Toggle Button */}
176
+ <button
177
+ onClick={toggleFullscreen}
178
+ className="h-[50px] px-4 py-3 bg-white dark:bg-gray-800 text-gray-700 dark:text-gray-300 border border-gray-300 dark:border-gray-600 rounded-md shadow-sm hover:bg-gray-50 dark:hover:bg-gray-700 focus:outline-none focus:ring-2 focus:ring-green-web focus:border-green-web transition-colors"
179
+ title={isFullscreen ? 'Exit fullscreen' : 'Enter fullscreen'}
180
+ >
181
+ {isFullscreen ? (
182
+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
183
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M9 9V4.5M9 9H4.5M9 9L3.75 3.75M9 15v4.5M9 15H4.5M9 15l-5.25 5.25M15 9h4.5M15 9V4.5M15 9l5.25-5.25M15 15h4.5M15 15v4.5m0-4.5l5.25 5.25" />
184
+ </svg>
185
+ ) : (
186
+ <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
187
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" />
188
+ </svg>
189
+ )}
190
+ </button>
191
+ </div>
192
+
193
+ {/* Import/Export Preferences */}
194
+ <div className="flex items-center gap-2 text-sm">
195
+ <span className="text-gray-600 dark:text-gray-400">Preferences:</span>
196
+ <button
197
+ onClick={handleExport}
198
+ className="inline-flex items-center px-3 py-1.5 text-gray-700 dark:text-gray-300 hover:text-green-web dark:hover:text-green-web transition-colors"
199
+ title="Export your preferences to a file"
200
+ >
201
+ <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
202
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-4l-4 4m0 0l-4-4m4 4V4" />
203
+ </svg>
204
+ Export
205
+ </button>
206
+ <span className="text-gray-300 dark:text-gray-600">|</span>
207
+ <button
208
+ onClick={triggerImport}
209
+ className="inline-flex items-center px-3 py-1.5 text-gray-700 dark:text-gray-300 hover:text-green-web dark:hover:text-green-web transition-colors"
210
+ title="Import preferences from a file"
211
+ >
212
+ <svg className="w-4 h-4 mr-1.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
213
+ <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
214
+ </svg>
215
+ Import
216
+ </button>
217
+ <input
218
+ ref={fileInputRef}
219
+ type="file"
220
+ accept="application/json,.json"
221
+ onChange={handleImport}
222
+ className="hidden"
223
+ />
224
+ </div>
225
+ </div>
226
+
227
+ {/* Page Content */}
228
+ <div className="flex-1 overflow-auto">
229
+ <Outlet />
230
+ </div>
231
+ </div>
232
+ )
233
+
234
+ if (isFullscreen) {
235
+ return (
236
+ <div className="fixed inset-0 z-50 bg-white dark:bg-gray-900 overflow-hidden flex flex-col">
237
+ <div className="h-full w-full overflow-auto p-6 md:p-8 lg:p-12">
238
+ {content}
239
+ </div>
240
+ </div>
241
+ )
242
+ }
243
+
244
+ return (
245
+ <div className="h-full overflow-hidden flex flex-col">
246
+ <main className="h-full w-full overflow-auto p-6 md:p-8 lg:p-12">
247
+ {content}
248
+ </main>
249
+ </div>
250
+ )
251
+ }
@@ -0,0 +1,415 @@
1
+ import { gql } from '@apollo/client'
2
+ import { useMutation } from '@apollo/client/react'
3
+ import { CheckCircleIcon, ExclamationCircleIcon } from '@heroicons/react/24/outline'
4
+ import { useAdminDataContext } from '../context/AdminDataContext'
5
+
6
+ function toReadableText(text: string): string {
7
+ return text.replace(/([a-z])([A-Z])/g, '$1 $2').replace(/^./, str => str.toUpperCase())
8
+ }
9
+ import { ErrorBoundary } from '@nestledjs/shared-components'
10
+ import { Form } from '@nestledjs/forms'
11
+ import { useEffect, useMemo, useState } from 'react'
12
+ import { Link, useNavigate, useParams } from 'react-router'
13
+
14
+ import { buildFormFields, cleanFormInput, getAdminDocuments } from '../utils/graphql-utils' // =================================
15
+
16
+ // =================================
17
+ // SECURITY UTILITIES
18
+ // =================================
19
+
20
+ // Sanitize and validate user input
21
+ function sanitizeInput(input: string | undefined): string {
22
+ if (!input || typeof input !== 'string') return ''
23
+
24
+ // Remove potentially dangerous characters and limit length
25
+ return input
26
+ .replace(/[<>"'%;()&+]/g, '') // Remove common injection characters
27
+ .replace(/javascript:/gi, '') // Remove javascript: protocols
28
+ .replace(/on\w+\s*=/gi, '') // Remove event handlers
29
+ .trim()
30
+ .substring(0, 100) // Limit length to prevent DoS
31
+ }
32
+
33
+ // Convert PascalCase to kebab-case for URLs (CourseChapter -> course-chapter)
34
+ const toKebabCase = (str: string): string => {
35
+ return str
36
+ .replace(/([a-z])([A-Z])/g, '$1-$2') // Insert dash between lowercase and uppercase
37
+ .toLowerCase() // Convert to lowercase
38
+ }
39
+
40
+ // Validation functions moved into component to access databaseModels from context
41
+
42
+ // Check if user has access to this data type (basic implementation)
43
+ function checkAccess(dataType: string): boolean {
44
+ // For now, allow access to all data types in admin
45
+ // In a real app, this would check user permissions
46
+ return true
47
+ }
48
+
49
+ // =================================
50
+ // MAIN COMPONENT
51
+ // =================================
52
+
53
+ export function AdminDataCreatePage() {
54
+ const { dataType } = useParams()
55
+ const { databaseModels, basePath = '/admin/data', formTheme } = useAdminDataContext()
56
+
57
+ // Helper function to find model by name
58
+ const findModelByName = (name: string) => {
59
+ return databaseModels.find(model => model.name === name)
60
+ }
61
+
62
+ // Validate data type against allowed models
63
+ const validateDataType = (dataType: string | undefined): string | null => {
64
+ const sanitized = sanitizeInput(dataType)
65
+ if (!sanitized) return null
66
+
67
+ // Convert kebab-case to PascalCase (course-chapter -> CourseChapter)
68
+ const properCaseDataType = sanitized
69
+ .split('-')
70
+ .map(word => word.charAt(0).toUpperCase() + word.slice(1).toLowerCase())
71
+ .join('')
72
+
73
+ // Check if this data type exists in our models
74
+ const model = databaseModels.find(m => m.name === properCaseDataType)
75
+ return model ? properCaseDataType : null
76
+ }
77
+
78
+ // Security validation
79
+ const validatedDataType = validateDataType(dataType)
80
+
81
+ // Determine what to render based on validation
82
+ const shouldShowUnauthorized = !validatedDataType
83
+ const shouldShowAccessDenied = validatedDataType && !checkAccess(validatedDataType)
84
+ const model = validatedDataType ? findModelByName(validatedDataType) : null
85
+ const shouldShowModelNotFound = validatedDataType && !shouldShowAccessDenied && !model
86
+
87
+ // Render error states
88
+ if (shouldShowUnauthorized) {
89
+ return (
90
+ <div className="flex flex-col justify-center py-12">
91
+ <div className="mt-8 mx-auto w-full max-w-md">
92
+ <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow sm:rounded-lg sm:px-10">
93
+ <div className="text-center">
94
+ <ExclamationCircleIcon className="mx-auto h-12 w-12 text-red-400" />
95
+ <h2 className="mt-4 text-lg font-medium text-gray-900 dark:text-gray-100">Unauthorized</h2>
96
+ <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
97
+ Invalid data type or insufficient permissions.
98
+ </p>
99
+ <div className="mt-6">
100
+ <Link
101
+ to={basePath}
102
+ className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-web hover:bg-green-web-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-web"
103
+ >
104
+ Return to Data Browser
105
+ </Link>
106
+ </div>
107
+ </div>
108
+ </div>
109
+ </div>
110
+ </div>
111
+ )
112
+ }
113
+
114
+ if (shouldShowAccessDenied) {
115
+ return (
116
+ <div className="flex flex-col justify-center py-12">
117
+ <div className="mt-8 mx-auto w-full max-w-md">
118
+ <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow sm:rounded-lg sm:px-10">
119
+ <div className="text-center">
120
+ <ExclamationCircleIcon className="mx-auto h-12 w-12 text-red-400" />
121
+ <h2 className="mt-4 text-lg font-medium text-gray-900 dark:text-gray-100">Access Denied</h2>
122
+ <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
123
+ You don't have permission to create {toReadableText(validatedDataType!)} records.
124
+ </p>
125
+ <div className="mt-6">
126
+ <Link
127
+ to={basePath}
128
+ className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-web hover:bg-green-web-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-web"
129
+ >
130
+ Return to Data Browser
131
+ </Link>
132
+ </div>
133
+ </div>
134
+ </div>
135
+ </div>
136
+ </div>
137
+ )
138
+ }
139
+
140
+ if (shouldShowModelNotFound) {
141
+ return (
142
+ <div className="flex flex-col justify-center py-12">
143
+ <div className="mt-8 mx-auto w-full max-w-md">
144
+ <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow sm:rounded-lg sm:px-10">
145
+ <div className="text-center">
146
+ <ExclamationCircleIcon className="mx-auto h-12 w-12 text-yellow-400" />
147
+ <h2 className="mt-4 text-lg font-medium text-gray-900 dark:text-gray-100">Model Not Found</h2>
148
+ <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
149
+ The data model for "{validatedDataType}" could not be found.
150
+ </p>
151
+ <div className="mt-6">
152
+ <Link
153
+ to={basePath}
154
+ className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-web hover:bg-green-web-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-web"
155
+ >
156
+ Return to Data Browser
157
+ </Link>
158
+ </div>
159
+ </div>
160
+ </div>
161
+ </div>
162
+ </div>
163
+ )
164
+ }
165
+
166
+ // At this point we know model exists and is valid
167
+ return <AdminDataCreatePageContent model={model!} basePath={basePath} formTheme={formTheme} />
168
+ }
169
+
170
+ // =================================
171
+ // CONTENT COMPONENT
172
+ // =================================
173
+
174
+ function AdminDataCreatePageContent({ model, basePath, formTheme }: Readonly<{ model: any; basePath: string; formTheme: any }>) {
175
+ const navigate = useNavigate()
176
+ const { sdk } = useAdminDataContext()
177
+
178
+ // State
179
+ const [submissionState, setSubmissionState] = useState<{
180
+ status: 'idle' | 'loading' | 'success' | 'error'
181
+ message?: string
182
+ }>({ status: 'idle' })
183
+
184
+ // Get GraphQL documents with error handling (memoized to prevent render loops)
185
+ const documents = useMemo(() => {
186
+ try {
187
+ return getAdminDocuments(sdk, model)
188
+ } catch (error) {
189
+ console.error('[AdminDataCreatePage] Error getting documents:', error)
190
+ return null
191
+ }
192
+ }, [sdk, model])
193
+
194
+ const CREATE_MUTATION = useMemo(() => {
195
+ if (!documents?.create) return null
196
+ try {
197
+ // Check if it's already a parsed GraphQL document
198
+ if (documents.create?.definitions && documents.create?.loc) {
199
+ return documents.create
200
+ }
201
+
202
+ return gql(documents.create)
203
+ } catch (error) {
204
+ console.error('[AdminDataCreatePage] Error parsing CREATE mutation:', error)
205
+ return null
206
+ }
207
+ }, [documents])
208
+
209
+ // Create mutation - call BEFORE any early returns to maintain hook order
210
+ const [createMutation] = useMutation(
211
+ CREATE_MUTATION ||
212
+ gql`
213
+ mutation PlaceholderCreate {
214
+ __typename
215
+ }
216
+ `,
217
+ )
218
+
219
+ // Early return AFTER all hooks are called
220
+ if (!documents || !CREATE_MUTATION) {
221
+ return (
222
+ <div className="min-h-screen bg-gray-50 dark:bg-gray-900 flex flex-col justify-center py-12 sm:px-6 lg:px-8">
223
+ <div className="mt-8 sm:mx-auto sm:w-full sm:max-w-2xl">
224
+ <div className="bg-white dark:bg-gray-800 py-8 px-4 shadow sm:rounded-lg sm:px-10">
225
+ <div className="text-center">
226
+ <ExclamationCircleIcon className="mx-auto h-12 w-12 text-red-400" />
227
+ <h2 className="mt-4 text-lg font-medium text-gray-900 dark:text-gray-100">GraphQL Schema Error</h2>
228
+ <p className="mt-2 text-sm text-gray-600 dark:text-gray-400">
229
+ Unable to load GraphQL documents for this model. Please ensure the API server is
230
+ running and the GraphQL schema is up to date.
231
+ </p>
232
+ <div className="mt-6">
233
+ <Link
234
+ to={basePath}
235
+ className="w-full flex justify-center py-2 px-4 border border-transparent rounded-md shadow-sm text-sm font-medium text-white bg-green-web hover:bg-green-web-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-green-web"
236
+ >
237
+ Return to Data Browser
238
+ </Link>
239
+ </div>
240
+ </div>
241
+ </div>
242
+ </div>
243
+ </div>
244
+ )
245
+ }
246
+
247
+ // Build form fields
248
+ const formFields = buildFormFields(sdk, model, 'create')
249
+
250
+ // Handle form submission
251
+ const handleSubmit = async (formData: Record<string, unknown>) => {
252
+ try {
253
+ setSubmissionState({ status: 'loading' })
254
+
255
+ // Clean the form input
256
+ const cleanedInput = cleanFormInput(formData, model)
257
+
258
+ // Execute mutation
259
+ const result = await createMutation({
260
+ variables: {
261
+ input: cleanedInput,
262
+ },
263
+ })
264
+
265
+ if ((result as any).errors) {
266
+ console.error('GraphQL errors:', (result as any).errors)
267
+ setSubmissionState({
268
+ status: 'error',
269
+ message: (result as any).errors.map((err: any) => err.message).join(', '),
270
+ })
271
+ return
272
+ }
273
+
274
+ setSubmissionState({
275
+ status: 'success',
276
+ message: `${toReadableText(model.name)} created successfully!`,
277
+ })
278
+
279
+ // Redirect after a brief delay to show success message
280
+ setTimeout(() => {
281
+ navigate(`/admin/data/${toKebabCase(model.pluralName)}`)
282
+ }, 1500)
283
+ } catch (error) {
284
+ console.error('Error creating record:', error)
285
+ setSubmissionState({
286
+ status: 'error',
287
+ message: error instanceof Error ? error.message : 'An unexpected error occurred',
288
+ })
289
+ }
290
+ }
291
+
292
+ // Clear submission state after errors
293
+ useEffect(() => {
294
+ if (submissionState.status === 'error') {
295
+ const timer = setTimeout(() => {
296
+ setSubmissionState({ status: 'idle' })
297
+ }, 5000)
298
+ return () => clearTimeout(timer)
299
+ }
300
+ }, [submissionState.status])
301
+
302
+ return (
303
+ <div className="space-y-6">
304
+ {/* Header */}
305
+ <div className="mb-8">
306
+ <nav className="flex mb-6" aria-label="Breadcrumb">
307
+ <ol className="flex items-center space-x-4">
308
+ <li>
309
+ <Link to="/admin/data" className="text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400">
310
+ Data Browser
311
+ </Link>
312
+ </li>
313
+ <li>
314
+ <div className="flex items-center">
315
+ <svg
316
+ className="flex-shrink-0 h-5 w-5 text-gray-300 dark:text-gray-600"
317
+ fill="currentColor"
318
+ viewBox="0 0 20 20"
319
+ >
320
+ <path
321
+ fillRule="evenodd"
322
+ d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 111.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
323
+ clipRule="evenodd"
324
+ />
325
+ </svg>
326
+ <Link
327
+ to={`/admin/data/${toKebabCase(model.pluralName)}`}
328
+ className="ml-4 text-gray-400 dark:text-gray-500 hover:text-gray-500 dark:hover:text-gray-400"
329
+ >
330
+ {toReadableText(model.pluralName)}
331
+ </Link>
332
+ </div>
333
+ </li>
334
+ <li>
335
+ <div className="flex items-center">
336
+ <svg
337
+ className="flex-shrink-0 h-5 w-5 text-gray-300 dark:text-gray-600"
338
+ fill="currentColor"
339
+ viewBox="0 0 20 20"
340
+ >
341
+ <path
342
+ fillRule="evenodd"
343
+ d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 111.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z"
344
+ clipRule="evenodd"
345
+ />
346
+ </svg>
347
+ <span className="ml-4 text-gray-500 dark:text-gray-400">Create New</span>
348
+ </div>
349
+ </li>
350
+ </ol>
351
+ </nav>
352
+ <h1 className="mt-4 text-3xl font-bold text-gray-900 dark:text-gray-100">
353
+ Create {toReadableText(model.name)}
354
+ </h1>
355
+ </div>
356
+
357
+ {/* Submission Status */}
358
+ {submissionState.status !== 'idle' && (
359
+ <div
360
+ className={`mb-6 rounded-md p-4 ${
361
+ submissionState.status === 'success'
362
+ ? 'bg-green-50 border border-green-200'
363
+ : submissionState.status === 'error'
364
+ ? 'bg-red-50 border border-red-200'
365
+ : 'bg-blue-50 border border-blue-200'
366
+ }`}
367
+ >
368
+ <div className="flex">
369
+ <div className="flex-shrink-0">
370
+ {submissionState.status === 'success' ? (
371
+ <CheckCircleIcon className="h-5 w-5 text-green-400" />
372
+ ) : submissionState.status === 'error' ? (
373
+ <ExclamationCircleIcon className="h-5 w-5 text-red-400" />
374
+ ) : (
375
+ <div className="h-5 w-5 border-2 border-blue-400 border-t-transparent rounded-full animate-spin" />
376
+ )}
377
+ </div>
378
+ <div className="ml-3">
379
+ <p
380
+ className={`text-sm font-medium ${
381
+ submissionState.status === 'success'
382
+ ? 'text-green-800'
383
+ : submissionState.status === 'error'
384
+ ? 'text-red-800'
385
+ : 'text-blue-800'
386
+ }`}
387
+ >
388
+ {submissionState.status === 'loading'
389
+ ? `Creating ${toReadableText(model.name)}...`
390
+ : submissionState.message}
391
+ </p>
392
+ </div>
393
+ </div>
394
+ </div>
395
+ )}
396
+
397
+ {/* Form */}
398
+ <div className="bg-white dark:bg-gray-800 shadow-sm rounded-lg">
399
+ <div className="px-6 py-8">
400
+ <Form
401
+ id={`create-${model.name.toLowerCase()}-form`}
402
+ fields={formFields}
403
+ submit={handleSubmit}
404
+ disabled={submissionState.status === 'loading'}
405
+ theme={formTheme}
406
+ />
407
+ </div>
408
+ </div>
409
+ </div>
410
+ )
411
+ }
412
+
413
+ export function AdminDataCreateErrorBoundary({ error }: Readonly<{ error: Error }>) {
414
+ return <ErrorBoundary error={error} />
415
+ }