@constructive-io/schema-builder 0.2.0 → 0.2.1

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 (131) hide show
  1. package/CHANGELOG.md +11 -0
  2. package/dist/card-widths-CmIxkRfh.cjs +28 -0
  3. package/dist/card-widths-CmIxkRfh.cjs.map +1 -0
  4. package/dist/card-widths-pI4Kw4Xz.js +22 -0
  5. package/dist/card-widths-pI4Kw4Xz.js.map +1 -0
  6. package/dist/core-WwCS0CKu.cjs +66 -0
  7. package/dist/core-WwCS0CKu.cjs.map +1 -0
  8. package/dist/core-kx6KjxE5.js +49 -0
  9. package/dist/core-kx6KjxE5.js.map +1 -0
  10. package/dist/core.cjs +14 -212
  11. package/dist/core.d.cts +3 -54
  12. package/dist/core.d.ts +3 -54
  13. package/dist/core.js +3 -200
  14. package/dist/create-table-card-BzNKfpXO.cjs +7726 -0
  15. package/dist/create-table-card-BzNKfpXO.cjs.map +1 -0
  16. package/dist/create-table-card-pZ0Aq6rr.js +7685 -0
  17. package/dist/create-table-card-pZ0Aq6rr.js.map +1 -0
  18. package/dist/delete-confirm-dialog-Ch4tWj6B.cjs +42 -0
  19. package/dist/delete-confirm-dialog-Ch4tWj6B.cjs.map +1 -0
  20. package/dist/delete-confirm-dialog-K0AWE643.js +37 -0
  21. package/dist/delete-confirm-dialog-K0AWE643.js.map +1 -0
  22. package/dist/empty-state-card-DMn8ADRq.cjs +62 -0
  23. package/dist/empty-state-card-DMn8ADRq.cjs.map +1 -0
  24. package/dist/empty-state-card-Dnn36JVH.js +57 -0
  25. package/dist/empty-state-card-Dnn36JVH.js.map +1 -0
  26. package/dist/fields.cjs +8 -7763
  27. package/dist/fields.d.cts +39 -39
  28. package/dist/fields.d.ts +39 -39
  29. package/dist/fields.js +2 -7735
  30. package/dist/generated-types-DZMUyNBH.d.cts +27 -0
  31. package/dist/generated-types-DZMUyNBH.d.ts +27 -0
  32. package/dist/index-9h0EROdb.d.cts +56 -0
  33. package/dist/index-CwQ9QpxA.d.ts +7 -0
  34. package/dist/index-DOWB1UBK.d.cts +56 -0
  35. package/dist/index-DOWB1UBK.d.ts +56 -0
  36. package/dist/index-Dgb_e3AP.d.cts +7 -0
  37. package/dist/index-p_NegPQ5.d.ts +56 -0
  38. package/dist/index.cjs +736 -13712
  39. package/dist/index.cjs.map +1 -1
  40. package/dist/index.d.cts +4 -10
  41. package/dist/index.d.ts +4 -10
  42. package/dist/index.js +725 -13680
  43. package/dist/index.js.map +1 -1
  44. package/dist/indexes-view-CJ1WQKdp.js +736 -0
  45. package/dist/indexes-view-CJ1WQKdp.js.map +1 -0
  46. package/dist/indexes-view-peIv6QUZ.cjs +759 -0
  47. package/dist/indexes-view-peIv6QUZ.cjs.map +1 -0
  48. package/dist/indexes.cjs +6 -1041
  49. package/dist/indexes.d.cts +27 -27
  50. package/dist/indexes.d.ts +27 -27
  51. package/dist/indexes.js +2 -1016
  52. package/dist/invalidate-database-entities-9DsT5NlP.cjs +2862 -0
  53. package/dist/invalidate-database-entities-9DsT5NlP.cjs.map +1 -0
  54. package/dist/invalidate-database-entities-CmmOT3S0.js +2559 -0
  55. package/dist/invalidate-database-entities-CmmOT3S0.js.map +1 -0
  56. package/dist/keyboard-activation-BQiV0scm.js +13 -0
  57. package/dist/keyboard-activation-BQiV0scm.js.map +1 -0
  58. package/dist/keyboard-activation-D-L0IU6Y.cjs +19 -0
  59. package/dist/keyboard-activation-D-L0IU6Y.cjs.map +1 -0
  60. package/dist/policies-view-BRbpbyB6.js +1018 -0
  61. package/dist/policies-view-BRbpbyB6.js.map +1 -0
  62. package/dist/policies-view-H1HTjpmv.cjs +1023 -0
  63. package/dist/policies-view-H1HTjpmv.cjs.map +1 -0
  64. package/dist/policies.cjs +10 -5939
  65. package/dist/policies.d.cts +55 -50
  66. package/dist/policies.d.ts +55 -50
  67. package/dist/policies.js +4 -5911
  68. package/dist/policy-config-form-BwyK7DGV.js +2502 -0
  69. package/dist/policy-config-form-BwyK7DGV.js.map +1 -0
  70. package/dist/policy-config-form-CefFo6Fw.cjs +2629 -0
  71. package/dist/policy-config-form-CefFo6Fw.cjs.map +1 -0
  72. package/dist/policy-types-D_sYWb-b.d.cts +81 -0
  73. package/dist/policy-types-D_sYWb-b.d.ts +81 -0
  74. package/dist/query-BmN_qO0W.js +171 -0
  75. package/dist/query-BmN_qO0W.js.map +1 -0
  76. package/dist/query-DU-KZleN.cjs +212 -0
  77. package/dist/query-DU-KZleN.cjs.map +1 -0
  78. package/dist/relationships-view-B5TAcPHU.cjs +2452 -0
  79. package/dist/relationships-view-B5TAcPHU.cjs.map +1 -0
  80. package/dist/relationships-view-DbwFh5r-.js +2417 -0
  81. package/dist/relationships-view-DbwFh5r-.js.map +1 -0
  82. package/dist/relationships.cjs +9 -4328
  83. package/dist/relationships.d.cts +93 -92
  84. package/dist/relationships.d.ts +93 -92
  85. package/dist/relationships.js +2 -4300
  86. package/dist/rolldown-runtime-D_qnwXdH.cjs +35 -0
  87. package/dist/schema-builder-sidebar-Ctu621Vw.cjs +604 -0
  88. package/dist/schema-builder-sidebar-Ctu621Vw.cjs.map +1 -0
  89. package/dist/schema-builder-sidebar-VR-Ctidc.js +593 -0
  90. package/dist/schema-builder-sidebar-VR-Ctidc.js.map +1 -0
  91. package/dist/table-editor-C-hHz3DJ.cjs +1935 -0
  92. package/dist/table-editor-C-hHz3DJ.cjs.map +1 -0
  93. package/dist/table-editor-IVp3B4nG.js +1906 -0
  94. package/dist/table-editor-IVp3B4nG.js.map +1 -0
  95. package/dist/tables.cjs +6 -5643
  96. package/dist/tables.d.cts +22 -21
  97. package/dist/tables.d.ts +22 -21
  98. package/dist/tables.js +3 -5618
  99. package/dist/testing.cjs +63 -62
  100. package/dist/testing.cjs.map +1 -1
  101. package/dist/testing.d.cts +4 -4
  102. package/dist/testing.d.ts +4 -4
  103. package/dist/testing.js +62 -61
  104. package/dist/testing.js.map +1 -1
  105. package/dist/types-GUrH1Qny.d.cts +200 -0
  106. package/dist/types-GUrH1Qny.d.ts +200 -0
  107. package/dist/use-update-table-C7v3gRyG.cjs +291 -0
  108. package/dist/use-update-table-C7v3gRyG.cjs.map +1 -0
  109. package/dist/use-update-table-Dz6knGoH.js +244 -0
  110. package/dist/use-update-table-Dz6knGoH.js.map +1 -0
  111. package/package.json +6 -6
  112. package/dist/core.cjs.map +0 -1
  113. package/dist/core.js.map +0 -1
  114. package/dist/fields.cjs.map +0 -1
  115. package/dist/fields.js.map +0 -1
  116. package/dist/generated-types-CnAlqHU_.d.cts +0 -25
  117. package/dist/generated-types-CnAlqHU_.d.ts +0 -25
  118. package/dist/indexes.cjs.map +0 -1
  119. package/dist/indexes.js.map +0 -1
  120. package/dist/policies.cjs.map +0 -1
  121. package/dist/policies.js.map +0 -1
  122. package/dist/policy-types-CEYAR5TN.d.cts +0 -79
  123. package/dist/policy-types-CEYAR5TN.d.ts +0 -79
  124. package/dist/relationships.cjs.map +0 -1
  125. package/dist/relationships.js.map +0 -1
  126. package/dist/tables.cjs.map +0 -1
  127. package/dist/tables.js.map +0 -1
  128. package/dist/types-Du86atZ8.d.cts +0 -199
  129. package/dist/types-Du86atZ8.d.ts +0 -199
  130. package/dist/types-bX2dCrdl.d.cts +0 -52
  131. package/dist/types-bX2dCrdl.d.ts +0 -52
