@sidekickdb/components 0.0.0 → 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 +92 -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 +106 -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,1890 @@
1
+ import React from 'react';
2
+ import { id } from '@sidekickdb/core';
3
+ import { InstantReactWebDatabase } from '@sidekickdb/react';
4
+ import {
5
+ useEffect,
6
+ useMemo,
7
+ useRef,
8
+ useState,
9
+ ReactNode,
10
+ MutableRefObject,
11
+ } from 'react';
12
+ import {
13
+ ArrowLeftIcon,
14
+ PlusIcon,
15
+ TrashIcon,
16
+ ArrowUturnLeftIcon,
17
+ PencilSquareIcon,
18
+ } from '@heroicons/react/24/solid';
19
+ import { errorToast, successToast } from '@lib/components/toast';
20
+ import {
21
+ ActionButton,
22
+ ActionForm,
23
+ Button,
24
+ Checkbox,
25
+ cn,
26
+ Content,
27
+ Divider,
28
+ IconButton,
29
+ InfoTip,
30
+ Label,
31
+ ProgressButton,
32
+ Select,
33
+ TextInput,
34
+ ToggleGroup,
35
+ } from '@lib/components/ui';
36
+ import {
37
+ RelationshipKinds,
38
+ relationshipConstraints,
39
+ relationshipConstraintsInverse,
40
+ } from '@lib/types';
41
+ import {
42
+ CheckedDataType,
43
+ DBAttr,
44
+ InstantIndexingJob,
45
+ InstantIndexingJobInvalidTriple,
46
+ SchemaAttr,
47
+ SchemaNamespace,
48
+ } from '@lib/types';
49
+ import {
50
+ createJob,
51
+ jobFetchLoop,
52
+ jobIsCompleted,
53
+ jobIsErrored,
54
+ } from '@lib/utils/indexingJobs';
55
+ import { EditSchemaScreen, useExplorerProps, useExplorerState } from './index';
56
+ import { useClose } from '@headlessui/react';
57
+ import {
58
+ PendingJob,
59
+ useEditBlobConstraints,
60
+ } from '@lib/hooks/useEditBlobConstraints';
61
+ import { RecentlyDeletedAttrs } from './recently-deleted';
62
+ import { useAttrNotes } from '@lib/hooks/useAttrNotes';
63
+ import { createRenameNamespaceOps } from '@lib/utils/renames';
64
+ import { useSWRConfig } from 'swr';
65
+
66
+ export function EditNamespaceDialog({
67
+ db,
68
+ namespace,
69
+ namespaces,
70
+ onClose,
71
+ isSystemCatalogNs,
72
+ screen,
73
+ onScreenChange,
74
+ }: {
75
+ db: InstantReactWebDatabase<any>;
76
+ namespace: SchemaNamespace;
77
+ namespaces: SchemaNamespace[];
78
+ onClose: (p?: { ok: boolean }) => void;
79
+ readOnly: boolean;
80
+ isSystemCatalogNs: boolean;
81
+ screen: EditSchemaScreen;
82
+ onScreenChange: (screen: EditSchemaScreen) => void;
83
+ }) {
84
+ const props = useExplorerProps();
85
+ const appId = props.appId;
86
+ const { history, explorerState } = useExplorerState();
87
+ const { mutate } = useSWRConfig();
88
+
89
+ const [isDeleting, setIsDeleting] = useState(false);
90
+
91
+ const setScreen = (s: EditSchemaScreen) => {
92
+ setIsDeleting(false);
93
+ onScreenChange(s);
94
+ };
95
+
96
+ const [renameNsInput, setRenameNsInput] = useState(namespace.name);
97
+ const [renameNsErrorText, setRenameNsErrorText] = useState<string | null>(
98
+ null,
99
+ );
100
+
101
+ async function deleteNs() {
102
+ const ops = namespace.attrs.map((attr) => ['delete-attr', attr.id]);
103
+ await db.core._reactor.pushOps(ops);
104
+ // update the recently deleted attr cache
105
+ setTimeout(() => {
106
+ mutate(['recently-deleted', appId]);
107
+ }, 500);
108
+ onClose({ ok: true });
109
+ }
110
+
111
+ async function renameNs(newName: string) {
112
+ if (newName.startsWith('$')) {
113
+ setRenameNsErrorText('Namespace name cannot start with $');
114
+ return;
115
+ }
116
+
117
+ const ops = createRenameNamespaceOps(newName, namespace, namespaces);
118
+
119
+ await db.core._reactor.pushOps(ops);
120
+ history.push(
121
+ {
122
+ namespace: newName,
123
+ },
124
+ true,
125
+ );
126
+ successToast('Renamed namespace to ' + newName);
127
+ setRenameNsInput('');
128
+ setScreen({ kind: 'main' });
129
+ }
130
+
131
+ const notes = useAttrNotes();
132
+
133
+ const screenAttr = useMemo(() => {
134
+ if (screen.kind !== 'edit-attr') return undefined;
135
+ return namespace.attrs.find(
136
+ (a) => a.id === screen.attrId && a.isForward === screen.isForward,
137
+ );
138
+ }, [
139
+ screen.kind === 'edit-attr' ? screen.attrId : null,
140
+ screen.kind === 'edit-attr' ? screen.isForward : null,
141
+ namespace.attrs,
142
+ ]);
143
+
144
+ return isDeleting ? (
145
+ <DeleteForm
146
+ name={namespace.name}
147
+ type="namespace"
148
+ onClose={onClose}
149
+ onConfirm={deleteNs}
150
+ />
151
+ ) : screen.kind === 'rename' ? (
152
+ <div className="px-2">
153
+ <button
154
+ onClick={() => {
155
+ setScreen({ kind: 'main' });
156
+ }}
157
+ className="mb-3"
158
+ >
159
+ <ArrowLeftIcon className="h-4 w-4 cursor-pointer" />
160
+ </button>
161
+ <h6 className="text-md pb-2 font-bold">Rename {namespace.name}</h6>
162
+ <form
163
+ onSubmit={(e) => {
164
+ e.preventDefault();
165
+ renameNs(renameNsInput);
166
+ }}
167
+ >
168
+ <Content className="pb-2 text-sm">
169
+ This will immediately rename the namespace. You'll need to{' '}
170
+ <strong className="dark:text-white">update your code</strong> to the
171
+ new name.
172
+ </Content>
173
+ <TextInput
174
+ disabled={isSystemCatalogNs}
175
+ value={renameNsInput}
176
+ onChange={(n) => setRenameNsInput(n)}
177
+ />
178
+ <div className="flex flex-col gap-2 rounded-sm py-2">
179
+ <Button
180
+ type="submit"
181
+ disabled={
182
+ renameNsInput.startsWith('$') || renameNsInput.length === 0
183
+ }
184
+ >
185
+ Rename {namespace.name} → {renameNsInput}
186
+ </Button>
187
+ </div>
188
+ </form>
189
+ </div>
190
+ ) : screen.kind === 'main' ? (
191
+ <div className="flex flex-col gap-4 px-2">
192
+ <div className="mr-8 flex gap-1">
193
+ <h5 className="flex items-center text-lg font-bold">
194
+ {namespace.name}
195
+ </h5>
196
+ <IconButton
197
+ variant="subtle"
198
+ onClick={() => {
199
+ setScreen({ kind: 'rename' });
200
+ }}
201
+ icon={
202
+ <PencilSquareIcon className="h-4 w-4 opacity-50"></PencilSquareIcon>
203
+ }
204
+ label="Rename"
205
+ ></IconButton>
206
+
207
+ <Button
208
+ className="ml-4"
209
+ disabled={isSystemCatalogNs}
210
+ title={
211
+ isSystemCatalogNs
212
+ ? `The ${namespace.name} namespace can't be deleted.`
213
+ : undefined
214
+ }
215
+ size="mini"
216
+ variant="secondary"
217
+ onClick={() => setIsDeleting(true)}
218
+ >
219
+ <TrashIcon className="inline" height="1rem" />
220
+ Delete
221
+ </Button>
222
+ </div>
223
+
224
+ <div className="flex flex-col gap-2">
225
+ {namespace.attrs.map((attr) => (
226
+ <div key={attr.id + '-' + attr.name} className="flex justify-between">
227
+ <div className="flex items-center gap-3">
228
+ <span className="py-0.5 font-bold">{attr.name}</span>
229
+ {notes.notes[attr.id]?.message && (
230
+ <InfoTip>
231
+ <div className="px-2 text-xs text-gray-500 dark:text-neutral-400">
232
+ {notes.notes[attr.id].message}
233
+ </div>
234
+ </InfoTip>
235
+ )}
236
+ </div>
237
+ {attr.name !== 'id' ? (
238
+ <Button
239
+ className="px-2"
240
+ size="mini"
241
+ variant="subtle"
242
+ onClick={() => {
243
+ notes.removeNote(attr.id);
244
+ setScreen({
245
+ kind: 'edit-attr',
246
+ attrId: attr.id,
247
+ isForward: attr.isForward,
248
+ });
249
+ }}
250
+ >
251
+ Edit
252
+ </Button>
253
+ ) : null}
254
+ </div>
255
+ ))}
256
+ </div>
257
+
258
+ <div>
259
+ <Button
260
+ size="mini"
261
+ variant="secondary"
262
+ onClick={() => setScreen({ kind: 'add-attr', attrKind: 'data' })}
263
+ >
264
+ <PlusIcon className="inline" height="12px" />
265
+ New attribute
266
+ </Button>
267
+ </div>
268
+ <RecentlyDeletedAttrs
269
+ notes={notes}
270
+ db={db}
271
+ appId={appId}
272
+ namespace={namespace}
273
+ />
274
+ </div>
275
+ ) : screen.kind === 'add-attr' ? (
276
+ <AddAttrForm
277
+ db={db}
278
+ namespace={namespace}
279
+ namespaces={namespaces}
280
+ onClose={() => setScreen({ kind: 'main' })}
281
+ constraints={getSystemConstraints({
282
+ namespaceName: namespace.name,
283
+ isSystemCatalogNs,
284
+ })}
285
+ attrType={screen.attrKind === 'link' ? 'ref' : 'blob'}
286
+ onAttrTypeChange={(t) =>
287
+ onScreenChange({
288
+ kind: 'add-attr',
289
+ attrKind: t === 'ref' ? 'link' : 'data',
290
+ })
291
+ }
292
+ />
293
+ ) : screen.kind === 'edit-attr' && screenAttr ? (
294
+ <EditAttrForm
295
+ db={db}
296
+ attr={screenAttr}
297
+ onClose={() => setScreen({ kind: 'main' })}
298
+ constraints={getSystemConstraints({
299
+ namespaceName: namespace.name,
300
+ isSystemCatalogNs: isSystemCatalogNs,
301
+ attr: screenAttr,
302
+ })}
303
+ />
304
+ ) : null;
305
+ }
306
+
307
+ function DeleteForm({
308
+ name,
309
+ type,
310
+ onClose,
311
+ onConfirm,
312
+ }: {
313
+ name: string;
314
+ type: 'namespace' | 'attribute';
315
+ onClose: () => void;
316
+ onConfirm: () => void;
317
+ }) {
318
+ return (
319
+ <ActionForm className="min flex flex-col gap-4">
320
+ <h5 className="flex items-center gap-2 text-lg font-bold">
321
+ <ArrowLeftIcon
322
+ height="1rem"
323
+ className="cursor-pointer"
324
+ onClick={() => onClose()}
325
+ />
326
+ Delete {name}
327
+ </h5>
328
+
329
+ <div className="flex flex-col gap-2">
330
+ <p className="pb-2">
331
+ Are you sure you want to delete the <strong>{name}</strong> {type}?
332
+ </p>
333
+ <ActionButton
334
+ variant="destructive"
335
+ label={`Delete ${name}`}
336
+ submitLabel="Deleting..."
337
+ errorMessage="Failed to delete"
338
+ onClick={onConfirm}
339
+ />
340
+ </div>
341
+ </ActionForm>
342
+ );
343
+ }
344
+
345
+ function AddAttrForm({
346
+ db,
347
+ namespace,
348
+ namespaces,
349
+ onClose,
350
+ constraints,
351
+ attrType,
352
+ onAttrTypeChange,
353
+ }: {
354
+ db: InstantReactWebDatabase<any>;
355
+ namespace: SchemaNamespace;
356
+ namespaces: SchemaNamespace[];
357
+ onClose: () => void;
358
+ constraints: SystemConstraints;
359
+ attrType: 'blob' | 'ref';
360
+ onAttrTypeChange: (attrType: 'blob' | 'ref') => void;
361
+ }) {
362
+ const [isRequired, setIsRequired] = useState(false);
363
+ const [isIndex, setIsIndex] = useState(false);
364
+ const [isUniq, setIsUniq] = useState(false);
365
+ const [isCascade, setIsCascade] = useState(false);
366
+ const [isCascadeReverse, setIsCascadeReverse] = useState(false);
367
+ const [checkedDataType, setCheckedDataType] =
368
+ useState<CheckedDataType | null>(null);
369
+ const [relationship, setRelationship] =
370
+ useState<RelationshipKinds>('many-many');
371
+
372
+ const [reverseNamespace, setReverseNamespace] = useState<
373
+ SchemaNamespace | undefined
374
+ >(() => namespaces.find((n) => n.name !== namespace.name) ?? namespaces[0]);
375
+ const [attrName, setAttrName] = useState('');
376
+ const [reverseAttrName, setReverseAttrName] = useState(namespace.name);
377
+
378
+ const isCascadeAllowed =
379
+ relationship === 'one-one' || relationship === 'one-many';
380
+ const isCascadeReverseAllowed =
381
+ relationship === 'one-one' || relationship === 'many-one';
382
+
383
+ const linkValidation = validateLink({
384
+ attrName,
385
+ reverseAttrName,
386
+ namespaceName: namespace.name,
387
+ reverseNamespaceName: reverseNamespace?.name,
388
+ });
389
+
390
+ const canSubmit = attrType === 'blob' ? attrName : linkValidation.isValidLink;
391
+
392
+ useEffect(() => {
393
+ if (attrType !== 'ref') return;
394
+ if (!reverseNamespace) return;
395
+
396
+ const isSelfLink = reverseNamespace.name === namespace.name;
397
+ setAttrName(isSelfLink ? 'parent' : reverseNamespace.name);
398
+ setReverseAttrName(isSelfLink ? 'children' : namespace.name);
399
+ if (isSelfLink) {
400
+ setRelationship('one-many');
401
+ }
402
+ }, [attrType, reverseNamespace]);
403
+
404
+ async function addAttr() {
405
+ if (attrType === 'blob') {
406
+ const attr: DBAttr = {
407
+ id: id(),
408
+ 'forward-identity': [id(), namespace.name, attrName],
409
+ 'value-type': 'blob',
410
+ cardinality: 'one',
411
+ 'unique?': isUniq,
412
+ 'index?': isIndex,
413
+ 'required?': isRequired,
414
+ 'checked-data-type': checkedDataType ?? undefined,
415
+ };
416
+
417
+ const ops = [['add-attr', attr]];
418
+ await db._core._reactor.pushOps(ops);
419
+ onClose();
420
+ } else {
421
+ // invariants
422
+ if (!reverseNamespace) throw new Error('No reverse namespace');
423
+
424
+ const attr: DBAttr = {
425
+ id: id(),
426
+ ...relationshipConstraints[relationship],
427
+ 'forward-identity': [id(), namespace.name, attrName],
428
+ 'reverse-identity': [id(), reverseNamespace.name, reverseAttrName],
429
+ 'value-type': 'ref',
430
+ 'index?': false,
431
+ 'required?': isRequired,
432
+ 'on-delete': isCascadeAllowed && isCascade ? 'cascade' : undefined,
433
+ 'on-delete-reverse':
434
+ isCascadeReverseAllowed && isCascadeReverse ? 'cascade' : undefined,
435
+ };
436
+
437
+ const ops = [['add-attr', attr]];
438
+ await db._core._reactor.pushOps(ops);
439
+ onClose();
440
+ }
441
+ }
442
+
443
+ return (
444
+ <ActionForm className="min flex flex-col gap-4">
445
+ <h5 className="flex items-center gap-2 text-lg font-bold">
446
+ <ArrowLeftIcon className="h-4 w-4 cursor-pointer" onClick={onClose} />
447
+ Add an attribute
448
+ </h5>
449
+
450
+ <div className="flex flex-col gap-1">
451
+ <h6 className="text-md font-bold">Type</h6>
452
+ <ToggleGroup
453
+ ariaLabel="Text alignment"
454
+ selectedId={attrType}
455
+ items={[
456
+ { id: 'blob', label: 'Data' },
457
+ { id: 'ref', label: 'Link' },
458
+ ]}
459
+ onChange={(item) => onAttrTypeChange(item.id as 'blob' | 'ref')}
460
+ />
461
+ </div>
462
+ {attrType === 'blob' ? (
463
+ <>
464
+ <div className="flex flex-1 flex-col gap-1">
465
+ <h6 className="text-md font-bold">Name</h6>
466
+ <TextInput value={attrName} onChange={(n) => setAttrName(n)} />
467
+ </div>
468
+ <div className="flex flex-col gap-2">
469
+ <h6 className="text-md font-bold">Constraints</h6>
470
+ <div className="flex gap-2">
471
+ <Checkbox
472
+ disabled={constraints.require.disabled}
473
+ checked={isRequired}
474
+ onChange={(enabled) => setIsRequired(enabled)}
475
+ label={
476
+ <span>
477
+ <strong>Require this attribute</strong> so all entities will
478
+ be guaranteed to have it
479
+ </span>
480
+ }
481
+ title={constraints.require.message}
482
+ />
483
+ </div>
484
+ <div className="flex gap-2">
485
+ <Checkbox
486
+ checked={isIndex}
487
+ onChange={(enabled) => setIsIndex(enabled)}
488
+ label={
489
+ <span>
490
+ <strong>Index this attribute</strong> to improve lookup
491
+ performance of values
492
+ </span>
493
+ }
494
+ />
495
+ </div>
496
+ <div className="flex gap-2">
497
+ <Checkbox
498
+ checked={isUniq}
499
+ onChange={(enabled) => setIsUniq(enabled)}
500
+ label={
501
+ <span>
502
+ <strong>Enforce uniqueness</strong> so no two entities can
503
+ have the same value for this attribute
504
+ </span>
505
+ }
506
+ />
507
+ </div>
508
+ </div>
509
+ <div className="flex flex-col gap-2">
510
+ <h6 className="text-md font-bold">Enforce type</h6>
511
+ <div className="flex gap-2">
512
+ <Select<CheckedDataType | 'none'>
513
+ value={checkedDataType || 'none'}
514
+ onChange={(v) => {
515
+ if (!v) {
516
+ return;
517
+ }
518
+ const { value } = v;
519
+ if (value === 'none') {
520
+ setCheckedDataType(null);
521
+ }
522
+ setCheckedDataType(value as CheckedDataType);
523
+ }}
524
+ options={[
525
+ {
526
+ label: 'Any (not enforced)',
527
+ value: 'none',
528
+ },
529
+ {
530
+ label: 'String',
531
+ value: 'string',
532
+ },
533
+ {
534
+ label: 'Number',
535
+ value: 'number',
536
+ },
537
+ {
538
+ label: 'Boolean',
539
+ value: 'boolean',
540
+ },
541
+ {
542
+ label: 'Date',
543
+ value: 'date',
544
+ },
545
+ ]}
546
+ />
547
+ </div>
548
+ </div>
549
+ </>
550
+ ) : attrType === 'ref' ? (
551
+ <>
552
+ <div className="flex flex-col gap-1">
553
+ <h6 className="text-md font-bold">Link to namespace</h6>
554
+ <Select
555
+ value={reverseNamespace?.id ?? undefined}
556
+ options={namespaces.map((ns) => {
557
+ const label =
558
+ ns.name + (ns.name === namespace.name ? ' (self-link)' : '');
559
+ return {
560
+ label,
561
+ value: ns.id,
562
+ };
563
+ })}
564
+ onChange={(item) => {
565
+ if (!item) return;
566
+ const ns = namespaces.find((n) => n.id === item.value);
567
+
568
+ setReverseNamespace(ns);
569
+ }}
570
+ />
571
+ </div>
572
+
573
+ <RelationshipConfigurator
574
+ relationship={relationship}
575
+ attrName={attrName}
576
+ reverseAttrName={reverseAttrName}
577
+ namespaceName={namespace.name}
578
+ reverseNamespaceName={reverseNamespace?.name}
579
+ setAttrName={setAttrName}
580
+ setReverseAttrName={setReverseAttrName}
581
+ setRelationship={setRelationship}
582
+ isCascadeAllowed={isCascadeAllowed}
583
+ isCascade={isCascade}
584
+ setIsCascade={setIsCascade}
585
+ isCascadeReverseAllowed={isCascadeReverseAllowed}
586
+ isCascadeReverse={isCascadeReverse}
587
+ setIsCascadeReverse={setIsCascadeReverse}
588
+ isRequired={isRequired}
589
+ setIsRequired={setIsRequired}
590
+ constraints={constraints}
591
+ />
592
+ </>
593
+ ) : null}
594
+
595
+ <div className="flex flex-col gap-2">
596
+ <ActionButton
597
+ type="submit"
598
+ label="Create attribute"
599
+ submitLabel="Creating attribute..."
600
+ errorMessage="Failed to create attribute"
601
+ disabled={!canSubmit}
602
+ className="border-gray-500 disabled:opacity-20"
603
+ onClick={addAttr}
604
+ />
605
+ {linkValidation.shouldShowSelfLinkNameError ? (
606
+ <span className="text-red-500">
607
+ Self-links must have different attribute names.
608
+ </span>
609
+ ) : null}
610
+ </div>
611
+ </ActionForm>
612
+ );
613
+ }
614
+
615
+ function jobWorkingStatus(job: InstantIndexingJob | null) {
616
+ if (
617
+ !job ||
618
+ (job.job_status !== 'processing' && job.job_status !== 'waiting')
619
+ ) {
620
+ return;
621
+ }
622
+
623
+ if (job.job_status === 'waiting') {
624
+ return 'Waiting for worker...';
625
+ }
626
+
627
+ if (!job.work_estimate) {
628
+ return 'Estimating work...';
629
+ }
630
+
631
+ const completed = Math.min(job.work_estimate, job.work_completed || 0);
632
+
633
+ const percent = Math.floor((completed / job.work_estimate) * 100);
634
+
635
+ return `${percent}% complete...`;
636
+ }
637
+
638
+ function InvalidTriplesSample({
639
+ indexingJob,
640
+ attr,
641
+ onClickSample,
642
+ }: {
643
+ indexingJob: InstantIndexingJob | null;
644
+ attr: SchemaAttr;
645
+ onClickSample: (triple: InstantIndexingJobInvalidTriple) => void;
646
+ }) {
647
+ if (!indexingJob?.invalid_triples_sample?.length) {
648
+ return;
649
+ }
650
+ return (
651
+ <div>
652
+ Here are the first few invalid entities we found:
653
+ <table className="dark:text-netural-500 mx-2 my-2 flex-1 text-left font-mono text-xs text-gray-500">
654
+ <thead className="bg-white text-gray-700 dark:bg-neutral-800 dark:text-white">
655
+ <tr>
656
+ <th className="pr-2">id</th>
657
+ <th className="max-w-fit pr-2">{attr.name}</th>
658
+ <th className="pr-2">type</th>
659
+ </tr>
660
+ </thead>
661
+ <tbody>
662
+ {indexingJob.invalid_triples_sample.slice(0, 3).map((t, i) => (
663
+ <tr
664
+ key={i}
665
+ className="cursor-pointer rounded-md px-2 whitespace-nowrap hover:bg-gray-200"
666
+ onClick={() => onClickSample(t)}
667
+ >
668
+ <td className="pr-2">
669
+ <pre>{t.entity_id}</pre>
670
+ </td>
671
+ <td className="truncate pr-2" style={{ maxWidth: '12rem' }}>
672
+ {JSON.stringify(t.value)}
673
+ </td>
674
+ <td className="pr-2">{t.json_type}</td>
675
+ </tr>
676
+ ))}
677
+ </tbody>
678
+ </table>
679
+ </div>
680
+ );
681
+ }
682
+
683
+ function IndexingJobError({
684
+ indexingJob,
685
+ attr,
686
+ onClose,
687
+ }: {
688
+ indexingJob?: InstantIndexingJob | null;
689
+ attr: SchemaAttr;
690
+ onClose: () => void;
691
+ }) {
692
+ const { history } = useExplorerState();
693
+ if (!indexingJob) return;
694
+ if (indexingJob.error === 'missing-required-error') {
695
+ return (
696
+ <div className="mt-2 mb-2 border-l-2 border-l-red-500 pl-2">
697
+ <div>
698
+ {indexingJob.error_data?.count} <code>{attr.namespace}</code>{' '}
699
+ {indexingJob.error_data?.count === 1 ? 'entity does' : 'entities do'}{' '}
700
+ not have <code>{attr.name}</code> set.
701
+ </div>
702
+ <InvalidTriplesSample
703
+ indexingJob={{
704
+ ...indexingJob,
705
+ invalid_triples_sample:
706
+ indexingJob.error_data &&
707
+ indexingJob.error_data['entity-ids']?.map((id) => ({
708
+ entity_id: String(id),
709
+ value: null,
710
+ json_type: attr.checkedDataType || 'null',
711
+ })),
712
+ }}
713
+ attr={attr}
714
+ onClickSample={(t) => {
715
+ history.push({
716
+ namespace: attr.namespace,
717
+ where: ['id', t.entity_id],
718
+ });
719
+ // It would be nice to have a way to minimize the dialog so you could go back
720
+ onClose();
721
+ }}
722
+ />
723
+ </div>
724
+ );
725
+ }
726
+
727
+ if (indexingJob.error === 'triple-too-large-error') {
728
+ return (
729
+ <div className="mt-2 mb-2 border-l-2 border-l-red-500 pl-2">
730
+ <div>Some of the existing data is too large to index. </div>
731
+ <InvalidTriplesSample
732
+ indexingJob={indexingJob}
733
+ attr={attr}
734
+ onClickSample={(t) => {
735
+ history.push({
736
+ namespace: attr.namespace,
737
+ where: ['id', t.entity_id],
738
+ });
739
+ // It would be nice to have a way to minimize the dialog so you could go back
740
+ onClose();
741
+ }}
742
+ />
743
+ </div>
744
+ );
745
+ }
746
+
747
+ if (indexingJob.error === 'invalid-triple-error') {
748
+ return (
749
+ <div className="mt-2 mb-2 border-l-2 border-l-red-500 pl-2">
750
+ <div>
751
+ The type can't be set to {indexingJob?.checked_data_type} because some
752
+ data is the wrong type.
753
+ </div>
754
+ <InvalidTriplesSample
755
+ indexingJob={indexingJob}
756
+ attr={attr}
757
+ onClickSample={(t) => {
758
+ history.push({
759
+ namespace: attr.namespace,
760
+ where: ['id', t.entity_id],
761
+ });
762
+ // It would be nice to have a way to minimize the dialog so you could go back
763
+ onClose();
764
+ }}
765
+ />
766
+ </div>
767
+ );
768
+ }
769
+
770
+ if (indexingJob.error === 'triple-not-unique-error') {
771
+ return (
772
+ <div className="mt-2 mb-2 border-l-2 border-l-red-500 pl-2">
773
+ <div>Some of the existing data is not unique. </div>
774
+ {indexingJob.invalid_unique_value != null ? (
775
+ <div>
776
+ Found{' '}
777
+ <span
778
+ className={
779
+ typeof indexingJob.invalid_unique_value === 'object'
780
+ ? ''
781
+ : 'cursor-pointer underline'
782
+ }
783
+ onClick={
784
+ typeof indexingJob.invalid_unique_value === 'object'
785
+ ? undefined
786
+ : () => {
787
+ history.push({
788
+ namespace: attr.namespace,
789
+ where: [attr.name, indexingJob.invalid_unique_value],
790
+ });
791
+ onClose();
792
+ }
793
+ }
794
+ >
795
+ multiple entities with value{' '}
796
+ <code>{JSON.stringify(indexingJob.invalid_unique_value)}</code>
797
+ </span>
798
+ .
799
+ </div>
800
+ ) : null}
801
+ <InvalidTriplesSample
802
+ indexingJob={indexingJob}
803
+ attr={attr}
804
+ onClickSample={(t) => {
805
+ history.push({
806
+ namespace: attr.namespace,
807
+ where: ['id', t.entity_id],
808
+ });
809
+ onClose();
810
+ }}
811
+ />
812
+ </div>
813
+ );
814
+ }
815
+ // Catchall for unexpected errors
816
+ if (indexingJob.error) {
817
+ return (
818
+ <div className="mt-2 mb-2 space-y-2 border-l-2 border-l-red-500 pl-2">
819
+ <div>
820
+ An unexpected error occured while changing constraints. Please share
821
+ these details with the administrator of your server:
822
+ </div>
823
+ <pre>id: "{indexingJob.id}"</pre>
824
+ </div>
825
+ );
826
+ }
827
+ }
828
+
829
+ function RelationshipConfigurator({
830
+ attrName,
831
+ reverseAttrName,
832
+ namespaceName,
833
+ reverseNamespaceName,
834
+ relationship,
835
+ setAttrName,
836
+ setReverseAttrName,
837
+ setRelationship,
838
+ isCascade,
839
+ setIsCascade,
840
+ isCascadeAllowed,
841
+ isCascadeReverse,
842
+ setIsCascadeReverse,
843
+ isCascadeReverseAllowed,
844
+ isRequired,
845
+ setIsRequired,
846
+ constraints,
847
+ }: {
848
+ relationship: RelationshipKinds;
849
+ reverseNamespaceName: string | undefined;
850
+ attrName: string;
851
+ reverseAttrName: string;
852
+ namespaceName: string;
853
+
854
+ setAttrName: (n: string) => void;
855
+ setReverseAttrName: (n: string) => void;
856
+ setRelationship: (n: RelationshipKinds) => void;
857
+
858
+ isCascadeAllowed: boolean;
859
+ isCascade: boolean;
860
+ setIsCascade: (n: boolean) => void;
861
+
862
+ isCascadeReverseAllowed: boolean;
863
+ isCascadeReverse: boolean;
864
+ setIsCascadeReverse: (n: boolean) => void;
865
+
866
+ isRequired: boolean;
867
+ setIsRequired: (n: boolean) => void;
868
+ constraints: SystemConstraints;
869
+ }) {
870
+ const isFullLink = attrName && reverseNamespaceName && reverseAttrName;
871
+
872
+ return (
873
+ <>
874
+ <div className="flex flex-col gap-4 md:flex-row md:gap-2">
875
+ <div className="flex flex-1 flex-col gap-1">
876
+ <h6 className="text-md font-bold">Forward attribute name</h6>
877
+ <TextInput
878
+ disabled={constraints.attr.disabled}
879
+ title={constraints.attr.message}
880
+ value={attrName}
881
+ onChange={(n) => setAttrName(n)}
882
+ />
883
+ <div className="rounded-xs py-0.5 text-xs text-gray-500 dark:text-neutral-400">
884
+ {isFullLink ? (
885
+ <>
886
+ <strong>
887
+ {namespaceName}.{attrName}
888
+ </strong>{' '}
889
+ will link to <strong>{reverseNamespaceName}</strong>
890
+ </>
891
+ ) : (
892
+ <>&nbsp;</>
893
+ )}
894
+ </div>
895
+ </div>
896
+
897
+ <div className="flex flex-1 flex-col gap-1">
898
+ <h6 className="text-md font-bold">Reverse attribute name</h6>
899
+ <TextInput
900
+ disabled={constraints.attr.disabled}
901
+ title={constraints.attr.message}
902
+ value={reverseAttrName}
903
+ onChange={(n) => setReverseAttrName(n)}
904
+ />
905
+ <div className="rounded-xs py-0.5 text-xs text-gray-500 dark:text-neutral-400">
906
+ {isFullLink ? (
907
+ <>
908
+ <strong>
909
+ {reverseNamespaceName}.{reverseAttrName}
910
+ </strong>{' '}
911
+ will link to <strong>{namespaceName}</strong>
912
+ </>
913
+ ) : (
914
+ <>&nbsp;</>
915
+ )}
916
+ </div>
917
+ </div>
918
+ </div>
919
+
920
+ <div className="flex flex-col gap-1">
921
+ <h6 className="text-md font-bold">Relationship</h6>
922
+ <RelationshipSelect
923
+ disabled={!isFullLink || constraints.attr.disabled}
924
+ value={relationship}
925
+ onChange={(v) => {
926
+ setRelationship(v.value);
927
+ }}
928
+ namespace={namespaceName}
929
+ reverseNamespace={reverseNamespaceName ?? ''}
930
+ attr={attrName}
931
+ reverseAttr={reverseAttrName}
932
+ title={
933
+ constraints.attr.disabled ? constraints.attr.message : undefined
934
+ }
935
+ />
936
+ <div
937
+ className={
938
+ 'text-xs wrap-break-word text-gray-500 dark:text-neutral-400'
939
+ }
940
+ >
941
+ {isFullLink ? (
942
+ relationshipDescriptions[relationship](
943
+ namespaceName,
944
+ reverseNamespaceName,
945
+ attrName,
946
+ reverseAttrName,
947
+ )
948
+ ) : (
949
+ <>&nbsp;</>
950
+ )}
951
+ </div>
952
+ </div>
953
+
954
+ <div className="flex gap-2">
955
+ <Checkbox
956
+ checked={isCascadeAllowed && isCascade}
957
+ disabled={!isCascadeAllowed || constraints.attr.disabled}
958
+ onChange={setIsCascade}
959
+ title={constraints.attr.message}
960
+ label={
961
+ <span className="dark:text-neutral-200">
962
+ <div>
963
+ <strong>
964
+ Cascade Delete {reverseNamespaceName} → {namespaceName}
965
+ </strong>
966
+ </div>
967
+ When a <strong>{reverseNamespaceName}</strong> entity is deleted,
968
+ all linked <strong>{namespaceName}</strong> will be deleted
969
+ automatically
970
+ </span>
971
+ }
972
+ />
973
+ </div>
974
+
975
+ <div className="flex gap-2">
976
+ <Checkbox
977
+ checked={isCascadeReverseAllowed && isCascadeReverse}
978
+ disabled={!isCascadeReverseAllowed || constraints.attr.disabled}
979
+ onChange={setIsCascadeReverse}
980
+ title={constraints.attr.message}
981
+ label={
982
+ <span className="dark:text-neutral-200">
983
+ <div>
984
+ <strong>
985
+ Cascade Delete {namespaceName} → {reverseNamespaceName}
986
+ </strong>
987
+ </div>
988
+ When a <strong>{namespaceName}</strong> entity is deleted, all
989
+ linked <strong>{reverseNamespaceName}</strong> will be deleted
990
+ automatically
991
+ </span>
992
+ }
993
+ />
994
+ </div>
995
+
996
+ <div className="flex flex-col gap-1">
997
+ <h6 className="text-md font-bold">Constraints</h6>
998
+ <div className="flex gap-2">
999
+ <Checkbox
1000
+ disabled={constraints.require.disabled}
1001
+ title={constraints.require.message}
1002
+ checked={isRequired}
1003
+ onChange={(enabled) => setIsRequired(enabled)}
1004
+ label={
1005
+ <span>
1006
+ <strong>Require this attribute</strong> so all entities will be
1007
+ guaranteed to have it
1008
+ </span>
1009
+ }
1010
+ />
1011
+ </div>
1012
+ </div>
1013
+ </>
1014
+ );
1015
+ }
1016
+
1017
+ function RelationshipSelect({
1018
+ value,
1019
+ disabled,
1020
+ onChange,
1021
+ namespace,
1022
+ attr,
1023
+ reverseNamespace,
1024
+ reverseAttr,
1025
+ title,
1026
+ }: {
1027
+ disabled?: boolean;
1028
+ value: RelationshipKinds;
1029
+ onChange: (v: { value: RelationshipKinds; label: string }) => void;
1030
+ namespace: string;
1031
+ attr: string;
1032
+ reverseNamespace: string;
1033
+ reverseAttr: string;
1034
+ title?: string;
1035
+ }) {
1036
+ return (
1037
+ <Select
1038
+ disabled={disabled}
1039
+ value={value}
1040
+ onChange={(v) => {
1041
+ if (!v) return;
1042
+
1043
+ onChange(v as { value: RelationshipKinds; label: string });
1044
+ }}
1045
+ options={[
1046
+ {
1047
+ label: 'Many-to-many',
1048
+ value: 'many-many',
1049
+ },
1050
+ {
1051
+ label: 'One-to-one',
1052
+ value: 'one-one',
1053
+ },
1054
+ {
1055
+ label: `${namespace} has-many ${
1056
+ attr || '---'
1057
+ } / ${reverseNamespace} has-one ${reverseAttr || '---'}`,
1058
+ value: 'many-one',
1059
+ },
1060
+ {
1061
+ label: `${namespace} has-one ${
1062
+ attr || '---'
1063
+ } / ${reverseNamespace} has-many ${reverseAttr || '---'}`,
1064
+ value: 'one-many',
1065
+ },
1066
+ ]}
1067
+ title={title}
1068
+ />
1069
+ );
1070
+ }
1071
+
1072
+ const relationshipDescriptions: Record<
1073
+ RelationshipKinds,
1074
+ (f: string, r: string, fa: string, ra: string) => ReactNode
1075
+ > = {
1076
+ 'many-many': (fn, rn, fa, ra) => (
1077
+ <>
1078
+ <strong>{fn}</strong> can have many <strong>{fa}</strong>, and{' '}
1079
+ <strong>{rn}</strong> can be associated with more than one{' '}
1080
+ <strong>{ra}</strong>
1081
+ </>
1082
+ ),
1083
+ 'one-one': (fn, rn, fa, ra) => (
1084
+ <>
1085
+ <strong>{fn}</strong> can have only one <strong>{fa}</strong>, and a{' '}
1086
+ <strong>{rn}</strong> can only have one <strong>{ra}</strong>
1087
+ </>
1088
+ ),
1089
+ 'many-one': (fn, rn, fa, ra) => (
1090
+ <>
1091
+ <strong>{fn}</strong> can have many <strong>{fa}</strong>, but{' '}
1092
+ <strong>{rn}</strong> can only have one <strong>{ra}</strong>
1093
+ </>
1094
+ ),
1095
+ 'one-many': (fn, rn, fa, ra) => (
1096
+ <>
1097
+ <strong>{fn}</strong> can have only one <strong>{fa}</strong>, but{' '}
1098
+ <strong>{rn}</strong> can be associated with more than one{' '}
1099
+ <strong>{ra}</strong>
1100
+ </>
1101
+ ),
1102
+ };
1103
+
1104
+ async function updateRequired({
1105
+ appId,
1106
+ attr,
1107
+ isRequired,
1108
+ authToken,
1109
+ setIndexingJob,
1110
+ stopFetchLoop,
1111
+ apiURI,
1112
+ }: {
1113
+ appId: string;
1114
+ attr: SchemaAttr;
1115
+ isRequired: boolean;
1116
+ authToken: string | undefined;
1117
+ setIndexingJob: (job: InstantIndexingJob) => void;
1118
+ apiURI: string;
1119
+ stopFetchLoop: MutableRefObject<null | (() => void)>;
1120
+ }) {
1121
+ if (!authToken || isRequired === attr.isRequired) {
1122
+ return;
1123
+ }
1124
+ stopFetchLoop.current?.();
1125
+ const friendlyName = `${attr.namespace}.${attr.name}`;
1126
+ try {
1127
+ const job = await createJob(
1128
+ {
1129
+ appId,
1130
+ attrId: attr.id,
1131
+ jobType: isRequired ? 'required' : 'remove-required',
1132
+ apiURI,
1133
+ },
1134
+ authToken,
1135
+ );
1136
+ setIndexingJob(job);
1137
+ const fetchLoop = jobFetchLoop(appId, job.id, authToken, apiURI);
1138
+ stopFetchLoop.current = fetchLoop.stop;
1139
+ const finishedJob = await fetchLoop.start((data, error) => {
1140
+ if (error) {
1141
+ errorToast(`Error while marking ${friendlyName} as required.`);
1142
+ }
1143
+ if (data) {
1144
+ setIndexingJob(data);
1145
+ }
1146
+ });
1147
+ if (finishedJob) {
1148
+ if (finishedJob.job_status === 'completed') {
1149
+ successToast(
1150
+ isRequired
1151
+ ? `Marked ${friendlyName} as required.`
1152
+ : `Marked ${friendlyName} as optional.`,
1153
+ );
1154
+ return 'completed';
1155
+ }
1156
+ if (finishedJob.job_status === 'canceled') {
1157
+ errorToast('Marking required was canceled.');
1158
+ return 'canceled';
1159
+ }
1160
+ if (finishedJob.job_status === 'errored') {
1161
+ if (finishedJob.error === 'invalid-triple-error') {
1162
+ errorToast(`Found invalid data while updating ${friendlyName}.`);
1163
+ } else {
1164
+ errorToast(`Encountered an error while updating ${friendlyName}.`);
1165
+ }
1166
+ return 'errored';
1167
+ }
1168
+ }
1169
+ } catch (e) {
1170
+ console.error(e);
1171
+ errorToast(`Unexpected error while updating ${friendlyName}`);
1172
+ return 'errored';
1173
+ }
1174
+ }
1175
+
1176
+ type BlobConstraintControlComponent<V> = (props: {
1177
+ pendingJob?: PendingJob;
1178
+ runningJob?: InstantIndexingJob;
1179
+ value: V;
1180
+ setValue: (v: V) => void;
1181
+ disabled: boolean;
1182
+ disabledReason?: string;
1183
+ attr: SchemaAttr;
1184
+ }) => JSX.Element;
1185
+
1186
+ const EditCheckedDataTypeControl: BlobConstraintControlComponent<
1187
+ CheckedDataType | 'any'
1188
+ > = ({
1189
+ pendingJob,
1190
+ runningJob,
1191
+ value,
1192
+ setValue,
1193
+ disabled,
1194
+ disabledReason,
1195
+ attr,
1196
+ }) => {
1197
+ const notRunning = !runningJob || jobIsCompleted(runningJob);
1198
+ const closeDialog = useClose();
1199
+
1200
+ // Revert to previous value if job errored
1201
+ useEffect(() => {
1202
+ if (runningJob && jobIsErrored(runningJob)) {
1203
+ setValue(attr.checkedDataType || 'any');
1204
+ }
1205
+ }, [runningJob]);
1206
+
1207
+ return (
1208
+ <>
1209
+ <div className="flex flex-col gap-2">
1210
+ <h6 className="text-md font-bold">
1211
+ Enforce type{' '}
1212
+ <InfoTip>
1213
+ <div className="w-48 text-sm">
1214
+ Checks the type on all existing entities and enforces the type
1215
+ when entities are created or updated.
1216
+ </div>
1217
+ </InfoTip>
1218
+ </h6>
1219
+ </div>
1220
+ <div className="flex items-center gap-2">
1221
+ <Select
1222
+ className={cn(
1223
+ pendingJob &&
1224
+ 'border-[#606AF4] ring-1 ring-[#606AF4] ring-inset focus:ring-[#606AF4]',
1225
+ )}
1226
+ disabled={disabled || (runningJob && !jobIsCompleted(runningJob))}
1227
+ title={disabled ? disabledReason : undefined}
1228
+ value={value}
1229
+ onChange={(v) => {
1230
+ if (!v) {
1231
+ return;
1232
+ }
1233
+ setValue(v.value as CheckedDataType | 'any');
1234
+ }}
1235
+ options={[
1236
+ {
1237
+ label: 'Any (not enforced)',
1238
+ value: 'any',
1239
+ },
1240
+ {
1241
+ label: 'String',
1242
+ value: 'string',
1243
+ },
1244
+ {
1245
+ label: 'Number',
1246
+ value: 'number',
1247
+ },
1248
+ {
1249
+ label: 'Boolean',
1250
+ value: 'boolean',
1251
+ },
1252
+ {
1253
+ label: 'Date',
1254
+ value: 'date',
1255
+ },
1256
+ ]}
1257
+ />
1258
+ {pendingJob && notRunning && (
1259
+ <ArrowUturnLeftIcon
1260
+ onClick={() => {
1261
+ setValue(attr.checkedDataType || 'any');
1262
+ }}
1263
+ height="1.2rem"
1264
+ className="cursor-pointer pr-2 text-[#606AF4]"
1265
+ />
1266
+ )}
1267
+ </div>
1268
+ {runningJob && jobIsErrored(runningJob) && (
1269
+ <IndexingJobError
1270
+ indexingJob={runningJob}
1271
+ attr={attr}
1272
+ onClose={closeDialog}
1273
+ />
1274
+ )}
1275
+ </>
1276
+ );
1277
+ };
1278
+
1279
+ const EditRequiredControl: BlobConstraintControlComponent<boolean> = ({
1280
+ pendingJob,
1281
+ runningJob,
1282
+ value,
1283
+ setValue,
1284
+ disabled,
1285
+ disabledReason,
1286
+ attr,
1287
+ }) => {
1288
+ const closeDialog = useClose();
1289
+
1290
+ // If job is errored, revert the value
1291
+ useEffect(() => {
1292
+ if (runningJob && jobIsErrored(runningJob)) {
1293
+ setValue(attr.isRequired || false);
1294
+ }
1295
+ }, [runningJob]);
1296
+
1297
+ return (
1298
+ <>
1299
+ <div className="flex justify-between">
1300
+ <Checkbox
1301
+ disabled={disabled || (runningJob && !jobIsCompleted(runningJob))}
1302
+ title={disabled ? disabledReason : undefined}
1303
+ checked={value}
1304
+ onChange={(enabled) => setValue(enabled)}
1305
+ label={
1306
+ <span
1307
+ className={cn(
1308
+ disabled || (runningJob && !jobIsCompleted(runningJob))
1309
+ ? 'cursor-default'
1310
+ : 'cursor-pointer',
1311
+ pendingJob && 'text-[#606AF4]',
1312
+ )}
1313
+ >
1314
+ <strong>Require this attribute</strong> so all entities will be
1315
+ guaranteed to have it
1316
+ </span>
1317
+ }
1318
+ />
1319
+ {pendingJob && (
1320
+ <ArrowUturnLeftIcon
1321
+ onClick={() => {
1322
+ setValue(!value);
1323
+ }}
1324
+ height="1.2rem"
1325
+ className="cursor-pointer pr-2 text-[#606AF4]"
1326
+ />
1327
+ )}
1328
+ </div>
1329
+ {runningJob && jobIsErrored(runningJob) && (
1330
+ <IndexingJobError
1331
+ indexingJob={runningJob}
1332
+ attr={attr}
1333
+ onClose={closeDialog}
1334
+ />
1335
+ )}
1336
+ </>
1337
+ );
1338
+ };
1339
+
1340
+ const EditIndexedControl: BlobConstraintControlComponent<boolean> = ({
1341
+ pendingJob,
1342
+ runningJob,
1343
+ value,
1344
+ setValue,
1345
+ disabled,
1346
+ disabledReason,
1347
+ attr,
1348
+ }) => {
1349
+ const closeDialog = useClose();
1350
+
1351
+ // If job is errored, revert the value
1352
+ useEffect(() => {
1353
+ if (runningJob && jobIsErrored(runningJob)) {
1354
+ setValue(attr.isIndex);
1355
+ }
1356
+ }, [runningJob]);
1357
+
1358
+ return (
1359
+ <>
1360
+ <div className="flex justify-between">
1361
+ <Checkbox
1362
+ disabled={disabled || (runningJob && !jobIsCompleted(runningJob))}
1363
+ title={disabled ? disabledReason : undefined}
1364
+ checked={value}
1365
+ onChange={(enabled) => setValue(enabled)}
1366
+ label={
1367
+ <span
1368
+ className={cn(
1369
+ disabled || (runningJob && !jobIsCompleted(runningJob))
1370
+ ? 'cursor-default'
1371
+ : 'cursor-pointer',
1372
+ pendingJob && 'text-[#606AF4]',
1373
+ )}
1374
+ >
1375
+ <strong>Index this attribute</strong> to improve lookup
1376
+ performance of values
1377
+ </span>
1378
+ }
1379
+ />
1380
+ {pendingJob && (
1381
+ <ArrowUturnLeftIcon
1382
+ onClick={() => {
1383
+ setValue(!value);
1384
+ }}
1385
+ height="1.2rem"
1386
+ className="cursor-pointer pr-2 text-[#606AF4]"
1387
+ />
1388
+ )}
1389
+ </div>
1390
+ {runningJob && jobIsErrored(runningJob) && (
1391
+ <IndexingJobError
1392
+ indexingJob={runningJob}
1393
+ attr={attr}
1394
+ onClose={closeDialog}
1395
+ />
1396
+ )}
1397
+ </>
1398
+ );
1399
+ };
1400
+
1401
+ const EditUniqueControl: BlobConstraintControlComponent<boolean> = ({
1402
+ pendingJob,
1403
+ runningJob,
1404
+ value,
1405
+ setValue,
1406
+ disabled,
1407
+ disabledReason,
1408
+ attr,
1409
+ }) => {
1410
+ const closeDialog = useClose();
1411
+
1412
+ // If job is errored, revert the value
1413
+ useEffect(() => {
1414
+ if (runningJob && jobIsErrored(runningJob)) {
1415
+ setValue(attr.isUniq);
1416
+ }
1417
+ }, [runningJob]);
1418
+
1419
+ return (
1420
+ <>
1421
+ <div className="flex justify-between">
1422
+ <Checkbox
1423
+ disabled={disabled || (runningJob && !jobIsCompleted(runningJob))}
1424
+ title={disabled ? disabledReason : undefined}
1425
+ checked={value}
1426
+ onChange={(enabled) => setValue(enabled)}
1427
+ label={
1428
+ <span
1429
+ className={cn(
1430
+ disabled || (runningJob && !jobIsCompleted(runningJob))
1431
+ ? 'cursor-default'
1432
+ : 'cursor-pointer',
1433
+ pendingJob && 'text-[#606AF4]',
1434
+ )}
1435
+ >
1436
+ <strong>Enforce uniqueness</strong> so no two entities can have
1437
+ the same value for this attribute
1438
+ </span>
1439
+ }
1440
+ />
1441
+ {pendingJob && (
1442
+ <ArrowUturnLeftIcon
1443
+ onClick={() => {
1444
+ setValue(!value);
1445
+ }}
1446
+ height="1.2rem"
1447
+ className="cursor-pointer pr-2 text-[#606AF4]"
1448
+ />
1449
+ )}
1450
+ </div>
1451
+ {runningJob && jobIsErrored(runningJob) && (
1452
+ <IndexingJobError
1453
+ indexingJob={runningJob}
1454
+ attr={attr}
1455
+ onClose={closeDialog}
1456
+ />
1457
+ )}
1458
+ </>
1459
+ );
1460
+ };
1461
+
1462
+ const EditBlobConstraints = ({
1463
+ appId,
1464
+ attr,
1465
+ constraints,
1466
+ }: {
1467
+ appId: string;
1468
+ attr: SchemaAttr;
1469
+ constraints: SystemConstraints;
1470
+ }) => {
1471
+ const [requiredChecked, setRequiredChecked] = useState(
1472
+ attr.isRequired || false,
1473
+ );
1474
+
1475
+ const [indexedChecked, setIndexedChecked] = useState(attr.isIndex);
1476
+
1477
+ const [uniqueChecked, setUniqueChecked] = useState(attr.isUniq);
1478
+
1479
+ const [checkedDataType, setCheckedDataType] = useState<
1480
+ CheckedDataType | 'any'
1481
+ >(attr.checkedDataType || 'any');
1482
+
1483
+ const explorerProps = useExplorerProps();
1484
+
1485
+ const { isPending, pending, apply, isRunning, running, progress } =
1486
+ useEditBlobConstraints({
1487
+ attr,
1488
+ appId,
1489
+ token: explorerProps.adminToken,
1490
+ isRequired: requiredChecked,
1491
+ isIndexed: indexedChecked,
1492
+ isUnique: uniqueChecked,
1493
+ checkedDataType,
1494
+ });
1495
+
1496
+ return (
1497
+ <div>
1498
+ <div className="flex flex-col gap-2">
1499
+ <h6 className="text-md font-bold">Constraints</h6>
1500
+ <EditRequiredControl
1501
+ pendingJob={pending.require}
1502
+ runningJob={running.require}
1503
+ value={requiredChecked}
1504
+ setValue={setRequiredChecked}
1505
+ disabled={constraints.require.disabled}
1506
+ disabledReason={constraints.require.message}
1507
+ attr={attr}
1508
+ />
1509
+ <EditIndexedControl
1510
+ pendingJob={pending.index}
1511
+ runningJob={running.index}
1512
+ value={indexedChecked}
1513
+ setValue={setIndexedChecked}
1514
+ disabled={constraints.attr.disabled}
1515
+ disabledReason={constraints.attr.message}
1516
+ attr={attr}
1517
+ />
1518
+ <EditUniqueControl
1519
+ pendingJob={pending.unique}
1520
+ runningJob={running.unique}
1521
+ value={uniqueChecked}
1522
+ setValue={setUniqueChecked}
1523
+ disabled={constraints.attr.disabled}
1524
+ disabledReason={constraints.attr.message}
1525
+ attr={attr}
1526
+ />
1527
+ <EditCheckedDataTypeControl
1528
+ pendingJob={pending.type}
1529
+ runningJob={running.type}
1530
+ value={checkedDataType}
1531
+ setValue={setCheckedDataType}
1532
+ disabled={constraints.attr.disabled}
1533
+ disabledReason={constraints.attr.message}
1534
+ attr={attr}
1535
+ />
1536
+ <ProgressButton
1537
+ loading={isRunning}
1538
+ percentage={!isRunning ? 0 : progress || 0}
1539
+ variant={isPending || isRunning ? 'primary' : 'secondary'}
1540
+ // Switching from primary <-> secondary changes height without this
1541
+ className="border"
1542
+ onClick={() => apply()}
1543
+ disabled={!isPending || isRunning}
1544
+ >
1545
+ {isRunning ? 'Updating Constraints...' : 'Update Constraints'}
1546
+ </ProgressButton>
1547
+ </div>
1548
+ </div>
1549
+ );
1550
+ };
1551
+
1552
+ function EditAttrForm({
1553
+ db,
1554
+ attr,
1555
+ onClose,
1556
+ constraints,
1557
+ }: {
1558
+ db: InstantReactWebDatabase<any>;
1559
+ attr: SchemaAttr;
1560
+ onClose: () => void;
1561
+ constraints: SystemConstraints;
1562
+ }) {
1563
+ const props = useExplorerProps();
1564
+ const appId = props.appId;
1565
+ const { mutate } = useSWRConfig();
1566
+ const [screen, setScreen] = useState<{ type: 'main' } | { type: 'delete' }>({
1567
+ type: 'main',
1568
+ });
1569
+
1570
+ const [attrName, setAttrName] = useState(attr.linkConfig.forward.attr);
1571
+ const [reverseAttrName, setReverseAttrName] = useState(
1572
+ attr.linkConfig.reverse?.attr,
1573
+ );
1574
+ const [relationship, setRelationship] = useState<RelationshipKinds>(() => {
1575
+ const relKey = `${attr.cardinality}-${attr.isUniq}`;
1576
+ const relKind = relationshipConstraintsInverse[relKey];
1577
+ return relKind;
1578
+ });
1579
+
1580
+ const explorerProps = useExplorerProps();
1581
+
1582
+ const [isCascade, setIsCascade] = useState(() => attr.onDelete === 'cascade');
1583
+
1584
+ const [isCascadeReverse, setIsCascadeReverse] = useState(
1585
+ () => attr.onDeleteReverse === 'cascade',
1586
+ );
1587
+
1588
+ const [isRequired, setIsRequired] = useState(attr.isRequired || false);
1589
+ const [wasRequired, _] = useState(isRequired);
1590
+
1591
+ const [indexingJob, setIndexingJob] = useState<InstantIndexingJob | null>(
1592
+ null,
1593
+ );
1594
+
1595
+ const stopFetchLoop = useRef<null | (() => void)>(null);
1596
+ const closeDialog = useClose();
1597
+
1598
+ useEffect(() => {
1599
+ return () => stopFetchLoop.current?.();
1600
+ }, [stopFetchLoop]);
1601
+
1602
+ const isCascadeAllowed =
1603
+ relationship === 'one-one' || relationship === 'one-many';
1604
+ const isCascadeReverseAllowed =
1605
+ relationship === 'one-one' || relationship === 'many-one';
1606
+
1607
+ const linkValidation = validateLink({
1608
+ attrName,
1609
+ reverseAttrName,
1610
+ namespaceName: attr.linkConfig.forward.namespace,
1611
+ reverseNamespaceName: attr.linkConfig.reverse?.namespace,
1612
+ });
1613
+
1614
+ async function updateRef() {
1615
+ if (!attr.linkConfig.reverse) {
1616
+ throw new Error('No reverse link config');
1617
+ }
1618
+
1619
+ if (isRequired !== wasRequired) {
1620
+ const res = await updateRequired({
1621
+ appId,
1622
+ attr,
1623
+ isRequired,
1624
+ authToken: explorerProps.adminToken,
1625
+ setIndexingJob,
1626
+ stopFetchLoop,
1627
+ apiURI: explorerProps.apiURI,
1628
+ });
1629
+
1630
+ if (res != 'completed') return;
1631
+ }
1632
+
1633
+ const ops = [
1634
+ [
1635
+ 'update-attr',
1636
+ {
1637
+ id: attr.id,
1638
+ ...relationshipConstraints[relationship],
1639
+ 'forward-identity': [
1640
+ attr.linkConfig.forward.id,
1641
+ attr.linkConfig.forward.namespace,
1642
+ attrName,
1643
+ ],
1644
+ 'reverse-identity': [
1645
+ attr.linkConfig.reverse.id,
1646
+ attr.linkConfig.reverse.namespace,
1647
+ reverseAttrName,
1648
+ ],
1649
+ 'on-delete': isCascadeAllowed && isCascade ? 'cascade' : null,
1650
+ 'on-delete-reverse':
1651
+ isCascadeReverseAllowed && isCascadeReverse ? 'cascade' : null,
1652
+ },
1653
+ ],
1654
+ ];
1655
+
1656
+ await db.core._reactor.pushOps(ops);
1657
+
1658
+ // avoid showing 2 success toasts
1659
+ if (isRequired == wasRequired) {
1660
+ successToast('Updated attribute');
1661
+ }
1662
+ }
1663
+
1664
+ async function renameBlobAttr() {
1665
+ const ops = [
1666
+ [
1667
+ 'update-attr',
1668
+ {
1669
+ id: attr.id,
1670
+ 'forward-identity': [
1671
+ attr.linkConfig.forward.id,
1672
+ attr.linkConfig.forward.namespace,
1673
+ attrName,
1674
+ ],
1675
+ },
1676
+ ],
1677
+ ];
1678
+
1679
+ await db.core._reactor.pushOps(ops);
1680
+
1681
+ successToast('Renamed attribute');
1682
+ }
1683
+
1684
+ async function deleteAttr() {
1685
+ await db.core._reactor.pushOps([['delete-attr', attr.id]]);
1686
+ // update the recently deleted attr cache
1687
+ setTimeout(() => {
1688
+ mutate(['recently-deleted', appId]);
1689
+ }, 500);
1690
+ onClose();
1691
+ }
1692
+
1693
+ if (screen.type === 'delete') {
1694
+ return (
1695
+ <DeleteForm
1696
+ onConfirm={deleteAttr}
1697
+ onClose={onClose}
1698
+ name={attr.name}
1699
+ type="attribute"
1700
+ />
1701
+ );
1702
+ }
1703
+ return (
1704
+ <div className="flex flex-col gap-4">
1705
+ <div className="mr-8 flex gap-4">
1706
+ <div className="flex items-center gap-2">
1707
+ <ArrowLeftIcon className="h-4 w-4 cursor-pointer" onClick={onClose} />
1708
+ <h5 className="flex items-center text-lg font-bold">
1709
+ Edit {attr.namespace}.{attr.name}
1710
+ </h5>
1711
+ </div>
1712
+
1713
+ <Button
1714
+ disabled={constraints.attr.disabled}
1715
+ title={constraints.attr.message}
1716
+ variant="secondary"
1717
+ size="mini"
1718
+ onClick={() => setScreen({ type: 'delete' })}
1719
+ >
1720
+ <TrashIcon className="inline" height="1rem" />
1721
+ Delete
1722
+ </Button>
1723
+ </div>
1724
+
1725
+ {attr.type === 'blob' ? (
1726
+ <>
1727
+ <EditBlobConstraints
1728
+ appId={appId}
1729
+ attr={attr}
1730
+ constraints={constraints}
1731
+ />
1732
+
1733
+ <Divider />
1734
+
1735
+ <ActionForm className="flex flex-col gap-1">
1736
+ <h6 className="text-md font-bold">Rename</h6>
1737
+ <Content className="text-sm">
1738
+ This will immediately rename the attribute. You'll need to{' '}
1739
+ <strong className="dark:text-white">update your code</strong> to
1740
+ the new name.
1741
+ </Content>
1742
+ <TextInput
1743
+ disabled={constraints.attr.disabled}
1744
+ title={constraints.attr.message}
1745
+ value={attrName}
1746
+ onChange={(n) => setAttrName(n)}
1747
+ />
1748
+ <div className="flex flex-col gap-2 rounded-sm py-2">
1749
+ <ActionButton
1750
+ type="submit"
1751
+ label={`Rename ${attr.name} → ${attrName}`}
1752
+ submitLabel="Renaming attribute..."
1753
+ errorMessage="Failed to rename attribute"
1754
+ disabled={
1755
+ constraints.attr.disabled ||
1756
+ !attrName ||
1757
+ attrName === attr.name
1758
+ }
1759
+ title={constraints.attr.message}
1760
+ onClick={renameBlobAttr}
1761
+ />
1762
+ </div>
1763
+ </ActionForm>
1764
+ </>
1765
+ ) : (
1766
+ <ActionForm className="flex flex-col gap-6">
1767
+ <RelationshipConfigurator
1768
+ relationship={relationship}
1769
+ attrName={attrName}
1770
+ reverseAttrName={reverseAttrName ?? ''}
1771
+ namespaceName={attr.linkConfig.forward.namespace}
1772
+ reverseNamespaceName={attr.linkConfig.reverse!.namespace}
1773
+ setAttrName={setAttrName}
1774
+ setReverseAttrName={setReverseAttrName}
1775
+ setRelationship={setRelationship}
1776
+ isCascadeAllowed={isCascadeAllowed}
1777
+ isCascade={isCascade}
1778
+ setIsCascade={setIsCascade}
1779
+ isCascadeReverseAllowed={isCascadeReverseAllowed}
1780
+ isCascadeReverse={isCascadeReverse}
1781
+ setIsCascadeReverse={setIsCascadeReverse}
1782
+ isRequired={isRequired}
1783
+ setIsRequired={setIsRequired}
1784
+ constraints={constraints}
1785
+ />
1786
+
1787
+ <IndexingJobError
1788
+ indexingJob={indexingJob}
1789
+ attr={attr}
1790
+ onClose={() => {
1791
+ closeDialog();
1792
+ onClose();
1793
+ }}
1794
+ />
1795
+
1796
+ <div className="flex flex-col gap-6">
1797
+ <ActionButton
1798
+ disabled={
1799
+ constraints.attr.disabled || !linkValidation.isValidLink
1800
+ }
1801
+ type="submit"
1802
+ label="Update relationship"
1803
+ submitLabel="Updating relationship..."
1804
+ errorMessage="Failed to update relationship"
1805
+ onClick={updateRef}
1806
+ title={constraints.attr.message}
1807
+ />
1808
+ {linkValidation.shouldShowSelfLinkNameError ? (
1809
+ <span className="text-red-500">
1810
+ Self-links must have different attribute names.
1811
+ </span>
1812
+ ) : null}
1813
+ </div>
1814
+ </ActionForm>
1815
+ )}
1816
+ </div>
1817
+ );
1818
+ }
1819
+ function validateLink({
1820
+ reverseNamespaceName,
1821
+ namespaceName,
1822
+ attrName,
1823
+ reverseAttrName,
1824
+ }: {
1825
+ reverseNamespaceName: string | undefined;
1826
+ reverseAttrName: string | undefined;
1827
+ namespaceName: string;
1828
+ attrName: string;
1829
+ }) {
1830
+ const isSelfLink =
1831
+ reverseNamespaceName && reverseNamespaceName === namespaceName;
1832
+ const isNonEmptyLink =
1833
+ attrName && namespaceName && reverseNamespaceName && reverseAttrName;
1834
+ const isValidSelfLinkNames = attrName !== reverseAttrName;
1835
+ const isValidLink =
1836
+ isNonEmptyLink && (isSelfLink ? isValidSelfLinkNames : true);
1837
+ const shouldShowSelfLinkNameError =
1838
+ isNonEmptyLink && isSelfLink && !isValidSelfLinkNames;
1839
+
1840
+ return {
1841
+ isSelfLink,
1842
+ isNonEmptyLink,
1843
+ isValidLink,
1844
+ shouldShowSelfLinkNameError,
1845
+ };
1846
+ }
1847
+
1848
+ type SystemConstraints = {
1849
+ attr: {
1850
+ disabled: boolean;
1851
+ message?: string;
1852
+ };
1853
+ require: {
1854
+ disabled: boolean;
1855
+ message?: string;
1856
+ };
1857
+ };
1858
+
1859
+ function getSystemConstraints({
1860
+ namespaceName,
1861
+ isSystemCatalogNs: isSystemCatalogNs,
1862
+ attr: isSystemCatalogAttr,
1863
+ }: {
1864
+ namespaceName: string;
1865
+ isSystemCatalogNs: boolean;
1866
+ attr?: SchemaAttr;
1867
+ }): SystemConstraints {
1868
+ const isSystemAttr = isSystemCatalogAttr?.catalog === 'system';
1869
+
1870
+ const attrMessage = isSystemCatalogAttr
1871
+ ? `${isSystemCatalogAttr.namespace}.${isSystemCatalogAttr.name} is managed by the system and can't be edited`
1872
+ : undefined;
1873
+
1874
+ const requireMessage = isSystemAttr
1875
+ ? attrMessage
1876
+ : isSystemCatalogNs
1877
+ ? `The ${namespaceName} namespace is managed by the system and can't modify required constraints yet.`
1878
+ : undefined;
1879
+
1880
+ return {
1881
+ attr: {
1882
+ disabled: isSystemAttr || false,
1883
+ message: attrMessage,
1884
+ },
1885
+ require: {
1886
+ disabled: isSystemAttr || isSystemCatalogNs,
1887
+ message: requireMessage,
1888
+ },
1889
+ };
1890
+ }