@constructive-io/schema-builder 0.2.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 (61) hide show
  1. package/CHANGELOG.md +26 -0
  2. package/LICENSE +21 -0
  3. package/README.md +33 -0
  4. package/dist/core.cjs +213 -0
  5. package/dist/core.cjs.map +1 -0
  6. package/dist/core.d.cts +54 -0
  7. package/dist/core.d.ts +54 -0
  8. package/dist/core.js +202 -0
  9. package/dist/core.js.map +1 -0
  10. package/dist/fields.cjs +7764 -0
  11. package/dist/fields.cjs.map +1 -0
  12. package/dist/fields.d.cts +49 -0
  13. package/dist/fields.d.ts +49 -0
  14. package/dist/fields.js +7737 -0
  15. package/dist/fields.js.map +1 -0
  16. package/dist/generated-types-CnAlqHU_.d.cts +25 -0
  17. package/dist/generated-types-CnAlqHU_.d.ts +25 -0
  18. package/dist/index.cjs +13752 -0
  19. package/dist/index.cjs.map +1 -0
  20. package/dist/index.d.cts +10 -0
  21. package/dist/index.d.ts +10 -0
  22. package/dist/index.js +13720 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/indexes.cjs +1043 -0
  25. package/dist/indexes.cjs.map +1 -0
  26. package/dist/indexes.d.cts +36 -0
  27. package/dist/indexes.d.ts +36 -0
  28. package/dist/indexes.js +1018 -0
  29. package/dist/indexes.js.map +1 -0
  30. package/dist/policies.cjs +5940 -0
  31. package/dist/policies.cjs.map +1 -0
  32. package/dist/policies.d.cts +103 -0
  33. package/dist/policies.d.ts +103 -0
  34. package/dist/policies.js +5913 -0
  35. package/dist/policies.js.map +1 -0
  36. package/dist/policy-types-CEYAR5TN.d.cts +79 -0
  37. package/dist/policy-types-CEYAR5TN.d.ts +79 -0
  38. package/dist/relationships.cjs +4329 -0
  39. package/dist/relationships.cjs.map +1 -0
  40. package/dist/relationships.d.cts +121 -0
  41. package/dist/relationships.d.ts +121 -0
  42. package/dist/relationships.js +4302 -0
  43. package/dist/relationships.js.map +1 -0
  44. package/dist/tables.cjs +5645 -0
  45. package/dist/tables.cjs.map +1 -0
  46. package/dist/tables.d.cts +29 -0
  47. package/dist/tables.d.ts +29 -0
  48. package/dist/tables.js +5620 -0
  49. package/dist/tables.js.map +1 -0
  50. package/dist/testing.cjs +69 -0
  51. package/dist/testing.cjs.map +1 -0
  52. package/dist/testing.d.cts +7 -0
  53. package/dist/testing.d.ts +7 -0
  54. package/dist/testing.js +67 -0
  55. package/dist/testing.js.map +1 -0
  56. package/dist/types-Du86atZ8.d.cts +199 -0
  57. package/dist/types-Du86atZ8.d.ts +199 -0
  58. package/dist/types-bX2dCrdl.d.cts +52 -0
  59. package/dist/types-bX2dCrdl.d.ts +52 -0
  60. package/package.json +165 -0
  61. package/src/styles.css +2 -0