@@ -0,0 +1,736 @@
1
+ 'use client';
2
+ import { E as useDeleteIndexMutation, P as useUpdateIndexMutation, Y as cn, l as useSchemaBuilderSelectors, o as asFieldIds, q as INDEX_TYPE_LABELS, t as invalidateDatabaseEntities, y as useCreateIndexMutation } from "./invalidate-database-entities-CmmOT3S0.js";
3
+ import { t as CARD_WIDTHS } from "./card-widths-pI4Kw4Xz.js";
4
+ import { t as handleActivationKeyDown } from "./keyboard-activation-BQiV0scm.js";
5
+ import { t as EmptyStateCard } from "./empty-state-card-Dnn36JVH.js";
6
+ import { t as DeleteConfirmDialog } from "./delete-confirm-dialog-K0AWE643.js";
7
+ import { useCardStack } from "@constructive-io/ui/stack";
8
+ import { useCallback, useEffect, useMemo, useState, useTransition } from "react";
9
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
10
+ import { Tooltip, TooltipContent, TooltipTrigger } from "@constructive-io/ui/tooltip";
11
+ import { Database, DatabaseZap, ListChecks, Loader2, Plus, Search, Shield, Table2, Trash2, Zap } from "lucide-react";
12
+ import { useMutation, useQueryClient } from "@tanstack/react-query";
13
+ import { Button } from "@constructive-io/ui/button";
14
+ import { toast } from "@constructive-io/ui/toast";
15
+ import { Input } from "@constructive-io/ui/input";
16
+ import { Label } from "@constructive-io/ui/label";
17
+ import { ScrollArea } from "@constructive-io/ui/scroll-area";
18
+ import { ResponsiveDiagram } from "@constructive-io/ui/responsive-diagram";
19
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@constructive-io/ui/select";
20
+ import { Switch } from "@constructive-io/ui/switch";
21
+ import { MultiSelect } from "@constructive-io/ui/multi-select";
22
+
23
+ //#region src/schema/schema-builder-indexes/lib/gql/hooks/schema-builder/use-index-mutations.ts
24
+ /**
25
+ * Hook for managing indexes
26
+ * Tier 4 wrapper: adds cache invalidation and table selection
27
+ */
28
+ function useCreateIndex() {
29
+ const queryClient = useQueryClient();
30
+ const { selectTable, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
31
+ const createIndexMutation = useCreateIndexMutation({ selection: { fields: {
32
+ id: true,
33
+ name: true
34
+ } } });
35
+ return useMutation({
36
+ mutationFn: async (input) => {
37
+ const databaseId = currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId;
38
+ if (!databaseId) throw new Error("Database ID not found");
39
+ const createdIndex = (await createIndexMutation.mutateAsync({
40
+ databaseId,
41
+ tableId: input.tableId,
42
+ name: input.name,
43
+ fieldIds: asFieldIds(input.fieldIds),
44
+ isUnique: input.isUnique ?? false,
45
+ accessMethod: input.accessMethod || "btree"
46
+ })).createIndex?.index;
47
+ if (!createdIndex?.id) throw new Error("Failed to create index");
48
+ return {
49
+ id: createdIndex.id,
50
+ name: createdIndex.name ?? ""
51
+ };
52
+ },
53
+ onSuccess: async (_createdIndex, variables) => {
54
+ await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
55
+ selectTable(variables.tableId);
56
+ },
57
+ onError: (error) => {
58
+ console.error("Failed to create index:", error);
59
+ }
60
+ });
61
+ }
62
+ function useUpdateIndex() {
63
+ const queryClient = useQueryClient();
64
+ const { selectTable, selectedTableId, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
65
+ const updateIndexMutation = useUpdateIndexMutation({ selection: { fields: {
66
+ id: true,
67
+ name: true
68
+ } } });
69
+ return useMutation({
70
+ mutationFn: async (input) => {
71
+ const patch = {};
72
+ if (input.name !== void 0) patch.name = input.name;
73
+ if (input.fieldIds !== void 0) patch.fieldIds = input.fieldIds;
74
+ if (input.isUnique !== void 0) patch.isUnique = input.isUnique;
75
+ if (input.accessMethod !== void 0) patch.accessMethod = input.accessMethod;
76
+ const updatedIndex = (await updateIndexMutation.mutateAsync({
77
+ id: input.id,
78
+ indexPatch: patch
79
+ })).updateIndex?.index;
80
+ if (!updatedIndex?.id) throw new Error("Failed to update index");
81
+ return {
82
+ id: updatedIndex.id,
83
+ name: updatedIndex.name ?? ""
84
+ };
85
+ },
86
+ onSuccess: async () => {
87
+ await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
88
+ if (selectedTableId) selectTable(selectedTableId);
89
+ },
90
+ onError: (error) => {
91
+ console.error("Failed to update index:", error);
92
+ }
93
+ });
94
+ }
95
+ function useDeleteIndex() {
96
+ const queryClient = useQueryClient();
97
+ const { selectTable, selectedTableId, currentDatabase, currentSchema } = useSchemaBuilderSelectors();
98
+ const deleteIndexMutation = useDeleteIndexMutation({ selection: { fields: { id: true } } });
99
+ return useMutation({
100
+ mutationFn: async (input) => {
101
+ await deleteIndexMutation.mutateAsync({ id: input.id });
102
+ return { id: input.id };
103
+ },
104
+ onSuccess: async () => {
105
+ await invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId ?? currentSchema?.metadata?.databaseId);
106
+ if (selectedTableId) selectTable(selectedTableId);
107
+ },
108
+ onError: (error) => {
109
+ console.error("Failed to delete index:", error);
110
+ }
111
+ });
112
+ }
113
+
114
+ //#endregion
115
+ //#region src/schema/schema-builder-indexes/components/table-editor/index-diagram.tsx
116
+ const THEME = {
117
+ primary: "#6366F1",
118
+ light: "#E0E7FF",
119
+ border: "#A5B4FC",
120
+ connector: "#6366F1",
121
+ connectorLight: "#C7D2FE"
122
+ };
123
+ const MAX_NAME_WIDTH = 120;
124
+ function truncateName(name, maxWidth) {
125
+ const maxChars = Math.floor(maxWidth / 7);
126
+ if (name.length <= maxChars) return name;
127
+ return name.slice(0, maxChars - 1) + "…";
128
+ }
129
+ function TableFieldsNode({ tableName, fields, theme }) {
130
+ const fieldsLabel = (fields.length > 0 ? fields : ["field"]).join(", ");
131
+ const sizeClasses = "h-14 w-14";
132
+ return /* @__PURE__ */ jsxs("div", {
133
+ className: "flex flex-col items-center gap-1.5",
134
+ children: [/* @__PURE__ */ jsxs("div", {
135
+ className: "relative",
136
+ children: [/* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
137
+ className: cn("absolute -top-1.5 -left-2 rounded-full border-2 bg-white", sizeClasses),
138
+ style: { borderColor: theme.border }
139
+ }), /* @__PURE__ */ jsx("div", {
140
+ className: cn("absolute -top-0.5 -left-1 rounded-full border-2 bg-white", sizeClasses),
141
+ style: { borderColor: theme.border }
142
+ })] }), /* @__PURE__ */ jsx("div", {
143
+ className: cn("relative flex items-center justify-center rounded-full border-2 shadow-sm", sizeClasses),
144
+ style: {
145
+ borderColor: theme.border,
146
+ backgroundColor: theme.light
147
+ },
148
+ children: /* @__PURE__ */ jsx(Database, {
149
+ className: "size-6",
150
+ style: { color: theme.primary }
151
+ })
152
+ })]
153
+ }), /* @__PURE__ */ jsxs("div", {
154
+ className: "flex flex-col items-center gap-0.5",
155
+ children: [/* @__PURE__ */ jsx("span", {
156
+ className: "truncate text-sm font-medium text-gray-600 dark:text-gray-300",
157
+ style: { maxWidth: MAX_NAME_WIDTH },
158
+ title: tableName,
159
+ children: truncateName(tableName || "Table", MAX_NAME_WIDTH)
160
+ }), /* @__PURE__ */ jsx("span", {
161
+ className: "truncate text-xs text-gray-600 dark:text-gray-400",
162
+ style: { maxWidth: MAX_NAME_WIDTH },
163
+ title: fieldsLabel,
164
+ children: truncateName(fieldsLabel, MAX_NAME_WIDTH)
165
+ })]
166
+ })]
167
+ });
168
+ }
169
+ function IndexNode({ indexName, typeLabel, theme, isUnique }) {
170
+ return /* @__PURE__ */ jsxs("div", {
171
+ className: "flex flex-col items-center gap-2",
172
+ children: [/* @__PURE__ */ jsxs("div", {
173
+ className: "relative",
174
+ children: [/* @__PURE__ */ jsxs("div", {
175
+ className: "flex flex-col items-center gap-1 rounded-lg border-2 bg-white px-3 py-2",
176
+ style: {
177
+ borderColor: theme.border,
178
+ backgroundColor: theme.light
179
+ },
180
+ children: [/* @__PURE__ */ jsx(DatabaseZap, {
181
+ className: "size-6",
182
+ style: { color: theme.primary }
183
+ }), /* @__PURE__ */ jsx("span", {
184
+ className: "max-w-[100px] truncate text-center text-xs font-medium",
185
+ style: { color: theme.primary },
186
+ title: typeLabel,
187
+ children: typeLabel
188
+ })]
189
+ }), isUnique && /* @__PURE__ */ jsx("div", {
190
+ className: "absolute -right-2 -bottom-2 flex h-6 w-6 items-center justify-center rounded-full border-2\n border-white shadow-sm",
191
+ style: { backgroundColor: theme.primary },
192
+ children: /* @__PURE__ */ jsx("span", {
193
+ className: "text-[10px] font-bold text-white",
194
+ children: "U"
195
+ })
196
+ })]
197
+ }), /* @__PURE__ */ jsx("span", {
198
+ className: "max-w-[100px] truncate text-center text-sm text-gray-600 dark:text-gray-300",
199
+ title: indexName,
200
+ children: truncateName(indexName || "Index", 100)
201
+ })]
202
+ });
203
+ }
204
+ function ArrowConnector({ theme, label }) {
205
+ return /* @__PURE__ */ jsxs("div", {
206
+ className: "relative flex flex-col items-center justify-center",
207
+ children: [/* @__PURE__ */ jsx("div", {
208
+ 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",
209
+ style: {
210
+ borderColor: theme.primary,
211
+ backgroundColor: theme.light,
212
+ color: theme.primary
213
+ },
214
+ children: label
215
+ }), /* @__PURE__ */ jsxs("svg", {
216
+ width: 90,
217
+ height: "40",
218
+ viewBox: "0 0 90 40",
219
+ fill: "none",
220
+ children: [
221
+ /* @__PURE__ */ jsx("circle", {
222
+ cx: "6",
223
+ cy: "20",
224
+ r: "4",
225
+ fill: theme.connector
226
+ }),
227
+ /* @__PURE__ */ jsx("line", {
228
+ x1: "10",
229
+ y1: "20",
230
+ x2: "74",
231
+ y2: "20",
232
+ stroke: theme.connectorLight,
233
+ strokeWidth: "2.5",
234
+ strokeLinecap: "round"
235
+ }),
236
+ /* @__PURE__ */ jsx("polygon", {
237
+ points: "84,20 76,15 76,25",
238
+ fill: theme.connector
239
+ })
240
+ ]
241
+ })]
242
+ });
243
+ }
244
+ function IndexDiagram({ tableName, indexName, fields, indexType, isUnique }) {
245
+ const theme = THEME;
246
+ const typeLabel = INDEX_TYPE_LABELS[indexType && INDEX_TYPE_LABELS[indexType] ? indexType : "btree"];
247
+ return /* @__PURE__ */ jsxs("div", {
248
+ className: "flex items-center justify-center gap-3",
249
+ children: [
250
+ /* @__PURE__ */ jsx(IndexNode, {
251
+ indexName: indexName || "Index",
252
+ typeLabel,
253
+ theme,
254
+ isUnique
255
+ }),
256
+ /* @__PURE__ */ jsx(ArrowConnector, {
257
+ theme,
258
+ label: "indexes"
259
+ }),
260
+ /* @__PURE__ */ jsx(TableFieldsNode, {
261
+ tableName,
262
+ fields,
263
+ theme
264
+ })
265
+ ]
266
+ });
267
+ }
268
+
269
+ //#endregion
270
+ //#region src/schema/schema-builder-indexes/components/table-editor/index-card.tsx
271
+ const FIELD_SUMMARY_LIMIT$1 = 4;
272
+ const indexTypeOptions = Object.keys(INDEX_TYPE_LABELS).map((value) => ({
273
+ value,
274
+ label: value === "btree" ? `${INDEX_TYPE_LABELS[value]} (default)` : INDEX_TYPE_LABELS[value]
275
+ }));
276
+ function normalizeIndexType(type) {
277
+ const raw = type?.toLowerCase();
278
+ return raw && raw in INDEX_TYPE_LABELS ? raw : "btree";
279
+ }
280
+ function generateIndexName(tableName, existingIndexes) {
281
+ let counter = 1;
282
+ let candidateName = `${tableName}_index_${counter}`;
283
+ while (existingIndexes.some((idx) => idx.name === candidateName)) {
284
+ counter++;
285
+ candidateName = `${tableName}_index_${counter}`;
286
+ }
287
+ return candidateName;
288
+ }
289
+ const IndexCard = ({ editingIndex: initialEditingIndex, card }) => {
290
+ const { currentTable } = useSchemaBuilderSelectors();
291
+ const createIndexMutation = useCreateIndex();
292
+ const updateIndexMutation = useUpdateIndex();
293
+ const [isPendingTransition, startTransition] = useTransition();
294
+ const indexes = currentTable?.indexes || [];
295
+ const [editingIndex, setEditingIndex] = useState(() => {
296
+ if (initialEditingIndex) return {
297
+ ...initialEditingIndex,
298
+ fields: [...initialEditingIndex.fields],
299
+ type: normalizeIndexType(initialEditingIndex.type)
300
+ };
301
+ return null;
302
+ });
303
+ const [originalIndex, setOriginalIndex] = useState(() => {
304
+ if (initialEditingIndex) return {
305
+ ...initialEditingIndex,
306
+ fields: [...initialEditingIndex.fields],
307
+ type: normalizeIndexType(initialEditingIndex.type)
308
+ };
309
+ return null;
310
+ });
311
+ const fieldOptions = useMemo(() => currentTable?.fields.map((field) => ({
312
+ label: field.name,
313
+ value: field.id
314
+ })) || [], [currentTable?.fields]);
315
+ const fieldNameMap = useMemo(() => {
316
+ const map = {};
317
+ currentTable?.fields.forEach((field) => {
318
+ map[field.id] = field.name;
319
+ });
320
+ return map;
321
+ }, [currentTable?.fields]);
322
+ useEffect(() => {
323
+ if (!initialEditingIndex && currentTable && !editingIndex) startTransition(() => {
324
+ const generatedName = generateIndexName(currentTable.name, indexes);
325
+ setEditingIndex({
326
+ id: `idx-${Date.now()}`,
327
+ name: generatedName,
328
+ fields: [],
329
+ unique: false,
330
+ type: "btree"
331
+ });
332
+ });
333
+ }, [
334
+ initialEditingIndex,
335
+ currentTable,
336
+ indexes,
337
+ editingIndex
338
+ ]);
339
+ const handleSaveIndex = useCallback(async () => {
340
+ if (!editingIndex || editingIndex.fields.length === 0 || !currentTable) return;
341
+ const trimmedName = editingIndex.name?.trim() ?? "";
342
+ if (!trimmedName) return;
343
+ const isExisting = indexes.some((index) => index.id === editingIndex.id);
344
+ try {
345
+ if (isExisting) {
346
+ await updateIndexMutation.mutateAsync({
347
+ id: editingIndex.id,
348
+ name: trimmedName,
349
+ fieldIds: editingIndex.fields,
350
+ isUnique: editingIndex.type === "btree" ? editingIndex.unique : false,
351
+ accessMethod: editingIndex.type
352
+ });
353
+ toast.success({
354
+ message: "Index updated",
355
+ description: `Index "${trimmedName}" has been updated`
356
+ });
357
+ } else {
358
+ await createIndexMutation.mutateAsync({
359
+ tableId: currentTable.id,
360
+ name: trimmedName,
361
+ fieldIds: editingIndex.fields,
362
+ isUnique: editingIndex.type === "btree" ? editingIndex.unique : false,
363
+ accessMethod: editingIndex.type
364
+ });
365
+ toast.success({
366
+ message: "Index created",
367
+ description: `Index "${trimmedName}" has been created`
368
+ });
369
+ }
370
+ card.close();
371
+ } catch (error) {
372
+ toast.error({
373
+ message: isExisting ? "Failed to update index" : "Failed to create index",
374
+ description: error instanceof Error ? error.message : "An error occurred"
375
+ });
376
+ }
377
+ }, [
378
+ editingIndex,
379
+ currentTable,
380
+ indexes,
381
+ updateIndexMutation,
382
+ createIndexMutation,
383
+ card
384
+ ]);
385
+ const handleNameChange = useCallback((event) => {
386
+ setEditingIndex((prev) => prev ? {
387
+ ...prev,
388
+ name: event.target.value
389
+ } : null);
390
+ }, []);
391
+ const handleFieldsChange = useCallback((values) => {
392
+ setEditingIndex((prev) => prev ? {
393
+ ...prev,
394
+ fields: values
395
+ } : null);
396
+ }, []);
397
+ const handleTypeChange = useCallback((value) => {
398
+ setEditingIndex((prev) => prev ? {
399
+ ...prev,
400
+ type: value,
401
+ unique: value === "btree" ? prev.unique : false
402
+ } : null);
403
+ }, []);
404
+ const handleUniqueChange = useCallback((checked) => {
405
+ setEditingIndex((prev) => prev ? {
406
+ ...prev,
407
+ unique: checked
408
+ } : null);
409
+ }, []);
410
+ const handleClose = useCallback(() => {
411
+ card.close();
412
+ }, [card]);
413
+ const hasChanges = useMemo(() => {
414
+ if (originalIndex === null) return true;
415
+ if (!editingIndex) return false;
416
+ 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]);
417
+ }, [editingIndex, originalIndex]);
418
+ if (!currentTable) return null;
419
+ const isEditMode = initialEditingIndex !== null;
420
+ const selectedIndexType = editingIndex?.type ?? "btree";
421
+ const selectedFieldNames = editingIndex?.fields.map((id) => fieldNameMap[id] || id) || [];
422
+ const canSave = editingIndex && editingIndex.fields.length > 0 && (editingIndex.name?.trim().length ?? 0) > 0 && hasChanges;
423
+ const isPending = createIndexMutation.isPending || updateIndexMutation.isPending;
424
+ return /* @__PURE__ */ jsxs("div", {
425
+ className: "flex h-full flex-col",
426
+ children: [/* @__PURE__ */ jsx(ScrollArea, {
427
+ className: "min-h-0 flex-1",
428
+ children: /* @__PURE__ */ jsxs("div", {
429
+ className: "space-y-6 p-6",
430
+ children: [/* @__PURE__ */ jsx(ResponsiveDiagram, {
431
+ className: "py-8",
432
+ children: /* @__PURE__ */ jsx(IndexDiagram, {
433
+ tableName: currentTable.name,
434
+ indexName: editingIndex?.name,
435
+ fields: selectedFieldNames,
436
+ indexType: selectedIndexType,
437
+ isUnique: editingIndex?.unique ?? false
438
+ })
439
+ }), editingIndex && /* @__PURE__ */ jsxs("div", {
440
+ className: "space-y-4",
441
+ children: [
442
+ /* @__PURE__ */ jsxs("div", {
443
+ className: "space-y-2",
444
+ children: [/* @__PURE__ */ jsx(Label, {
445
+ className: "block",
446
+ htmlFor: "index-name",
447
+ children: "Index name"
448
+ }), /* @__PURE__ */ jsx(Input, {
449
+ id: "index-name",
450
+ value: editingIndex.name,
451
+ onChange: handleNameChange,
452
+ placeholder: "e.g. table_index_1"
453
+ })]
454
+ }),
455
+ /* @__PURE__ */ jsxs("div", {
456
+ className: "space-y-2",
457
+ children: [/* @__PURE__ */ jsx(Label, {
458
+ className: "block",
459
+ children: "Fields"
460
+ }), /* @__PURE__ */ jsx(MultiSelect, {
461
+ options: fieldOptions,
462
+ defaultValue: editingIndex.fields,
463
+ onValueChange: handleFieldsChange,
464
+ placeholder: "Select fields",
465
+ dropdownMaxHeight: "300px",
466
+ maxCount: FIELD_SUMMARY_LIMIT$1
467
+ })]
468
+ }),
469
+ /* @__PURE__ */ jsxs("div", {
470
+ className: "space-y-2",
471
+ children: [/* @__PURE__ */ jsx(Label, {
472
+ className: "block",
473
+ children: "Index type"
474
+ }), /* @__PURE__ */ jsxs(Select, {
475
+ value: selectedIndexType,
476
+ onValueChange: handleTypeChange,
477
+ children: [/* @__PURE__ */ jsx(SelectTrigger, { children: /* @__PURE__ */ jsx(SelectValue, { placeholder: "Select index type" }) }), /* @__PURE__ */ jsx(SelectContent, { children: indexTypeOptions.map((option) => /* @__PURE__ */ jsx(SelectItem, {
478
+ value: option.value,
479
+ children: option.label
480
+ }, option.value)) })]
481
+ })]
482
+ }),
483
+ selectedIndexType === "btree" && /* @__PURE__ */ jsxs("div", {
484
+ className: "flex items-center justify-between",
485
+ children: [/* @__PURE__ */ jsx(Label, {
486
+ htmlFor: "index-unique",
487
+ children: "Unique"
488
+ }), /* @__PURE__ */ jsx(Switch, {
489
+ id: "index-unique",
490
+ checked: editingIndex.unique ?? false,
491
+ onCheckedChange: handleUniqueChange
492
+ })]
493
+ })
494
+ ]
495
+ })]
496
+ })
497
+ }), /* @__PURE__ */ jsxs("div", {
498
+ className: "flex justify-end gap-2 border-t p-4",
499
+ children: [/* @__PURE__ */ jsx(Button, {
500
+ variant: "outline",
501
+ disabled: isPending,
502
+ onClick: handleClose,
503
+ children: "Cancel"
504
+ }), /* @__PURE__ */ jsxs(Button, {
505
+ onClick: handleSaveIndex,
506
+ disabled: !canSave || isPending,
507
+ children: [isPending && /* @__PURE__ */ jsx(Loader2, { className: "h-4 w-4 animate-spin" }), isPending ? "Saving..." : isEditMode ? "Update index" : "Create index"]
508
+ })]
509
+ })]
510
+ });
511
+ };
512
+
513
+ //#endregion
514
+ //#region src/schema/schema-builder-indexes/components/table-editor/indexes/index-empty-state.tsx
515
+ function IndexEmptyState({ onCreateClick, tableName }) {
516
+ return /* @__PURE__ */ jsx(EmptyStateCard, {
517
+ icon: ListChecks,
518
+ title: tableName ? /* @__PURE__ */ jsxs(Fragment, { children: ["No indexes for ", tableName] }) : "Create your first index",
519
+ 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.",
520
+ actionLabel: "Create Index",
521
+ actionIcon: ListChecks,
522
+ onAction: onCreateClick,
523
+ features: [
524
+ {
525
+ icon: Zap,
526
+ title: "Faster Queries",
527
+ description: "Speed up data retrieval operations"
528
+ },
529
+ {
530
+ icon: Search,
531
+ title: "Efficient Lookups",
532
+ description: "Quick access to specific rows"
533
+ },
534
+ {
535
+ icon: Shield,
536
+ title: "Unique Constraints",
537
+ description: "Enforce data uniqueness rules"
538
+ }
539
+ ]
540
+ });
541
+ }
542
+
543
+ //#endregion
544
+ //#region src/schema/schema-builder-indexes/components/table-editor/indexes/indexes-view.tsx
545
+ const FIELD_SUMMARY_LIMIT = 4;
546
+ function buildFieldSummary(fieldIds, tableFields, limit = FIELD_SUMMARY_LIMIT) {
547
+ const fieldNameList = fieldIds.map((fieldId) => tableFields.find((field) => field.id === fieldId)?.name || fieldId).filter(Boolean);
548
+ const visibleFields = fieldNameList.slice(0, limit);
549
+ const remainingCount = Math.max(fieldNameList.length - visibleFields.length, 0);
550
+ const hasFields = fieldNameList.length > 0;
551
+ return {
552
+ fieldSummary: hasFields ? `${visibleFields.join(", ")}${remainingCount > 0 ? `, +${remainingCount} more` : ""}` : "None",
553
+ fieldNameList,
554
+ hasFields
555
+ };
556
+ }
557
+ function NoTableSelectedState() {
558
+ return /* @__PURE__ */ jsxs("div", {
559
+ className: "flex min-h-0 flex-1 flex-col items-center justify-center p-6",
560
+ children: [
561
+ /* @__PURE__ */ jsx("div", {
562
+ className: "bg-muted/50 mb-4 flex h-16 w-16 items-center justify-center rounded-full",
563
+ children: /* @__PURE__ */ jsx(Table2, { className: "text-muted-foreground h-8 w-8" })
564
+ }),
565
+ /* @__PURE__ */ jsx("h3", {
566
+ className: "mb-1 text-balance text-lg font-semibold",
567
+ children: "No table selected"
568
+ }),
569
+ /* @__PURE__ */ jsx("p", {
570
+ className: "text-muted-foreground max-w-sm text-center text-sm",
571
+ children: "Select a table from the sidebar to view and manage its indexes."
572
+ })
573
+ ]
574
+ });
575
+ }
576
+ function IndexesView() {
577
+ const [deleteTarget, setDeleteTarget] = useState(null);
578
+ const [isDeleting, setIsDeleting] = useState(false);
579
+ const stack = useCardStack();
580
+ const { currentTable } = useSchemaBuilderSelectors();
581
+ const deleteIndexMutation = useDeleteIndex();
582
+ if (!currentTable) return /* @__PURE__ */ jsx(NoTableSelectedState, {});
583
+ const indexes = currentTable.indexes || [];
584
+ const hasIndexes = indexes.length > 0;
585
+ const handleOpenCreate = () => {
586
+ stack.push({
587
+ id: "index-new",
588
+ title: "Create Index",
589
+ Component: IndexCard,
590
+ props: { editingIndex: null },
591
+ width: CARD_WIDTHS.medium
592
+ });
593
+ };
594
+ const handleOpenEdit = (index) => {
595
+ stack.push({
596
+ id: `index-${index.id}`,
597
+ title: "Edit Index",
598
+ Component: IndexCard,
599
+ props: { editingIndex: index },
600
+ width: CARD_WIDTHS.medium
601
+ });
602
+ };
603
+ const handleDeleteRequest = (indexId, indexName) => {
604
+ setDeleteTarget({
605
+ id: indexId,
606
+ name: indexName
607
+ });
608
+ };
609
+ const handleDeleteConfirm = async () => {
610
+ if (!deleteTarget) return;
611
+ setIsDeleting(true);
612
+ try {
613
+ await deleteIndexMutation.mutateAsync({ id: deleteTarget.id });
614
+ toast.success({ message: "Index deleted" });
615
+ setDeleteTarget(null);
616
+ } catch (error) {
617
+ toast.error({
618
+ message: "Failed to delete index",
619
+ description: error instanceof Error ? error.message : "An error occurred"
620
+ });
621
+ } finally {
622
+ setIsDeleting(false);
623
+ }
624
+ };
625
+ return /* @__PURE__ */ jsxs(Fragment, { children: [/* @__PURE__ */ jsx("div", {
626
+ className: "flex min-h-0 flex-1 flex-col overflow-auto p-6",
627
+ children: !hasIndexes ? /* @__PURE__ */ jsx(IndexEmptyState, {
628
+ onCreateClick: handleOpenCreate,
629
+ tableName: currentTable.name
630
+ }) : /* @__PURE__ */ jsxs("div", {
631
+ className: "mx-auto w-full max-w-4xl space-y-6",
632
+ children: [/* @__PURE__ */ jsxs("div", {
633
+ className: "flex items-center justify-between",
634
+ children: [/* @__PURE__ */ jsxs("div", { children: [/* @__PURE__ */ jsx("h2", {
635
+ className: "text-balance text-xl font-semibold tracking-tight",
636
+ children: "Indexes"
637
+ }), /* @__PURE__ */ jsxs("p", {
638
+ className: "text-muted-foreground mt-1 text-sm",
639
+ children: [
640
+ indexes.length,
641
+ " index",
642
+ indexes.length !== 1 ? "es" : "",
643
+ " on",
644
+ " ",
645
+ /* @__PURE__ */ jsx("code", {
646
+ className: "bg-muted rounded px-1.5 py-0.5 font-mono text-xs",
647
+ children: currentTable.name
648
+ })
649
+ ]
650
+ })] }), /* @__PURE__ */ jsxs(Button, {
651
+ onClick: handleOpenCreate,
652
+ children: [/* @__PURE__ */ jsx(Plus, { className: "mr-2 h-4 w-4" }), "Add Index"]
653
+ })]
654
+ }), /* @__PURE__ */ jsx("div", {
655
+ className: "space-y-3",
656
+ children: indexes.map((index) => {
657
+ const { fieldNameList, hasFields } = buildFieldSummary(index.fields, currentTable.fields);
658
+ return /* @__PURE__ */ jsxs("div", {
659
+ role: "button",
660
+ tabIndex: 0,
661
+ onClick: () => handleOpenEdit(index),
662
+ onKeyDown: (event) => {
663
+ handleActivationKeyDown(event, () => handleOpenEdit(index));
664
+ },
665
+ className: cn(`group relative cursor-pointer rounded-xl border p-4 transition-[background-color,border-color,box-shadow,scale]
666
+ duration-150 ease-out motion-safe:active:scale-[0.96]`, "border-border/60 hover:border-border/80 hover:bg-muted/30"),
667
+ children: [/* @__PURE__ */ jsxs("div", {
668
+ className: "flex items-center justify-between",
669
+ children: [/* @__PURE__ */ jsxs("div", {
670
+ className: "flex items-center gap-2",
671
+ children: [
672
+ /* @__PURE__ */ jsx(ListChecks, { className: "text-muted-foreground h-4 w-4" }),
673
+ /* @__PURE__ */ jsx("p", {
674
+ className: "truncate text-sm font-semibold",
675
+ children: index.name || "Unnamed index"
676
+ }),
677
+ /* @__PURE__ */ jsx("span", {
678
+ className: cn("rounded-full px-2 py-0.5 text-[10px] font-semibold tracking-wide uppercase", "border border-blue-500/30 bg-blue-500/10 text-blue-600 dark:text-blue-400"),
679
+ children: INDEX_TYPE_LABELS[index.type ?? "btree"] ?? index.type ?? "B-tree"
680
+ }),
681
+ index.unique && /* @__PURE__ */ jsx("span", {
682
+ className: cn("rounded-full px-2 py-0.5 text-[10px] font-semibold tracking-wide uppercase", "border border-emerald-500/30 bg-emerald-500/10 text-emerald-600 dark:text-emerald-400"),
683
+ children: "Unique"
684
+ })
685
+ ]
686
+ }), /* @__PURE__ */ jsx(Button, {
687
+ variant: "ghost",
688
+ size: "sm",
689
+ "aria-label": "Delete index",
690
+ className: "text-muted-foreground hover:text-destructive hover:bg-destructive/10 h-8 w-8 shrink-0 p-0",
691
+ onClick: (e) => {
692
+ e.stopPropagation();
693
+ handleDeleteRequest(index.id, index.name || "this index");
694
+ },
695
+ children: /* @__PURE__ */ jsx(Trash2, { className: "h-4 w-4" })
696
+ })]
697
+ }), /* @__PURE__ */ jsx("div", {
698
+ className: "mt-2.5 flex flex-wrap items-center gap-1.5",
699
+ children: hasFields ? /* @__PURE__ */ jsxs(Fragment, { children: [fieldNameList.slice(0, FIELD_SUMMARY_LIMIT).map((name) => /* @__PURE__ */ jsx("span", {
700
+ className: "bg-muted/60 text-foreground/80 rounded-md px-2 py-0.5 font-mono text-xs",
701
+ children: name
702
+ }, name)), fieldNameList.length > FIELD_SUMMARY_LIMIT && /* @__PURE__ */ jsxs(Tooltip, { children: [/* @__PURE__ */ jsx(TooltipTrigger, {
703
+ asChild: true,
704
+ children: /* @__PURE__ */ jsxs("span", {
705
+ className: "text-muted-foreground rounded-md px-1.5 py-0.5 text-xs",
706
+ children: [
707
+ "+",
708
+ fieldNameList.length - FIELD_SUMMARY_LIMIT,
709
+ " more"
710
+ ]
711
+ })
712
+ }), /* @__PURE__ */ jsx(TooltipContent, {
713
+ className: "max-w-xs",
714
+ children: fieldNameList.join(", ")
715
+ })] })] }) : /* @__PURE__ */ jsx("span", {
716
+ className: "text-muted-foreground text-xs",
717
+ children: "No fields"
718
+ })
719
+ })]
720
+ }, index.id);
721
+ })
722
+ })]
723
+ })
724
+ }), /* @__PURE__ */ jsx(DeleteConfirmDialog, {
725
+ entityType: "Index",
726
+ entityName: deleteTarget?.name ?? null,
727
+ open: !!deleteTarget,
728
+ onOpenChange: () => setDeleteTarget(null),
729
+ onConfirm: handleDeleteConfirm,
730
+ isPending: isDeleting
731
+ })] });
732
+ }
733
+
734
+ //#endregion
735
+ export { useUpdateIndex as i, useCreateIndex as n, useDeleteIndex as r, IndexesView as t };
736
+ //# sourceMappingURL=indexes-view-CJ1WQKdp.js.map