@sidekickdb/components 0.0.0-stage → 2.0.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 (144) hide show
  1. package/.turbo/turbo-build.log +20 -0
  2. package/LICENSE.md +202 -0
  3. package/NOTICE +27 -0
  4. package/README.md +93 -2
  5. package/app/App.css +38 -0
  6. package/app/App.tsx +63 -0
  7. package/app/index.css +18 -0
  8. package/app/main.tsx +10 -0
  9. package/dist/components/DialogContentPrimitive.d.ts +1 -0
  10. package/dist/components/DialogContentPrimitive.d.ts.map +1 -0
  11. package/dist/components/StyleMe.d.ts +15 -0
  12. package/dist/components/StyleMe.d.ts.map +1 -0
  13. package/dist/components/error-boundary.d.ts +17 -0
  14. package/dist/components/error-boundary.d.ts.map +1 -0
  15. package/dist/components/explorer/__tests__/edit-row-dialog.test.d.ts +2 -0
  16. package/dist/components/explorer/__tests__/edit-row-dialog.test.d.ts.map +1 -0
  17. package/dist/components/explorer/__tests__/format-value.test.d.ts +2 -0
  18. package/dist/components/explorer/__tests__/format-value.test.d.ts.map +1 -0
  19. package/dist/components/explorer/edit-namespace-dialog.d.ts +17 -0
  20. package/dist/components/explorer/edit-namespace-dialog.d.ts.map +1 -0
  21. package/dist/components/explorer/edit-row-dialog.d.ts +15 -0
  22. package/dist/components/explorer/edit-row-dialog.d.ts.map +1 -0
  23. package/dist/components/explorer/expandable-deleted-attr.d.ts +15 -0
  24. package/dist/components/explorer/expandable-deleted-attr.d.ts.map +1 -0
  25. package/dist/components/explorer/explorer-layout.d.ts +9 -0
  26. package/dist/components/explorer/explorer-layout.d.ts.map +1 -0
  27. package/dist/components/explorer/format-value.d.ts +2 -0
  28. package/dist/components/explorer/format-value.d.ts.map +1 -0
  29. package/dist/components/explorer/index.d.ts +128 -0
  30. package/dist/components/explorer/index.d.ts.map +1 -0
  31. package/dist/components/explorer/inner-explorer.d.ts +17 -0
  32. package/dist/components/explorer/inner-explorer.d.ts.map +1 -0
  33. package/dist/components/explorer/new-namespace-dialog.d.ts +10 -0
  34. package/dist/components/explorer/new-namespace-dialog.d.ts.map +1 -0
  35. package/dist/components/explorer/query-inspector.d.ts +11 -0
  36. package/dist/components/explorer/query-inspector.d.ts.map +1 -0
  37. package/dist/components/explorer/recently-deleted.d.ts +36 -0
  38. package/dist/components/explorer/recently-deleted.d.ts.map +1 -0
  39. package/dist/components/explorer/search-input.d.ts +9 -0
  40. package/dist/components/explorer/search-input.d.ts.map +1 -0
  41. package/dist/components/explorer/table-components.d.ts +16 -0
  42. package/dist/components/explorer/table-components.d.ts.map +1 -0
  43. package/dist/components/explorer/view-settings.d.ts +10 -0
  44. package/dist/components/explorer/view-settings.d.ts.map +1 -0
  45. package/dist/components/rosePineDawnTheme.d.ts +13 -0
  46. package/dist/components/rosePineDawnTheme.d.ts.map +1 -0
  47. package/dist/components/select.d.ts +16 -0
  48. package/dist/components/select.d.ts.map +1 -0
  49. package/dist/components/toast.d.ts +4 -0
  50. package/dist/components/toast.d.ts.map +1 -0
  51. package/dist/components/ui.d.ts +349 -0
  52. package/dist/components/ui.d.ts.map +1 -0
  53. package/dist/config.d.ts +11 -0
  54. package/dist/config.d.ts.map +1 -0
  55. package/dist/hooks/__tests__/explorer.test.d.ts +2 -0
  56. package/dist/hooks/__tests__/explorer.test.d.ts.map +1 -0
  57. package/dist/hooks/explorer.d.ts +33 -0
  58. package/dist/hooks/explorer.d.ts.map +1 -0
  59. package/dist/hooks/useAttrNotes.d.ts +10 -0
  60. package/dist/hooks/useAttrNotes.d.ts.map +1 -0
  61. package/dist/hooks/useClickOutside.d.ts +3 -0
  62. package/dist/hooks/useClickOutside.d.ts.map +1 -0
  63. package/dist/hooks/useColumnVisibility.d.ts +12 -0
  64. package/dist/hooks/useColumnVisibility.d.ts.map +1 -0
  65. package/dist/hooks/useEditBlobConstraints.d.ts +32 -0
  66. package/dist/hooks/useEditBlobConstraints.d.ts.map +1 -0
  67. package/dist/hooks/useExplorerHistory.d.ts +1 -0
  68. package/dist/hooks/useExplorerHistory.d.ts.map +1 -0
  69. package/dist/hooks/useIsOverflow.d.ts +6 -0
  70. package/dist/hooks/useIsOverflow.d.ts.map +1 -0
  71. package/dist/hooks/useLocalStorage.d.ts +2 -0
  72. package/dist/hooks/useLocalStorage.d.ts.map +1 -0
  73. package/dist/hooks/useMonacoJSONSchema.d.ts +3 -0
  74. package/dist/hooks/useMonacoJSONSchema.d.ts.map +1 -0
  75. package/dist/hooks/useStableDB.d.ts +7 -0
  76. package/dist/hooks/useStableDB.d.ts.map +1 -0
  77. package/dist/index.cjs +15 -0
  78. package/dist/index.d.ts +7 -0
  79. package/dist/index.d.ts.map +1 -0
  80. package/dist/index.js +9751 -0
  81. package/dist/schema.d.ts +5 -0
  82. package/dist/schema.d.ts.map +1 -0
  83. package/dist/style.css +1 -0
  84. package/dist/types.d.ts +241 -0
  85. package/dist/types.d.ts.map +1 -0
  86. package/dist/utils/format.d.ts +2 -0
  87. package/dist/utils/format.d.ts.map +1 -0
  88. package/dist/utils/indexingJobs.d.ts +24 -0
  89. package/dist/utils/indexingJobs.d.ts.map +1 -0
  90. package/dist/utils/parsePermsJSON.d.ts +11 -0
  91. package/dist/utils/parsePermsJSON.d.ts.map +1 -0
  92. package/dist/utils/renames.d.ts +3 -0
  93. package/dist/utils/renames.d.ts.map +1 -0
  94. package/dist/utils/tableWidthSize.d.ts +9 -0
  95. package/dist/utils/tableWidthSize.d.ts.map +1 -0
  96. package/index.html +13 -0
  97. package/package.json +111 -3
  98. package/src/components/DialogContentPrimitive.tsx +0 -0
  99. package/src/components/StyleMe.tsx +97 -0
  100. package/src/components/error-boundary.tsx +76 -0
  101. package/src/components/explorer/__tests__/edit-row-dialog.test.ts +31 -0
  102. package/src/components/explorer/__tests__/format-value.test.ts +9 -0
  103. package/src/components/explorer/edit-namespace-dialog.tsx +1890 -0
  104. package/src/components/explorer/edit-row-dialog.tsx +1367 -0
  105. package/src/components/explorer/expandable-deleted-attr.tsx +170 -0
  106. package/src/components/explorer/explorer-layout.tsx +196 -0
  107. package/src/components/explorer/format-value.ts +9 -0
  108. package/src/components/explorer/index.tsx +280 -0
  109. package/src/components/explorer/inner-explorer.tsx +1524 -0
  110. package/src/components/explorer/new-namespace-dialog.tsx +55 -0
  111. package/src/components/explorer/query-inspector.tsx +395 -0
  112. package/src/components/explorer/recently-deleted.tsx +349 -0
  113. package/src/components/explorer/search-input.tsx +358 -0
  114. package/src/components/explorer/table-components.tsx +416 -0
  115. package/src/components/explorer/view-settings.tsx +76 -0
  116. package/src/components/rosePineDawnTheme.ts +45 -0
  117. package/src/components/select.tsx +198 -0
  118. package/src/components/toast.tsx +18 -0
  119. package/src/components/ui.tsx +1740 -0
  120. package/src/config.ts +57 -0
  121. package/src/hooks/__tests__/explorer.test.ts +109 -0
  122. package/src/hooks/explorer.tsx +137 -0
  123. package/src/hooks/useAttrNotes.ts +27 -0
  124. package/src/hooks/useClickOutside.ts +23 -0
  125. package/src/hooks/useColumnVisibility.ts +39 -0
  126. package/src/hooks/useEditBlobConstraints.ts +185 -0
  127. package/src/hooks/useExplorerHistory.ts +0 -0
  128. package/src/hooks/useIsOverflow.ts +24 -0
  129. package/src/hooks/useLocalStorage.ts +51 -0
  130. package/src/hooks/useMonacoJSONSchema.ts +41 -0
  131. package/src/hooks/useStableDB.ts +31 -0
  132. package/src/index.tsx +12 -0
  133. package/src/schema.ts +286 -0
  134. package/src/style.css +84 -0
  135. package/src/types.ts +359 -0
  136. package/src/utils/format.ts +13 -0
  137. package/src/utils/indexingJobs.ts +126 -0
  138. package/src/utils/parsePermsJSON.ts +35 -0
  139. package/src/utils/renames.ts +42 -0
  140. package/src/utils/tableWidthSize.ts +62 -0
  141. package/tailwind.config.cjs +48 -0
  142. package/tsconfig.json +22 -0
  143. package/vite-env.d.ts +1 -0
  144. package/vite.config.ts +50 -0