@@ -0,0 +1,1043 @@
1
+ 'use client';
2
+ 'use strict';
3
+
4
+ var react = require('react');
5
+ var button = require('@constructive-io/ui/button');
6
+ var stack = require('@constructive-io/ui/stack');
7
+ var toast = require('@constructive-io/ui/toast');
8
+ var tooltip = require('@constructive-io/ui/tooltip');
9
+ var lucideReact = require('lucide-react');
10
+ var FluentContextSelector = require('@fluentui/react-context-selector');
11
+ var zustand = require('zustand');
12
+ var jsxRuntime = require('react/jsx-runtime');
13
+ var reactQuery = require('@tanstack/react-query');
14
+ var clsx = require('clsx');
15
+ var tailwindMerge = require('tailwind-merge');
16
+ var alertDialog = require('@constructive-io/ui/alert-dialog');
17
+ var input = require('@constructive-io/ui/input');
18
+ var label = require('@constructive-io/ui/label');
19
+ var multiSelect = require('@constructive-io/ui/multi-select');
20
+ var responsiveDiagram = require('@constructive-io/ui/responsive-diagram');
21
+ var scrollArea = require('@constructive-io/ui/scroll-area');
22
+ var select = require('@constructive-io/ui/select');
23
+ var _switch = require('@constructive-io/ui/switch');
24
+
25
+ function _interopNamespace(e) {
26
+ if (e && e.__esModule) return e;
27
+ var n = Object.create(null);
28
+ if (e) {
29
+ Object.keys(e).forEach(function (k) {
30
+ if (k !== 'default') {
31
+ var d = Object.getOwnPropertyDescriptor(e, k);
32
+ Object.defineProperty(n, k, d.get ? d : {
33
+ enumerable: true,
34
+ get: function () { return e[k]; }
35
+ });
36
+ }
37
+ });
38
+ }
39
+ n.default = e;
40
+ return Object.freeze(n);
41
+ }
42
+
43
+ var FluentContextSelector__namespace = /*#__PURE__*/_interopNamespace(FluentContextSelector);
44
+
45
+ var INDEX_TYPE_LABELS = {
46
+ btree: "B-Tree",
47
+ hash: "Hash",
48
+ gin: "GIN",
49
+ gist: "GiST",
50
+ spgist: "SP-GiST",
51
+ brin: "BRIN"
52
+ };
53
+ var SchemaBuilderContext = react.createContext(null);
54
+ function useSchemaBuilder() {
55
+ const value = react.useContext(SchemaBuilderContext);
56
+ if (!value) throw new Error("SchemaBuilderProvider is missing");
57
+ return value;
58
+ }
59
+ function useSchemaBuilderStore(selector) {
60
+ const { store } = useSchemaBuilder();
61
+ return zustand.useStore(store, selector);
62
+ }
63
+ var featureByMutation = {
64
+ createField: "fields",
65
+ createForeignKeyConstraint: "relationships",
66
+ createIndex: "indexes",
67
+ createPrimaryKeyConstraint: "fields",
68
+ createTableGrant: "policies",
69
+ createTable: "policies",
70
+ createUniqueConstraint: "fields",
71
+ deleteField: "fields",
72
+ deleteForeignKeyConstraint: "relationships",
73
+ deleteIndex: "indexes",
74
+ deletePolicy: "policies",
75
+ deletePrimaryKeyConstraint: "fields",
76
+ deleteTable: "tables",
77
+ deleteUniqueConstraint: "fields",
78
+ updateField: "fields",
79
+ updateForeignKeyConstraint: "relationships",
80
+ updateIndex: "indexes",
81
+ updatePolicy: "policies",
82
+ updatePrimaryKeyConstraint: "fields",
83
+ updateTable: "tables"
84
+ };
85
+ function useGeneratedMutation(operation, options) {
86
+ const { adapter, scope, onInvalidate } = useSchemaBuilder();
87
+ const feature = featureByMutation[operation];
88
+ const operationFn = adapter[feature][operation];
89
+ const selection = options?.selection?.fields;
90
+ return reactQuery.useMutation({
91
+ mutationFn: (variables) => operationFn(variables, { scope, selection }),
92
+ onSuccess: () => onInvalidate?.({ scope, feature, operation })
93
+ });
94
+ }
95
+ var apiKeys = { all: ["schema-builder", "apis"] };
96
+ var domainKeys = {
97
+ all: ["schema-builder", "domains"],
98
+ lists: () => ["schema-builder", "domains", "list"]
99
+ };
100
+ var schemaKeys = { all: ["schema-builder", "schemas"] };
101
+ var siteKeys = { all: ["schema-builder", "sites"] };
102
+ var useCreateIndexMutation = (options) => useGeneratedMutation("createIndex", options);
103
+ var useDeleteIndexMutation = (options) => useGeneratedMutation("deleteIndex", options);
104
+ var useUpdateIndexMutation = (options) => useGeneratedMutation("updateIndex", options);
105
+
106
+ // src/compat/block-config.tsx
107
+ function useSchemaBuilderRuntime() {
108
+ const runtime = useSchemaBuilder();
109
+ return {
110
+ ...runtime,
111
+ setCurrentDatabaseApi: (api) => runtime.store.getState().setCurrentDatabaseApi(api)
112
+ };
113
+ }
114
+ function useSchemaBuilderRuntimeStore(selector) {
115
+ return useSchemaBuilderStore(selector);
116
+ }
117
+ var accessibleDatabasesQueryKeys = {
118
+ all: ["accessible-databases"]};
119
+ var databaseConstraintsQueryKeys = {
120
+ all: ["database-constraints"]};
121
+
122
+ // src/schema/schema-builder-core/lib/gql/hooks/schema-builder/use-schema-builder-selectors.ts
123
+ var fluentContextSelector = FluentContextSelector__namespace.default ?? FluentContextSelector__namespace;
124
+ var { createContext: createContext2, useContextSelector } = fluentContextSelector;
125
+ var EMPTY_STORE_SCHEMAS = [];
126
+ var EMPTY_SCHEMAS = EMPTY_STORE_SCHEMAS;
127
+ var NOOP_SELECT_ORG = (_orgId) => void 0;
128
+ var NOOP_SELECT_SCHEMA = (_schemaKey) => void 0;
129
+ var NOOP_SET_ACTIVE_TAB = (_tab) => void 0;
130
+ var IS_CUSTOM_SCHEMA = (schemaKey) => schemaKey.startsWith("custom-");
131
+ var SchemaBuilderDataContext = createContext2(null);
132
+ function useSchemaBuilderDataSelector(selector) {
133
+ return useContextSelector(SchemaBuilderDataContext, (state) => {
134
+ if (!state) {
135
+ throw new Error("SchemaBuilderDataProvider is missing");
136
+ }
137
+ return selector(state);
138
+ });
139
+ }
140
+ function useSchemaBuilderSelectors() {
141
+ const {
142
+ scope,
143
+ store,
144
+ selectField: selectFieldFromContext,
145
+ selectTable: selectTableFromContext
146
+ } = useSchemaBuilderRuntime();
147
+ const selectedFieldId = useSchemaBuilderRuntimeStore((state) => state.selectedFieldId);
148
+ const currentDatabaseApi = useSchemaBuilderRuntimeStore((state) => state.currentDatabaseApi);
149
+ const selectedOrgId = scope.orgId;
150
+ const activeTab = "schemas";
151
+ const customSchemas = EMPTY_SCHEMAS;
152
+ const selectOrg = NOOP_SELECT_ORG;
153
+ const selectSchema = NOOP_SELECT_SCHEMA;
154
+ const selectField = react.useCallback(
155
+ (fieldId) => selectFieldFromContext(fieldId),
156
+ [selectFieldFromContext]
157
+ );
158
+ const clearAllSelections = react.useCallback(() => {
159
+ selectTableFromContext(null);
160
+ selectFieldFromContext(null);
161
+ }, [selectTableFromContext, selectFieldFromContext]);
162
+ const setActiveTab = NOOP_SET_ACTIVE_TAB;
163
+ const setCurrentDatabaseApi = react.useCallback(
164
+ (api) => store.getState().setCurrentDatabaseApi(api),
165
+ [store]
166
+ );
167
+ const availableSchemas = useSchemaBuilderDataSelector((state) => state.availableSchemas);
168
+ const selectedSchemaKey = useSchemaBuilderDataSelector((state) => state.selectedSchemaKey);
169
+ const currentSchemaInfo = useSchemaBuilderDataSelector((state) => state.currentSchemaInfo);
170
+ const currentSchema = useSchemaBuilderDataSelector((state) => state.currentSchema);
171
+ const currentTable = useSchemaBuilderDataSelector((state) => state.currentTable);
172
+ const selectedTableId = useSchemaBuilderDataSelector((state) => state.selectedTableId);
173
+ const isLoading = useSchemaBuilderDataSelector((state) => state.isLoading);
174
+ const isFetching = useSchemaBuilderDataSelector((state) => state.isFetching);
175
+ const error = useSchemaBuilderDataSelector((state) => state.error);
176
+ const refetch = useSchemaBuilderDataSelector((state) => state.refetch);
177
+ const selectTableFromProvider = useSchemaBuilderDataSelector((state) => state.selectTable);
178
+ const currentField = react.useMemo(
179
+ () => currentTable?.fields.find((f) => f.id === selectedFieldId) ?? null,
180
+ [currentTable, selectedFieldId]
181
+ );
182
+ const currentDatabase = react.useMemo(() => {
183
+ if (!currentSchemaInfo?.databaseInfo) return null;
184
+ return {
185
+ schemaKey: selectedSchemaKey,
186
+ databaseId: currentSchemaInfo.databaseInfo.id,
187
+ name: currentSchemaInfo.databaseInfo.name,
188
+ label: currentSchemaInfo.databaseInfo.label ?? null,
189
+ schemaId: currentSchemaInfo.databaseInfo.schemaId ?? null
190
+ };
191
+ }, [currentSchemaInfo, selectedSchemaKey]);
192
+ const isCustomSchema = IS_CUSTOM_SCHEMA;
193
+ const getSchemaByKey = react.useCallback(
194
+ (key) => availableSchemas.find((schema) => schema.key === key) ?? null,
195
+ [availableSchemas]
196
+ );
197
+ const selectTable = react.useCallback(
198
+ (tableId, tableName) => {
199
+ selectTableFromProvider(tableId, tableName);
200
+ selectField(null);
201
+ },
202
+ [selectTableFromProvider, selectField]
203
+ );
204
+ return {
205
+ // Entity selection state
206
+ selectedOrgId,
207
+ selectedSchemaKey,
208
+ selectedTableId,
209
+ selectedFieldId,
210
+ activeTab,
211
+ // Entity selection actions (with cascade clearing)
212
+ selectOrg,
213
+ selectSchema,
214
+ selectTable,
215
+ selectField,
216
+ clearAllSelections,
217
+ setActiveTab,
218
+ // Derived data
219
+ availableSchemas,
220
+ currentSchema,
221
+ currentTable,
222
+ currentField,
223
+ currentDatabase,
224
+ // API state (from Zustand)
225
+ currentDatabaseApi,
226
+ setCurrentDatabaseApi,
227
+ // Helpers
228
+ isCustomSchema,
229
+ getSchemaByKey,
230
+ // Loading/error
231
+ isLoading,
232
+ isFetching,
233
+ error,
234
+ refetch,
235
+ // Custom schemas
236
+ customSchemas
237
+ };
238
+ }
239
+
240
+ // src/schema/schema-builder-core/lib/data/mutation-input.ts
241
+ var asFieldIds = (ids) => ids;
242
+
243
+ // src/schema/schema-builder-core/lib/gql/hooks/dashboard/dashboard-query-keys.ts
244
+ function isDashboardCacheScopeKey(value) {
245
+ if (!value || typeof value !== "object") return false;
246
+ const candidate = value;
247
+ return "databaseId" in candidate && "endpoint" in candidate;
248
+ }
249
+ var blueprintTemplateKeys = { all: ["schema-builder", "blueprint-templates"] };
250
+ var databasePoliciesQueryKeys = {
251
+ all: ["database-policies"],
252
+ byDatabase: (databaseId) => ["database-policies", databaseId]
253
+ };
254
+ var databaseTablesQueryKeys = {
255
+ all: ["database-tables"],
256
+ byDatabase: (databaseId) => [...databaseTablesQueryKeys.all, { databaseId }],
257
+ byDatabaseWithOptions: (databaseId, options) => [...databaseTablesQueryKeys.byDatabase(databaseId), options]
258
+ };
259
+ var userDatabasesQueryKeys = {
260
+ all: ["user-databases"]};
261
+
262
+ // src/schema/schema-builder-core/lib/gql/hooks/schema-builder/modules/invalidate-database-entities.ts
263
+ var invalidateQueryKey = (queryClient, queryKey) => queryClient.invalidateQueries({ queryKey });
264
+ function invalidateDashboardQueries(queryClient, databaseId) {
265
+ const matchesDashboard = (queryKey) => {
266
+ const [root, scope] = queryKey;
267
+ if (root !== "sheets") return false;
268
+ if (!databaseId) return true;
269
+ return isDashboardCacheScopeKey(scope) && scope.databaseId === databaseId;
270
+ };
271
+ queryClient.removeQueries({
272
+ predicate: (query) => {
273
+ if (!matchesDashboard(query.queryKey)) return false;
274
+ const type = query.queryKey[2];
275
+ return type === "meta" || type === "relations";
276
+ }
277
+ });
278
+ return queryClient.invalidateQueries({
279
+ predicate: (query) => matchesDashboard(query.queryKey)
280
+ });
281
+ }
282
+ async function invalidateDatabaseEntities(queryClient, databaseId) {
283
+ const tasks = [];
284
+ tasks.push(invalidateQueryKey(queryClient, ["@constructive-io/schema-builder"]));
285
+ if (databaseId) {
286
+ tasks.push(invalidateQueryKey(queryClient, databaseTablesQueryKeys.byDatabase(databaseId)));
287
+ tasks.push(invalidateQueryKey(queryClient, databasePoliciesQueryKeys.byDatabase(databaseId)));
288
+ tasks.push(invalidateQueryKey(queryClient, domainKeys.lists()));
289
+ tasks.push(invalidateQueryKey(queryClient, ["database-table"]));
290
+ }
291
+ tasks.push(invalidateDashboardQueries(queryClient, databaseId));
292
+ tasks.push(invalidateQueryKey(queryClient, userDatabasesQueryKeys.all));
293
+ tasks.push(invalidateQueryKey(queryClient, accessibleDatabasesQueryKeys.all));
294
+ tasks.push(invalidateQueryKey(queryClient, databaseConstraintsQueryKeys.all));
295
+ tasks.push(invalidateQueryKey(queryClient, apiKeys.all));
296
+ tasks.push(invalidateQueryKey(queryClient, schemaKeys.all));
297
+ tasks.push(invalidateQueryKey(queryClient, siteKeys.all));
298
+ tasks.push(invalidateQueryKey(queryClient, blueprintTemplateKeys.all));
299
+ tasks.push(invalidateQueryKey(queryClient, databaseTablesQueryKeys.all));
300
+ tasks.push(invalidateQueryKey(queryClient, databasePoliciesQueryKeys.all));
301
+ tasks.push(invalidateQueryKey(queryClient, domainKeys.all));
302
+ await Promise.allSettled(tasks);
303
+ }
304
+
305
+ // src/schema/schema-builder-indexes/lib/gql/hooks/schema-builder/use-index-mutations.ts
306
+ function useCreateIndex() {
307
+ const queryClient = reactQuery.useQueryClient();
308
+ const { selectTable, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
309
+ const createIndexMutation = useCreateIndexMutation({ selection: { fields: { id: true, name: true } } });
310
+ return reactQuery.useMutation({
311
+ mutationFn: async (input) => {
312
+ const databaseId = currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId;
313
+ if (!databaseId) {
314
+ throw new Error("Database ID not found");
315
+ }
316
+ const result = await createIndexMutation.mutateAsync({
317
+ databaseId,
318
+ tableId: input.tableId,
319
+ name: input.name,
320
+ fieldIds: asFieldIds(input.fieldIds),
321
+ isUnique: input.isUnique ?? false,
322
+ accessMethod: input.accessMethod || "btree"
323
+ });
324
+ const createdIndex = result.createIndex?.index;
325
+ if (!createdIndex?.id) {
326
+ throw new Error("Failed to create index");
327
+ }
328
+ return { id: createdIndex.id, name: createdIndex.name ?? "" };
329
+ },
330
+ onSuccess: async (_createdIndex, variables) => {
331
+ await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
332
+ selectTable(variables.tableId);
333
+ },
334
+ onError: (error) => {
335
+ console.error("Failed to create index:", error);
336
+ }
337
+ });
338
+ }
339
+ function useUpdateIndex() {
340
+ const queryClient = reactQuery.useQueryClient();
341
+ const { selectTable, selectedTableId, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
342
+ const updateIndexMutation = useUpdateIndexMutation({ selection: { fields: { id: true, name: true } } });
343
+ return reactQuery.useMutation({
344
+ mutationFn: async (input) => {
345
+ const patch = {};
346
+ if (input.name !== void 0) patch.name = input.name;
347
+ if (input.fieldIds !== void 0) patch.fieldIds = input.fieldIds;
348
+ if (input.isUnique !== void 0) patch.isUnique = input.isUnique;
349
+ if (input.accessMethod !== void 0) patch.accessMethod = input.accessMethod;
350
+ const result = await updateIndexMutation.mutateAsync({ id: input.id, indexPatch: patch });
351
+ const updatedIndex = result.updateIndex?.index;
352
+ if (!updatedIndex?.id) {
353
+ throw new Error("Failed to update index");
354
+ }
355
+ return { id: updatedIndex.id, name: updatedIndex.name ?? "" };
356
+ },
357
+ onSuccess: async () => {
358
+ await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
359
+ if (selectedTableId) {
360
+ selectTable(selectedTableId);
361
+ }
362
+ },
363
+ onError: (error) => {
364
+ console.error("Failed to update index:", error);
365
+ }
366
+ });
367
+ }
368
+ function useDeleteIndex() {
369
+ const queryClient = reactQuery.useQueryClient();
370
+ const { selectTable, selectedTableId, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
371
+ const deleteIndexMutation = useDeleteIndexMutation({ selection: { fields: { id: true } } });
372
+ return reactQuery.useMutation({
373
+ mutationFn: async (input) => {
374
+ await deleteIndexMutation.mutateAsync({ id: input.id });
375
+ return { id: input.id };
376
+ },
377
+ onSuccess: async () => {
378
+ await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
379
+ if (selectedTableId) {
380
+ selectTable(selectedTableId);
381
+ }
382
+ },
383
+ onError: (error) => {
384
+ console.error("Failed to delete index:", error);
385
+ }
386
+ });
387
+ }
388
+
389
+ // src/schema/schema-builder-core/lib/stack/card-widths.ts
390
+ var CARD_WIDTHS = {
391
+ /** Default for most forms (480px) */
392
+ medium: 480};
393
+
394
+ // src/schema/schema-builder-core/lib/keyboard-activation.ts
395
+ function handleActivationKeyDown(event, activate, disabled = false) {
396
+ if (event.target !== event.currentTarget || disabled) return;
397
+ if (event.key === "Enter" || event.key === " ") {
398
+ event.preventDefault();
399
+ activate();
400
+ }
401
+ }
402
+ function cn(...inputs) {
403
+ return tailwindMerge.twMerge(clsx.clsx(inputs));
404
+ }
405
+ function DeleteConfirmDialog({
406
+ entityType,
407
+ entityName,
408
+ open,
409
+ onOpenChange,
410
+ onConfirm,
411
+ isPending
412
+ }) {
413
+ return /* @__PURE__ */ jsxRuntime.jsx(alertDialog.AlertDialog, { open, onOpenChange: (next) => !next && !isPending && onOpenChange(false), children: /* @__PURE__ */ jsxRuntime.jsxs(alertDialog.AlertDialogContent, { children: [
414
+ /* @__PURE__ */ jsxRuntime.jsxs(alertDialog.AlertDialogHeader, { children: [
415
+ /* @__PURE__ */ jsxRuntime.jsxs(alertDialog.AlertDialogTitle, { children: [
416
+ "Delete ",
417
+ entityType
418
+ ] }),
419
+ /* @__PURE__ */ jsxRuntime.jsxs(alertDialog.AlertDialogDescription, { children: [
420
+ "Are you sure you want to delete",
421
+ " ",
422
+ /* @__PURE__ */ jsxRuntime.jsxs("strong", { className: "text-foreground", children: [
423
+ "\u201C",
424
+ entityName,
425
+ "\u201D"
426
+ ] }),
427
+ "? This action cannot be undone."
428
+ ] })
429
+ ] }),
430
+ /* @__PURE__ */ jsxRuntime.jsxs(alertDialog.AlertDialogFooter, { children: [
431
+ /* @__PURE__ */ jsxRuntime.jsx(alertDialog.AlertDialogCancel, { disabled: isPending, children: "Cancel" }),
432
+ /* @__PURE__ */ jsxRuntime.jsxs(
433
+ alertDialog.AlertDialogAction,
434
+ {
435
+ onClick: onConfirm,
436
+ disabled: isPending,
437
+ className: "bg-destructive text-destructive-foreground hover:bg-destructive/90",
438
+ children: [
439
+ isPending ? /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "mr-2 h-4 w-4 animate-spin" }) : null,
440
+ isPending ? "Deleting..." : "Delete"
441
+ ]
442
+ }
443
+ )
444
+ ] })
445
+ ] }) });
446
+ }
447
+ var THEME = {
448
+ primary: "#6366F1",
449
+ light: "#E0E7FF",
450
+ border: "#A5B4FC",
451
+ connector: "#6366F1",
452
+ connectorLight: "#C7D2FE"
453
+ };
454
+ var MAX_NAME_WIDTH = 120;
455
+ function truncateName(name, maxWidth) {
456
+ const avgCharWidth = 7;
457
+ const maxChars = Math.floor(maxWidth / avgCharWidth);
458
+ if (name.length <= maxChars) return name;
459
+ return name.slice(0, maxChars - 1) + "\u2026";
460
+ }
461
+ function TableFieldsNode({ tableName, fields, theme }) {
462
+ const displayFields = fields.length > 0 ? fields : ["field"];
463
+ const fieldsLabel = displayFields.join(", ");
464
+ const sizeClasses = "h-14 w-14";
465
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center gap-1.5", children: [
466
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative", children: [
467
+ /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
468
+ /* @__PURE__ */ jsxRuntime.jsx(
469
+ "div",
470
+ {
471
+ className: cn("absolute -top-1.5 -left-2 rounded-full border-2 bg-white", sizeClasses),
472
+ style: { borderColor: theme.border }
473
+ }
474
+ ),
475
+ /* @__PURE__ */ jsxRuntime.jsx(
476
+ "div",
477
+ {
478
+ className: cn("absolute -top-0.5 -left-1 rounded-full border-2 bg-white", sizeClasses),
479
+ style: { borderColor: theme.border }
480
+ }
481
+ )
482
+ ] }),
483
+ /* @__PURE__ */ jsxRuntime.jsx(
484
+ "div",
485
+ {
486
+ className: cn("relative flex items-center justify-center rounded-full border-2 shadow-sm", sizeClasses),
487
+ style: { borderColor: theme.border, backgroundColor: theme.light },
488
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Database, { className: "size-6", style: { color: theme.primary } })
489
+ }
490
+ )
491
+ ] }),
492
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center gap-0.5", children: [
493
+ /* @__PURE__ */ jsxRuntime.jsx(
494
+ "span",
495
+ {
496
+ className: "truncate text-sm font-medium text-gray-600 dark:text-gray-300",
497
+ style: { maxWidth: MAX_NAME_WIDTH },
498
+ title: tableName,
499
+ children: truncateName(tableName || "Table", MAX_NAME_WIDTH)
500
+ }
501
+ ),
502
+ /* @__PURE__ */ jsxRuntime.jsx(
503
+ "span",
504
+ {
505
+ className: "truncate text-xs text-gray-600 dark:text-gray-400",
506
+ style: { maxWidth: MAX_NAME_WIDTH },
507
+ title: fieldsLabel,
508
+ children: truncateName(fieldsLabel, MAX_NAME_WIDTH)
509
+ }
510
+ )
511
+ ] })
512
+ ] });
513
+ }
514
+ function IndexNode({
515
+ indexName,
516
+ typeLabel,
517
+ theme,
518
+ isUnique
519
+ }) {
520
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center gap-2", children: [
521
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative", children: [
522
+ /* @__PURE__ */ jsxRuntime.jsxs(
523
+ "div",
524
+ {
525
+ className: "flex flex-col items-center gap-1 rounded-lg border-2 bg-white px-3 py-2",
526
+ style: { borderColor: theme.border, backgroundColor: theme.light },
527
+ children: [
528
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.DatabaseZap, { className: "size-6", style: { color: theme.primary } }),
529
+ /* @__PURE__ */ jsxRuntime.jsx(
530
+ "span",
531
+ {
532
+ className: "max-w-[100px] truncate text-center text-xs font-medium",
533
+ style: { color: theme.primary },
534
+ title: typeLabel,
535
+ children: typeLabel
536
+ }
537
+ )
538
+ ]
539
+ }
540
+ ),
541
+ isUnique && /* @__PURE__ */ jsxRuntime.jsx(
542
+ "div",
543
+ {
544
+ className: "absolute -right-2 -bottom-2 flex h-6 w-6 items-center justify-center rounded-full border-2\n border-white shadow-sm",
545
+ style: { backgroundColor: theme.primary },
546
+ children: /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-[10px] font-bold text-white", children: "U" })
547
+ }
548
+ )
549
+ ] }),
550
+ /* @__PURE__ */ jsxRuntime.jsx("span", { className: "max-w-[100px] truncate text-center text-sm text-gray-600 dark:text-gray-300", title: indexName, children: truncateName(indexName || "Index", 100) })
551
+ ] });
552
+ }
553
+ function ArrowConnector({ theme, label }) {
554
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "relative flex flex-col items-center justify-center", children: [
555
+ /* @__PURE__ */ jsxRuntime.jsx(
556
+ "div",
557
+ {
558
+ className: "absolute -top-2 left-1/2 -translate-x-1/2 rounded border px-1.5 py-px text-[10px] leading-tight\n font-medium whitespace-nowrap",
559
+ style: {
560
+ borderColor: theme.primary,
561
+ backgroundColor: theme.light,
562
+ color: theme.primary
563
+ },
564
+ children: label
565
+ }
566
+ ),
567
+ /* @__PURE__ */ jsxRuntime.jsxs("svg", { width: 90, height: "40", viewBox: "0 0 90 40", fill: "none", children: [
568
+ /* @__PURE__ */ jsxRuntime.jsx("circle", { cx: "6", cy: "20", r: "4", fill: theme.connector }),
569
+ /* @__PURE__ */ jsxRuntime.jsx("line", { x1: "10", y1: "20", x2: "74", y2: "20", stroke: theme.connectorLight, strokeWidth: "2.5", strokeLinecap: "round" }),
570
+ /* @__PURE__ */ jsxRuntime.jsx("polygon", { points: "84,20 76,15 76,25", fill: theme.connector })
571
+ ] })
572
+ ] });
573
+ }
574
+ function IndexDiagram({ tableName, indexName, fields, indexType, isUnique }) {
575
+ const theme = THEME;
576
+ const safeIndexType = indexType && INDEX_TYPE_LABELS[indexType] ? indexType : "btree";
577
+ const typeLabel = INDEX_TYPE_LABELS[safeIndexType];
578
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-center gap-3", children: [
579
+ /* @__PURE__ */ jsxRuntime.jsx(IndexNode, { indexName: indexName || "Index", typeLabel, theme, isUnique }),
580
+ /* @__PURE__ */ jsxRuntime.jsx(ArrowConnector, { theme, label: "indexes" }),
581
+ /* @__PURE__ */ jsxRuntime.jsx(TableFieldsNode, { tableName, fields, theme })
582
+ ] });
583
+ }
584
+ var FIELD_SUMMARY_LIMIT = 4;
585
+ var indexTypeOptions = Object.keys(INDEX_TYPE_LABELS).map((value) => ({
586
+ value,
587
+ label: value === "btree" ? `${INDEX_TYPE_LABELS[value]} (default)` : INDEX_TYPE_LABELS[value]
588
+ }));
589
+ function normalizeIndexType(type) {
590
+ const raw = type?.toLowerCase();
591
+ return raw && raw in INDEX_TYPE_LABELS ? raw : "btree";
592
+ }
593
+ function generateIndexName(tableName, existingIndexes) {
594
+ let counter = 1;
595
+ let candidateName = `${tableName}_index_${counter}`;
596
+ while (existingIndexes.some((idx) => idx.name === candidateName)) {
597
+ counter++;
598
+ candidateName = `${tableName}_index_${counter}`;
599
+ }
600
+ return candidateName;
601
+ }
602
+ var IndexCard = ({ editingIndex: initialEditingIndex, card }) => {
603
+ const { currentTable } = useSchemaBuilderSelectors();
604
+ const createIndexMutation = useCreateIndex();
605
+ const updateIndexMutation = useUpdateIndex();
606
+ const [isPendingTransition, startTransition] = react.useTransition();
607
+ const indexes = currentTable?.indexes || [];
608
+ const [editingIndex, setEditingIndex] = react.useState(() => {
609
+ if (initialEditingIndex) {
610
+ return {
611
+ ...initialEditingIndex,
612
+ fields: [...initialEditingIndex.fields],
613
+ type: normalizeIndexType(initialEditingIndex.type)
614
+ };
615
+ }
616
+ return null;
617
+ });
618
+ const [originalIndex, setOriginalIndex] = react.useState(() => {
619
+ if (initialEditingIndex) {
620
+ return {
621
+ ...initialEditingIndex,
622
+ fields: [...initialEditingIndex.fields],
623
+ type: normalizeIndexType(initialEditingIndex.type)
624
+ };
625
+ }
626
+ return null;
627
+ });
628
+ const fieldOptions = react.useMemo(
629
+ () => currentTable?.fields.map((field) => ({
630
+ label: field.name,
631
+ value: field.id
632
+ })) || [],
633
+ [currentTable?.fields]
634
+ );
635
+ const fieldNameMap = react.useMemo(() => {
636
+ const map = {};
637
+ currentTable?.fields.forEach((field) => {
638
+ map[field.id] = field.name;
639
+ });
640
+ return map;
641
+ }, [currentTable?.fields]);
642
+ react.useEffect(() => {
643
+ if (!initialEditingIndex && currentTable && !editingIndex) {
644
+ startTransition(() => {
645
+ const generatedName = generateIndexName(currentTable.name, indexes);
646
+ setEditingIndex({
647
+ id: `idx-${Date.now()}`,
648
+ name: generatedName,
649
+ fields: [],
650
+ unique: false,
651
+ type: "btree"
652
+ });
653
+ });
654
+ }
655
+ }, [initialEditingIndex, currentTable, indexes, editingIndex]);
656
+ const handleSaveIndex = react.useCallback(async () => {
657
+ if (!editingIndex || editingIndex.fields.length === 0 || !currentTable) return;
658
+ const trimmedName = editingIndex.name?.trim() ?? "";
659
+ if (!trimmedName) return;
660
+ const isExisting = indexes.some((index) => index.id === editingIndex.id);
661
+ try {
662
+ if (isExisting) {
663
+ await updateIndexMutation.mutateAsync({
664
+ id: editingIndex.id,
665
+ name: trimmedName,
666
+ fieldIds: editingIndex.fields,
667
+ isUnique: editingIndex.type === "btree" ? editingIndex.unique : false,
668
+ accessMethod: editingIndex.type
669
+ });
670
+ toast.toast.success({
671
+ message: "Index updated",
672
+ description: `Index "${trimmedName}" has been updated`
673
+ });
674
+ } else {
675
+ await createIndexMutation.mutateAsync({
676
+ tableId: currentTable.id,
677
+ name: trimmedName,
678
+ fieldIds: editingIndex.fields,
679
+ isUnique: editingIndex.type === "btree" ? editingIndex.unique : false,
680
+ accessMethod: editingIndex.type
681
+ });
682
+ toast.toast.success({
683
+ message: "Index created",
684
+ description: `Index "${trimmedName}" has been created`
685
+ });
686
+ }
687
+ card.close();
688
+ } catch (error) {
689
+ toast.toast.error({
690
+ message: isExisting ? "Failed to update index" : "Failed to create index",
691
+ description: error instanceof Error ? error.message : "An error occurred"
692
+ });
693
+ }
694
+ }, [editingIndex, currentTable, indexes, updateIndexMutation, createIndexMutation, card]);
695
+ const handleNameChange = react.useCallback(
696
+ (event) => {
697
+ setEditingIndex((prev) => prev ? { ...prev, name: event.target.value } : null);
698
+ },
699
+ []
700
+ );
701
+ const handleFieldsChange = react.useCallback((values) => {
702
+ setEditingIndex((prev) => prev ? { ...prev, fields: values } : null);
703
+ }, []);
704
+ const handleTypeChange = react.useCallback((value) => {
705
+ setEditingIndex(
706
+ (prev) => prev ? {
707
+ ...prev,
708
+ type: value,
709
+ unique: value === "btree" ? prev.unique : false
710
+ } : null
711
+ );
712
+ }, []);
713
+ const handleUniqueChange = react.useCallback((checked) => {
714
+ setEditingIndex((prev) => prev ? { ...prev, unique: checked } : null);
715
+ }, []);
716
+ const handleClose = react.useCallback(() => {
717
+ card.close();
718
+ }, [card]);
719
+ const hasChanges = react.useMemo(() => {
720
+ if (originalIndex === null) return true;
721
+ if (!editingIndex) return false;
722
+ return editingIndex.name !== originalIndex.name || editingIndex.type !== originalIndex.type || editingIndex.unique !== originalIndex.unique || editingIndex.fields.length !== originalIndex.fields.length || editingIndex.fields.some((f, i) => f !== originalIndex.fields[i]);
723
+ }, [editingIndex, originalIndex]);
724
+ if (!currentTable) return null;
725
+ const isEditMode = initialEditingIndex !== null;
726
+ const selectedIndexType = editingIndex?.type ?? "btree";
727
+ const selectedFieldNames = editingIndex?.fields.map((id) => fieldNameMap[id] || id) || [];
728
+ const canSave = editingIndex && editingIndex.fields.length > 0 && (editingIndex.name?.trim().length ?? 0) > 0 && hasChanges;
729
+ const isPending = createIndexMutation.isPending || updateIndexMutation.isPending;
730
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex h-full flex-col", children: [
731
+ /* @__PURE__ */ jsxRuntime.jsx(scrollArea.ScrollArea, { className: "min-h-0 flex-1", children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-6 p-6", children: [
732
+ /* @__PURE__ */ jsxRuntime.jsx(responsiveDiagram.ResponsiveDiagram, { className: "py-8", children: /* @__PURE__ */ jsxRuntime.jsx(
733
+ IndexDiagram,
734
+ {
735
+ tableName: currentTable.name,
736
+ indexName: editingIndex?.name,
737
+ fields: selectedFieldNames,
738
+ indexType: selectedIndexType,
739
+ isUnique: editingIndex?.unique ?? false
740
+ }
741
+ ) }),
742
+ editingIndex && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-4", children: [
743
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
744
+ /* @__PURE__ */ jsxRuntime.jsx(label.Label, { className: "block", htmlFor: "index-name", children: "Index name" }),
745
+ /* @__PURE__ */ jsxRuntime.jsx(
746
+ input.Input,
747
+ {
748
+ id: "index-name",
749
+ value: editingIndex.name,
750
+ onChange: handleNameChange,
751
+ placeholder: "e.g. table_index_1"
752
+ }
753
+ )
754
+ ] }),
755
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
756
+ /* @__PURE__ */ jsxRuntime.jsx(label.Label, { className: "block", children: "Fields" }),
757
+ /* @__PURE__ */ jsxRuntime.jsx(
758
+ multiSelect.MultiSelect,
759
+ {
760
+ options: fieldOptions,
761
+ defaultValue: editingIndex.fields,
762
+ onValueChange: handleFieldsChange,
763
+ placeholder: "Select fields",
764
+ dropdownMaxHeight: "300px",
765
+ maxCount: FIELD_SUMMARY_LIMIT
766
+ }
767
+ )
768
+ ] }),
769
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "space-y-2", children: [
770
+ /* @__PURE__ */ jsxRuntime.jsx(label.Label, { className: "block", children: "Index type" }),
771
+ /* @__PURE__ */ jsxRuntime.jsxs(select.Select, { value: selectedIndexType, onValueChange: handleTypeChange, children: [
772
+ /* @__PURE__ */ jsxRuntime.jsx(select.SelectTrigger, { children: /* @__PURE__ */ jsxRuntime.jsx(select.SelectValue, { placeholder: "Select index type" }) }),
773
+ /* @__PURE__ */ jsxRuntime.jsx(select.SelectContent, { children: indexTypeOptions.map((option) => /* @__PURE__ */ jsxRuntime.jsx(select.SelectItem, { value: option.value, children: option.label }, option.value)) })
774
+ ] })
775
+ ] }),
776
+ selectedIndexType === "btree" && /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
777
+ /* @__PURE__ */ jsxRuntime.jsx(label.Label, { htmlFor: "index-unique", children: "Unique" }),
778
+ /* @__PURE__ */ jsxRuntime.jsx(
779
+ _switch.Switch,
780
+ {
781
+ id: "index-unique",
782
+ checked: editingIndex.unique ?? false,
783
+ onCheckedChange: handleUniqueChange
784
+ }
785
+ )
786
+ ] })
787
+ ] })
788
+ ] }) }),
789
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex justify-end gap-2 border-t p-4", children: [
790
+ /* @__PURE__ */ jsxRuntime.jsx(button.Button, { variant: "outline", disabled: isPending, onClick: handleClose, children: "Cancel" }),
791
+ /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { onClick: handleSaveIndex, disabled: !canSave || isPending, children: [
792
+ isPending && /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Loader2, { className: "h-4 w-4 animate-spin" }),
793
+ isPending ? "Saving..." : isEditMode ? "Update index" : "Create index"
794
+ ] })
795
+ ] })
796
+ ] });
797
+ };
798
+ function EmptyStateCard({
799
+ icon: Icon,
800
+ title,
801
+ description,
802
+ actionLabel,
803
+ actionIcon: ActionIcon,
804
+ onAction,
805
+ actionTestId,
806
+ features,
807
+ className
808
+ }) {
809
+ return /* @__PURE__ */ jsxRuntime.jsx("div", { className: cn("@container flex w-full items-center justify-center py-12", className), children: /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "bg-card border-border max-w-2xl rounded-lg border p-6 @md:p-8", children: [
810
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex flex-col items-center text-center", children: [
811
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-primary/20 bg-primary/10 mb-4 flex h-20 w-20 items-center justify-center rounded-2xl border", children: /* @__PURE__ */ jsxRuntime.jsx(Icon, { className: "text-primary h-10 w-10" }) }),
812
+ /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "mb-2 text-balance text-xl font-semibold", children: title }),
813
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground mb-6 max-w-lg text-sm", children: description }),
814
+ actionLabel && onAction && /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { onClick: onAction, size: "xl", className: "px-12", "data-testid": actionTestId, children: [
815
+ ActionIcon && /* @__PURE__ */ jsxRuntime.jsx(ActionIcon, { className: "mr-2 h-4 w-4" }),
816
+ actionLabel
817
+ ] })
818
+ ] }),
819
+ features && features.length > 0 && /* @__PURE__ */ jsxRuntime.jsx("div", { className: "border-border mt-8 grid grid-cols-1 gap-4 border-t pt-6 @sm:grid-cols-3", children: features.map((feature) => /* @__PURE__ */ jsxRuntime.jsxs(
820
+ "div",
821
+ {
822
+ className: "flex flex-row items-center gap-3 text-left @sm:flex-col @sm:items-center @sm:gap-0 @sm:text-center",
823
+ children: [
824
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "bg-muted flex h-10 w-10 shrink-0 items-center justify-center rounded-lg @sm:mb-2", children: /* @__PURE__ */ jsxRuntime.jsx(feature.icon, { className: "text-muted-foreground h-5 w-5" }) }),
825
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
826
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "mb-0.5 text-balance text-sm font-medium @sm:mb-1", children: feature.title }),
827
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground text-xs", children: feature.description })
828
+ ] })
829
+ ]
830
+ },
831
+ feature.title
832
+ )) })
833
+ ] }) });
834
+ }
835
+ function IndexEmptyState({ onCreateClick, tableName }) {
836
+ return /* @__PURE__ */ jsxRuntime.jsx(
837
+ EmptyStateCard,
838
+ {
839
+ icon: lucideReact.ListChecks,
840
+ title: tableName ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
841
+ "No indexes for ",
842
+ tableName
843
+ ] }) : "Create your first index",
844
+ description: tableName ? `Add an index to improve query performance on ${tableName}. Indexes speed up data retrieval by creating efficient lookup structures.` : "Create indexes to optimize query performance. Indexes help the database find and retrieve data faster.",
845
+ actionLabel: "Create Index",
846
+ actionIcon: lucideReact.ListChecks,
847
+ onAction: onCreateClick,
848
+ features: [
849
+ { icon: lucideReact.Zap, title: "Faster Queries", description: "Speed up data retrieval operations" },
850
+ { icon: lucideReact.Search, title: "Efficient Lookups", description: "Quick access to specific rows" },
851
+ { icon: lucideReact.Shield, title: "Unique Constraints", description: "Enforce data uniqueness rules" }
852
+ ]
853
+ }
854
+ );
855
+ }
856
+ var FIELD_SUMMARY_LIMIT2 = 4;
857
+ function buildFieldSummary(fieldIds, tableFields, limit = FIELD_SUMMARY_LIMIT2) {
858
+ const fieldNameList = fieldIds.map((fieldId) => tableFields.find((field) => field.id === fieldId)?.name || fieldId).filter(Boolean);
859
+ const visibleFields = fieldNameList.slice(0, limit);
860
+ const remainingCount = Math.max(fieldNameList.length - visibleFields.length, 0);
861
+ const hasFields = fieldNameList.length > 0;
862
+ const fieldSummary = hasFields ? `${visibleFields.join(", ")}${remainingCount > 0 ? `, +${remainingCount} more` : ""}` : "None";
863
+ return {
864
+ fieldSummary,
865
+ fieldNameList,
866
+ hasFields
867
+ };
868
+ }
869
+ function NoTableSelectedState() {
870
+ return /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex min-h-0 flex-1 flex-col items-center justify-center p-6", children: [
871
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "bg-muted/50 mb-4 flex h-16 w-16 items-center justify-center rounded-full", children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Table2, { className: "text-muted-foreground h-8 w-8" }) }),
872
+ /* @__PURE__ */ jsxRuntime.jsx("h3", { className: "mb-1 text-balance text-lg font-semibold", children: "No table selected" }),
873
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "text-muted-foreground max-w-sm text-center text-sm", children: "Select a table from the sidebar to view and manage its indexes." })
874
+ ] });
875
+ }
876
+ function IndexesView() {
877
+ const [deleteTarget, setDeleteTarget] = react.useState(null);
878
+ const [isDeleting, setIsDeleting] = react.useState(false);
879
+ const stack$1 = stack.useCardStack();
880
+ const { currentTable } = useSchemaBuilderSelectors();
881
+ const deleteIndexMutation = useDeleteIndex();
882
+ if (!currentTable) {
883
+ return /* @__PURE__ */ jsxRuntime.jsx(NoTableSelectedState, {});
884
+ }
885
+ const indexes = currentTable.indexes || [];
886
+ const hasIndexes = indexes.length > 0;
887
+ const handleOpenCreate = () => {
888
+ stack$1.push({
889
+ id: "index-new",
890
+ title: "Create Index",
891
+ Component: IndexCard,
892
+ props: { editingIndex: null },
893
+ width: CARD_WIDTHS.medium
894
+ });
895
+ };
896
+ const handleOpenEdit = (index) => {
897
+ stack$1.push({
898
+ id: `index-${index.id}`,
899
+ title: "Edit Index",
900
+ Component: IndexCard,
901
+ props: { editingIndex: index },
902
+ width: CARD_WIDTHS.medium
903
+ });
904
+ };
905
+ const handleDeleteRequest = (indexId, indexName) => {
906
+ setDeleteTarget({ id: indexId, name: indexName });
907
+ };
908
+ const handleDeleteConfirm = async () => {
909
+ if (!deleteTarget) return;
910
+ setIsDeleting(true);
911
+ try {
912
+ await deleteIndexMutation.mutateAsync({ id: deleteTarget.id });
913
+ toast.toast.success({ message: "Index deleted" });
914
+ setDeleteTarget(null);
915
+ } catch (error) {
916
+ toast.toast.error({
917
+ message: "Failed to delete index",
918
+ description: error instanceof Error ? error.message : "An error occurred"
919
+ });
920
+ } finally {
921
+ setIsDeleting(false);
922
+ }
923
+ };
924
+ return /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
925
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "flex min-h-0 flex-1 flex-col overflow-auto p-6", children: !hasIndexes ? /* @__PURE__ */ jsxRuntime.jsx(IndexEmptyState, { onCreateClick: handleOpenCreate, tableName: currentTable.name }) : /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "mx-auto w-full max-w-4xl space-y-6", children: [
926
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
927
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { children: [
928
+ /* @__PURE__ */ jsxRuntime.jsx("h2", { className: "text-balance text-xl font-semibold tracking-tight", children: "Indexes" }),
929
+ /* @__PURE__ */ jsxRuntime.jsxs("p", { className: "text-muted-foreground mt-1 text-sm", children: [
930
+ indexes.length,
931
+ " index",
932
+ indexes.length !== 1 ? "es" : "",
933
+ " on",
934
+ " ",
935
+ /* @__PURE__ */ jsxRuntime.jsx("code", { className: "bg-muted rounded px-1.5 py-0.5 font-mono text-xs", children: currentTable.name })
936
+ ] })
937
+ ] }),
938
+ /* @__PURE__ */ jsxRuntime.jsxs(button.Button, { onClick: handleOpenCreate, children: [
939
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Plus, { className: "mr-2 h-4 w-4" }),
940
+ "Add Index"
941
+ ] })
942
+ ] }),
943
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "space-y-3", children: indexes.map((index) => {
944
+ const { fieldNameList, hasFields } = buildFieldSummary(index.fields, currentTable.fields);
945
+ return /* @__PURE__ */ jsxRuntime.jsxs(
946
+ "div",
947
+ {
948
+ role: "button",
949
+ tabIndex: 0,
950
+ onClick: () => handleOpenEdit(index),
951
+ onKeyDown: (event) => {
952
+ handleActivationKeyDown(event, () => handleOpenEdit(index));
953
+ },
954
+ className: cn(
955
+ `group relative cursor-pointer rounded-xl border p-4 transition-[background-color,border-color,box-shadow,scale]
956
+ duration-150 ease-out motion-safe:active:scale-[0.96]`,
957
+ "border-border/60 hover:border-border/80 hover:bg-muted/30"
958
+ ),
959
+ children: [
960
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center justify-between", children: [
961
+ /* @__PURE__ */ jsxRuntime.jsxs("div", { className: "flex items-center gap-2", children: [
962
+ /* @__PURE__ */ jsxRuntime.jsx(lucideReact.ListChecks, { className: "text-muted-foreground h-4 w-4" }),
963
+ /* @__PURE__ */ jsxRuntime.jsx("p", { className: "truncate text-sm font-semibold", children: index.name || "Unnamed index" }),
964
+ /* @__PURE__ */ jsxRuntime.jsx(
965
+ "span",
966
+ {
967
+ className: cn(
968
+ "rounded-full px-2 py-0.5 text-[10px] font-semibold tracking-wide uppercase",
969
+ "border border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400"
970
+ ),
971
+ children: INDEX_TYPE_LABELS[index.type ?? "btree"] ?? index.type ?? "B-tree"
972
+ }
973
+ ),
974
+ index.unique && /* @__PURE__ */ jsxRuntime.jsx(
975
+ "span",
976
+ {
977
+ className: cn(
978
+ "rounded-full px-2 py-0.5 text-[10px] font-semibold tracking-wide uppercase",
979
+ "border border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"
980
+ ),
981
+ children: "Unique"
982
+ }
983
+ )
984
+ ] }),
985
+ /* @__PURE__ */ jsxRuntime.jsx(
986
+ button.Button,
987
+ {
988
+ variant: "ghost",
989
+ size: "sm",
990
+ "aria-label": "Delete index",
991
+ className: "text-muted-foreground hover:text-destructive hover:bg-destructive/10 h-8 w-8 shrink-0 p-0",
992
+ onClick: (e) => {
993
+ e.stopPropagation();
994
+ handleDeleteRequest(index.id, index.name || "this index");
995
+ },
996
+ children: /* @__PURE__ */ jsxRuntime.jsx(lucideReact.Trash2, { className: "h-4 w-4" })
997
+ }
998
+ )
999
+ ] }),
1000
+ /* @__PURE__ */ jsxRuntime.jsx("div", { className: "mt-2.5 flex flex-wrap items-center gap-1.5", children: hasFields ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
1001
+ fieldNameList.slice(0, FIELD_SUMMARY_LIMIT2).map((name) => /* @__PURE__ */ jsxRuntime.jsx(
1002
+ "span",
1003
+ {
1004
+ className: "bg-muted/60 text-foreground/80 rounded-md px-2 py-0.5 font-mono text-xs",
1005
+ children: name
1006
+ },
1007
+ name
1008
+ )),
1009
+ fieldNameList.length > FIELD_SUMMARY_LIMIT2 && /* @__PURE__ */ jsxRuntime.jsxs(tooltip.Tooltip, { children: [
1010
+ /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipTrigger, { asChild: true, children: /* @__PURE__ */ jsxRuntime.jsxs("span", { className: "text-muted-foreground rounded-md px-1.5 py-0.5 text-xs", children: [
1011
+ "+",
1012
+ fieldNameList.length - FIELD_SUMMARY_LIMIT2,
1013
+ " more"
1014
+ ] }) }),
1015
+ /* @__PURE__ */ jsxRuntime.jsx(tooltip.TooltipContent, { className: "max-w-xs", children: fieldNameList.join(", ") })
1016
+ ] })
1017
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx("span", { className: "text-muted-foreground text-xs", children: "No fields" }) })
1018
+ ]
1019
+ },
1020
+ index.id
1021
+ );
1022
+ }) })
1023
+ ] }) }),
1024
+ /* @__PURE__ */ jsxRuntime.jsx(
1025
+ DeleteConfirmDialog,
1026
+ {
1027
+ entityType: "Index",
1028
+ entityName: deleteTarget?.name ?? null,
1029
+ open: !!deleteTarget,
1030
+ onOpenChange: () => setDeleteTarget(null),
1031
+ onConfirm: handleDeleteConfirm,
1032
+ isPending: isDeleting
1033
+ }
1034
+ )
1035
+ ] });
1036
+ }
1037
+
1038
+ exports.IndexesView = IndexesView;
1039
+ exports.useCreateIndex = useCreateIndex;
1040
+ exports.useDeleteIndex = useDeleteIndex;
1041
+ exports.useUpdateIndex = useUpdateIndex;
1042
+ //# sourceMappingURL=indexes.cjs.map
1043
+ //# sourceMappingURL=indexes.cjs.map