@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,1935 @@
1
+ 'use client';
2
+ const require_invalidate_database_entities = require('./invalidate-database-entities-9DsT5NlP.cjs');
3
+ const require_use_update_table = require('./use-update-table-C7v3gRyG.cjs');
4
+ const require_card_widths = require('./card-widths-CmIxkRfh.cjs');
5
+ const require_keyboard_activation = require('./keyboard-activation-D-L0IU6Y.cjs');
6
+ const require_empty_state_card = require('./empty-state-card-DMn8ADRq.cjs');
7
+ const require_create_table_card = require('./create-table-card-BzNKfpXO.cjs');
8
+ let _constructive_io_ui_stack = require("@constructive-io/ui/stack");
9
+ let motion_react = require("motion/react");
10
+ let react = require("react");
11
+ let react_jsx_runtime = require("react/jsx-runtime");
12
+ let _constructive_io_ui_tooltip = require("@constructive-io/ui/tooltip");
13
+ let _remixicon_react = require("@remixicon/react");
14
+ let lucide_react = require("lucide-react");
15
+ let _tanstack_react_query = require("@tanstack/react-query");
16
+ let _constructive_io_ui_button = require("@constructive-io/ui/button");
17
+ let _dnd_kit_core = require("@dnd-kit/core");
18
+ let _dnd_kit_utilities = require("@dnd-kit/utilities");
19
+ let _constructive_io_ui_toast = require("@constructive-io/ui/toast");
20
+ let _constructive_io_ui_combobox = require("@constructive-io/ui/combobox");
21
+ let _constructive_io_ui_input = require("@constructive-io/ui/input");
22
+ let _constructive_io_ui_label = require("@constructive-io/ui/label");
23
+ let _constructive_io_ui_scroll_area = require("@constructive-io/ui/scroll-area");
24
+ let _constructive_io_ui_checkbox = require("@constructive-io/ui/checkbox");
25
+ let _constructive_io_ui_collapsible = require("@constructive-io/ui/collapsible");
26
+ let _constructive_io_ui_input_group = require("@constructive-io/ui/input-group");
27
+
28
+ //#region src/schema/schema-builder-core/lib/schema/constraint-mapping.ts
29
+ /**
30
+ * Updates a common constraint in the field constraints
31
+ */
32
+ function updateCommonConstraint(constraints, constraintId, value) {
33
+ const updated = { ...constraints };
34
+ switch (constraintId) {
35
+ case "primaryKey":
36
+ updated.primaryKey = value;
37
+ if (value) updated.nullable = false;
38
+ break;
39
+ case "unique":
40
+ updated.unique = value;
41
+ break;
42
+ case "nullable":
43
+ updated.nullable = value;
44
+ if (value) updated.primaryKey = false;
45
+ break;
46
+ }
47
+ return updated;
48
+ }
49
+
50
+ //#endregion
51
+ //#region src/schema/schema-builder-fields/components/table-editor/draggable-field-type.tsx
52
+ const DraggableFieldType = (0, react.memo)(function DraggableFieldType({ typeInfo, isDragging = false, className }) {
53
+ const { attributes, listeners, setNodeRef, transform, isDragging: isBeingDragged } = (0, _dnd_kit_core.useDraggable)({
54
+ id: `field-type-${typeInfo.type}`,
55
+ data: { typeInfo }
56
+ });
57
+ const style = { transform: _dnd_kit_utilities.CSS.Translate.toString(transform) };
58
+ const IconComponent = typeInfo.icon;
59
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
60
+ ref: setNodeRef,
61
+ style,
62
+ ...listeners,
63
+ ...attributes,
64
+ className: require_invalidate_database_entities.cn(`group hover:bg-accent flex cursor-grab items-center gap-3 rounded-lg border border-transparent px-2.5 py-2
65
+ transition-[background-color,border-color,box-shadow,opacity] duration-150 ease-out active:cursor-grabbing`, "touch-none select-none", "hover:border-border/60 hover:shadow-sm", {
66
+ "opacity-50": isBeingDragged && !isDragging,
67
+ "border-primary/30 bg-primary/5 shadow-md": isDragging
68
+ }, className),
69
+ children: [
70
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
71
+ className: "bg-muted/60 text-muted-foreground flex h-8 w-8 flex-shrink-0 items-center justify-center\n rounded-md",
72
+ children: IconComponent ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(IconComponent, { className: "h-4 w-4" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
73
+ className: "font-mono text-xs font-medium",
74
+ children: typeInfo.type.charAt(0).toUpperCase()
75
+ })
76
+ }),
77
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
78
+ className: "min-w-0 flex-1",
79
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
80
+ className: "text-foreground block truncate text-sm font-medium",
81
+ children: typeInfo.label
82
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
83
+ className: "text-muted-foreground truncate text-xs",
84
+ children: typeInfo.description
85
+ })]
86
+ }),
87
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
88
+ className: "flex-shrink-0 opacity-0 transition-opacity group-hover:opacity-100",
89
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_remixicon_react.RiDragDropLine, { className: "text-muted-foreground h-4 w-4" })
90
+ })
91
+ ]
92
+ });
93
+ });
94
+
95
+ //#endregion
96
+ //#region src/schema/schema-builder-fields/components/table-editor/draggable-field-type-icon.tsx
97
+ function DraggableFieldTypeIcon({ typeInfo, isDragging = false, className }) {
98
+ const { attributes, listeners, setNodeRef, transform, isDragging: isBeingDragged } = (0, _dnd_kit_core.useDraggable)({
99
+ id: `field-type-rail-${typeInfo.type}`,
100
+ data: {
101
+ typeInfo,
102
+ source: "rail"
103
+ }
104
+ });
105
+ const style = { transform: _dnd_kit_utilities.CSS.Translate.toString(transform) };
106
+ const IconComponent = typeInfo.icon;
107
+ const badge = typeInfo.badge;
108
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_tooltip.Tooltip, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_tooltip.TooltipTrigger, {
109
+ asChild: true,
110
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("button", {
111
+ ref: setNodeRef,
112
+ style,
113
+ ...listeners,
114
+ ...attributes,
115
+ "aria-label": `Drag ${typeInfo.label} field type`,
116
+ className: require_invalidate_database_entities.cn(`group bg-background hover:bg-accent relative aspect-square w-10 cursor-grab rounded-lg border
117
+ transition-[background-color,border-color,box-shadow,opacity] duration-150 ease-out active:cursor-grabbing`, "flex items-center justify-center", "touch-none select-none", {
118
+ "opacity-50": isBeingDragged && !isDragging,
119
+ "border-primary/30 bg-primary/5 shadow-lg": isDragging,
120
+ "hover:border-primary/40 hover:shadow-sm": !isBeingDragged
121
+ }, className),
122
+ type: "button",
123
+ children: [IconComponent ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(IconComponent, { className: require_invalidate_database_entities.cn("text-muted-foreground h-4 w-4 transition-colors", "group-hover:text-foreground") }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
124
+ className: "text-muted-foreground group-hover:text-foreground font-mono text-xs font-medium",
125
+ children: typeInfo.type.charAt(0).toUpperCase()
126
+ }), badge && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
127
+ className: require_invalidate_database_entities.cn("absolute inset-x-0 bottom-0.5", "flex items-center justify-center", "text-muted-foreground/60 group-hover:text-muted-foreground", "font-mono text-[7px] font-medium uppercase leading-none tracking-wide", "transition-colors"),
128
+ children: badge
129
+ })]
130
+ })
131
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_tooltip.TooltipContent, {
132
+ side: "left",
133
+ align: "center",
134
+ className: "max-w-[200px]",
135
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
136
+ className: "space-y-1",
137
+ children: [
138
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
139
+ className: "font-medium",
140
+ children: typeInfo.label
141
+ }),
142
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
143
+ className: "text-muted-foreground text-xs",
144
+ children: typeInfo.description
145
+ }),
146
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
147
+ className: "text-muted-foreground/70 text-xs",
148
+ children: "Drag to add to table"
149
+ })
150
+ ]
151
+ })
152
+ })] });
153
+ }
154
+
155
+ //#endregion
156
+ //#region src/schema/schema-builder-fields/lib/gql/hooks/schema-builder/use-field-mutations.ts
157
+ /**
158
+ * Hook for field mutations (create, update, delete)
159
+ * Tier 4 wrapper: orchestrates field + constraint mutations
160
+ */
161
+ function fieldDefinitionToCreateInput(field, tableId, databaseId) {
162
+ let defaultValue = field.constraints.defaultValue?.toString() || void 0;
163
+ const backendType = require_invalidate_database_entities.cellTypeToBackendType(field.type);
164
+ if (backendType === "uuid" && field.constraints.primaryKey && !defaultValue) defaultValue = "uuidv7()";
165
+ const { smartTags, chk, chkExpr, ...constraintFields } = require_invalidate_database_entities.mapConstraintsToFieldPatch(field);
166
+ return {
167
+ name: field.name,
168
+ type: require_invalidate_database_entities.toFieldType(backendType),
169
+ tableId,
170
+ databaseId,
171
+ description: require_invalidate_database_entities.stripEmpty(field.description),
172
+ label: require_invalidate_database_entities.stripEmpty(field.label),
173
+ defaultValue: require_invalidate_database_entities.toFieldDefault(defaultValue),
174
+ isRequired: field.isRequired ?? !field.constraints.nullable,
175
+ fieldOrder: field.fieldOrder,
176
+ ...constraintFields,
177
+ smartTags,
178
+ chk,
179
+ chkExpr
180
+ };
181
+ }
182
+ function fieldDefinitionToPatch(field) {
183
+ let defaultValue = field.constraints.defaultValue?.toString() || void 0;
184
+ const backendType = require_invalidate_database_entities.cellTypeToBackendType(field.type);
185
+ if (backendType === "uuid" && field.constraints.primaryKey && !defaultValue) defaultValue = "uuidv7()";
186
+ const { smartTags, chk, chkExpr, ...constraintFields } = require_invalidate_database_entities.mapConstraintsToFieldPatch(field);
187
+ return {
188
+ name: field.name,
189
+ type: require_invalidate_database_entities.toFieldType(backendType),
190
+ description: require_invalidate_database_entities.stripEmpty(field.description),
191
+ label: require_invalidate_database_entities.stripEmpty(field.label),
192
+ defaultValue: require_invalidate_database_entities.toFieldDefault(defaultValue),
193
+ isRequired: field.isRequired ?? !field.constraints.nullable,
194
+ fieldOrder: field.fieldOrder,
195
+ ...constraintFields,
196
+ smartTags,
197
+ chk,
198
+ chkExpr
199
+ };
200
+ }
201
+ function useCreateField() {
202
+ const queryClient = (0, _tanstack_react_query.useQueryClient)();
203
+ const { selectTable, selectedTableId, currentDatabase } = require_invalidate_database_entities.useSchemaBuilderSelectors();
204
+ const createFieldMutation = require_invalidate_database_entities.useCreateFieldMutation({ selection: { fields: {
205
+ id: true,
206
+ name: true,
207
+ type: true
208
+ } } });
209
+ const createPkMutation = require_invalidate_database_entities.useCreatePrimaryKeyConstraintMutation({ selection: { fields: { id: true } } });
210
+ const updatePkMutation = require_invalidate_database_entities.useUpdatePrimaryKeyConstraintMutation({ selection: { fields: { id: true } } });
211
+ const createUniqueMutation = require_invalidate_database_entities.useCreateUniqueConstraintMutation({ selection: { fields: { id: true } } });
212
+ return (0, _tanstack_react_query.useMutation)({
213
+ mutationFn: async (input) => {
214
+ const fieldInput = fieldDefinitionToCreateInput(input.field, input.tableId, input.databaseId);
215
+ const createdField = (await createFieldMutation.mutateAsync(fieldInput)).createField?.field;
216
+ if (!createdField?.id || !createdField?.name) throw new Error("Failed to create field");
217
+ const errors = [];
218
+ if (input.field.constraints.primaryKey) if (input.existingPrimaryKeyConstraintId && input.allPrimaryKeyFieldIds) {
219
+ const updatedFieldIds = [...input.allPrimaryKeyFieldIds, createdField.id];
220
+ try {
221
+ await updatePkMutation.mutateAsync({
222
+ id: input.existingPrimaryKeyConstraintId,
223
+ primaryKeyConstraintPatch: { fieldIds: require_invalidate_database_entities.asFieldIds(updatedFieldIds) }
224
+ });
225
+ } catch (error) {
226
+ errors.push(`Failed to update primary key constraint: ${error instanceof Error ? error.message : "Unknown error"}`);
227
+ throw new Error(errors.join("; "));
228
+ }
229
+ } else try {
230
+ await createPkMutation.mutateAsync({
231
+ tableId: input.tableId,
232
+ databaseId: input.databaseId,
233
+ fieldIds: require_invalidate_database_entities.asFieldIds([createdField.id]),
234
+ name: `${input.tableName}_pkey`,
235
+ type: "p"
236
+ });
237
+ } catch (error) {
238
+ errors.push(`Failed to create primary key constraint: ${error instanceof Error ? error.message : "Unknown error"}`);
239
+ throw new Error(errors.join("; "));
240
+ }
241
+ if (input.field.constraints.unique) try {
242
+ await createUniqueMutation.mutateAsync({
243
+ tableId: input.tableId,
244
+ databaseId: input.databaseId,
245
+ fieldIds: require_invalidate_database_entities.asFieldIds([createdField.id]),
246
+ name: `${input.field.name}_key`,
247
+ type: "u"
248
+ });
249
+ } catch (error) {
250
+ errors.push(`Failed to create unique constraint: ${error instanceof Error ? error.message : "Unknown error"}`);
251
+ throw new Error(errors.join("; "));
252
+ }
253
+ return {
254
+ id: createdField.id,
255
+ name: createdField.name,
256
+ type: require_invalidate_database_entities.fieldTypeToTypeName(createdField.type)
257
+ };
258
+ },
259
+ onSuccess: async (_result, variables) => {
260
+ await require_invalidate_database_entities.invalidateDatabaseEntities(queryClient, variables.databaseId ?? currentDatabase?.databaseId);
261
+ if (selectedTableId) selectTable(selectedTableId);
262
+ },
263
+ onError: (error) => {
264
+ console.error("Failed to create field:", error);
265
+ }
266
+ });
267
+ }
268
+ function useUpdateField() {
269
+ const queryClient = (0, _tanstack_react_query.useQueryClient)();
270
+ const { selectTable, selectedTableId, currentDatabase } = require_invalidate_database_entities.useSchemaBuilderSelectors();
271
+ const updateFieldMutation = require_invalidate_database_entities.useUpdateFieldMutation({ selection: { fields: {
272
+ id: true,
273
+ name: true,
274
+ type: true
275
+ } } });
276
+ const createPkMutation = require_invalidate_database_entities.useCreatePrimaryKeyConstraintMutation({ selection: { fields: { id: true } } });
277
+ const updatePkMutation = require_invalidate_database_entities.useUpdatePrimaryKeyConstraintMutation({ selection: { fields: { id: true } } });
278
+ const deletePkMutation = require_invalidate_database_entities.useDeletePrimaryKeyConstraintMutation({ selection: { fields: { id: true } } });
279
+ const createUniqueMutation = require_invalidate_database_entities.useCreateUniqueConstraintMutation({ selection: { fields: { id: true } } });
280
+ const deleteUniqueMutation = require_invalidate_database_entities.useDeleteUniqueConstraintMutation({ selection: { fields: { id: true } } });
281
+ return (0, _tanstack_react_query.useMutation)({
282
+ mutationFn: async (input) => {
283
+ const patch = fieldDefinitionToPatch(input.field);
284
+ const errors = [];
285
+ const updatedField = (await updateFieldMutation.mutateAsync({
286
+ id: input.id,
287
+ fieldPatch: patch
288
+ })).updateField?.field;
289
+ if (!updatedField?.id) throw new Error("Failed to update field");
290
+ const hasPrimaryKey = input.field.constraints.primaryKey;
291
+ const hadPrimaryKey = input.wasPartOfPrimaryKey || false;
292
+ if (hasPrimaryKey && !hadPrimaryKey) if (input.existingPrimaryKeyConstraintId && input.allPrimaryKeyFieldIds) {
293
+ const updatedFieldIds = [...input.allPrimaryKeyFieldIds, input.id];
294
+ try {
295
+ await updatePkMutation.mutateAsync({
296
+ id: input.existingPrimaryKeyConstraintId,
297
+ primaryKeyConstraintPatch: { fieldIds: require_invalidate_database_entities.asFieldIds(updatedFieldIds) }
298
+ });
299
+ } catch (error) {
300
+ errors.push(`Failed to update primary key constraint: ${error instanceof Error ? error.message : "Unknown error"}`);
301
+ }
302
+ } else try {
303
+ await createPkMutation.mutateAsync({
304
+ tableId: input.tableId,
305
+ databaseId: input.databaseId,
306
+ fieldIds: require_invalidate_database_entities.asFieldIds([input.id]),
307
+ name: `${input.tableName}_pkey`,
308
+ type: "p"
309
+ });
310
+ } catch (error) {
311
+ errors.push(`Failed to create primary key constraint: ${error instanceof Error ? error.message : "Unknown error"}`);
312
+ }
313
+ else if (!hasPrimaryKey && hadPrimaryKey) {
314
+ if (input.existingPrimaryKeyConstraintId && input.allPrimaryKeyFieldIds) {
315
+ const remainingFieldIds = input.allPrimaryKeyFieldIds.filter((id) => id !== input.id);
316
+ if (remainingFieldIds.length > 0) try {
317
+ await updatePkMutation.mutateAsync({
318
+ id: input.existingPrimaryKeyConstraintId,
319
+ primaryKeyConstraintPatch: { fieldIds: require_invalidate_database_entities.asFieldIds(remainingFieldIds) }
320
+ });
321
+ } catch (error) {
322
+ errors.push(`Failed to update primary key constraint: ${error instanceof Error ? error.message : "Unknown error"}`);
323
+ }
324
+ else try {
325
+ await deletePkMutation.mutateAsync({ id: input.existingPrimaryKeyConstraintId });
326
+ } catch (error) {
327
+ errors.push(`Failed to delete primary key constraint: ${error instanceof Error ? error.message : "Unknown error"}`);
328
+ }
329
+ }
330
+ }
331
+ const hasUnique = input.field.constraints.unique;
332
+ const hadUnique = !!input.existingUniqueConstraintId;
333
+ if (hasUnique && !hadUnique) try {
334
+ await createUniqueMutation.mutateAsync({
335
+ tableId: input.tableId,
336
+ databaseId: input.databaseId,
337
+ fieldIds: require_invalidate_database_entities.asFieldIds([input.id]),
338
+ name: `${input.tableName}_${input.field.name}_key`,
339
+ type: "u"
340
+ });
341
+ } catch (error) {
342
+ errors.push(`Failed to create unique constraint: ${error instanceof Error ? error.message : "Unknown error"}`);
343
+ }
344
+ else if (!hasUnique && hadUnique && input.existingUniqueConstraintId) try {
345
+ await deleteUniqueMutation.mutateAsync({ id: input.existingUniqueConstraintId });
346
+ } catch (error) {
347
+ errors.push(`Failed to delete unique constraint: ${error instanceof Error ? error.message : "Unknown error"}`);
348
+ }
349
+ if (errors.length > 0) console.warn("Field updated with constraint errors:", errors.join("; "));
350
+ return updatedField;
351
+ },
352
+ onSuccess: async (_result, variables) => {
353
+ await require_invalidate_database_entities.invalidateDatabaseEntities(queryClient, variables.databaseId ?? currentDatabase?.databaseId);
354
+ if (selectedTableId) selectTable(selectedTableId);
355
+ },
356
+ onError: (error) => {
357
+ console.error("Failed to update field:", error);
358
+ }
359
+ });
360
+ }
361
+ function useDeleteField() {
362
+ const queryClient = (0, _tanstack_react_query.useQueryClient)();
363
+ const { selectTable, selectedTableId, currentDatabase } = require_invalidate_database_entities.useSchemaBuilderSelectors();
364
+ const deleteFieldMutation = require_invalidate_database_entities.useDeleteFieldMutation({ selection: { fields: { id: true } } });
365
+ const updatePkMutation = require_invalidate_database_entities.useUpdatePrimaryKeyConstraintMutation({ selection: { fields: { id: true } } });
366
+ const deletePkMutation = require_invalidate_database_entities.useDeletePrimaryKeyConstraintMutation({ selection: { fields: { id: true } } });
367
+ const deleteUniqueMutation = require_invalidate_database_entities.useDeleteUniqueConstraintMutation({ selection: { fields: { id: true } } });
368
+ return (0, _tanstack_react_query.useMutation)({
369
+ mutationFn: async (input) => {
370
+ if (input.wasPartOfPrimaryKey && input.primaryKeyConstraintId) if (input.allPrimaryKeyFieldIds && input.allPrimaryKeyFieldIds.length > 1) {
371
+ const remainingFieldIds = input.allPrimaryKeyFieldIds.filter((id) => id !== input.id);
372
+ await updatePkMutation.mutateAsync({
373
+ id: input.primaryKeyConstraintId,
374
+ primaryKeyConstraintPatch: { fieldIds: require_invalidate_database_entities.asFieldIds(remainingFieldIds) }
375
+ });
376
+ } else await deletePkMutation.mutateAsync({ id: input.primaryKeyConstraintId });
377
+ if (input.uniqueConstraintId) await deleteUniqueMutation.mutateAsync({ id: input.uniqueConstraintId });
378
+ await deleteFieldMutation.mutateAsync({ id: input.id });
379
+ return input.id;
380
+ },
381
+ onSuccess: async () => {
382
+ await require_invalidate_database_entities.invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId);
383
+ if (selectedTableId) selectTable(selectedTableId);
384
+ },
385
+ onError: (error) => {
386
+ console.error("Failed to delete field:", error);
387
+ }
388
+ });
389
+ }
390
+ function useUpdateFieldOrder() {
391
+ const queryClient = (0, _tanstack_react_query.useQueryClient)();
392
+ const { selectTable, selectedTableId, currentDatabase } = require_invalidate_database_entities.useSchemaBuilderSelectors();
393
+ const updateFieldMutation = require_invalidate_database_entities.useUpdateFieldMutation({ selection: { fields: { id: true } } });
394
+ return (0, _tanstack_react_query.useMutation)({
395
+ mutationFn: async (fieldUpdates) => {
396
+ const updatePromises = fieldUpdates.map((update) => updateFieldMutation.mutateAsync({
397
+ id: update.id,
398
+ fieldPatch: { fieldOrder: update.fieldOrder }
399
+ }));
400
+ await Promise.all(updatePromises);
401
+ return fieldUpdates;
402
+ },
403
+ onSuccess: async () => {
404
+ await require_invalidate_database_entities.invalidateDatabaseEntities(queryClient, currentDatabase?.databaseId);
405
+ if (selectedTableId) selectTable(selectedTableId);
406
+ },
407
+ onError: (error) => {
408
+ console.error("Failed to update field order:", error);
409
+ }
410
+ });
411
+ }
412
+
413
+ //#endregion
414
+ //#region src/schema/schema-builder-fields/components/table-editor/constraint-card.tsx
415
+ const CONSTRAINT_CONFIG = {
416
+ primaryKey: {
417
+ label: "Primary Key",
418
+ description: "Uniquely identifies each row (automatically sets UNIQUE + NOT NULL)",
419
+ badge: "PK",
420
+ icon: lucide_react.Key,
421
+ colors: {
422
+ selected: "ring-2 ring-blue-500/50 bg-blue-500/5",
423
+ badge: "bg-blue-500/10 text-blue-600 border-blue-500/20",
424
+ icon: "text-blue-500"
425
+ }
426
+ },
427
+ unique: {
428
+ label: "Unique",
429
+ description: "All values in this column must be different",
430
+ badge: "UNIQUE",
431
+ icon: lucide_react.Fingerprint,
432
+ colors: {
433
+ selected: "ring-2 ring-purple-500/50 bg-purple-500/5",
434
+ badge: "bg-purple-500/10 text-purple-600 border-purple-500/20",
435
+ icon: "text-purple-500"
436
+ }
437
+ },
438
+ nullable: {
439
+ label: "Nullable",
440
+ description: "Allow NULL values in this column",
441
+ badge: "NULLABLE",
442
+ icon: lucide_react.CircleDot,
443
+ colors: {
444
+ selected: "ring-2 ring-green-500/50 bg-green-500/5",
445
+ badge: "bg-green-500/10 text-green-600 border-green-500/20",
446
+ icon: "text-green-500"
447
+ }
448
+ }
449
+ };
450
+ function ConstraintCard({ type, selected, disabled, disabledReason, onToggle }) {
451
+ const config = CONSTRAINT_CONFIG[type];
452
+ const Icon = config.icon;
453
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
454
+ className: require_invalidate_database_entities.cn(`flex items-center justify-between gap-4 rounded-lg border p-4 transition-[background-color,border-color,box-shadow,scale]
455
+ duration-150 ease-out motion-safe:active:scale-[0.96]`, disabled ? "cursor-not-allowed opacity-50" : "cursor-pointer hover:border-border", selected && !disabled ? config.colors.selected : "bg-card border-border/50"),
456
+ onClick: () => !disabled && onToggle(),
457
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
458
+ className: "flex items-start gap-3",
459
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
460
+ className: require_invalidate_database_entities.cn("mt-0.5 flex size-8 shrink-0 items-center justify-center rounded-md", selected && !disabled ? config.colors.icon : "text-muted-foreground", selected && !disabled ? "bg-background" : "bg-muted/50"),
461
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, { className: "size-4" })
462
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
463
+ className: "flex-1 space-y-1",
464
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
465
+ className: "flex items-center gap-2",
466
+ children: [
467
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
468
+ className: require_invalidate_database_entities.cn("text-sm font-medium", selected && !disabled ? config.colors.icon : "text-foreground"),
469
+ children: config.label
470
+ }),
471
+ selected && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
472
+ className: require_invalidate_database_entities.cn("rounded border px-1.5 py-0.5 text-[10px] font-medium", config.colors.badge),
473
+ children: config.badge
474
+ }),
475
+ disabled && disabledReason && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
476
+ className: "text-muted-foreground text-xs",
477
+ children: [
478
+ "(",
479
+ disabledReason,
480
+ ")"
481
+ ]
482
+ })
483
+ ]
484
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
485
+ className: "text-muted-foreground text-xs leading-relaxed",
486
+ children: config.description
487
+ })]
488
+ })]
489
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_checkbox.Checkbox, {
490
+ checked: selected,
491
+ disabled,
492
+ onCheckedChange: () => !disabled && onToggle(),
493
+ onClick: (e) => e.stopPropagation(),
494
+ className: "shrink-0"
495
+ })]
496
+ });
497
+ }
498
+
499
+ //#endregion
500
+ //#region src/schema/schema-builder-fields/components/table-editor/validation-rules-section.tsx
501
+ function ValidationRulesSection({ dataType, values, onChange, disabled }) {
502
+ const configurable = require_invalidate_database_entities.getFieldTypeInfo(dataType)?.configurable;
503
+ if (!(configurable && (configurable.length || configurable.pattern || configurable.range || configurable.precision || configurable.scale))) return null;
504
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
505
+ className: "space-y-4",
506
+ children: [
507
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_label.Label, { children: ["Validation Rules ", /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
508
+ className: "text-muted-foreground",
509
+ children: "(optional)"
510
+ })] }),
511
+ configurable.length && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
512
+ className: "grid grid-cols-2 gap-4",
513
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
514
+ className: "space-y-2",
515
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, {
516
+ htmlFor: "minLength",
517
+ className: "text-muted-foreground text-xs",
518
+ children: "Min Length"
519
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
520
+ id: "minLength",
521
+ type: "number",
522
+ placeholder: "e.g., 3",
523
+ value: values.minLength ?? "",
524
+ onChange: (e) => onChange("minLength", e.target.value ? parseInt(e.target.value) : void 0),
525
+ disabled
526
+ })]
527
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
528
+ className: "space-y-2",
529
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, {
530
+ htmlFor: "maxLength",
531
+ className: "text-muted-foreground text-xs",
532
+ children: "Max Length"
533
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
534
+ id: "maxLength",
535
+ type: "number",
536
+ placeholder: "e.g., 255",
537
+ value: values.maxLength ?? "",
538
+ onChange: (e) => onChange("maxLength", e.target.value ? parseInt(e.target.value) : void 0),
539
+ disabled
540
+ })]
541
+ })]
542
+ }),
543
+ configurable.pattern && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
544
+ className: "space-y-2",
545
+ children: [
546
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, {
547
+ htmlFor: "pattern",
548
+ className: "text-muted-foreground text-xs",
549
+ children: "Regex Pattern"
550
+ }),
551
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
552
+ id: "pattern",
553
+ placeholder: "e.g., ^[a-z]+$",
554
+ value: values.pattern ?? "",
555
+ onChange: (e) => onChange("pattern", e.target.value || void 0),
556
+ disabled,
557
+ className: "font-mono text-sm"
558
+ }),
559
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
560
+ className: "text-muted-foreground text-xs",
561
+ children: "Validate values with a regular expression"
562
+ })
563
+ ]
564
+ }),
565
+ (configurable.precision || configurable.scale) && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
566
+ className: "grid grid-cols-2 gap-4",
567
+ children: [configurable.precision && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
568
+ className: "space-y-2",
569
+ children: [
570
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, {
571
+ htmlFor: "precision",
572
+ className: "text-muted-foreground text-xs",
573
+ children: "Precision"
574
+ }),
575
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
576
+ id: "precision",
577
+ type: "number",
578
+ placeholder: "e.g., 10",
579
+ value: values.precision ?? "",
580
+ onChange: (e) => onChange("precision", e.target.value ? parseInt(e.target.value) : void 0),
581
+ disabled
582
+ }),
583
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
584
+ className: "text-muted-foreground text-xs",
585
+ children: "Total digits"
586
+ })
587
+ ]
588
+ }), configurable.scale && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
589
+ className: "space-y-2",
590
+ children: [
591
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, {
592
+ htmlFor: "scale",
593
+ className: "text-muted-foreground text-xs",
594
+ children: "Scale"
595
+ }),
596
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
597
+ id: "scale",
598
+ type: "number",
599
+ placeholder: "e.g., 2",
600
+ value: values.scale ?? "",
601
+ onChange: (e) => onChange("scale", e.target.value ? parseInt(e.target.value) : void 0),
602
+ disabled
603
+ }),
604
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
605
+ className: "text-muted-foreground text-xs",
606
+ children: "Decimal places"
607
+ })
608
+ ]
609
+ })]
610
+ }),
611
+ configurable.range && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
612
+ className: "grid grid-cols-2 gap-4",
613
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
614
+ className: "space-y-2",
615
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, {
616
+ htmlFor: "minValue",
617
+ className: "text-muted-foreground text-xs",
618
+ children: "Min Value"
619
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
620
+ id: "minValue",
621
+ type: "number",
622
+ placeholder: "e.g., 0",
623
+ value: values.minValue ?? "",
624
+ onChange: (e) => onChange("minValue", e.target.value ? parseFloat(e.target.value) : void 0),
625
+ disabled
626
+ })]
627
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
628
+ className: "space-y-2",
629
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, {
630
+ htmlFor: "maxValue",
631
+ className: "text-muted-foreground text-xs",
632
+ children: "Max Value"
633
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
634
+ id: "maxValue",
635
+ type: "number",
636
+ placeholder: "e.g., 100",
637
+ value: values.maxValue ?? "",
638
+ onChange: (e) => onChange("maxValue", e.target.value ? parseFloat(e.target.value) : void 0),
639
+ disabled
640
+ })]
641
+ })]
642
+ })
643
+ ]
644
+ });
645
+ }
646
+
647
+ //#endregion
648
+ //#region src/schema/schema-builder-fields/components/table-editor/add-field-card.tsx
649
+ const fieldTypes = require_invalidate_database_entities.getAllFieldTypes();
650
+ const AddFieldCard = ({ editingField: initialEditingField, preSelectedType, primaryKeyConstraintId, uniqueConstraintId, allPrimaryKeyFieldIds = [], isPartOfPrimaryKey = false, remoteFields = [], card }) => {
651
+ const { currentTable, currentSchema, currentDatabase } = require_invalidate_database_entities.useSchemaBuilderSelectors();
652
+ const createFieldMutation = useCreateField();
653
+ const updateFieldMutation = useUpdateField();
654
+ const [columnName, setColumnName] = (0, react.useState)(() => initialEditingField?.name ?? "");
655
+ const [dataType, setDataType] = (0, react.useState)(() => initialEditingField?.type ?? preSelectedType ?? "text");
656
+ const [constraints, setConstraints] = (0, react.useState)(() => initialEditingField?.constraints ?? { nullable: true });
657
+ const [defaultValue, setDefaultValue] = (0, react.useState)(() => initialEditingField?.constraints.defaultValue?.toString() ?? "");
658
+ const [minLength, setMinLength] = (0, react.useState)(() => initialEditingField?.constraints.minLength);
659
+ const [maxLength, setMaxLength] = (0, react.useState)(() => initialEditingField?.constraints.maxLength);
660
+ const [pattern, setPattern] = (0, react.useState)(() => initialEditingField?.constraints.pattern);
661
+ const [precision, setPrecision] = (0, react.useState)(() => initialEditingField?.constraints.precision);
662
+ const [scale, setScale] = (0, react.useState)(() => initialEditingField?.constraints.scale);
663
+ const [minValue, setMinValue] = (0, react.useState)(() => initialEditingField?.constraints.minValue);
664
+ const [maxValue, setMaxValue] = (0, react.useState)(() => initialEditingField?.constraints.maxValue);
665
+ const [typeSearchTerm, setTypeSearchTerm] = (0, react.useState)("");
666
+ const [isSaving, setIsSaving] = (0, react.useState)(false);
667
+ const fieldNameInputRef = (0, react.useRef)(null);
668
+ const tableId = currentTable?.id || "";
669
+ const databaseId = currentDatabase?.databaseId ?? (currentSchema?.metadata?.databaseId || "");
670
+ const tableName = currentTable?.name || "";
671
+ const isEditMode = initialEditingField !== null;
672
+ const isPending = createFieldMutation.isPending || updateFieldMutation.isPending;
673
+ (0, react.useEffect)(() => {
674
+ if (isEditMode) return;
675
+ const timer = setTimeout(() => {
676
+ fieldNameInputRef.current?.focus();
677
+ }, 100);
678
+ return () => clearTimeout(timer);
679
+ }, [isEditMode]);
680
+ const fieldTypeOptions = (0, react.useMemo)(() => fieldTypes.filter((type) => type.label.toLowerCase().includes(typeSearchTerm.toLowerCase())).map((fieldType) => ({
681
+ label: fieldType.label,
682
+ value: fieldType.type
683
+ })), [typeSearchTerm]);
684
+ const selectedFieldTypeOption = fieldTypeOptions.find((o) => o.value === dataType) ?? null;
685
+ const handleConstraintToggle = (0, react.useCallback)((type) => {
686
+ const updatedConstraints = updateCommonConstraint(constraints, type, !constraints[type]);
687
+ setConstraints(updatedConstraints);
688
+ }, [constraints]);
689
+ const validationRulesValues = (0, react.useMemo)(() => ({
690
+ minLength,
691
+ maxLength,
692
+ pattern,
693
+ precision,
694
+ scale,
695
+ minValue,
696
+ maxValue
697
+ }), [
698
+ minLength,
699
+ maxLength,
700
+ pattern,
701
+ precision,
702
+ scale,
703
+ minValue,
704
+ maxValue
705
+ ]);
706
+ const handleValidationRuleChange = (0, react.useCallback)((field, value) => {
707
+ switch (field) {
708
+ case "minLength":
709
+ setMinLength(value);
710
+ break;
711
+ case "maxLength":
712
+ setMaxLength(value);
713
+ break;
714
+ case "pattern":
715
+ setPattern(value);
716
+ break;
717
+ case "precision":
718
+ setPrecision(value);
719
+ break;
720
+ case "scale":
721
+ setScale(value);
722
+ break;
723
+ case "minValue":
724
+ setMinValue(value);
725
+ break;
726
+ case "maxValue":
727
+ setMaxValue(value);
728
+ break;
729
+ }
730
+ }, []);
731
+ const buildFieldDefinition = (0, react.useCallback)(() => {
732
+ return {
733
+ id: initialEditingField?.id || `temp-field-${Date.now()}`,
734
+ name: columnName.trim(),
735
+ type: dataType,
736
+ constraints: {
737
+ ...constraints,
738
+ defaultValue: defaultValue.trim() || void 0,
739
+ minLength,
740
+ maxLength,
741
+ pattern: pattern?.trim() || void 0,
742
+ precision,
743
+ scale,
744
+ minValue,
745
+ maxValue
746
+ },
747
+ fieldOrder: initialEditingField?.fieldOrder ?? (remoteFields.length > 0 ? Math.max(...remoteFields.map((f) => f.fieldOrder ?? 0)) + 1 : 0)
748
+ };
749
+ }, [
750
+ initialEditingField,
751
+ columnName,
752
+ dataType,
753
+ constraints,
754
+ defaultValue,
755
+ minLength,
756
+ maxLength,
757
+ pattern,
758
+ precision,
759
+ scale,
760
+ minValue,
761
+ maxValue,
762
+ remoteFields
763
+ ]);
764
+ const canSave = (0, react.useMemo)(() => {
765
+ if (!columnName.trim()) return false;
766
+ if (!dataType) return false;
767
+ return true;
768
+ }, [columnName, dataType]);
769
+ const handleSave = (0, react.useCallback)(async () => {
770
+ if (!canSave || !currentTable) return;
771
+ setIsSaving(true);
772
+ const field = buildFieldDefinition();
773
+ try {
774
+ if (isEditMode && initialEditingField) {
775
+ await updateFieldMutation.mutateAsync({
776
+ id: initialEditingField.id,
777
+ field,
778
+ tableId,
779
+ databaseId,
780
+ tableName,
781
+ existingPrimaryKeyConstraintId: primaryKeyConstraintId,
782
+ existingUniqueConstraintId: uniqueConstraintId,
783
+ allPrimaryKeyFieldIds,
784
+ wasPartOfPrimaryKey: isPartOfPrimaryKey
785
+ });
786
+ _constructive_io_ui_toast.toast.success({
787
+ message: "Field updated",
788
+ description: `Field "${field.name}" has been updated successfully`
789
+ });
790
+ } else {
791
+ await createFieldMutation.mutateAsync({
792
+ field,
793
+ tableId,
794
+ databaseId,
795
+ tableName,
796
+ existingPrimaryKeyConstraintId: primaryKeyConstraintId,
797
+ allPrimaryKeyFieldIds
798
+ });
799
+ _constructive_io_ui_toast.toast.success({
800
+ message: "Field created",
801
+ description: `Field "${field.name}" has been created successfully`
802
+ });
803
+ }
804
+ card.close();
805
+ } catch (error) {
806
+ _constructive_io_ui_toast.toast.error({
807
+ message: isEditMode ? "Failed to update field" : "Failed to create field",
808
+ description: error instanceof Error ? error.message : "An error occurred"
809
+ });
810
+ setIsSaving(false);
811
+ }
812
+ }, [
813
+ canSave,
814
+ currentTable,
815
+ buildFieldDefinition,
816
+ isEditMode,
817
+ initialEditingField,
818
+ updateFieldMutation,
819
+ createFieldMutation,
820
+ tableId,
821
+ databaseId,
822
+ tableName,
823
+ primaryKeyConstraintId,
824
+ uniqueConstraintId,
825
+ allPrimaryKeyFieldIds,
826
+ isPartOfPrimaryKey,
827
+ card
828
+ ]);
829
+ const handleClose = (0, react.useCallback)(() => {
830
+ card.close();
831
+ }, [card]);
832
+ const handleSubmit = (0, react.useCallback)((e) => {
833
+ e.preventDefault();
834
+ if (canSave && !isPending) handleSave();
835
+ }, [
836
+ canSave,
837
+ isPending,
838
+ handleSave
839
+ ]);
840
+ if (!currentTable) return null;
841
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
842
+ className: "flex h-full flex-col",
843
+ onSubmit: handleSubmit,
844
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_scroll_area.ScrollArea, {
845
+ className: "min-h-0 flex-1",
846
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
847
+ className: "space-y-6 p-6",
848
+ children: [
849
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
850
+ className: "space-y-2",
851
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, {
852
+ htmlFor: "columnName",
853
+ children: "Field Name"
854
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
855
+ id: "columnName",
856
+ ref: fieldNameInputRef,
857
+ placeholder: "e.g., user_email",
858
+ value: columnName,
859
+ onChange: (e) => setColumnName(e.target.value),
860
+ disabled: isPending,
861
+ autoComplete: "off"
862
+ })]
863
+ }),
864
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
865
+ className: "space-y-2",
866
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, { children: "Data Type" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_combobox.Combobox, {
867
+ items: fieldTypeOptions,
868
+ value: selectedFieldTypeOption,
869
+ onValueChange: (next) => {
870
+ if (next) setDataType(next.value);
871
+ },
872
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_combobox.ComboboxTrigger, {
873
+ className: require_invalidate_database_entities.cn("flex h-9 w-full items-center justify-between rounded-md border border-input bg-background px-3 py-2 text-sm", "hover:bg-muted/50 focus-visible:ring-1 focus-visible:ring-ring"),
874
+ disabled: isPending,
875
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
876
+ className: "flex min-w-0 flex-1 items-center gap-2",
877
+ children: (() => {
878
+ const selectedTypeInfo = require_invalidate_database_entities.getFieldTypeInfo(dataType);
879
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
880
+ className: "text-muted-foreground flex shrink-0 items-center justify-center",
881
+ children: typeof selectedTypeInfo?.icon === "string" ? selectedTypeInfo.icon : selectedTypeInfo?.icon ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(selectedTypeInfo.icon, { className: "size-4" }) : dataType.charAt(0).toUpperCase()
882
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
883
+ className: "truncate",
884
+ children: selectedTypeInfo?.label || dataType
885
+ })] });
886
+ })()
887
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.ChevronsUpDownIcon, {
888
+ className: "text-muted-foreground/50 shrink-0",
889
+ size: 16
890
+ })]
891
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_combobox.ComboboxPopup, {
892
+ className: "[&>[data-slot=combobox-popup]]:min-w-72",
893
+ children: [
894
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_combobox.ComboboxInput, {
895
+ value: typeSearchTerm,
896
+ onChange: (e) => setTypeSearchTerm(e.target.value),
897
+ placeholder: "Search field types...",
898
+ showTrigger: false
899
+ }),
900
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_combobox.ComboboxEmpty, { children: "No field types found." }),
901
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_combobox.ComboboxList, { children: (option) => {
902
+ const fieldTypeInfo = require_invalidate_database_entities.getFieldTypeInfo(option.value);
903
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_combobox.ComboboxItem, {
904
+ value: option,
905
+ className: "flex flex-row-reverse items-center justify-end gap-3 px-2",
906
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
907
+ className: "flex flex-1 items-center gap-2.5",
908
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
909
+ className: "text-muted-foreground flex size-5 shrink-0 items-center justify-center",
910
+ children: typeof fieldTypeInfo?.icon === "string" ? fieldTypeInfo.icon : fieldTypeInfo?.icon ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(fieldTypeInfo.icon, { className: "size-4" }) : fieldTypeInfo?.type.charAt(0).toUpperCase()
911
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
912
+ className: "flex flex-col",
913
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
914
+ className: "text-sm",
915
+ children: option.label
916
+ }), fieldTypeInfo?.description && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
917
+ className: "text-muted-foreground text-xs",
918
+ children: fieldTypeInfo.description
919
+ })]
920
+ })]
921
+ })
922
+ }, option.value);
923
+ } })
924
+ ]
925
+ })]
926
+ })]
927
+ }),
928
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
929
+ className: "space-y-3",
930
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_label.Label, { children: "Constraints" }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
931
+ className: "space-y-3",
932
+ children: [
933
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConstraintCard, {
934
+ type: "primaryKey",
935
+ selected: constraints.primaryKey ?? false,
936
+ onToggle: () => handleConstraintToggle("primaryKey"),
937
+ disabled: isPending
938
+ }),
939
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConstraintCard, {
940
+ type: "unique",
941
+ selected: constraints.unique ?? false,
942
+ onToggle: () => handleConstraintToggle("unique"),
943
+ disabled: isPending || constraints.primaryKey,
944
+ disabledReason: constraints.primaryKey ? "set by PK" : void 0
945
+ }),
946
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConstraintCard, {
947
+ type: "nullable",
948
+ selected: constraints.nullable ?? false,
949
+ onToggle: () => handleConstraintToggle("nullable"),
950
+ disabled: isPending || constraints.primaryKey,
951
+ disabledReason: constraints.primaryKey ? "disabled by PK" : void 0
952
+ })
953
+ ]
954
+ })]
955
+ }),
956
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
957
+ className: "space-y-2",
958
+ children: [
959
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_label.Label, {
960
+ htmlFor: "defaultValue",
961
+ children: ["Default Value ", /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
962
+ className: "text-muted-foreground",
963
+ children: "(optional)"
964
+ })]
965
+ }),
966
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
967
+ id: "defaultValue",
968
+ placeholder: "e.g., 0, true, now()",
969
+ value: defaultValue,
970
+ onChange: (e) => setDefaultValue(e.target.value),
971
+ disabled: isPending
972
+ }),
973
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
974
+ className: "text-muted-foreground text-xs",
975
+ children: "SQL functions or static values"
976
+ })
977
+ ]
978
+ }),
979
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ValidationRulesSection, {
980
+ dataType,
981
+ values: validationRulesValues,
982
+ onChange: handleValidationRuleChange,
983
+ disabled: isPending
984
+ })
985
+ ]
986
+ })
987
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
988
+ className: "flex justify-end gap-3 border-t p-4",
989
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_button.Button, {
990
+ type: "button",
991
+ variant: "outline",
992
+ onClick: handleClose,
993
+ disabled: isPending,
994
+ children: "Cancel"
995
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_button.Button, {
996
+ type: "submit",
997
+ disabled: !canSave || isPending,
998
+ children: [isSaving ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Loader2, { className: "mr-2 size-4 animate-spin" }) : null, isEditMode ? "Save" : "Create"]
999
+ })]
1000
+ })]
1001
+ });
1002
+ };
1003
+
1004
+ //#endregion
1005
+ //#region src/schema/schema-builder-fields/components/table-editor/fields-list-view.tsx
1006
+ function ConstraintIndicator({ type, label }) {
1007
+ const styles = {
1008
+ pk: "bg-amber-500/10 text-amber-600 dark:text-amber-400 border-amber-500/20",
1009
+ unique: "bg-violet-500/10 text-violet-600 dark:text-violet-400 border-violet-500/20",
1010
+ nullable: "bg-emerald-500/10 text-emerald-600 dark:text-emerald-400 border-emerald-500/20",
1011
+ required: "bg-rose-500/10 text-rose-600 dark:text-rose-400 border-rose-500/20"
1012
+ };
1013
+ const Icon = {
1014
+ pk: _remixicon_react.RiKey2Line,
1015
+ unique: _remixicon_react.RiFingerprintLine,
1016
+ nullable: null,
1017
+ required: _remixicon_react.RiShieldCheckLine
1018
+ }[type];
1019
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("span", {
1020
+ className: require_invalidate_database_entities.cn(`inline-flex items-center gap-1 rounded-md border px-1.5 py-0.5 text-[10px] font-semibold tracking-wide
1021
+ uppercase`, "transition-[background-color,border-color,color] duration-150 ease-out", styles[type]),
1022
+ children: [Icon && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(Icon, { className: "size-2.5" }), label]
1023
+ });
1024
+ }
1025
+ function FieldsListView({ fields, constraints, selectedFieldIds, onSelectionChange, onFieldClick, disabled }) {
1026
+ const pkConstraint = (0, react.useMemo)(() => constraints.find((c) => c.type === "primary_key"), [constraints]);
1027
+ const handleSelectAll = (0, react.useCallback)((checked) => {
1028
+ if (checked) onSelectionChange(new Set(fields.map((f) => f.id)));
1029
+ else onSelectionChange(/* @__PURE__ */ new Set());
1030
+ }, [fields, onSelectionChange]);
1031
+ const handleSelectRow = (0, react.useCallback)((fieldId, checked) => {
1032
+ const newSelected = new Set(selectedFieldIds);
1033
+ if (checked) newSelected.add(fieldId);
1034
+ else newSelected.delete(fieldId);
1035
+ onSelectionChange(newSelected);
1036
+ }, [selectedFieldIds, onSelectionChange]);
1037
+ const allSelected = fields.length > 0 && selectedFieldIds.size === fields.length;
1038
+ const someSelected = selectedFieldIds.size > 0 && selectedFieldIds.size < fields.length;
1039
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1040
+ className: "min-w-[720px]",
1041
+ children: [
1042
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1043
+ className: require_invalidate_database_entities.cn(`bg-muted/30 border-border/50 grid
1044
+ grid-cols-[40px_minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1.2fr)] gap-3 border-b px-3 py-2`, "text-muted-foreground/70 text-[10px] font-semibold tracking-widest uppercase"),
1045
+ children: [
1046
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1047
+ className: "flex items-center justify-center",
1048
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_checkbox.Checkbox, {
1049
+ checked: allSelected,
1050
+ indeterminate: someSelected,
1051
+ onCheckedChange: (checked) => handleSelectAll(checked),
1052
+ disabled: disabled || fields.length === 0
1053
+ })
1054
+ }),
1055
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { children: "Field" }),
1056
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { children: "Type" }),
1057
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { children: "Constraints" }),
1058
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", { children: "Default" })
1059
+ ]
1060
+ }),
1061
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1062
+ className: "divide-border/30 divide-y",
1063
+ children: fields.map((field, index) => {
1064
+ const isSelected = selectedFieldIds.has(field.id);
1065
+ const fieldTypeInfo = require_invalidate_database_entities.getFieldTypeInfo(field.type);
1066
+ const isPartOfPrimaryKey = pkConstraint?.fields.includes(field.id) || false;
1067
+ const isUnique = (constraints.find((c) => c.type === "unique" && c.fields.length === 1 && c.fields[0] === field.id) !== void 0 || isPartOfPrimaryKey) && !isPartOfPrimaryKey;
1068
+ const isNullable = field.constraints.nullable && !isPartOfPrimaryKey;
1069
+ const isRequired = !field.constraints.nullable && !isPartOfPrimaryKey;
1070
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1071
+ role: "button",
1072
+ tabIndex: disabled ? -1 : 0,
1073
+ "aria-disabled": disabled || void 0,
1074
+ "data-chat-component": "field-row",
1075
+ "data-chat-field-name": field.name,
1076
+ "data-chat-field-type": field.type,
1077
+ "data-chat-nullable": String(field.constraints.nullable),
1078
+ className: require_invalidate_database_entities.cn(`group grid grid-cols-[40px_minmax(0,1.2fr)_minmax(0,1fr)_minmax(0,1fr)_minmax(0,1.2fr)] gap-3 px-3
1079
+ py-2.5`, "cursor-pointer transition-colors duration-150 ease-out", "hover:bg-muted/40", isSelected && "bg-primary/5"),
1080
+ style: { animationDelay: `${index * 30}ms` },
1081
+ onClick: () => {
1082
+ if (!disabled) onFieldClick(field);
1083
+ },
1084
+ onKeyDown: (event) => {
1085
+ require_keyboard_activation.handleActivationKeyDown(event, () => onFieldClick(field), disabled);
1086
+ },
1087
+ children: [
1088
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1089
+ className: "flex items-center justify-center",
1090
+ onClick: (e) => e.stopPropagation(),
1091
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_checkbox.Checkbox, {
1092
+ checked: isSelected,
1093
+ onCheckedChange: (checked) => handleSelectRow(field.id, checked),
1094
+ disabled
1095
+ })
1096
+ }),
1097
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1098
+ className: "flex items-center gap-2",
1099
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1100
+ className: require_invalidate_database_entities.cn("truncate font-mono text-[13px] font-medium tracking-tight", "text-foreground/90 group-hover:text-foreground", "transition-colors duration-200"),
1101
+ children: field.name
1102
+ })
1103
+ }),
1104
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1105
+ className: "flex items-center",
1106
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1107
+ className: require_invalidate_database_entities.cn("inline-flex items-center gap-1.5 rounded-md px-2 py-1", "bg-muted/60 group-hover:bg-muted/80", "border-border/40 border", "transition-[background-color,border-color] duration-150 ease-out"),
1108
+ children: [fieldTypeInfo?.icon && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1109
+ className: "text-muted-foreground/70 flex items-center",
1110
+ children: typeof fieldTypeInfo.icon === "string" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1111
+ className: "text-xs",
1112
+ children: fieldTypeInfo.icon
1113
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(fieldTypeInfo.icon, { className: "size-3.5" })
1114
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1115
+ className: "text-foreground/70 font-mono text-[11px] font-medium",
1116
+ children: fieldTypeInfo?.label || field.type
1117
+ })]
1118
+ })
1119
+ }),
1120
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1121
+ className: "flex flex-wrap items-center gap-1",
1122
+ children: [
1123
+ isPartOfPrimaryKey && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConstraintIndicator, {
1124
+ type: "pk",
1125
+ label: "PK"
1126
+ }),
1127
+ isUnique && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConstraintIndicator, {
1128
+ type: "unique",
1129
+ label: "Unique"
1130
+ }),
1131
+ isNullable && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConstraintIndicator, {
1132
+ type: "nullable",
1133
+ label: "Null"
1134
+ }),
1135
+ isRequired && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(ConstraintIndicator, {
1136
+ type: "required",
1137
+ label: "Req"
1138
+ }),
1139
+ !isPartOfPrimaryKey && !isNullable && !isUnique && !isRequired && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1140
+ className: "text-muted-foreground/30 text-xs",
1141
+ children: "—"
1142
+ })
1143
+ ]
1144
+ }),
1145
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1146
+ className: "flex items-center",
1147
+ children: field.constraints.defaultValue ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("code", {
1148
+ className: require_invalidate_database_entities.cn("text-muted-foreground truncate rounded px-1.5 py-0.5 font-mono text-[11px]", "bg-muted/40 group-hover:bg-muted/60", "transition-colors duration-200"),
1149
+ children: field.constraints.defaultValue.toString()
1150
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1151
+ className: "text-muted-foreground/30 text-[11px] italic",
1152
+ children: "null"
1153
+ })
1154
+ })
1155
+ ]
1156
+ }, field.id);
1157
+ })
1158
+ }),
1159
+ fields.length === 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1160
+ className: "flex flex-col items-center justify-center py-12",
1161
+ children: [
1162
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1163
+ className: require_invalidate_database_entities.cn("bg-muted/30 mb-3 flex size-12 items-center justify-center rounded-xl", "border-border/50 border border-dashed"),
1164
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_remixicon_react.RiSparklingLine, { className: "text-muted-foreground/40 size-5" })
1165
+ }),
1166
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1167
+ className: "text-muted-foreground/60 text-sm font-medium",
1168
+ children: "No fields defined"
1169
+ }),
1170
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1171
+ className: "text-muted-foreground/40 mt-1 text-xs",
1172
+ children: "Add your first field to start building the schema"
1173
+ })
1174
+ ]
1175
+ })
1176
+ ]
1177
+ });
1178
+ }
1179
+
1180
+ //#endregion
1181
+ //#region src/schema/schema-builder-fields/components/table-editor/fields-section.tsx
1182
+ function FieldsSection({ onAddFieldRef } = {}) {
1183
+ const { currentTable } = require_invalidate_database_entities.useSchemaBuilderSelectors();
1184
+ const stack = (0, _constructive_io_ui_stack.useCardStack)();
1185
+ const deleteFieldMutation = useDeleteField();
1186
+ const [selectedFieldIds, setSelectedFieldIds] = (0, react.useState)(/* @__PURE__ */ new Set());
1187
+ const { setNodeRef: setDropZoneRef, isOver: isOverDropZone } = (0, _dnd_kit_core.useDroppable)({ id: "column-editor-dropzone" });
1188
+ const remoteFields = (0, react.useMemo)(() => currentTable?.fields || [], [currentTable?.fields]);
1189
+ const constraints = (0, react.useMemo)(() => currentTable?.constraints || [], [currentTable?.constraints]);
1190
+ const sortedFields = (0, react.useMemo)(() => {
1191
+ return [...remoteFields].sort((a, b) => {
1192
+ const aIsUuid = a.type === "uuid";
1193
+ const bIsUuid = b.type === "uuid";
1194
+ if (aIsUuid && !bIsUuid) return -1;
1195
+ if (!aIsUuid && bIsUuid) return 1;
1196
+ return (a.fieldOrder ?? 0) - (b.fieldOrder ?? 0);
1197
+ });
1198
+ }, [remoteFields]);
1199
+ (0, react.useEffect)(() => {
1200
+ setSelectedFieldIds(/* @__PURE__ */ new Set());
1201
+ }, [currentTable?.id]);
1202
+ const getFieldConstraintInfo = (0, react.useCallback)((field) => {
1203
+ if (!field) return {};
1204
+ const pkConstraint = constraints.find((c) => c.type === "primary_key");
1205
+ const uniqueConstraint = constraints.find((c) => c.type === "unique" && c.fields.length === 1 && c.fields[0] === field.id);
1206
+ return {
1207
+ primaryKeyConstraintId: pkConstraint?.id,
1208
+ uniqueConstraintId: uniqueConstraint?.id,
1209
+ allPrimaryKeyFieldIds: pkConstraint?.fields || [],
1210
+ isPartOfPrimaryKey: pkConstraint?.fields.includes(field.id) || false
1211
+ };
1212
+ }, [constraints]);
1213
+ const handleAddField = (0, react.useCallback)(() => {
1214
+ stack.push({
1215
+ id: "add-field-new",
1216
+ title: "Add Field",
1217
+ Component: AddFieldCard,
1218
+ props: {
1219
+ editingField: null,
1220
+ preSelectedType: null,
1221
+ remoteFields
1222
+ },
1223
+ width: require_card_widths.CARD_WIDTHS.wide
1224
+ });
1225
+ }, [stack, remoteFields]);
1226
+ const handleFieldClick = (0, react.useCallback)((field) => {
1227
+ const constraintInfo = getFieldConstraintInfo(field);
1228
+ stack.push({
1229
+ id: `edit-field-${field.id}`,
1230
+ title: "Edit Field",
1231
+ Component: AddFieldCard,
1232
+ props: {
1233
+ editingField: field,
1234
+ preSelectedType: null,
1235
+ primaryKeyConstraintId: constraintInfo.primaryKeyConstraintId,
1236
+ uniqueConstraintId: constraintInfo.uniqueConstraintId,
1237
+ allPrimaryKeyFieldIds: constraintInfo.allPrimaryKeyFieldIds,
1238
+ isPartOfPrimaryKey: constraintInfo.isPartOfPrimaryKey,
1239
+ remoteFields
1240
+ },
1241
+ width: require_card_widths.CARD_WIDTHS.wide
1242
+ });
1243
+ }, [
1244
+ stack,
1245
+ getFieldConstraintInfo,
1246
+ remoteFields
1247
+ ]);
1248
+ const handleFieldDrop = (0, react.useCallback)((field) => {
1249
+ stack.push({
1250
+ id: `add-field-${field.type}`,
1251
+ title: "Add Field",
1252
+ Component: AddFieldCard,
1253
+ props: {
1254
+ editingField: null,
1255
+ preSelectedType: field.type,
1256
+ remoteFields
1257
+ },
1258
+ width: require_card_widths.CARD_WIDTHS.wide
1259
+ });
1260
+ }, [stack, remoteFields]);
1261
+ (0, react.useEffect)(() => {
1262
+ onAddFieldRef?.(handleFieldDrop);
1263
+ }, [onAddFieldRef, handleFieldDrop]);
1264
+ const [isDeleting, setIsDeleting] = (0, react.useState)(false);
1265
+ const handleBulkDelete = (0, react.useCallback)(async () => {
1266
+ if (selectedFieldIds.size === 0) return;
1267
+ const fieldsToDelete = sortedFields.filter((f) => selectedFieldIds.has(f.id));
1268
+ if (fieldsToDelete.length === 0) return;
1269
+ const pkConstraint = constraints.find((c) => c.type === "primary_key");
1270
+ setIsDeleting(true);
1271
+ const results = await Promise.allSettled(fieldsToDelete.map((field) => {
1272
+ const isPartOfPrimaryKey = pkConstraint?.fields.includes(field.id) || false;
1273
+ const uniqueConstraint = constraints.find((c) => c.type === "unique" && c.fields.length === 1 && c.fields[0] === field.id);
1274
+ return deleteFieldMutation.mutateAsync({
1275
+ id: field.id,
1276
+ primaryKeyConstraintId: pkConstraint?.id,
1277
+ uniqueConstraintId: uniqueConstraint?.id,
1278
+ allPrimaryKeyFieldIds: pkConstraint?.fields || [],
1279
+ wasPartOfPrimaryKey: isPartOfPrimaryKey
1280
+ });
1281
+ }));
1282
+ const deletedIds = [];
1283
+ const failed = [];
1284
+ results.forEach((result, i) => {
1285
+ if (result.status === "fulfilled") deletedIds.push(fieldsToDelete[i].id);
1286
+ else failed.push({ name: fieldsToDelete[i].name });
1287
+ });
1288
+ setIsDeleting(false);
1289
+ if (deletedIds.length > 0) setSelectedFieldIds((prev) => {
1290
+ const next = new Set(prev);
1291
+ for (const id of deletedIds) next.delete(id);
1292
+ return next;
1293
+ });
1294
+ if (deletedIds.length > 0 && failed.length === 0) _constructive_io_ui_toast.toast.success({ message: `${deletedIds.length} field${deletedIds.length > 1 ? "s" : ""} deleted` });
1295
+ else if (deletedIds.length > 0 && failed.length > 0) _constructive_io_ui_toast.toast.warning({
1296
+ message: `${deletedIds.length} deleted, ${failed.length} failed`,
1297
+ description: `Failed to delete: ${failed.map((f) => f.name).join(", ")}`
1298
+ });
1299
+ else _constructive_io_ui_toast.toast.error({
1300
+ message: "Failed to delete fields",
1301
+ description: `Failed to delete: ${failed.map((f) => f.name).join(", ")}`
1302
+ });
1303
+ }, [
1304
+ selectedFieldIds,
1305
+ sortedFields,
1306
+ constraints,
1307
+ deleteFieldMutation
1308
+ ]);
1309
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1310
+ "data-chat-component": "fields-section",
1311
+ "data-chat-table-name": currentTable?.name ?? "",
1312
+ "data-chat-field-count": String(remoteFields.length),
1313
+ className: "space-y-3",
1314
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1315
+ className: "flex items-center justify-between",
1316
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
1317
+ className: "text-balance text-sm font-medium",
1318
+ children: "Fields"
1319
+ }), selectedFieldIds.size > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_button.Button, {
1320
+ variant: "outline",
1321
+ size: "sm",
1322
+ className: "text-destructive hover:bg-destructive/10 hover:text-destructive border-destructive/30 gap-1.5",
1323
+ onClick: handleBulkDelete,
1324
+ disabled: isDeleting,
1325
+ children: [isDeleting ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Loader2, { className: "size-3.5 animate-spin" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Trash2, { className: "size-3.5" }), isDeleting ? "Deleting..." : `Delete (${selectedFieldIds.size})`]
1326
+ })]
1327
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1328
+ ref: setDropZoneRef,
1329
+ className: require_invalidate_database_entities.cn("bg-card/50 border-border/50 overflow-hidden rounded-lg border transition-colors", isOverDropZone ? "border-primary bg-primary/5" : null),
1330
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1331
+ className: "overflow-x-auto",
1332
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FieldsListView, {
1333
+ fields: sortedFields,
1334
+ constraints,
1335
+ selectedFieldIds,
1336
+ onSelectionChange: setSelectedFieldIds,
1337
+ onFieldClick: handleFieldClick,
1338
+ disabled: isDeleting
1339
+ })
1340
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1341
+ className: require_invalidate_database_entities.cn("flex items-center justify-center gap-3 border-t border-dashed p-4", "border-border/40 bg-muted/20", "transition-[background-color,border-color] duration-150 ease-out", isOverDropZone && "border-primary/50 bg-primary/5"),
1342
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_button.Button, {
1343
+ variant: "outline",
1344
+ size: "sm",
1345
+ className: require_invalidate_database_entities.cn("gap-1.5 px-3 text-xs font-medium", "hover:bg-primary/10 hover:text-primary hover:border-primary/30", "transition-[background-color,border-color,color,scale] duration-150 ease-out motion-safe:active:scale-[0.96]"),
1346
+ onClick: handleAddField,
1347
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Plus, { className: "size-3.5" }), "Add Field"]
1348
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1349
+ className: "text-muted-foreground/80 text-xs",
1350
+ children: "or drag field types here"
1351
+ })]
1352
+ })]
1353
+ })]
1354
+ });
1355
+ }
1356
+
1357
+ //#endregion
1358
+ //#region src/schema/schema-builder-tables/components/table-editor/no-table-selected-view.tsx
1359
+ function NoTableSelectedView({ className }) {
1360
+ const { selectTable, currentSchema } = require_invalidate_database_entities.useSchemaBuilderSelectors();
1361
+ const stack = (0, _constructive_io_ui_stack.useCardStack)();
1362
+ const handleCreateTable = () => {
1363
+ stack.push({
1364
+ id: "create-table-select-model",
1365
+ title: "Create Table",
1366
+ description: "Securely create a new table based on its access model",
1367
+ Component: require_create_table_card.CreateTableCard,
1368
+ props: { onTableCreated: (table) => {
1369
+ selectTable(table.id, table.name);
1370
+ } },
1371
+ width: require_card_widths.CARD_WIDTHS.extraWide
1372
+ });
1373
+ };
1374
+ if (currentSchema && currentSchema.tables.length > 0) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1375
+ className: require_invalidate_database_entities.cn("flex flex-1 items-center justify-center p-6", className),
1376
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1377
+ className: "text-center",
1378
+ children: [
1379
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1380
+ className: "bg-muted mx-auto mb-6 flex h-16 w-16 items-center justify-center rounded-full",
1381
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Table2, { className: "text-muted-foreground h-8 w-8" })
1382
+ }),
1383
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
1384
+ className: "mb-2 text-balance text-lg font-medium",
1385
+ children: "No Table Selected"
1386
+ }),
1387
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", {
1388
+ className: "text-muted-foreground mb-6 max-w-md text-sm",
1389
+ children: "Select a table from the sidebar to start editing its structure."
1390
+ })
1391
+ ]
1392
+ })
1393
+ });
1394
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(require_empty_state_card.EmptyStateCard, {
1395
+ icon: lucide_react.Table2,
1396
+ title: "Create your first table",
1397
+ description: "Create a table to start defining fields, relationships, and access policies.",
1398
+ className,
1399
+ actionLabel: "Create Table",
1400
+ actionIcon: lucide_react.Plus,
1401
+ onAction: handleCreateTable,
1402
+ features: [
1403
+ {
1404
+ icon: lucide_react.Database,
1405
+ title: "Flexible Schema",
1406
+ description: "Easy to modify & extend"
1407
+ },
1408
+ {
1409
+ icon: lucide_react.Lock,
1410
+ title: "Access Control",
1411
+ description: "Built-in security models"
1412
+ },
1413
+ {
1414
+ icon: lucide_react.Zap,
1415
+ title: "Type Safe",
1416
+ description: "Strong data validation"
1417
+ }
1418
+ ]
1419
+ });
1420
+ }
1421
+
1422
+ //#endregion
1423
+ //#region src/schema/schema-builder-tables/components/table-editor/table-metadata-section.tsx
1424
+ function TableMetadataReadOnly({ tableName }) {
1425
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1426
+ className: "flex min-w-0 flex-wrap items-center justify-between gap-3",
1427
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("h2", {
1428
+ className: "min-w-0",
1429
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1430
+ className: "sr-only",
1431
+ children: "Table"
1432
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1433
+ className: "border-border/60 bg-muted/40 text-foreground inline-flex max-w-full items-center rounded-md border\n px-2 py-1 font-mono text-base font-semibold tracking-tight",
1434
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1435
+ className: "truncate",
1436
+ children: tableName
1437
+ })
1438
+ })]
1439
+ })
1440
+ });
1441
+ }
1442
+ function TableMetadataEditable({ currentTable }) {
1443
+ const [editedName, setEditedName] = (0, react.useState)(currentTable.name);
1444
+ const [committedName, setCommittedName] = (0, react.useState)(currentTable.name);
1445
+ const updateTableMutation = require_use_update_table.useUpdateTable();
1446
+ (0, react.useEffect)(() => {
1447
+ setEditedName(currentTable.name);
1448
+ setCommittedName(currentTable.name);
1449
+ }, [currentTable.id, currentTable.name]);
1450
+ const isNameChanged = editedName !== committedName;
1451
+ const handleTableNameChange = (value) => {
1452
+ const validName = value.toLowerCase().replace(/[^a-z0-9_]/g, "_").replace(/_{2,}/g, "_");
1453
+ setEditedName(validName);
1454
+ };
1455
+ const handleSaveTableName = async () => {
1456
+ if (!editedName) return;
1457
+ try {
1458
+ await updateTableMutation.mutateAsync({
1459
+ id: currentTable.id,
1460
+ name: editedName
1461
+ });
1462
+ setCommittedName(editedName);
1463
+ _constructive_io_ui_toast.toast.success({
1464
+ message: "Table updated",
1465
+ description: `Table name changed to "${editedName}"`
1466
+ });
1467
+ } catch (error) {
1468
+ _constructive_io_ui_toast.toast.error({
1469
+ message: "Failed to update table",
1470
+ description: error instanceof Error ? error.message : "An error occurred"
1471
+ });
1472
+ }
1473
+ };
1474
+ const handleCancelTableName = () => {
1475
+ setEditedName(committedName);
1476
+ };
1477
+ const handleFormSubmit = (e) => {
1478
+ e.preventDefault();
1479
+ if (isNameChanged) handleSaveTableName();
1480
+ };
1481
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1482
+ className: "flex flex-wrap items-center justify-between gap-3",
1483
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h2", {
1484
+ className: "text-foreground text-balance text-lg font-semibold tracking-tight",
1485
+ children: "Edit Table"
1486
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("form", {
1487
+ onSubmit: handleFormSubmit,
1488
+ className: "flex min-w-0 items-center gap-2",
1489
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("label", {
1490
+ className: "sr-only",
1491
+ htmlFor: "table-name",
1492
+ children: "Table name"
1493
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1494
+ className: "relative flex min-w-0 items-center gap-2",
1495
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input.Input, {
1496
+ id: "table-name",
1497
+ value: editedName,
1498
+ onChange: (e) => handleTableNameChange(e.target.value),
1499
+ className: "h-8 w-56 rounded-lg text-sm",
1500
+ placeholder: "Enter table name...",
1501
+ disabled: updateTableMutation.isPending
1502
+ }), isNameChanged && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1503
+ className: "flex items-center gap-1.5",
1504
+ children: updateTableMutation.isPending ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Loader2, { className: "text-muted-foreground h-4 w-4 animate-spin" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_tooltip.Tooltip, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_tooltip.TooltipTrigger, {
1505
+ asChild: true,
1506
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_button.Button, {
1507
+ type: "submit",
1508
+ variant: "default",
1509
+ size: "xs",
1510
+ className: "bg-foreground text-background hover:bg-foreground/90 size-6 rounded-lg border-none",
1511
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.Check, { className: "size-3.5" })
1512
+ })
1513
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_tooltip.TooltipContent, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "Save" }) })] }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_tooltip.Tooltip, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_tooltip.TooltipTrigger, {
1514
+ asChild: true,
1515
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_button.Button, {
1516
+ type: "button",
1517
+ onClick: handleCancelTableName,
1518
+ variant: "secondary",
1519
+ size: "xs",
1520
+ className: "text-muted-foreground size-6 rounded-lg border-none",
1521
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.X, { className: "size-3.5" })
1522
+ })
1523
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_tooltip.TooltipContent, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("p", { children: "Cancel" }) })] })] })
1524
+ })]
1525
+ })]
1526
+ })]
1527
+ });
1528
+ }
1529
+ function TableMetadataSection({ isEditable = false }) {
1530
+ const { currentTable } = require_invalidate_database_entities.useSchemaBuilderSelectors();
1531
+ if (!currentTable?.name || !currentTable?.id) return null;
1532
+ if (!isEditable) return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TableMetadataReadOnly, { tableName: currentTable.name });
1533
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TableMetadataEditable, { currentTable: {
1534
+ id: currentTable.id,
1535
+ name: currentTable.name
1536
+ } });
1537
+ }
1538
+
1539
+ //#endregion
1540
+ //#region src/schema/schema-builder-fields/components/table-editor/types-library.tsx
1541
+ const basicTypes$1 = require_invalidate_database_entities.getBasicFieldTypes();
1542
+ const advancedTypes = require_invalidate_database_entities.getAdvancedFieldTypes();
1543
+ const allTypes = [...basicTypes$1, ...advancedTypes];
1544
+ function TypesLibrary() {
1545
+ const [searchQuery, setSearchQuery] = (0, react.useState)("");
1546
+ const [sectionsExpanded, setSectionsExpanded] = (0, react.useState)(() => ({
1547
+ basic: true,
1548
+ advanced: false
1549
+ }));
1550
+ const toggleSection = (section) => setSectionsExpanded((prev) => ({
1551
+ ...prev,
1552
+ [section]: !prev[section]
1553
+ }));
1554
+ const { filteredBasicTypes, filteredAdvancedTypes } = (0, react.useMemo)(() => {
1555
+ if (!searchQuery.trim()) return {
1556
+ filteredBasicTypes: basicTypes$1,
1557
+ filteredAdvancedTypes: advancedTypes
1558
+ };
1559
+ const searchResults = require_invalidate_database_entities.searchFieldTypes(searchQuery);
1560
+ const matchingTypes = new Set(searchResults.map((r) => r.type));
1561
+ return {
1562
+ filteredBasicTypes: basicTypes$1.filter((type) => matchingTypes.has(type.type)),
1563
+ filteredAdvancedTypes: advancedTypes.filter((type) => matchingTypes.has(type.type))
1564
+ };
1565
+ }, [searchQuery]);
1566
+ const totalFilteredCount = filteredBasicTypes.length + filteredAdvancedTypes.length;
1567
+ const totalTypesCount = allTypes.length;
1568
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1569
+ className: "flex h-full min-h-0 flex-col",
1570
+ children: [
1571
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1572
+ className: "px-3 pt-3 pb-2",
1573
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_input_group.InputGroup, { children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input_group.InputGroupAddon, { children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_remixicon_react.RiSearchLine, {}) }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_input_group.InputGroupInput, {
1574
+ placeholder: "Search types...",
1575
+ value: searchQuery,
1576
+ onChange: (e) => {
1577
+ const value = e.target.value;
1578
+ (0, react.startTransition)(() => setSearchQuery(value));
1579
+ },
1580
+ size: "sm"
1581
+ })] }), searchQuery && /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", {
1582
+ className: "text-muted-foreground mt-1.5 text-xs",
1583
+ children: [
1584
+ totalFilteredCount,
1585
+ " of ",
1586
+ totalTypesCount,
1587
+ " types"
1588
+ ]
1589
+ })]
1590
+ }),
1591
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1592
+ className: "scrollbar-neutral-thin min-h-0 flex-1 space-y-2 overflow-auto px-2 pb-2",
1593
+ children: totalFilteredCount === 0 ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1594
+ className: "text-muted-foreground p-4 text-center text-sm",
1595
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("p", { children: [
1596
+ "No types found for “",
1597
+ searchQuery,
1598
+ "”"
1599
+ ] })
1600
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(react_jsx_runtime.Fragment, { children: [filteredBasicTypes.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TypesSection, {
1601
+ title: "Basic",
1602
+ types: filteredBasicTypes,
1603
+ isExpanded: sectionsExpanded.basic,
1604
+ onToggleExpand: () => toggleSection("basic")
1605
+ }), filteredAdvancedTypes.length > 0 && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TypesSection, {
1606
+ title: "Advanced",
1607
+ types: filteredAdvancedTypes,
1608
+ isExpanded: sectionsExpanded.advanced,
1609
+ onToggleExpand: () => toggleSection("advanced")
1610
+ })] })
1611
+ }),
1612
+ /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1613
+ className: "text-muted-foreground/70 flex items-center gap-1.5 border-t px-3 py-2 text-xs",
1614
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(_remixicon_react.RiDragDropLine, { className: "h-3 w-3" }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", { children: "Drag or use the keyboard to add fields." })]
1615
+ })
1616
+ ]
1617
+ });
1618
+ }
1619
+ function TypesSection({ title, types, isExpanded, onToggleExpand }) {
1620
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_collapsible.Collapsible, {
1621
+ open: isExpanded,
1622
+ onOpenChange: onToggleExpand,
1623
+ className: "flex min-h-0 shrink-0 flex-col",
1624
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_constructive_io_ui_collapsible.CollapsibleTrigger, {
1625
+ className: "group flex w-full cursor-pointer items-center gap-2 rounded-lg py-1.5 pr-2 pl-1 transition-colors\n duration-150 bg-card hover:bg-muted/50 data-[state=open]:bg-muted/50",
1626
+ children: [
1627
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)(motion_react.motion.div, {
1628
+ animate: { rotate: isExpanded ? 90 : 0 },
1629
+ transition: {
1630
+ type: "spring",
1631
+ stiffness: 400,
1632
+ damping: 25
1633
+ },
1634
+ className: "flex shrink-0 items-center justify-center",
1635
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.ChevronRight, { className: "text-muted-foreground/60 h-3.5 w-3.5" })
1636
+ }),
1637
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1638
+ className: "text-muted-foreground text-xs font-medium",
1639
+ children: title
1640
+ }),
1641
+ /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1642
+ className: "text-muted-foreground/70 ml-auto text-[10px] tabular-nums",
1643
+ children: types.length
1644
+ })
1645
+ ]
1646
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(motion_react.AnimatePresence, {
1647
+ initial: false,
1648
+ children: isExpanded && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(motion_react.motion.div, {
1649
+ initial: {
1650
+ opacity: 0,
1651
+ y: -4
1652
+ },
1653
+ animate: {
1654
+ opacity: 1,
1655
+ y: 0
1656
+ },
1657
+ exit: {
1658
+ opacity: 0,
1659
+ y: -4
1660
+ },
1661
+ transition: {
1662
+ ...require_use_update_table.springs.stiff,
1663
+ opacity: {
1664
+ duration: require_use_update_table.durations.fast,
1665
+ ease: require_use_update_table.easings.easeOut
1666
+ }
1667
+ },
1668
+ className: "min-h-0 overflow-hidden",
1669
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1670
+ className: "mt-1.5 space-y-1",
1671
+ children: types.map((typeInfo) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DraggableFieldType, {
1672
+ typeInfo,
1673
+ className: "w-full"
1674
+ }, typeInfo.type))
1675
+ })
1676
+ })
1677
+ })]
1678
+ });
1679
+ }
1680
+
1681
+ //#endregion
1682
+ //#region src/schema/schema-builder-fields/components/table-editor/types-library-rail.tsx
1683
+ const basicTypes = require_invalidate_database_entities.getBasicFieldTypes();
1684
+ function TypesLibraryRail({ className }) {
1685
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1686
+ className,
1687
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1688
+ className: "scrollbar-neutral-thin flex h-full flex-col items-center gap-1.5 overflow-y-auto py-1.5",
1689
+ children: basicTypes.map((typeInfo) => /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DraggableFieldTypeIcon, { typeInfo }, typeInfo.type))
1690
+ })
1691
+ });
1692
+ }
1693
+
1694
+ //#endregion
1695
+ //#region src/schema/schema-builder-fields/components/table-editor/use-field-dnd.ts
1696
+ const COLUMN_EDITOR_DROPZONE_ID = "column-editor-dropzone";
1697
+ const DEFAULT_DROP_ANIMATION = { sideEffects: (0, _dnd_kit_core.defaultDropAnimationSideEffects)({ styles: { active: { opacity: "0.5" } } }) };
1698
+ function useFieldDnD(currentTable) {
1699
+ const [activeId, setActiveId] = (0, react.useState)(null);
1700
+ const [draggedType, setDraggedType] = (0, react.useState)(null);
1701
+ const [dragSource, setDragSource] = (0, react.useState)(null);
1702
+ const [addFieldFn, setAddFieldFn] = (0, react.useState)(null);
1703
+ const sensors = (0, _dnd_kit_core.useSensors)((0, _dnd_kit_core.useSensor)(_dnd_kit_core.KeyboardSensor), (0, _dnd_kit_core.useSensor)(_dnd_kit_core.PointerSensor, { activationConstraint: { distance: 8 } }));
1704
+ const handleDragStart = (event) => {
1705
+ const { active } = event;
1706
+ setActiveId(active.id);
1707
+ const data = active.data.current;
1708
+ if (data?.typeInfo) {
1709
+ setDraggedType(data.typeInfo);
1710
+ setDragSource(data.source ?? "panel");
1711
+ }
1712
+ };
1713
+ const customCollisionDetection = (args) => {
1714
+ return (0, _dnd_kit_core.rectIntersection)(args).filter((collision) => collision.id === COLUMN_EDITOR_DROPZONE_ID);
1715
+ };
1716
+ const handleDragEnd = (event) => {
1717
+ const { over } = event;
1718
+ if (!over) {
1719
+ setActiveId(null);
1720
+ setDraggedType(null);
1721
+ setDragSource(null);
1722
+ return;
1723
+ }
1724
+ if (!(over.id === "column-editor-dropzone") || !draggedType || !addFieldFn || !currentTable) {
1725
+ setActiveId(null);
1726
+ setDraggedType(null);
1727
+ setDragSource(null);
1728
+ return;
1729
+ }
1730
+ if (over.id === "column-editor-dropzone") {
1731
+ const newField = {
1732
+ id: `temp-field-${Date.now()}`,
1733
+ name: "",
1734
+ type: draggedType.type,
1735
+ constraints: require_invalidate_database_entities.getDefaultConstraintsForType(draggedType.type),
1736
+ fieldOrder: 1e3
1737
+ };
1738
+ addFieldFn(newField);
1739
+ }
1740
+ setActiveId(null);
1741
+ setDraggedType(null);
1742
+ setDragSource(null);
1743
+ };
1744
+ const handleDragCancel = () => {
1745
+ setActiveId(null);
1746
+ setDraggedType(null);
1747
+ setDragSource(null);
1748
+ };
1749
+ return {
1750
+ sensors,
1751
+ customCollisionDetection,
1752
+ handleDragStart,
1753
+ handleDragEnd,
1754
+ handleDragCancel,
1755
+ handleAddFieldRef: (0, react.useCallback)((fn) => {
1756
+ setAddFieldFn(() => fn);
1757
+ }, []),
1758
+ activeId,
1759
+ draggedType,
1760
+ dragSource
1761
+ };
1762
+ }
1763
+
1764
+ //#endregion
1765
+ //#region src/schema/schema-builder-fields/components/table-editor/table-editor.tsx
1766
+ const PANEL_WIDTH_EXPANDED = 380;
1767
+ const PANEL_WIDTH_COLLAPSED = 56;
1768
+ const tweenConfig = {
1769
+ duration: require_use_update_table.durations.normal,
1770
+ ease: require_use_update_table.easings.easeOut
1771
+ };
1772
+ const totalTypesCount = require_invalidate_database_entities.FIELD_TYPE_CATEGORIES.reduce((sum, cat) => sum + cat.types.length, 0);
1773
+ function TypesLibraryHeader({ isExpanded, onToggle }) {
1774
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1775
+ className: "flex items-center justify-between border-b px-3 py-2",
1776
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1777
+ className: "flex items-center gap-2",
1778
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("h3", {
1779
+ className: "text-balance text-sm font-medium",
1780
+ children: "Types Library"
1781
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("span", {
1782
+ className: "text-muted-foreground bg-muted rounded-md px-1.5 py-0.5 text-xs tabular-nums",
1783
+ children: totalTypesCount
1784
+ })]
1785
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_button.Button, {
1786
+ variant: "ghost",
1787
+ size: "sm",
1788
+ onClick: onToggle,
1789
+ className: "h-7 w-7 p-0",
1790
+ "aria-label": isExpanded ? "Collapse panel" : "Expand panel",
1791
+ children: isExpanded ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.ChevronRight, { className: "h-4 w-4" }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.ChevronLeft, { className: "h-4 w-4" })
1792
+ })]
1793
+ });
1794
+ }
1795
+ function CollapsedHeader({ onToggle }) {
1796
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1797
+ className: "flex items-center justify-center border-b py-2",
1798
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_button.Button, {
1799
+ variant: "ghost",
1800
+ size: "sm",
1801
+ onClick: onToggle,
1802
+ className: "h-7 w-7 p-0",
1803
+ "aria-label": "Expand panel",
1804
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(lucide_react.ChevronLeft, { className: "h-4 w-4" })
1805
+ })
1806
+ });
1807
+ }
1808
+ function TableEditor() {
1809
+ const { currentTable } = require_invalidate_database_entities.useSchemaBuilderSelectors();
1810
+ const { sensors, customCollisionDetection, handleDragStart, handleDragEnd, handleDragCancel, handleAddFieldRef, activeId, draggedType, dragSource } = useFieldDnD(currentTable);
1811
+ const panelExpanded = require_use_update_table.useTypesLibraryExpanded();
1812
+ const togglePanel = require_use_update_table.useToggleTypesLibraryExpanded();
1813
+ return /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_constructive_io_ui_tooltip.TooltipProvider, {
1814
+ delayDuration: 300,
1815
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(_dnd_kit_core.DndContext, {
1816
+ sensors,
1817
+ collisionDetection: customCollisionDetection,
1818
+ onDragStart: handleDragStart,
1819
+ onDragEnd: handleDragEnd,
1820
+ onDragCancel: handleDragCancel,
1821
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1822
+ "data-chat-component": "table-editor",
1823
+ "data-chat-table-name": currentTable?.name ?? "",
1824
+ className: "relative flex min-h-0 min-w-0 flex-1 overflow-hidden",
1825
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1826
+ className: require_invalidate_database_entities.cn("scrollbar-neutral-thin relative min-h-0 w-full min-w-0 flex-1 overflow-auto"),
1827
+ style: { paddingRight: currentTable ? panelExpanded ? PANEL_WIDTH_EXPANDED : PANEL_WIDTH_COLLAPSED : 0 },
1828
+ children: currentTable ? /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1829
+ className: "min-h-full min-w-full space-y-8 p-6 pb-12",
1830
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(TableMetadataSection, {}), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(FieldsSection, { onAddFieldRef: handleAddFieldRef })]
1831
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1832
+ className: "flex min-h-full min-w-full items-start justify-center p-6 pb-12",
1833
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(NoTableSelectedView, { className: "mt-20" })
1834
+ })
1835
+ }), currentTable && /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1836
+ "data-state": panelExpanded ? "expanded" : "collapsed",
1837
+ className: "bg-background border-border/60 absolute top-0 right-0 z-10 flex h-full flex-col border-l",
1838
+ style: { width: panelExpanded ? PANEL_WIDTH_EXPANDED : PANEL_WIDTH_COLLAPSED },
1839
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsxs)("div", {
1840
+ className: "relative flex h-full min-h-0 flex-1 flex-col overflow-hidden",
1841
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsxs)(motion_react.motion.div, {
1842
+ className: "absolute inset-0 flex h-full flex-col",
1843
+ style: { pointerEvents: panelExpanded ? "none" : "auto" },
1844
+ initial: false,
1845
+ animate: { opacity: panelExpanded ? 0 : 1 },
1846
+ transition: tweenConfig,
1847
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(CollapsedHeader, { onToggle: togglePanel }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TypesLibraryRail, { className: "min-h-0 flex-1 py-2" })]
1848
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsxs)(motion_react.motion.div, {
1849
+ className: "absolute inset-0 flex h-full flex-col overflow-hidden",
1850
+ style: { pointerEvents: panelExpanded ? "auto" : "none" },
1851
+ initial: false,
1852
+ animate: { opacity: panelExpanded ? 1 : 0 },
1853
+ transition: tweenConfig,
1854
+ children: [/* @__PURE__ */ (0, react_jsx_runtime.jsx)(TypesLibraryHeader, {
1855
+ isExpanded: panelExpanded,
1856
+ onToggle: togglePanel
1857
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)("div", {
1858
+ className: "min-h-0 flex-1 overflow-hidden",
1859
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(TypesLibrary, {})
1860
+ })]
1861
+ })]
1862
+ })
1863
+ })]
1864
+ }), /* @__PURE__ */ (0, react_jsx_runtime.jsx)(_dnd_kit_core.DragOverlay, {
1865
+ dropAnimation: DEFAULT_DROP_ANIMATION,
1866
+ children: /* @__PURE__ */ (0, react_jsx_runtime.jsx)(motion_react.AnimatePresence, {
1867
+ initial: false,
1868
+ children: activeId && draggedType && /* @__PURE__ */ (0, react_jsx_runtime.jsx)(motion_react.motion.div, {
1869
+ className: "rotate-3 transform",
1870
+ initial: {
1871
+ opacity: 0,
1872
+ scale: .9,
1873
+ y: 4
1874
+ },
1875
+ animate: {
1876
+ opacity: 1,
1877
+ scale: 1,
1878
+ y: 0
1879
+ },
1880
+ exit: { opacity: 0 },
1881
+ transition: {
1882
+ ...require_use_update_table.springs.stiff,
1883
+ opacity: {
1884
+ duration: require_use_update_table.durations.instant,
1885
+ ease: require_use_update_table.easings.easeOut
1886
+ }
1887
+ },
1888
+ children: dragSource === "rail" ? /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DraggableFieldTypeIcon, {
1889
+ typeInfo: draggedType,
1890
+ isDragging: true,
1891
+ className: "border-primary/50 bg-background border-2 shadow-2xl"
1892
+ }) : /* @__PURE__ */ (0, react_jsx_runtime.jsx)(DraggableFieldType, {
1893
+ typeInfo: draggedType,
1894
+ isDragging: true,
1895
+ className: "border-primary/50 bg-background border-2 shadow-2xl"
1896
+ })
1897
+ }, activeId)
1898
+ })
1899
+ })]
1900
+ })
1901
+ });
1902
+ }
1903
+
1904
+ //#endregion
1905
+ Object.defineProperty(exports, 'TableEditor', {
1906
+ enumerable: true,
1907
+ get: function () {
1908
+ return TableEditor;
1909
+ }
1910
+ });
1911
+ Object.defineProperty(exports, 'useCreateField', {
1912
+ enumerable: true,
1913
+ get: function () {
1914
+ return useCreateField;
1915
+ }
1916
+ });
1917
+ Object.defineProperty(exports, 'useDeleteField', {
1918
+ enumerable: true,
1919
+ get: function () {
1920
+ return useDeleteField;
1921
+ }
1922
+ });
1923
+ Object.defineProperty(exports, 'useUpdateField', {
1924
+ enumerable: true,
1925
+ get: function () {
1926
+ return useUpdateField;
1927
+ }
1928
+ });
1929
+ Object.defineProperty(exports, 'useUpdateFieldOrder', {
1930
+ enumerable: true,
1931
+ get: function () {
1932
+ return useUpdateFieldOrder;
1933
+ }
1934
+ });
1935
+ //# sourceMappingURL=table-editor-C-hHz3DJ.cjs.map