@@ -0,0 +1,1367 @@
1
+ import React from 'react';
2
+ import { id, InstantReactWebDatabase, tx } from '@sidekickdb/react';
3
+ import {
4
+ TextareaHTMLAttributes,
5
+ useEffect,
6
+ useLayoutEffect,
7
+ useMemo,
8
+ useRef,
9
+ useState,
10
+ } from 'react';
11
+
12
+ import {
13
+ ActionButton,
14
+ ActionForm,
15
+ Button,
16
+ CodeEditor,
17
+ Label,
18
+ Select,
19
+ Checkbox,
20
+ } from '@lib/components/ui';
21
+ import { SchemaAttr, SchemaNamespace, SchemaNamespaceMap } from '@lib/types';
22
+ import { errorToast, successToast } from '@lib/components/toast';
23
+ import * as Tooltip from '@radix-ui/react-tooltip';
24
+ import {
25
+ Combobox,
26
+ ComboboxInput,
27
+ ComboboxOption,
28
+ ComboboxOptions,
29
+ } from '@headlessui/react';
30
+ import {
31
+ ArrowUturnLeftIcon,
32
+ ArrowPathIcon,
33
+ Cog8ToothIcon,
34
+ TrashIcon,
35
+ InformationCircleIcon,
36
+ } from '@heroicons/react/24/solid';
37
+ import { validate } from 'uuid';
38
+ import clsx from 'clsx';
39
+ import { ClockIcon } from '@heroicons/react/24/outline';
40
+ import { useExplorerProps } from '.';
41
+
42
+ type FieldType = 'string' | 'number' | 'boolean' | 'json';
43
+ type FieldTypeOption = { value: FieldType; label: string };
44
+
45
+ const fieldTypeOptions: FieldTypeOption[] = [
46
+ { value: 'string', label: 'string' },
47
+ { value: 'number', label: 'number' },
48
+ { value: 'boolean', label: 'boolean' },
49
+ { value: 'json', label: 'json' },
50
+ ];
51
+
52
+ interface ResizingTextAreaProps
53
+ extends TextareaHTMLAttributes<HTMLTextAreaElement> {
54
+ onSave?: () => void;
55
+ }
56
+
57
+ function ResizingTextArea({
58
+ onSave,
59
+ onChange,
60
+ onKeyDown,
61
+ ...props
62
+ }: ResizingTextAreaProps) {
63
+ const textareaRef = useRef<HTMLTextAreaElement>(null);
64
+
65
+ const autoResize = (element: HTMLTextAreaElement) => {
66
+ // Capture the scroll position before resizing
67
+ const scrollContainer = element.closest('.overflow-y-auto');
68
+ const scrollTop = scrollContainer?.scrollTop || 0;
69
+
70
+ // Resize the textarea
71
+ element.style.height = 'auto';
72
+ element.style.height = element.scrollHeight + 'px';
73
+
74
+ // Restore scroll position
75
+ if (scrollContainer) {
76
+ scrollContainer.scrollTop = scrollTop;
77
+ }
78
+ };
79
+
80
+ useEffect(() => {
81
+ if (textareaRef.current) {
82
+ autoResize(textareaRef.current);
83
+ if (textareaRef.current) {
84
+ autoResize(textareaRef.current);
85
+ }
86
+ }
87
+ }, [props.value]);
88
+
89
+ return (
90
+ <textarea
91
+ ref={textareaRef}
92
+ className="flex min-h-[34px] w-full flex-1 resize-none overflow-hidden rounded-xs border-gray-200 bg-white px-3 py-1 placeholder:text-gray-400 dark:border-neutral-700 dark:bg-neutral-800 dark:placeholder:text-neutral-500"
93
+ rows={1}
94
+ placeholder="hello world (Shift+Enter for new line)"
95
+ {...props}
96
+ onChange={(e) => {
97
+ onChange?.(e);
98
+ autoResize(e.target);
99
+ }}
100
+ onKeyDown={(e) => {
101
+ if (e.key === 'Enter' && !e.shiftKey && onSave) {
102
+ e.preventDefault();
103
+ onSave();
104
+ }
105
+ onKeyDown?.(e);
106
+ }}
107
+ />
108
+ );
109
+ }
110
+
111
+ const defaultValueByType: Record<FieldType, any> = {
112
+ string: '',
113
+ number: 0,
114
+ boolean: false,
115
+ json: {},
116
+ };
117
+
118
+ function validFieldTypeOptions(checkedDataType?: string): FieldTypeOption[] {
119
+ if (!checkedDataType) {
120
+ return fieldTypeOptions;
121
+ }
122
+
123
+ if (checkedDataType === 'date') {
124
+ return fieldTypeOptions.filter(
125
+ (opt) => opt.value === 'string' || opt.value === 'number',
126
+ );
127
+ }
128
+
129
+ return fieldTypeOptions.filter((opt) => opt.value === checkedDataType);
130
+ }
131
+
132
+ // returns true if value is an object or array (but not null)
133
+ const isJsonObject = (value: any) => !!value && typeof value === 'object';
134
+
135
+ function isValidJson(value: any) {
136
+ try {
137
+ JSON.parse(value);
138
+ return true;
139
+ } catch (e) {
140
+ return false;
141
+ }
142
+ }
143
+
144
+ function tryJsonParse(value: any) {
145
+ try {
146
+ return JSON.parse(value);
147
+ } catch (e) {
148
+ return value;
149
+ }
150
+ }
151
+
152
+ function getAppropriateFieldType(attr: SchemaAttr, value: any): FieldType {
153
+ // Use the checkedDatatype if it's set
154
+ if (attr.checkedDataType) {
155
+ if (attr.checkedDataType === 'date') {
156
+ return 'string';
157
+ }
158
+ return attr.checkedDataType;
159
+ }
160
+
161
+ if (value != null) {
162
+ // if object or array, label as "json" for now
163
+ const t = isJsonObject(value) ? 'json' : typeof value;
164
+ // defaults to 'string' type (fieldTypeOptions[0])
165
+ const option = fieldTypeOptions.find((opt) => opt.value === t);
166
+
167
+ if (option) {
168
+ return option.value;
169
+ }
170
+ }
171
+
172
+ // For nulls we guess the based on what we could infer from previous values
173
+ // for this attribute
174
+ if (attr.inferredTypes?.length) {
175
+ return attr.inferredTypes[0];
176
+ }
177
+
178
+ // Fallback to the first option
179
+ return fieldTypeOptions[0].value;
180
+ }
181
+
182
+ export function parseFieldValue(value: any, type: FieldType) {
183
+ // Preserve null regardless of type
184
+ if (value === null) {
185
+ return null;
186
+ }
187
+
188
+ if (type === 'number') {
189
+ const text = String(value);
190
+ const number = Number(text);
191
+ if (text.trim() !== '' && Number.isFinite(number)) {
192
+ return number;
193
+ }
194
+ const cleaned = text.replace(/[^\d.-]/g, '');
195
+ if (
196
+ cleaned === '' ||
197
+ cleaned === '-' ||
198
+ cleaned === '.' ||
199
+ cleaned === '-.'
200
+ ) {
201
+ return cleaned;
202
+ }
203
+ const match = cleaned.match(/^(-?\d*\.?\d*)\.?$/);
204
+ return match ? Number(match[0]) : '';
205
+ } else if (type === 'boolean') {
206
+ return value === 'true';
207
+ } else if (type === 'string') {
208
+ return isJsonObject(value) ? JSON.stringify(value) : String(value);
209
+ } else if (type === 'json') {
210
+ return tryJsonParse(value);
211
+ }
212
+
213
+ return value;
214
+ }
215
+
216
+ function uuidValidate(uuid: string): string | null {
217
+ return validate(uuid) ? null : 'Invalid UUID.';
218
+ }
219
+
220
+ const REQUIRED_FIELD_ERROR = 'This field is required.';
221
+
222
+ function isEmptyRequiredBlobValue(type: FieldType, value: any): boolean {
223
+ if (value === null || value === undefined) {
224
+ return true;
225
+ }
226
+ switch (type) {
227
+ case 'string':
228
+ return String(value).trim() === '';
229
+ case 'number':
230
+ if (value === '') {
231
+ return true;
232
+ }
233
+ if (typeof value === 'string') {
234
+ return value === '-' || value === '.' || value === '-.';
235
+ }
236
+ return false;
237
+ case 'boolean':
238
+ case 'json':
239
+ return false;
240
+ default:
241
+ return false;
242
+ }
243
+ }
244
+
245
+ function getEffectiveRefLinkCount(
246
+ item: Record<string, any>,
247
+ attrName: string,
248
+ refUpdatesForAttr:
249
+ | Record<string, { action: 'link' | 'unlink'; item: any }>
250
+ | undefined,
251
+ ): number {
252
+ const existingCount = (item[attrName] || []).filter(
253
+ (x: any) => refUpdatesForAttr?.[x.id]?.action !== 'unlink',
254
+ ).length;
255
+ const newLinkCount = Object.values(refUpdatesForAttr || {}).filter(
256
+ (v) => v.action === 'link',
257
+ ).length;
258
+ return existingCount + newLinkCount;
259
+ }
260
+
261
+ function RefItemTooltip({
262
+ db,
263
+ namespace,
264
+ item,
265
+ }: {
266
+ db: InstantReactWebDatabase<any>;
267
+ namespace: SchemaNamespaceMap;
268
+ item: Record<string, any>;
269
+ }) {
270
+ const [open, setOpen] = useState(false);
271
+ const [loadObject, setLoadObject] = useState(false);
272
+
273
+ const { data, isLoading } = db.useQuery(
274
+ open || loadObject
275
+ ? { [namespace.name]: { $: { where: { id: item.id } } } }
276
+ : null,
277
+ );
278
+
279
+ return (
280
+ <Tooltip.Provider>
281
+ <Tooltip.Root delayDuration={0} open={open}>
282
+ <Tooltip.Trigger
283
+ asChild={true}
284
+ onMouseEnter={() => setLoadObject(true)}
285
+ onTouchStart={() => setLoadObject(true)}
286
+ >
287
+ <span>
288
+ <Button
289
+ size="mini"
290
+ variant="subtle"
291
+ onClick={() => setOpen((v) => !v)}
292
+ >
293
+ <InformationCircleIcon height={14} />
294
+ </Button>
295
+ </span>
296
+ </Tooltip.Trigger>
297
+ <Tooltip.Content collisionPadding={10} side="bottom">
298
+ <div className="relative">
299
+ <div
300
+ className="bg-opacity-90 max-w-md overflow-auto border bg-white p-2 font-mono text-xs whitespace-pre shadow-md backdrop-blur-xs dark:border-neutral-700 dark:bg-neutral-800"
301
+ style={{
302
+ maxHeight: `var(--radix-popper-available-height)`,
303
+ }}
304
+ >
305
+ {JSON.stringify(data?.[namespace.name]?.[0] || item, null, 2)}
306
+ </div>
307
+ {isLoading ? (
308
+ <div className="absolute top-0 right-0 animate-spin p-2 opacity-50">
309
+ <Cog8ToothIcon width={12} />
310
+ </div>
311
+ ) : null}
312
+ </div>
313
+ </Tooltip.Content>
314
+ </Tooltip.Root>
315
+ </Tooltip.Provider>
316
+ );
317
+ }
318
+
319
+ function LinkComboboxItem({
320
+ q,
321
+ option,
322
+ uniqueAttrs,
323
+ filterableAttrs,
324
+ }: {
325
+ q: string;
326
+ option: any;
327
+ uniqueAttrs: SchemaAttr[];
328
+ filterableAttrs: SchemaAttr[];
329
+ }) {
330
+ const [open, setOpen] = useState(false);
331
+ return (
332
+ <ComboboxOption
333
+ key={option.id}
334
+ value={option}
335
+ className={clsx(
336
+ 'cursor-pointer px-3 py-1 data-focus:bg-blue-100 dark:border-neutral-700 dark:bg-neutral-800',
337
+ {},
338
+ )}
339
+ >
340
+ <Tooltip.Provider>
341
+ <Tooltip.Root delayDuration={0} open={open}>
342
+ <Tooltip.Trigger
343
+ asChild={true}
344
+ onMouseEnter={() => setOpen(true)}
345
+ onMouseLeave={() => setOpen(false)}
346
+ >
347
+ <div>
348
+ <div>
349
+ <code>{option.id}</code>
350
+ </div>
351
+ <div className="truncate">
352
+ {filterableAttrs
353
+ .filter(
354
+ (a) =>
355
+ option.hasOwnProperty(a.name) &&
356
+ !a.isUniq &&
357
+ q &&
358
+ JSON.stringify(option[a.name])
359
+ .toLowerCase()
360
+ .indexOf(q.toLowerCase()) !== -1,
361
+ )
362
+ .slice(0, 3)
363
+ .map((a) => (
364
+ <div key={a.id}>
365
+ <span className="font-medium">{a.name}</span>:{' '}
366
+ {JSON.stringify(option[a.name])}
367
+ </div>
368
+ ))}
369
+ {uniqueAttrs
370
+ .filter((a) => option.hasOwnProperty(a.name))
371
+ .slice(0, 3)
372
+ .map((a) => (
373
+ <div key={a.id}>
374
+ <span className="font-medium">{a.name}</span>:{' '}
375
+ {JSON.stringify(option[a.name])}
376
+ </div>
377
+ ))}
378
+ </div>
379
+ </div>
380
+ </Tooltip.Trigger>
381
+ <Tooltip.Content collisionPadding={10}>
382
+ <div
383
+ className="bg-opacity-90 max-w-md overflow-auto border bg-white p-2 font-mono text-xs whitespace-pre shadow-md backdrop-blur-xs dark:border-neutral-700 dark:bg-neutral-800"
384
+ style={{
385
+ maxHeight: `var(--radix-popper-available-height)`,
386
+ }}
387
+ >
388
+ {JSON.stringify(option, null, 2)}
389
+ </div>
390
+ </Tooltip.Content>
391
+ </Tooltip.Root>
392
+ </Tooltip.Provider>
393
+ </ComboboxOption>
394
+ );
395
+ }
396
+
397
+ function LinkCombobox({
398
+ db,
399
+ namespace,
400
+ onLinkRef,
401
+ ignoreIds,
402
+ onClose,
403
+ }: {
404
+ db: InstantReactWebDatabase<any>;
405
+ namespace: SchemaNamespaceMap;
406
+ onLinkRef: (item: any) => void;
407
+ ignoreIds: Set<string>;
408
+ onClose: () => void;
409
+ }) {
410
+ const [q, setq] = useState('');
411
+
412
+ const inputRef = useRef<HTMLInputElement | null>(null);
413
+
414
+ const { uniqueAttrs, filterableAttrs } = useMemo(() => {
415
+ const uniqueAttrs: SchemaAttr[] = [];
416
+ const filterableAttrs: SchemaAttr[] = [];
417
+ for (const [_k, attr] of Object.entries(namespace.attrs)) {
418
+ if (attr.isUniq && attr.name !== 'id' && attr.type === 'blob') {
419
+ uniqueAttrs.push(attr);
420
+ }
421
+ if (
422
+ attr.isIndex &&
423
+ (attr.checkedDataType === 'string' || attr.checkedDataType === 'number')
424
+ ) {
425
+ filterableAttrs.push(attr);
426
+ }
427
+ }
428
+ return { uniqueAttrs, filterableAttrs };
429
+ }, [namespace.attrs]);
430
+
431
+ const query = useMemo(() => {
432
+ const clauses: any[] = [{ $entityIdStartsWith: q }];
433
+ let numVal;
434
+ try {
435
+ const num = JSON.parse(q);
436
+ if (typeof num === 'number') {
437
+ numVal = num;
438
+ }
439
+ } catch (e) {}
440
+
441
+ for (const attr of filterableAttrs) {
442
+ if (attr.checkedDataType === 'string' && q.trim()) {
443
+ clauses.push({ [attr.name]: { $ilike: `%${q.trim()}%` } });
444
+ }
445
+ if (attr.checkedDataType === 'number' && numVal != null) {
446
+ clauses.push({ [attr.name]: numVal });
447
+ }
448
+ }
449
+ for (const attr of uniqueAttrs) {
450
+ if (!attr.checkedDataType) {
451
+ clauses.push({ [attr.name]: q });
452
+ if (numVal != null) {
453
+ clauses.push({ [attr.name]: numVal });
454
+ }
455
+ }
456
+ }
457
+ return {
458
+ [namespace.name]: {
459
+ $: {
460
+ where: {
461
+ or: clauses,
462
+ },
463
+ limit: 20,
464
+ },
465
+ },
466
+ };
467
+ }, [namespace.name, filterableAttrs, q]);
468
+
469
+ const { data, isLoading } = db.useQuery(query);
470
+
471
+ const options = data?.[namespace.name]?.filter((o) => !ignoreIds.has(o.id));
472
+
473
+ return (
474
+ <div className="relative mt-1 w-full">
475
+ <Combobox
476
+ key={isLoading ? 'query-loading' : 'query-loaded'}
477
+ onChange={(option: any) => {
478
+ if (option) {
479
+ onLinkRef(option);
480
+ setq('');
481
+ onClose();
482
+ }
483
+ }}
484
+ onClose={onClose}
485
+ immediate={true}
486
+ >
487
+ <ComboboxInput
488
+ ref={inputRef}
489
+ autoFocus={true}
490
+ size={32}
491
+ className="w-full rounded-md border border-gray-300 px-3 py-2 text-sm dark:border-neutral-700 dark:bg-neutral-800 dark:placeholder:text-neutral-500"
492
+ value={q}
493
+ onChange={(e) => {
494
+ setq(e.target.value);
495
+ }}
496
+ placeholder={`Search ${namespace.name}...`}
497
+ />
498
+
499
+ <ComboboxOptions
500
+ portal={false}
501
+ unmount={false}
502
+ static={true}
503
+ className="absolute left-0 z-10 mt-1 max-h-[25vh] w-full divide-y overflow-scroll rounded-md border border-gray-300 bg-white shadow-lg empty:invisible dark:border-neutral-700 dark:bg-neutral-800"
504
+ >
505
+ {(options || []).map((o) => (
506
+ <LinkComboboxItem
507
+ key={o.id}
508
+ q={q}
509
+ option={o}
510
+ uniqueAttrs={uniqueAttrs}
511
+ filterableAttrs={filterableAttrs}
512
+ />
513
+ ))}
514
+ </ComboboxOptions>
515
+ {options?.length || isLoading ? null : (
516
+ <div className="absolute left-0 z-10 mt-1 w-full divide-y overflow-scroll rounded-md border border-gray-300 bg-white p-2 shadow-lg dark:border-neutral-700 dark:bg-neutral-800">
517
+ No matching rows in <code>{namespace.name}</code>
518
+ </div>
519
+ )}
520
+ </Combobox>
521
+ </div>
522
+ );
523
+ }
524
+
525
+ function RefItem({
526
+ db,
527
+ item,
528
+ attr,
529
+ namespace,
530
+ refUpdates,
531
+ handleLinkRef,
532
+ handleUnlinkRef,
533
+ }: {
534
+ db: InstantReactWebDatabase<any>;
535
+ item: Record<string, any>;
536
+ attr: SchemaAttr;
537
+ namespace: SchemaNamespaceMap;
538
+ refUpdates: null | Record<string, { action: 'link' | 'unlink'; item: any }>;
539
+ handleLinkRef: (attr: SchemaAttr, item: any) => void;
540
+ handleUnlinkRef: (attr: SchemaAttr, id: string) => void;
541
+ }) {
542
+ const [showAddLink, setShowAddLink] = useState(false);
543
+ const searchIgnoreIds = useMemo(() => {
544
+ const res: Set<string> = new Set();
545
+ for (const [k] of Object.entries(refUpdates || {})) {
546
+ res.add(k);
547
+ }
548
+ for (const linkItem of item[attr.name] || []) {
549
+ res.add(linkItem.id);
550
+ }
551
+ return res;
552
+ }, [item[attr.name], refUpdates]);
553
+
554
+ const cardinality = attr.cardinality;
555
+ const hasLink = item[attr.name]?.length > 0;
556
+
557
+ return (
558
+ <>
559
+ {item[attr.name]?.map((x: any) => {
560
+ const markedForUnlink = refUpdates?.[x.id]?.action === 'unlink';
561
+ return (
562
+ <div key={x.id}>
563
+ <code className={markedForUnlink ? 'line-through' : ''}>
564
+ {x.id}
565
+ </code>
566
+ <RefItemTooltip db={db} namespace={namespace} item={x} />
567
+ <Button
568
+ title={markedForUnlink ? 'Undo' : 'Unlink'}
569
+ type="link"
570
+ size="mini"
571
+ variant={markedForUnlink ? 'subtle' : 'destructive'}
572
+ className="border-none"
573
+ onClick={() =>
574
+ markedForUnlink
575
+ ? handleLinkRef(attr, x)
576
+ : handleUnlinkRef(attr, x.id)
577
+ }
578
+ >
579
+ {markedForUnlink ? (
580
+ <ArrowUturnLeftIcon height={14} />
581
+ ) : (
582
+ <TrashIcon height={14} />
583
+ )}
584
+ </Button>
585
+ </div>
586
+ );
587
+ })}
588
+ {Object.entries(refUpdates || {}).map(([id, { action, item }]) => {
589
+ if (action !== 'link') {
590
+ return;
591
+ }
592
+
593
+ return (
594
+ <div key={id}>
595
+ <code>{id}</code>
596
+ <RefItemTooltip db={db} namespace={namespace} item={item} />
597
+ <Button
598
+ title={'Remove'}
599
+ type="link"
600
+ size="mini"
601
+ variant={'destructive'}
602
+ className="border-none"
603
+ onClick={() => handleUnlinkRef(attr, id)}
604
+ >
605
+ <TrashIcon height={14} />
606
+ </Button>
607
+ </div>
608
+ );
609
+ })}
610
+ {showAddLink ? (
611
+ <LinkCombobox
612
+ namespace={namespace}
613
+ onLinkRef={(item) => handleLinkRef(attr, item)}
614
+ db={db}
615
+ ignoreIds={searchIgnoreIds}
616
+ onClose={() => setShowAddLink(false)}
617
+ />
618
+ ) : (
619
+ <Button variant="secondary" onClick={() => setShowAddLink(true)}>
620
+ {cardinality === 'many' || !hasLink ? 'Add link' : 'Replace link'}
621
+ </Button>
622
+ )}
623
+ </>
624
+ );
625
+ }
626
+
627
+ const isEditableBlobAttr = (namespace: SchemaNamespace, attr: SchemaAttr) => {
628
+ switch (namespace.name) {
629
+ case '$files': {
630
+ return attr.type === 'blob' && attr.name === 'path';
631
+ }
632
+ case '$streams': {
633
+ return false;
634
+ }
635
+ default: {
636
+ return attr.type === 'blob';
637
+ }
638
+ }
639
+ };
640
+
641
+ const isEditableRefAttr = (attr: SchemaAttr) => {
642
+ switch (attr.namespace) {
643
+ case '$streams': {
644
+ return false;
645
+ }
646
+ default: {
647
+ return attr.type === 'ref';
648
+ }
649
+ }
650
+ };
651
+
652
+ export function isEditableExplorerAttr(
653
+ namespace: SchemaNamespace,
654
+ attr: SchemaAttr,
655
+ ) {
656
+ if (attr.name === 'id') {
657
+ return false;
658
+ }
659
+ return (
660
+ isEditableBlobAttr(namespace, attr) ||
661
+ (attr.type === 'ref' && isEditableRefAttr(attr))
662
+ );
663
+ }
664
+
665
+ function scrollFieldSectionIntoView(
666
+ section: HTMLElement,
667
+ scrollParent: HTMLElement | null,
668
+ ) {
669
+ if (scrollParent) {
670
+ const parentRect = scrollParent.getBoundingClientRect();
671
+ const sectionRect = section.getBoundingClientRect();
672
+ scrollParent.scrollTop +=
673
+ sectionRect.top -
674
+ parentRect.top -
675
+ (parentRect.height - sectionRect.height) / 2;
676
+ return;
677
+ }
678
+ section.scrollIntoView({ block: 'center', inline: 'nearest' });
679
+ }
680
+
681
+ export function EditRowDialog({
682
+ db,
683
+ namespace,
684
+ item,
685
+ onClose,
686
+ focusAttr,
687
+ }: {
688
+ db: InstantReactWebDatabase<any>;
689
+ namespace: SchemaNamespace;
690
+ item: Record<string, any>;
691
+ onClose: () => void;
692
+ focusAttr?: string;
693
+ }) {
694
+ const op: 'edit' | 'add' = item.id ? 'edit' : 'add';
695
+ const explorerProps = useExplorerProps();
696
+ const formBodyRef = useRef<HTMLDivElement>(null);
697
+ const fieldSectionRefs = useRef<Record<string, HTMLDivElement | null>>({});
698
+ const setFieldSectionRef = (name: string) => (el: HTMLDivElement | null) => {
699
+ fieldSectionRefs.current[name] = el;
700
+ };
701
+ const [pendingFocusField, setPendingFocusField] = useState<string | null>(
702
+ null,
703
+ );
704
+
705
+ const editableBlobAttrs: SchemaAttr[] = [];
706
+ const editableRefAttrs: SchemaAttr[] = [];
707
+
708
+ for (const a of namespace.attrs) {
709
+ if (a.name !== 'id') {
710
+ if (isEditableBlobAttr(namespace, a)) {
711
+ editableBlobAttrs.push(a);
712
+ }
713
+ if (a.type === 'ref' && isEditableRefAttr(a)) {
714
+ editableRefAttrs.push(a);
715
+ }
716
+ }
717
+ }
718
+
719
+ const currentBlobs = editableBlobAttrs.reduce(
720
+ (acc, attr) => {
721
+ const val = item[attr.name];
722
+ const t = getAppropriateFieldType(attr, val);
723
+
724
+ const defaultValue =
725
+ op === 'add' ? (attr.isRequired ? defaultValueByType[t] : null) : val;
726
+
727
+ return {
728
+ ...acc,
729
+ [attr.name]: {
730
+ type: t,
731
+ value: defaultValue,
732
+ error: null,
733
+ },
734
+ };
735
+ },
736
+ {} as Record<string, { type: FieldType; value: any; error: string | null }>,
737
+ );
738
+
739
+ const [blobUpdates, setUpdatedBlobValues] = useState<Record<string, any>>({
740
+ ...currentBlobs,
741
+ ...(op === 'add' ? { id: { type: 'string', value: id() } } : {}),
742
+ });
743
+
744
+ const [refUpdates, setRefUpdates] = useState<
745
+ // Map of attr-name -> id -> add or remove
746
+ Record<string, Record<string, { item: any; action: 'link' | 'unlink' }>>
747
+ >({});
748
+
749
+ const [jsonUpdates, setJsonUpdates] = useState<Record<string, any>>({});
750
+ const [refFieldErrors, setRefFieldErrors] = useState<
751
+ Record<string, string | null>
752
+ >({});
753
+ const [nullFields, setNullFields] = useState<Record<string, boolean>>(
754
+ editableBlobAttrs.reduce((acc, attr) => {
755
+ // Don't set nullFields for new rows
756
+ return {
757
+ ...acc,
758
+ [attr.name]:
759
+ op === 'edit'
760
+ ? item[attr.name] === null || item[attr.name] === undefined
761
+ : blobUpdates[attr.name].value === null,
762
+ };
763
+ }, {}),
764
+ );
765
+
766
+ const hasRefFieldErrors = Object.values(refFieldErrors).some(Boolean);
767
+ const hasFormErrors =
768
+ Object.values(blobUpdates).some((u) => !!u.error) || hasRefFieldErrors;
769
+ const [shouldDisplayErrors, setShouldDisplayErrors] = useState(false);
770
+
771
+ const shouldAutoFocus = (fieldName: string) => focusAttr === fieldName;
772
+
773
+ useLayoutEffect(() => {
774
+ if (!focusAttr) {
775
+ return;
776
+ }
777
+ const section = fieldSectionRefs.current[focusAttr];
778
+ if (section) {
779
+ scrollFieldSectionIntoView(section, formBodyRef.current);
780
+ }
781
+ const field = blobUpdates[focusAttr];
782
+ if (field?.type === 'boolean' && !nullFields[focusAttr]) {
783
+ section?.querySelector<HTMLElement>('[role="combobox"]')?.focus();
784
+ }
785
+ }, [focusAttr, blobUpdates, nullFields]);
786
+
787
+ useLayoutEffect(() => {
788
+ if (!pendingFocusField) {
789
+ return;
790
+ }
791
+ const section = fieldSectionRefs.current[pendingFocusField];
792
+ if (section) {
793
+ scrollFieldSectionIntoView(section, formBodyRef.current);
794
+ section.querySelector<HTMLElement>('input, textarea')?.focus();
795
+ }
796
+ setPendingFocusField(null);
797
+ }, [pendingFocusField, nullFields]);
798
+
799
+ const handleResetForm = () => {
800
+ setRefUpdates({});
801
+ setRefFieldErrors({});
802
+
803
+ // Reset the blobUpdates to the original values
804
+ setUpdatedBlobValues({ ...currentBlobs });
805
+
806
+ // Reset the nullFields state based on the original item
807
+ setNullFields(
808
+ editableBlobAttrs.reduce((acc, attr) => {
809
+ return {
810
+ ...acc,
811
+ [attr.name]:
812
+ op === 'edit'
813
+ ? item[attr.name] === null || item[attr.name] === undefined
814
+ : false,
815
+ };
816
+ }, {}),
817
+ );
818
+
819
+ // Also reset any JSON updates to match the original values
820
+ const resetJsonUpdates: Record<string, any> = {};
821
+ editableBlobAttrs.forEach((attr) => {
822
+ if (
823
+ currentBlobs[attr.name]?.type === 'json' &&
824
+ item[attr.name] !== undefined
825
+ ) {
826
+ resetJsonUpdates[attr.name] =
827
+ item[attr.name] === null
828
+ ? 'null'
829
+ : JSON.stringify(item[attr.name], null, 2);
830
+ }
831
+ });
832
+ setJsonUpdates(resetJsonUpdates);
833
+
834
+ // Reset shouldDisplayErrors to clean state
835
+ setShouldDisplayErrors(false);
836
+ };
837
+
838
+ const handleChangeFieldType = (field: string, type: FieldType) => {
839
+ setUpdatedBlobValues((prev) => {
840
+ const value = prev[field]?.value;
841
+
842
+ return {
843
+ ...prev,
844
+ [field]: { type, value: parseFieldValue(value, type) },
845
+ };
846
+ });
847
+ };
848
+
849
+ const handleUpdateFieldValue = (
850
+ field: string,
851
+ value: any,
852
+ validate?: (value: any) => string | null,
853
+ ) => {
854
+ let error = validate ? validate(value) : null;
855
+ setUpdatedBlobValues((prev) => {
856
+ const type = prev[field]?.type || 'string';
857
+ if (!error && prev[field]?.error === REQUIRED_FIELD_ERROR) {
858
+ error = null;
859
+ }
860
+
861
+ return {
862
+ ...prev,
863
+ [field]: {
864
+ type,
865
+ value: parseFieldValue(value, type),
866
+ error,
867
+ },
868
+ };
869
+ });
870
+ };
871
+
872
+ const handleUpdateJson = (field: string, value: any) => {
873
+ setJsonUpdates((prev) => ({ ...prev, [field]: value }));
874
+
875
+ setUpdatedBlobValues((prev) => {
876
+ const current = prev[field] || {};
877
+
878
+ if (value === '') {
879
+ return {
880
+ ...prev,
881
+ [field]: { type: 'json', value: undefined, error: 'Invalid JSON' },
882
+ };
883
+ }
884
+
885
+ if (isValidJson(value)) {
886
+ return {
887
+ ...prev,
888
+ [field]: { type: 'json', value: JSON.parse(value), error: null },
889
+ };
890
+ }
891
+
892
+ return {
893
+ ...prev,
894
+ [field]: { ...current, type: 'json', error: 'Invalid JSON' },
895
+ };
896
+ });
897
+ };
898
+
899
+ const handleNullToggle = (field: string, checked: boolean) => {
900
+ setNullFields((prev) => ({ ...prev, [field]: checked }));
901
+ const currentType = blobUpdates[field]?.type || 'string';
902
+
903
+ if (checked) {
904
+ setUpdatedBlobValues((prev) => ({
905
+ ...prev,
906
+ [field]: {
907
+ type: currentType,
908
+ value: null, // set field to null
909
+ error: null,
910
+ },
911
+ }));
912
+
913
+ if (currentType === 'json') {
914
+ setJsonUpdates((prev) => ({ ...prev, [field]: 'null' }));
915
+ }
916
+ } else {
917
+ setUpdatedBlobValues((prev) => ({
918
+ ...prev,
919
+ [field]: {
920
+ type: currentType,
921
+ value: defaultValueByType[currentType as FieldType], // set to default
922
+ error: null,
923
+ },
924
+ }));
925
+
926
+ if (currentType === 'json') {
927
+ setJsonUpdates((prev) => ({ ...prev, [field]: '{}' }));
928
+ }
929
+ setPendingFocusField(field);
930
+ }
931
+ };
932
+
933
+ const handleUnlinkRef = (attr: SchemaAttr, id: string) => {
934
+ setRefUpdates((v) => {
935
+ const existing = item[attr.name]?.find((x: any) => x.id === id);
936
+ if (existing) {
937
+ return {
938
+ ...v,
939
+ [attr.name]: {
940
+ ...(v[attr.name] || {}),
941
+ [id]: { action: 'unlink', item: null },
942
+ },
943
+ };
944
+ }
945
+ const { [id]: _, ...withoutId } = v[attr.name] || {};
946
+
947
+ return {
948
+ ...v,
949
+ [attr.name]: withoutId,
950
+ };
951
+ });
952
+ };
953
+
954
+ const handleLinkRef = (attr: SchemaAttr, linkItem: any) => {
955
+ setRefFieldErrors((prev) => {
956
+ if (!prev[attr.name]) {
957
+ return prev;
958
+ }
959
+ return { ...prev, [attr.name]: null };
960
+ });
961
+ setRefUpdates((v) => {
962
+ const id = linkItem.id;
963
+ const existing = v[attr.name]?.[id];
964
+ // This is a undo
965
+ if (existing && existing.action === 'unlink') {
966
+ if (attr.cardinality === 'one') {
967
+ const { [attr.name]: _, ...rest } = v;
968
+ return rest;
969
+ }
970
+ const { [id]: _, ...withoutId } = v[attr.name];
971
+ return {
972
+ ...v,
973
+ [attr.name]: withoutId,
974
+ };
975
+ }
976
+
977
+ // Replace an existing link
978
+ // Need to unlink the old one
979
+ if (attr.cardinality === 'one' && item[attr.name]?.length) {
980
+ const existingLink = item[attr.name][0];
981
+ return {
982
+ ...v,
983
+ [attr.name]: {
984
+ [id]: { action: 'link', item: linkItem },
985
+ [existingLink.id]: { action: 'unlink', item: null },
986
+ },
987
+ };
988
+ }
989
+
990
+ // Add a new link
991
+ return {
992
+ ...v,
993
+ [attr.name]: {
994
+ ...(v[attr.name] || {}),
995
+ [id]: { action: 'link', item: linkItem },
996
+ },
997
+ };
998
+ });
999
+ };
1000
+
1001
+ const handleSaveRow = async () => {
1002
+ const requiredBlobErrors: Record<string, string> = {};
1003
+ const requiredRefErrors: Record<string, string> = {};
1004
+
1005
+ for (const attr of editableBlobAttrs) {
1006
+ if (!attr.isRequired) {
1007
+ continue;
1008
+ }
1009
+ const field = blobUpdates[attr.name];
1010
+ if (
1011
+ nullFields[attr.name] ||
1012
+ isEmptyRequiredBlobValue(field?.type ?? 'string', field?.value)
1013
+ ) {
1014
+ requiredBlobErrors[attr.name] = REQUIRED_FIELD_ERROR;
1015
+ }
1016
+ }
1017
+
1018
+ for (const attr of editableRefAttrs) {
1019
+ if (!attr.isRequired) {
1020
+ continue;
1021
+ }
1022
+ if (
1023
+ getEffectiveRefLinkCount(item, attr.name, refUpdates[attr.name]) === 0
1024
+ ) {
1025
+ requiredRefErrors[attr.name] = REQUIRED_FIELD_ERROR;
1026
+ }
1027
+ }
1028
+
1029
+ const hasRequiredErrors =
1030
+ Object.keys(requiredBlobErrors).length > 0 ||
1031
+ Object.keys(requiredRefErrors).length > 0;
1032
+ const hasExistingErrors =
1033
+ Object.values(blobUpdates).some((u) => !!u.error) ||
1034
+ Object.values(refFieldErrors).some(Boolean);
1035
+
1036
+ if (hasRequiredErrors || hasExistingErrors) {
1037
+ if (hasRequiredErrors) {
1038
+ setUpdatedBlobValues((prev) => {
1039
+ const next = { ...prev };
1040
+ for (const [field, error] of Object.entries(requiredBlobErrors)) {
1041
+ next[field] = { ...next[field], error };
1042
+ }
1043
+ return next;
1044
+ });
1045
+ setRefFieldErrors((prev) => ({ ...prev, ...requiredRefErrors }));
1046
+ }
1047
+ setShouldDisplayErrors(true);
1048
+ return;
1049
+ }
1050
+
1051
+ const params = Object.fromEntries(
1052
+ Object.entries(blobUpdates).map(([field, { value }]) => {
1053
+ return [field, value];
1054
+ }),
1055
+ );
1056
+ const itemId = item.id || params.id || id();
1057
+ delete params.id;
1058
+ try {
1059
+ let chunks = tx[namespace.name][itemId];
1060
+ const unlinks = [];
1061
+ const links = [];
1062
+ for (const [attrName, v] of Object.entries(refUpdates)) {
1063
+ for (const [id, { action }] of Object.entries(v)) {
1064
+ if (action === 'link') {
1065
+ links.push({ [attrName]: id });
1066
+ }
1067
+ if (action === 'unlink') {
1068
+ unlinks.push({ [attrName]: id });
1069
+ }
1070
+ }
1071
+ }
1072
+
1073
+ // Do unlinks first
1074
+ for (const unlink of unlinks) {
1075
+ chunks = chunks.unlink(unlink);
1076
+ }
1077
+ chunks = chunks.update(params);
1078
+ for (const link of links) {
1079
+ chunks = chunks.link(link);
1080
+ }
1081
+
1082
+ await db.transact(chunks);
1083
+
1084
+ onClose();
1085
+ successToast('Successfully updated row!');
1086
+ } catch (e: any) {
1087
+ const message = e.message;
1088
+ if (message) {
1089
+ errorToast(`Failed to save row: ${message}`);
1090
+ } else {
1091
+ throw e;
1092
+ }
1093
+ }
1094
+ };
1095
+
1096
+ return (
1097
+ <ActionForm className="flex min-h-0 flex-1 flex-col overflow-hidden">
1098
+ <div className="shrink-0 px-1">
1099
+ <h5 className="flex text-lg font-bold">
1100
+ {op == 'edit' ? 'Edit row' : 'Add row'}
1101
+ </h5>
1102
+ <code className="font-mono text-sm font-medium text-gray-500 dark:text-neutral-500">
1103
+ {op == 'edit' ? (
1104
+ <>
1105
+ {namespace.name}['{item.id}']
1106
+ </>
1107
+ ) : (
1108
+ <>{namespace.name}</>
1109
+ )}
1110
+ </code>
1111
+ </div>
1112
+ <div
1113
+ ref={formBodyRef}
1114
+ className="scrollbar-gutter-stable mt-4 min-h-0 flex-1 overflow-y-auto px-4 pb-4"
1115
+ >
1116
+ <div className="flex flex-col gap-4">
1117
+ {op === 'add' ? (
1118
+ <div key="id" className="flex flex-col gap-1">
1119
+ <div className="flex items-center justify-between">
1120
+ <Label className="font-mono">
1121
+ <div className="flex gap-1">
1122
+ id{' '}
1123
+ <Button
1124
+ type="link"
1125
+ size="mini"
1126
+ variant="subtle"
1127
+ onClick={() => handleUpdateFieldValue('id', id())}
1128
+ >
1129
+ <ArrowPathIcon height={14} />
1130
+ </Button>
1131
+ </div>
1132
+ </Label>
1133
+ </div>
1134
+ <div className="flex flex-col gap-1">
1135
+ <input
1136
+ className="flex w-full flex-1 rounded-xs border-gray-200 bg-white px-3 py-1 placeholder:text-gray-400 dark:border-neutral-700 dark:bg-neutral-800"
1137
+ value={blobUpdates.id?.value ?? ''}
1138
+ onChange={(e) =>
1139
+ handleUpdateFieldValue('id', e.target.value, uuidValidate)
1140
+ }
1141
+ />
1142
+ </div>{' '}
1143
+ {blobUpdates.id?.error && shouldDisplayErrors && (
1144
+ <span className="text-sm font-medium text-red-500">
1145
+ {blobUpdates.id.error}
1146
+ </span>
1147
+ )}
1148
+ </div>
1149
+ ) : null}
1150
+
1151
+ {editableBlobAttrs.map((attr, i) => {
1152
+ const tabIndex = i + 1;
1153
+ const { type, value, error } = blobUpdates[attr.name] || {
1154
+ type: 'string',
1155
+ value: defaultValueByType['string'],
1156
+ };
1157
+ const json =
1158
+ jsonUpdates[attr.name] ||
1159
+ (value !== null ? JSON.stringify(value, null, 2) : 'null');
1160
+ const isNullField = nullFields[attr.name];
1161
+ const autoFocusField = shouldAutoFocus(attr.name);
1162
+
1163
+ return (
1164
+ <div
1165
+ key={attr.name}
1166
+ ref={setFieldSectionRef(attr.name)}
1167
+ className="flex flex-col gap-1"
1168
+ >
1169
+ <div className="flex items-center justify-between">
1170
+ <Label className="font-mono">{attr.name}</Label>
1171
+ <div className="flex items-center gap-2">
1172
+ <div className="flex items-center">
1173
+ {!attr.isRequired && (
1174
+ <Checkbox
1175
+ checked={isNullField}
1176
+ onChange={(checked) =>
1177
+ handleNullToggle(attr.name, checked)
1178
+ }
1179
+ label={
1180
+ <span className="text-[10px] text-gray-600 uppercase dark:text-neutral-600">
1181
+ null
1182
+ </span>
1183
+ }
1184
+ />
1185
+ )}
1186
+ </div>
1187
+ <Select
1188
+ className="w-24 rounded-sm px-2 py-0.5 text-sm"
1189
+ value={type}
1190
+ options={validFieldTypeOptions(attr.checkedDataType)}
1191
+ onChange={(option) =>
1192
+ handleChangeFieldType(
1193
+ attr.name,
1194
+ option!.value as FieldType,
1195
+ )
1196
+ }
1197
+ />
1198
+ </div>
1199
+ </div>
1200
+ <div className="flex flex-col gap-1">
1201
+ {!isNullField ? (
1202
+ <div className="flex space-x-1">
1203
+ <div className="flex-1">
1204
+ {type === 'json' ? (
1205
+ <div className="h-32 w-full rounded-sm border">
1206
+ <CodeEditor
1207
+ darkMode={explorerProps.darkMode}
1208
+ tabIndex={tabIndex}
1209
+ language="json"
1210
+ value={json}
1211
+ onChange={(code) =>
1212
+ handleUpdateJson(attr.name, code)
1213
+ }
1214
+ onMount={(editor) => {
1215
+ if (autoFocusField) {
1216
+ editor.focus();
1217
+ }
1218
+ }}
1219
+ />
1220
+ </div>
1221
+ ) : type === 'boolean' ? (
1222
+ <Select
1223
+ tabIndex={tabIndex}
1224
+ value={value}
1225
+ options={[
1226
+ { value: 'false', label: 'false' },
1227
+ { value: 'true', label: 'true' },
1228
+ ]}
1229
+ onChange={(option) =>
1230
+ handleUpdateFieldValue(attr.name, option!.value)
1231
+ }
1232
+ />
1233
+ ) : type === 'number' ? (
1234
+ <input
1235
+ tabIndex={tabIndex}
1236
+ type="number"
1237
+ autoFocus={autoFocusField}
1238
+ className="flex w-full flex-1 rounded-xs border-gray-200 bg-white px-3 py-1 placeholder:text-gray-400 dark:border-neutral-700 dark:bg-neutral-800"
1239
+ value={value ?? ''}
1240
+ onChange={(num) =>
1241
+ handleUpdateFieldValue(
1242
+ attr.name,
1243
+ num.target.value,
1244
+ )
1245
+ }
1246
+ />
1247
+ ) : (
1248
+ <ResizingTextArea
1249
+ tabIndex={tabIndex}
1250
+ autoFocus={autoFocusField}
1251
+ value={value ?? ''}
1252
+ onChange={(e) =>
1253
+ handleUpdateFieldValue(attr.name, e.target.value)
1254
+ }
1255
+ onSave={handleSaveRow}
1256
+ />
1257
+ )}
1258
+ </div>
1259
+ {attr.checkedDataType === 'date' && (
1260
+ <Button
1261
+ variant="subtle"
1262
+ size="mini"
1263
+ onClick={() => {
1264
+ handleUpdateFieldValue(
1265
+ attr.name,
1266
+ type === 'number'
1267
+ ? Date.now()
1268
+ : new Date().toISOString(),
1269
+ );
1270
+ }}
1271
+ >
1272
+ <ClockIcon height={14} />
1273
+ now
1274
+ </Button>
1275
+ )}
1276
+ </div>
1277
+ ) : (
1278
+ <button
1279
+ type="button"
1280
+ autoFocus={autoFocusField}
1281
+ onClick={() => handleNullToggle(attr.name, false)}
1282
+ className="flex-1 rounded-xs border border-gray-200 bg-gray-50 px-3 py-1 text-left text-gray-500 italic dark:border-neutral-700 dark:bg-neutral-800 dark:text-neutral-400"
1283
+ >
1284
+ null
1285
+ </button>
1286
+ )}
1287
+ {error && shouldDisplayErrors && (
1288
+ <span className="text-sm font-medium text-red-500">
1289
+ {error}
1290
+ </span>
1291
+ )}
1292
+ </div>
1293
+ </div>
1294
+ );
1295
+ })}
1296
+
1297
+ {editableRefAttrs.map((attr, i) => {
1298
+ const namespace = attr.isForward
1299
+ ? attr.linkConfig.reverse!.nsMap
1300
+ : attr.linkConfig.forward.nsMap;
1301
+
1302
+ if (!namespace) {
1303
+ // Sometimes we get links to namespaces that don't exist
1304
+ return null;
1305
+ }
1306
+
1307
+ return (
1308
+ <div
1309
+ key={attr.name}
1310
+ ref={setFieldSectionRef(attr.name)}
1311
+ className="flex flex-col gap-1"
1312
+ >
1313
+ <div className="flex items-center justify-between">
1314
+ <Label className="font-mono">{attr.name}</Label>
1315
+ <span className="rounded-sm px-2 py-0.5 text-sm">
1316
+ Link to <code>{namespace.name}</code>
1317
+ </span>
1318
+ </div>
1319
+ <div className="flex flex-col gap-1">
1320
+ <RefItem
1321
+ db={db}
1322
+ item={item}
1323
+ namespace={namespace}
1324
+ attr={attr}
1325
+ refUpdates={refUpdates[attr.name]}
1326
+ handleLinkRef={handleLinkRef}
1327
+ handleUnlinkRef={handleUnlinkRef}
1328
+ />
1329
+ {refFieldErrors[attr.name] && shouldDisplayErrors && (
1330
+ <span className="text-sm font-medium text-red-500">
1331
+ {refFieldErrors[attr.name]}
1332
+ </span>
1333
+ )}
1334
+ </div>
1335
+ </div>
1336
+ );
1337
+ })}
1338
+ </div>
1339
+ </div>
1340
+ <div className="mt-2 shrink-0 border-t border-gray-200 bg-white px-1 pt-4 dark:border-neutral-700 dark:bg-neutral-800">
1341
+ <div className="flex flex-row items-center justify-between gap-1">
1342
+ {shouldDisplayErrors && hasFormErrors ? (
1343
+ <span className="text-sm font-medium text-red-500">
1344
+ Failed to save. Please check above for errors.
1345
+ </span>
1346
+ ) : (
1347
+ <span />
1348
+ )}
1349
+ <div className="flex flex-row items-center gap-1">
1350
+ <Button type="button" variant="secondary" onClick={handleResetForm}>
1351
+ Reset
1352
+ </Button>
1353
+ <ActionButton
1354
+ tabIndex={editableBlobAttrs.length + 1}
1355
+ type="submit"
1356
+ variant="primary"
1357
+ label="Save"
1358
+ submitLabel="Saving..."
1359
+ errorMessage="Failed to save row."
1360
+ onClick={handleSaveRow}
1361
+ />
1362
+ </div>
1363
+ </div>
1364
+ </div>
1365
+ </ActionForm>
1366
+ );
1367
+ }