@constructive-io/sheets 0.13.1 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +231 -148
  2. package/dist/advanced.cjs +7220 -4030
  3. package/dist/advanced.cjs.map +1 -1
  4. package/dist/advanced.d.cts +2 -2
  5. package/dist/advanced.d.ts +2 -2
  6. package/dist/advanced.js +5 -5
  7. package/dist/auth.cjs.map +1 -1
  8. package/dist/auth.js +3 -3
  9. package/dist/chunk-CJ4PRA64.js +312 -0
  10. package/dist/chunk-CJ4PRA64.js.map +1 -0
  11. package/dist/chunk-II3MSNRO.js +18 -0
  12. package/dist/chunk-II3MSNRO.js.map +1 -0
  13. package/dist/{chunk-MXVNIKES.js → chunk-J7KK4UWI.js} +6 -6
  14. package/dist/chunk-MBSHDF55.js +839 -0
  15. package/dist/chunk-MBSHDF55.js.map +1 -0
  16. package/dist/{chunk-ZKANUG3F.js → chunk-MOFFS5WQ.js} +20 -15
  17. package/dist/chunk-MOFFS5WQ.js.map +1 -0
  18. package/dist/chunk-VCBY2AMT.js +8920 -0
  19. package/dist/chunk-VCBY2AMT.js.map +1 -0
  20. package/dist/{chunk-H5HR5HUJ.js → chunk-ZOQDSOMO.js} +50 -312
  21. package/dist/chunk-ZOQDSOMO.js.map +1 -0
  22. package/dist/date-editor-ORCB43ZM.js +346 -0
  23. package/dist/date-editor-ORCB43ZM.js.map +1 -0
  24. package/dist/grid-cell-types-YNIVK4hN.d.cts +346 -0
  25. package/dist/grid-cell-types-YNIVK4hN.d.ts +346 -0
  26. package/dist/index.cjs +22910 -12084
  27. package/dist/index.cjs.map +1 -1
  28. package/dist/index.d.cts +1497 -337
  29. package/dist/index.d.ts +1497 -337
  30. package/dist/index.js +12833 -6142
  31. package/dist/index.js.map +1 -1
  32. package/dist/sheets-context-Bb7ZoNBg.d.cts +436 -0
  33. package/dist/sheets-context-CPuf31LS.d.ts +436 -0
  34. package/dist/testing.cjs +1253 -638
  35. package/dist/testing.cjs.map +1 -1
  36. package/dist/testing.d.cts +80 -11
  37. package/dist/testing.d.ts +80 -11
  38. package/dist/testing.js +791 -148
  39. package/dist/testing.js.map +1 -1
  40. package/package.json +5 -5
  41. package/dist/chunk-4EZ6A23C.js +0 -44
  42. package/dist/chunk-4EZ6A23C.js.map +0 -1
  43. package/dist/chunk-5QPNOKMA.js +0 -4397
  44. package/dist/chunk-5QPNOKMA.js.map +0 -1
  45. package/dist/chunk-AYMXT3ME.js +0 -540
  46. package/dist/chunk-AYMXT3ME.js.map +0 -1
  47. package/dist/chunk-H5HR5HUJ.js.map +0 -1
  48. package/dist/chunk-PZL2BCWF.js +0 -168
  49. package/dist/chunk-PZL2BCWF.js.map +0 -1
  50. package/dist/chunk-X7DHTSOX.js +0 -21
  51. package/dist/chunk-X7DHTSOX.js.map +0 -1
  52. package/dist/chunk-ZKANUG3F.js.map +0 -1
  53. package/dist/date-editor-ZFNDKYBD.js +0 -358
  54. package/dist/date-editor-ZFNDKYBD.js.map +0 -1
  55. package/dist/grid-cell-types-Pbe2m2tE.d.cts +0 -253
  56. package/dist/grid-cell-types-Pbe2m2tE.d.ts +0 -253
  57. package/dist/map-picker-ZUGGOIZS.js +0 -290
  58. package/dist/map-picker-ZUGGOIZS.js.map +0 -1
  59. package/dist/sheets-context-CY1RmDKL.d.cts +0 -244
  60. package/dist/sheets-context-Cu3Ec_ca.d.ts +0 -244
  61. /package/dist/{chunk-MXVNIKES.js.map → chunk-J7KK4UWI.js.map} +0 -0
@@ -1,4397 +0,0 @@
1
- "use client";
2
- import {
3
- createSheetsExecute,
4
- createSheetsUpload,
5
- reuseSheetsPlaceholderData,
6
- sheetsQueryKeys
7
- } from "./chunk-AYMXT3ME.js";
8
- import {
9
- useSheetsContext,
10
- useSheetsStore,
11
- useSheetsStoreApi
12
- } from "./chunk-H5HR5HUJ.js";
13
- import {
14
- BOOLEAN_TYPES,
15
- DATE_TIME_TYPES,
16
- EditorFocusTrap,
17
- GEOMETRY_TYPES,
18
- MEDIA_TYPES,
19
- NUMBER_TYPES,
20
- OVERLAY,
21
- OVERLAY_SM,
22
- isArrayCellType
23
- } from "./chunk-PZL2BCWF.js";
24
- import {
25
- cn
26
- } from "./chunk-YDQQA46V.js";
27
- import {
28
- sheetsLogger
29
- } from "./chunk-X7DHTSOX.js";
30
-
31
- // src/row-identity.ts
32
- import {
33
- assessTableWriteCapability,
34
- resolveRowIdentity,
35
- rowIdentityToPrimaryKey,
36
- serializeRowIdentity
37
- } from "@constructive-io/data";
38
- function isLegacyScalarId(primaryKey) {
39
- const entries = Object.entries(primaryKey);
40
- return entries.length === 1 && entries[0][0] === "id" && (typeof entries[0][1] === "string" || typeof entries[0][1] === "number");
41
- }
42
- function resolveSheetsRowIdentity(table, row) {
43
- const resolution = resolveRowIdentity(table, row);
44
- if (resolution.status === "read-only") {
45
- return { status: "unavailable", reason: "no-primary-key" };
46
- }
47
- if (resolution.status === "invalid-row") {
48
- return { status: "unavailable", reason: "invalid-row" };
49
- }
50
- const primaryKey = rowIdentityToPrimaryKey(resolution.identity);
51
- return {
52
- status: "identified",
53
- identifier: isLegacyScalarId(primaryKey) ? primaryKey.id : primaryKey,
54
- primaryKey,
55
- key: serializeRowIdentity(resolution.identity)
56
- };
57
- }
58
- function resolveSheetsIdentifier(table, identifier) {
59
- const row = typeof identifier === "object" && identifier !== null ? identifier : { id: identifier };
60
- return resolveSheetsRowIdentity(table, row);
61
- }
62
- function sheetsIdentifierToWhere(table, identifier) {
63
- const resolution = resolveSheetsIdentifier(table, identifier);
64
- if (resolution.status !== "identified") return null;
65
- return Object.fromEntries(
66
- Object.entries(resolution.primaryKey).map(([field, value]) => [field, { equalTo: value }])
67
- );
68
- }
69
- function sheetsIdentifierCacheKey(table, identifier) {
70
- const resolution = resolveSheetsIdentifier(table, identifier);
71
- if (resolution.status !== "identified") return null;
72
- return typeof resolution.identifier === "object" ? resolution.key : resolution.identifier;
73
- }
74
- function sheetsRowKey(table, row, index) {
75
- const resolution = resolveSheetsRowIdentity(table, row);
76
- if (resolution.status === "identified") {
77
- return typeof resolution.identifier === "object" ? resolution.key : String(resolution.identifier);
78
- }
79
- return `${table.schemaName ?? ""}:${table.name}:row:${index}`;
80
- }
81
- function getSheetsWriteCapability(table) {
82
- return table ? assessTableWriteCapability(table) : null;
83
- }
84
- function canRunSheetsMutation(capability, operation) {
85
- if (!capability || capability.status !== "mutable") return false;
86
- return capability.operations[operation];
87
- }
88
- function assertSheetsMutationAllowed(table, operation) {
89
- const capability = assessTableWriteCapability(table);
90
- if (capability.status === "read-only") {
91
- throw new Error(`Table '${table.name}' is read-only because it has no primary key.`);
92
- }
93
- if (!capability.operations[operation]) {
94
- const article = operation === "update" ? "an" : "a";
95
- throw new Error(`Table '${table.name}' does not expose ${article} ${operation} mutation.`);
96
- }
97
- }
98
-
99
- // src/hooks/use-sheets-table.ts
100
- import { useMemo } from "react";
101
- import { useMutation, useQuery as useQuery2, useQueryClient } from "@tanstack/react-query";
102
-
103
- // src/hooks/use-sheets-meta.ts
104
- import { useQuery } from "@tanstack/react-query";
105
-
106
- // src/adapter/postgraphile-adapter.ts
107
- import {
108
- META_CONTRACT_INTROSPECTION_DOCUMENT,
109
- META_DOCUMENT,
110
- SCHEMA_INTROSPECTION_QUERY,
111
- analyzeSchemaIntrospectionCompatibility,
112
- assertMetaContract,
113
- assertMetaQuery,
114
- buildPostGraphileCreate,
115
- buildPostGraphileDelete,
116
- buildPostGraphileUpdate,
117
- buildSelect,
118
- createError,
119
- normalizeSchemaEnumInputValues,
120
- prepareCreateInput,
121
- prepareUpdateInput,
122
- toCamelCasePlural,
123
- toCamelCaseSingular,
124
- toCreateMutationName,
125
- toPatchFieldName,
126
- toUpdateMutationName
127
- } from "@constructive-io/data";
128
- var compatibilityChecks = /* @__PURE__ */ new WeakMap();
129
- var enumMappings = /* @__PURE__ */ new WeakMap();
130
- async function ensureCurrentMetaContract(execute) {
131
- const cached = compatibilityChecks.get(execute);
132
- if (cached) return cached;
133
- const check = execute(META_CONTRACT_INTROSPECTION_DOCUMENT).then(
134
- (result) => {
135
- assertMetaContract(result);
136
- }
137
- );
138
- compatibilityChecks.set(execute, check);
139
- try {
140
- await check;
141
- } catch (error) {
142
- if (compatibilityChecks.get(execute) === check) compatibilityChecks.delete(execute);
143
- throw error;
144
- }
145
- }
146
- function hasDeclaredEnums(meta) {
147
- return Boolean(meta._meta?.tables?.some(
148
- (table) => table?.fields?.some((field) => Boolean(field?.enumValues?.name))
149
- ));
150
- }
151
- function schemaCompatibilityError(missingPaths) {
152
- const detail = missingPaths.length > 0 ? ` Missing: ${missingPaths.join(", ")}.` : "";
153
- return createError.graphql(
154
- `The GraphQL schema does not match the enum values declared by Constructive _meta.${detail}`,
155
- "SCHEMA_INTROSPECTION_INCOMPATIBLE"
156
- );
157
- }
158
- function normalizeMutationEnums(ctx, input, execute) {
159
- const hasEnumInput = ctx.table.fields.some(
160
- (field) => Boolean(field.enumValues?.length) && Object.prototype.hasOwnProperty.call(input, field.name)
161
- );
162
- if (!hasEnumInput) return input;
163
- const mappings = enumMappings.get(execute);
164
- if (!mappings) {
165
- throw createError.graphql(
166
- "Enum schema mappings are unavailable. Load table metadata before mutating enum fields.",
167
- "ENUM_MAPPING_UNAVAILABLE"
168
- );
169
- }
170
- return normalizeSchemaEnumInputValues(input, ctx.table, mappings);
171
- }
172
- function createPostGraphileAdapter() {
173
- return {
174
- async fetchMeta(execute) {
175
- await ensureCurrentMetaContract(execute);
176
- const meta = await execute(META_DOCUMENT);
177
- assertMetaQuery(meta);
178
- if (!hasDeclaredEnums(meta)) {
179
- enumMappings.set(execute, []);
180
- return meta;
181
- }
182
- try {
183
- const introspection = await execute(SCHEMA_INTROSPECTION_QUERY);
184
- const analysis = analyzeSchemaIntrospectionCompatibility(introspection, meta);
185
- if (analysis.status !== "compatible") {
186
- throw schemaCompatibilityError(analysis.missingPaths);
187
- }
188
- enumMappings.set(execute, analysis.enumMappings);
189
- } catch (error) {
190
- enumMappings.delete(execute);
191
- throw error;
192
- }
193
- return meta;
194
- },
195
- async listRows(ctx, query, execute) {
196
- const { table, allTables, tableName } = ctx;
197
- const { relationFieldMap, ...queryOptions } = query;
198
- const variables = transformToPostGraphileVariables(table, queryOptions);
199
- const doc = buildSelect(table, allTables, {
200
- ...queryOptions,
201
- relationFieldMap
202
- });
203
- const result = await execute(doc, variables);
204
- const queryTableName = toCamelCasePlural(tableName, table);
205
- const connection = result[queryTableName];
206
- if (connection && typeof connection === "object" && "nodes" in connection) {
207
- const nodes = connection.nodes || [];
208
- return {
209
- rows: transformRelationData(nodes, table),
210
- totalCount: connection.totalCount ?? 0,
211
- pageInfo: connection.pageInfo
212
- };
213
- }
214
- const directData = connection || [];
215
- return {
216
- rows: transformRelationData(directData, table),
217
- totalCount: directData.length
218
- };
219
- },
220
- async createRow(ctx, data, execute, options = {}) {
221
- const { table, allTables, tableName } = ctx;
222
- const doc = buildPostGraphileCreate(table, allTables, {
223
- ...options,
224
- fieldSelection: options.fieldSelection || "display"
225
- });
226
- const singularName = toCamelCaseSingular(tableName, table);
227
- const sanitizedData = normalizeMutationEnums(
228
- ctx,
229
- prepareCreateInput(data),
230
- execute
231
- );
232
- const variables = {
233
- input: {
234
- [singularName]: sanitizedData
235
- }
236
- };
237
- const result = await execute(doc, variables);
238
- const mutationName = toCreateMutationName(tableName, table);
239
- const createdRow = result[mutationName]?.[singularName] ?? null;
240
- return createdRow;
241
- },
242
- async updateRow(ctx, id, patch, execute, options = {}) {
243
- const { table, allTables, tableName } = ctx;
244
- const doc = buildPostGraphileUpdate(table, allTables, {
245
- ...options,
246
- fieldSelection: options.fieldSelection || "display"
247
- });
248
- const patchFieldName = toPatchFieldName(tableName, table);
249
- const sanitizedPatch = prepareUpdateInput(patch);
250
- if (Object.keys(sanitizedPatch).length === 0) return null;
251
- const normalizedPatch = normalizeMutationEnums(ctx, sanitizedPatch, execute);
252
- const variables = {
253
- input: {
254
- ...typeof id === "object" ? id : { id },
255
- [patchFieldName]: normalizedPatch
256
- }
257
- };
258
- const result = await execute(doc, variables);
259
- const mutationName = toUpdateMutationName(tableName, table);
260
- const singularName = toCamelCaseSingular(tableName, table);
261
- const updatedRow = result[mutationName]?.[singularName] ?? null;
262
- return updatedRow;
263
- },
264
- async deleteRow(ctx, id, execute, options = {}) {
265
- const { table, allTables } = ctx;
266
- const doc = buildPostGraphileDelete(table, allTables, options);
267
- const variables = {
268
- input: typeof id === "object" ? id : { id }
269
- };
270
- await execute(doc, variables);
271
- }
272
- };
273
- }
274
-
275
- // src/adapter/use-sheets-adapter.ts
276
- var defaultAdapter = createPostGraphileAdapter();
277
- function useSheetsAdapter() {
278
- const { config } = useSheetsContext();
279
- return config.adapter ?? defaultAdapter;
280
- }
281
-
282
- // src/hooks/use-sheets-meta.ts
283
- var metaKey = (scope) => sheetsQueryKeys.meta(scope);
284
- function useSheetsMeta(options = {}) {
285
- const { enabled = true } = options;
286
- const { execute, scopeKey } = useSheetsContext();
287
- const adapter = useSheetsAdapter();
288
- return useQuery({
289
- queryKey: metaKey(scopeKey),
290
- queryFn: () => adapter.fetchMeta(execute),
291
- staleTime: 5 * 60 * 1e3,
292
- // 5 min - finite so invalidation + remount triggers refetch
293
- gcTime: 30 * 60 * 1e3,
294
- // 30 min - survive long schema-editing sessions
295
- refetchOnMount: true,
296
- // Respect staleTime and refetch stale metadata on mount
297
- enabled
298
- });
299
- }
300
-
301
- // src/hooks/use-sheets-table.ts
302
- import { cleanTable } from "@constructive-io/data";
303
- import { createError as createError2 } from "@constructive-io/data";
304
- import {
305
- buildSelect as buildSelect2,
306
- toCamelCasePlural as toCamelCasePlural2,
307
- toCamelCaseSingular as toCamelCaseSingular2,
308
- toOrderByEnumValue
309
- } from "@constructive-io/data";
310
-
311
- // src/hooks/relation-field-resolution.ts
312
- import { toCamelCase, toPascalCase, pluralize, singularize } from "inflekt";
313
- import { TypedDocumentString } from "@constructive-io/data";
314
- var TypeFieldsDoc = new TypedDocumentString(`
315
- query TypeFields($typeName: String!) {
316
- __type(name: $typeName) {
317
- fields {
318
- name
319
- }
320
- }
321
- }
322
- `);
323
- async function resolveRelationFieldMap({
324
- table,
325
- fieldSelection,
326
- scopeKey,
327
- queryClient,
328
- execute
329
- }) {
330
- const requestedRelationFields = getRequestedRelationFields(fieldSelection);
331
- if (requestedRelationFields.length === 0) {
332
- return {};
333
- }
334
- const relations = collectRelationDescriptors(table);
335
- if (relations.length === 0) {
336
- return {};
337
- }
338
- const relationByFieldName = new Map(relations.map((relation) => [relation.fieldName, relation]));
339
- const relationFieldsSet = new Set(relations.map((relation) => relation.fieldName));
340
- const candidateFields = requestedRelationFields.filter((fieldName) => relationFieldsSet.has(fieldName));
341
- if (candidateFields.length === 0) {
342
- return {};
343
- }
344
- const availableFields = await getTypeFieldSet(table, scopeKey, queryClient, execute);
345
- const relationFieldMap = {};
346
- if (!availableFields || availableFields.size === 0) {
347
- candidateFields.forEach((fieldName) => {
348
- if (fieldName.includes("ByMy")) {
349
- relationFieldMap[fieldName] = fieldName.replace("ByMy", "By");
350
- }
351
- });
352
- return relationFieldMap;
353
- }
354
- candidateFields.forEach((fieldName) => {
355
- if (availableFields.has(fieldName)) {
356
- return;
357
- }
358
- const relation = relationByFieldName.get(fieldName);
359
- const candidates = buildRelationFieldCandidates(fieldName, relation);
360
- const match = candidates.find((candidate) => availableFields.has(candidate));
361
- relationFieldMap[fieldName] = match ?? null;
362
- });
363
- return relationFieldMap;
364
- }
365
- function getRequestedRelationFields(fieldSelection) {
366
- if (!fieldSelection || typeof fieldSelection === "string") {
367
- return [];
368
- }
369
- const requested = /* @__PURE__ */ new Set();
370
- const selection = fieldSelection;
371
- (selection.includeRelations ?? []).forEach((fieldName) => requested.add(fieldName));
372
- if (selection.include) {
373
- Object.entries(selection.include).forEach(([fieldName, value]) => {
374
- if (value) {
375
- requested.add(fieldName);
376
- }
377
- });
378
- }
379
- return Array.from(requested);
380
- }
381
- function collectRelationDescriptors(table) {
382
- const descriptors = [];
383
- table.relations.belongsTo.forEach((relation) => {
384
- if (!relation.fieldName) return;
385
- descriptors.push({
386
- fieldName: relation.fieldName,
387
- kind: "belongsTo",
388
- referencedTableName: relation.referencesTable || void 0,
389
- keyNames: relation.keys.map((key) => key.name).filter(Boolean)
390
- });
391
- });
392
- table.relations.hasOne.forEach((relation) => {
393
- if (!relation.fieldName) return;
394
- descriptors.push({
395
- fieldName: relation.fieldName,
396
- kind: "hasOne",
397
- referencedTableName: relation.referencedByTable || void 0,
398
- keyNames: relation.keys.map((key) => key.name).filter(Boolean)
399
- });
400
- });
401
- table.relations.hasMany.forEach((relation) => {
402
- if (!relation.fieldName) return;
403
- descriptors.push({
404
- fieldName: relation.fieldName,
405
- kind: "hasMany",
406
- referencedTableName: relation.referencedByTable || void 0,
407
- keyNames: relation.keys.map((key) => key.name).filter(Boolean)
408
- });
409
- });
410
- table.relations.manyToMany.forEach((relation) => {
411
- if (!relation.fieldName) return;
412
- descriptors.push({
413
- fieldName: relation.fieldName,
414
- kind: "manyToMany",
415
- referencedTableName: relation.rightTable || void 0,
416
- keyNames: []
417
- });
418
- });
419
- return descriptors;
420
- }
421
- function buildRelationFieldCandidates(fieldName, relation) {
422
- const candidates = /* @__PURE__ */ new Set();
423
- const add = (value) => {
424
- if (!value) return;
425
- candidates.add(value);
426
- };
427
- add(fieldName);
428
- add(fieldName.replace(/ByMy([A-Z])/g, "By$1"));
429
- add(fieldName.replace(/My([A-Z])/g, "$1"));
430
- const byMatch = /^(.*)By(.+)$/.exec(fieldName);
431
- if (byMatch) {
432
- const [, prefixRaw, suffixRaw] = byMatch;
433
- const cleanedSuffix = suffixRaw.replace(/^My/, "");
434
- const prefixSingular = singularize(prefixRaw);
435
- const prefixPlural = pluralize(prefixSingular);
436
- add(`${prefixRaw}By${cleanedSuffix}`);
437
- add(`${prefixSingular}By${cleanedSuffix}`);
438
- add(`${prefixPlural}By${cleanedSuffix}`);
439
- }
440
- if (!relation) {
441
- return Array.from(candidates);
442
- }
443
- const firstKey = relation.keyNames[0];
444
- const keyPascalCase = firstKey ? toPascalCase(firstKey) : null;
445
- const relationTable = relation.referencedTableName;
446
- if (relationTable) {
447
- const singularRef = toCamelCase(relationTable);
448
- const pluralRef = pluralize(singularRef);
449
- add(singularRef);
450
- add(pluralRef);
451
- if (keyPascalCase) {
452
- add(`${singularRef}By${keyPascalCase}`);
453
- add(`${pluralRef}By${keyPascalCase}`);
454
- }
455
- }
456
- if (relation.kind === "hasMany" || relation.kind === "manyToMany") {
457
- const fieldPrefix = fieldName.split("By")[0];
458
- add(pluralize(singularize(fieldPrefix)));
459
- }
460
- return Array.from(candidates);
461
- }
462
- async function getTypeFieldSet(table, scopeKey, queryClient, execute) {
463
- const typeNames = [table.inflection?.tableType, table.name].filter((candidate) => typeof candidate === "string" && candidate.trim().length > 0).filter((candidate, index, values) => values.indexOf(candidate) === index);
464
- for (const typeName of typeNames) {
465
- const fields = await queryClient.fetchQuery({
466
- queryKey: sheetsQueryKeys.typeFields(scopeKey, typeName),
467
- queryFn: async () => {
468
- const response = await execute(TypeFieldsDoc, { typeName });
469
- return (response.__type?.fields ?? []).map((field) => field?.name).filter((name) => typeof name === "string" && name.length > 0);
470
- },
471
- staleTime: 5 * 60 * 1e3,
472
- gcTime: 30 * 60 * 1e3
473
- });
474
- if (fields.length > 0) {
475
- return new Set(fields);
476
- }
477
- }
478
- return null;
479
- }
480
-
481
- // src/hooks/orderby-enum-resolution.ts
482
- import { TypedDocumentString as TypedDocumentString2 } from "@constructive-io/data";
483
- var EnumValuesDoc = new TypedDocumentString2(`
484
- query EnumValues($typeName: String!) {
485
- __type(name: $typeName) {
486
- enumValues {
487
- name
488
- }
489
- }
490
- }
491
- `);
492
- async function getOrderByEnumValues(orderByTypeName, scopeKey, queryClient, execute) {
493
- const values = await queryClient.fetchQuery({
494
- queryKey: sheetsQueryKeys.enumValues(scopeKey, orderByTypeName),
495
- queryFn: async () => {
496
- const response = await execute(EnumValuesDoc, { typeName: orderByTypeName });
497
- const names = (response.__type?.enumValues ?? []).map((v) => v?.name).filter((name) => typeof name === "string" && name.length > 0);
498
- return new Set(names);
499
- },
500
- staleTime: 5 * 60 * 1e3,
501
- gcTime: 30 * 60 * 1e3
502
- });
503
- return values.size > 0 ? values : null;
504
- }
505
- async function validateOrderByVariables(variables, table, scopeKey, queryClient, execute) {
506
- if (!variables.orderBy || !Array.isArray(variables.orderBy) || !table.inflection?.orderByType) {
507
- return;
508
- }
509
- const validValues = await getOrderByEnumValues(table.inflection.orderByType, scopeKey, queryClient, execute);
510
- if (!validValues) return;
511
- variables.orderBy = variables.orderBy.filter((v) => validValues.has(v));
512
- if (variables.orderBy.length === 0) {
513
- delete variables.orderBy;
514
- }
515
- }
516
-
517
- // src/hooks/use-sheets-table.ts
518
- function transformRelationData(data, table) {
519
- if (!data) return [];
520
- if (!Array.isArray(data)) return data;
521
- const transformed = data.map((row) => {
522
- if (!row || typeof row !== "object") return row;
523
- const transformedRow = { ...row };
524
- const hasManyRelations = table.relations.hasMany || [];
525
- const manyToManyRelations = table.relations.manyToMany || [];
526
- const connectionRelations = [...hasManyRelations, ...manyToManyRelations];
527
- connectionRelations.forEach((relation) => {
528
- const fieldName = relation.fieldName;
529
- if (!fieldName || !(fieldName in transformedRow)) return;
530
- const relationValue = transformedRow[fieldName];
531
- if (relationValue && typeof relationValue === "object" && "nodes" in relationValue) {
532
- const connectionData = relationValue;
533
- transformedRow[fieldName] = connectionData.nodes || [];
534
- }
535
- });
536
- return transformedRow;
537
- });
538
- return transformed;
539
- }
540
- var sheetsTableQueryKeys = {
541
- scope: (scope) => sheetsQueryKeys.scope(scope),
542
- table: (scope, tableName) => sheetsQueryKeys.table(scope, tableName),
543
- tableRows: (scope, tableName, options) => sheetsQueryKeys.tableRows(scope, tableName, options),
544
- tableRow: (scope, tableName, id) => sheetsQueryKeys.tableRow(scope, tableName, id),
545
- tableCount: (scope, tableName, where) => sheetsQueryKeys.tableCount(scope, tableName, where)
546
- };
547
- var sheetsTableMutationKeys = {
548
- create: (scope, tableName) => [...sheetsTableQueryKeys.table(scope, tableName), "mutation", "create"],
549
- update: (scope, tableName) => [...sheetsTableQueryKeys.table(scope, tableName), "mutation", "update"],
550
- delete: (scope, tableName) => [...sheetsTableQueryKeys.table(scope, tableName), "mutation", "delete"]
551
- };
552
- function transformToPostGraphileVariables(table, options = {}) {
553
- const variables = {};
554
- const limitValue = options.limit ?? options.first;
555
- if (limitValue !== void 0) {
556
- variables.first = limitValue;
557
- }
558
- if (options.offset !== void 0) {
559
- variables.offset = options.offset;
560
- }
561
- if (options.after !== void 0) {
562
- variables.after = options.after;
563
- }
564
- if (options.before !== void 0) {
565
- variables.before = options.before;
566
- }
567
- if (options.orderBy && options.orderBy.length > 0) {
568
- const availableFields = new Set(table.fields.map((field) => field.name));
569
- variables.orderBy = options.orderBy.filter(({ field }) => availableFields.has(field)).map(({ field, direction }) => toOrderByEnumValue(field, direction));
570
- }
571
- if (options.where) {
572
- variables.where = options.where;
573
- }
574
- return variables;
575
- }
576
- function useSheetsTable(tableName, options = {}) {
577
- const queryClient = useQueryClient();
578
- const { execute, scopeKey } = useSheetsContext();
579
- const { data: meta } = useSheetsMeta();
580
- const adapter = useSheetsAdapter();
581
- const metaTables = useMemo(() => {
582
- if (!meta?._meta?.tables) return [];
583
- return meta._meta.tables.filter((candidate) => candidate != null);
584
- }, [meta]);
585
- const tables = useMemo(() => metaTables.map(cleanTable), [metaTables]);
586
- const table = useMemo(
587
- () => tables.find((candidate) => candidate.name === tableName) ?? null,
588
- [tables, tableName]
589
- );
590
- const tableMeta = useMemo(
591
- () => metaTables.find((candidate) => candidate.name === tableName) ?? null,
592
- [metaTables, tableName]
593
- );
594
- const resolveIdentifier = (identifier) => {
595
- if (!tableMeta) throw createError2.notFound(`Table '${tableName}' not found`);
596
- const resolution = resolveSheetsIdentifier(tableMeta, identifier);
597
- if (resolution.status !== "identified") {
598
- throw createError2.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);
599
- }
600
- return resolution.identifier;
601
- };
602
- const rowCacheKey = (row) => {
603
- if (!tableMeta || !row) return null;
604
- const resolution = resolveSheetsRowIdentity(tableMeta, row);
605
- if (resolution.status !== "identified") return null;
606
- return typeof resolution.identifier === "object" ? resolution.key : resolution.identifier;
607
- };
608
- const { enabled = true, select: fieldSelection, mutationOptions = {}, ...queryOptions } = options;
609
- const finalQueryOptions = {
610
- ...queryOptions,
611
- fieldSelection
612
- };
613
- const {
614
- data,
615
- isLoading,
616
- error,
617
- refetch
618
- } = useQuery2({
619
- queryKey: sheetsTableQueryKeys.tableRows(scopeKey, tableName, finalQueryOptions),
620
- queryFn: async () => {
621
- if (!table) {
622
- throw createError2.notFound(`Table '${tableName}' not found`);
623
- }
624
- const variables = transformToPostGraphileVariables(table, finalQueryOptions);
625
- const [relationFieldMap] = await Promise.all([
626
- resolveRelationFieldMap({
627
- table,
628
- fieldSelection: finalQueryOptions.fieldSelection,
629
- scopeKey,
630
- queryClient,
631
- execute
632
- }),
633
- validateOrderByVariables(variables, table, scopeKey, queryClient, execute)
634
- ]);
635
- const validatedOrderByEnum = new Set(variables.orderBy ?? []);
636
- const availableOrderByFields = new Set(table.fields.map((field) => field.name));
637
- const validatedOrderBy = finalQueryOptions.orderBy?.filter(
638
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has(toOrderByEnumValue(field, direction))
639
- );
640
- const { rows, totalCount: totalCount2 } = await adapter.listRows(
641
- { table, allTables: tables, tableName },
642
- {
643
- ...finalQueryOptions,
644
- orderBy: validatedOrderBy,
645
- // resolveRelationFieldMap yields `string | null` (null = omit field). The
646
- // contract narrows to `string`, but the null values are passed through to
647
- // buildSelect unchanged at runtime — behavior is identical to before.
648
- relationFieldMap
649
- },
650
- execute
651
- );
652
- return { rows, totalCount: totalCount2 };
653
- },
654
- enabled: enabled && !!table,
655
- placeholderData: (previousData, previousQuery) => reuseSheetsPlaceholderData(previousData, previousQuery?.queryKey, scopeKey),
656
- staleTime: 5 * 60 * 1e3
657
- // 5 minutes
658
- });
659
- const rowsData = data?.rows ?? [];
660
- const totalCount = data?.totalCount ?? 0;
661
- const createMutation = useMutation({
662
- mutationKey: sheetsTableMutationKeys.create(scopeKey, tableName),
663
- mutationFn: async (data2) => {
664
- if (!table || !tableMeta) {
665
- throw createError2.notFound(`Table '${tableName}' not found`);
666
- }
667
- assertSheetsMutationAllowed(tableMeta, "create");
668
- const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(cleanTable) : [];
669
- const createdRow = await adapter.createRow({ table, allTables, tableName }, data2, execute, {
670
- ...mutationOptions,
671
- fieldSelection: mutationOptions.fieldSelection || fieldSelection || "display"
672
- });
673
- return { createdRow, __rawResult: {} };
674
- },
675
- onSuccess: ({ createdRow }) => {
676
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
677
- queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });
678
- const createdRowKey = rowCacheKey(createdRow);
679
- if (createdRowKey !== null) {
680
- queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, createdRowKey), createdRow);
681
- }
682
- }
683
- });
684
- const updateMutation = useMutation({
685
- mutationKey: sheetsTableMutationKeys.update(scopeKey, tableName),
686
- mutationFn: async ({ id, patch }) => {
687
- if (!table || !tableMeta) {
688
- throw createError2.notFound(`Table '${tableName}' not found`);
689
- }
690
- assertSheetsMutationAllowed(tableMeta, "update");
691
- const mutationIdentifier = resolveIdentifier(id);
692
- const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(cleanTable) : [];
693
- const updatedRow = await adapter.updateRow({ table, allTables, tableName }, mutationIdentifier, patch, execute, {
694
- ...mutationOptions,
695
- fieldSelection: mutationOptions.fieldSelection || fieldSelection || "display"
696
- });
697
- return { updatedRow, __rawResult: {} };
698
- },
699
- // Optimistic patch: an inline cell edit must show the new value instantly,
700
- // not after the server round-trip + the onSuccess refetch round-trip. The
701
- // active rows cache is `{ rows, totalCount }` keyed by `tableRows(...options)`;
702
- // patch every cached `tableRows` variant that holds the row (the active query
703
- // key embeds `finalQueryOptions`, but other option permutations may be cached
704
- // too), matching the row by its scalar `id`.
705
- onMutate: async ({ id, patch }) => {
706
- const tablePrefix = sheetsTableQueryKeys.table(scopeKey, tableName);
707
- await queryClient.cancelQueries({ queryKey: tablePrefix });
708
- const targetKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, id) : null;
709
- const isRowsKey = (key) => key[key.length - 2] === "rows";
710
- const previousRows = queryClient.getQueriesData({ queryKey: tablePrefix }).filter(([key]) => isRowsKey(key));
711
- for (const [key] of previousRows) {
712
- queryClient.setQueryData(key, (old) => {
713
- if (!old) return old;
714
- let changed = false;
715
- const rows = old.rows.map((row) => {
716
- if (targetKey !== null && rowCacheKey(row) === targetKey) {
717
- changed = true;
718
- return { ...row, ...patch };
719
- }
720
- return row;
721
- });
722
- return changed ? { ...old, rows } : old;
723
- });
724
- }
725
- return { previousRows };
726
- },
727
- onError: (_err, _vars, ctx) => {
728
- ctx?.previousRows.forEach(([key, data2]) => queryClient.setQueryData(key, data2));
729
- },
730
- onSuccess: ({ updatedRow }) => {
731
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
732
- const updatedRowKey = rowCacheKey(updatedRow);
733
- if (updatedRowKey !== null) {
734
- queryClient.setQueryData(sheetsTableQueryKeys.tableRow(scopeKey, tableName, updatedRowKey), updatedRow);
735
- }
736
- }
737
- });
738
- const deleteMutation = useMutation({
739
- mutationKey: sheetsTableMutationKeys.delete(scopeKey, tableName),
740
- mutationFn: async (idOrPk) => {
741
- if (!table || !tableMeta) {
742
- throw createError2.notFound(`Table '${tableName}' not found`);
743
- }
744
- assertSheetsMutationAllowed(tableMeta, "delete");
745
- const mutationIdentifier = resolveIdentifier(idOrPk);
746
- const allTables = meta?._meta?.tables ? meta._meta.tables.filter((t) => t != null).map(cleanTable) : [];
747
- await adapter.deleteRow({ table, allTables, tableName }, mutationIdentifier, execute, mutationOptions);
748
- return { deletedId: idOrPk, __rawResult: {} };
749
- },
750
- onSuccess: ({ deletedId }) => {
751
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
752
- queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.infiniteTable(scopeKey, tableName) });
753
- const deletedRowKey = tableMeta ? sheetsIdentifierCacheKey(tableMeta, deletedId) : null;
754
- if (deletedRowKey !== null) {
755
- queryClient.removeQueries({
756
- queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableName, deletedRowKey)
757
- });
758
- }
759
- }
760
- });
761
- const findOne = async (id) => {
762
- if (!table || !tableMeta) {
763
- throw createError2.notFound(`Table '${tableName}' not found`);
764
- }
765
- const where = sheetsIdentifierToWhere(tableMeta, id);
766
- if (!where) {
767
- throw createError2.badRequest(`Cannot resolve a primary-key identity for table '${tableName}'.`);
768
- }
769
- const doc = buildSelect2(table, tables, {
770
- where,
771
- limit: 1
772
- });
773
- const variables = transformToPostGraphileVariables(table, {
774
- where,
775
- limit: 1
776
- });
777
- const result = await execute(doc, variables);
778
- const singularName = toCamelCaseSingular2(tableName, table);
779
- const singularData = result[singularName];
780
- if (singularData && typeof singularData === "object") {
781
- return singularData;
782
- }
783
- const queryTableName = toCamelCasePlural2(tableName, table);
784
- const data2 = result[queryTableName];
785
- if (data2 && typeof data2 === "object" && "nodes" in data2) {
786
- const nodes = data2.nodes || [];
787
- const transformedNodes = transformRelationData(nodes, table);
788
- return transformedNodes[0] || null;
789
- }
790
- const rows = result[tableName] || [];
791
- const transformedRows = transformRelationData(rows, table);
792
- return transformedRows[0] || null;
793
- };
794
- const invalidate = () => {
795
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) });
796
- };
797
- return {
798
- // Data
799
- data: rowsData,
800
- totalCount,
801
- isLoading,
802
- error,
803
- // Single row operations
804
- findOne,
805
- // Mutations
806
- create: (data2) => createMutation.mutateAsync(data2),
807
- update: (id, patch) => updateMutation.mutateAsync({ id, patch }),
808
- delete: (id) => deleteMutation.mutateAsync(id),
809
- // Mutation states
810
- isCreating: createMutation.isPending,
811
- isUpdating: updateMutation.isPending,
812
- isDeleting: deleteMutation.isPending,
813
- // Mutation errors
814
- createError: createMutation.error,
815
- updateError: updateMutation.error,
816
- deleteError: deleteMutation.error,
817
- // Utilities
818
- refetch,
819
- invalidate
820
- };
821
- }
822
-
823
- // src/cell-model/factories/badges.ts
824
- function parseTsvectorForPreview(tsvector) {
825
- if (!tsvector || typeof tsvector !== "string") return [];
826
- const results = [];
827
- try {
828
- const regex = /'([^']+)':([0-9A-D,]+)/g;
829
- let match;
830
- while ((match = regex.exec(tsvector)) !== null) {
831
- const lexeme = match[1];
832
- const posStr = match[2];
833
- const weights = Array.from(
834
- new Set(
835
- posStr.split(",").map((p) => p.match(/[A-D]$/)?.[0]).filter((w) => !!w)
836
- )
837
- ).sort();
838
- results.push({ lexeme, weights });
839
- }
840
- } catch {
841
- }
842
- return results;
843
- }
844
- function deriveBadges(value, metadata) {
845
- if (value === null || value === void 0) {
846
- return [];
847
- }
848
- if (metadata.cellType === "tags") {
849
- if (Array.isArray(value)) {
850
- return value.map((v) => v == null ? "" : String(v)).filter((v) => v.length > 0);
851
- }
852
- if (typeof value === "string") {
853
- return value.split(",").map((v) => v.trim()).filter((v) => v.length > 0);
854
- }
855
- }
856
- if (metadata.cellType === "tsvector" && typeof value === "string") {
857
- const tokens = parseTsvectorForPreview(value);
858
- return tokens.map((t) => t.weights.length ? `${t.lexeme} ${t.weights.join(",")}` : t.lexeme);
859
- }
860
- if (Array.isArray(value)) {
861
- return value.map((item) => {
862
- if (item === null || item === void 0) return "";
863
- if (typeof item === "string") return item;
864
- if (typeof item === "number") return String(item);
865
- if (typeof item === "boolean") return String(item);
866
- if (item instanceof Date) return item.toISOString().split("T")[0];
867
- if (typeof item === "object") return JSON.stringify(item);
868
- return String(item);
869
- });
870
- }
871
- return [String(value)];
872
- }
873
- var badgesSheetsCellFactory = {
874
- canHandle(cellType, _value) {
875
- return isArrayCellType(cellType) || cellType === "tsvector";
876
- },
877
- create(value, metadata) {
878
- return {
879
- kind: "badges",
880
- data: deriveBadges(value, metadata),
881
- displayData: "",
882
- readonly: false,
883
- meta: { cellType: metadata.cellType }
884
- };
885
- }
886
- };
887
-
888
- // src/cell-model/factories/boolean.ts
889
- function canHandle(cellType, _value) {
890
- return BOOLEAN_TYPES.has(cellType);
891
- }
892
- function create(value, _metadata) {
893
- const boolValue = value === null || value === void 0 ? false : typeof value === "boolean" ? value : Boolean(value);
894
- return { kind: "boolean", data: boolValue, displayData: "", readonly: false };
895
- }
896
- var booleanSheetsCellFactory = { canHandle, create };
897
-
898
- // src/cell-model/factories/datetime.ts
899
- function canHandle2(cellType, _value) {
900
- return DATE_TIME_TYPES.has(cellType);
901
- }
902
- function create2(value, metadata) {
903
- const meta = { cellType: metadata.cellType };
904
- if (value === null || value === void 0) {
905
- return { kind: "text", data: "", displayData: "", readonly: false, meta };
906
- }
907
- const text = String(value);
908
- return { kind: "text", data: text, displayData: text, readonly: false, meta };
909
- }
910
- var dateTimeSheetsCellFactory = { canHandle: canHandle2, create: create2 };
911
-
912
- // src/grid/sheets.formatters.ts
913
- function compactJsonPreview(value, maxLen = 80) {
914
- try {
915
- const s = typeof value === "string" ? value : JSON.stringify(value);
916
- if (s.length <= maxLen) return s;
917
- return s.slice(0, maxLen - 1) + "\u2026";
918
- } catch {
919
- const s = String(value);
920
- return s.length > maxLen ? s.slice(0, maxLen - 1) + "\u2026" : s;
921
- }
922
- }
923
-
924
- // src/cell-model/factories/geometry.ts
925
- function canHandle3(cellType, _value) {
926
- return GEOMETRY_TYPES.has(cellType);
927
- }
928
- function create3(value, _metadata, deriveGeometry) {
929
- if (deriveGeometry) {
930
- return deriveGeometry(value ?? null);
931
- }
932
- const display = compactJsonPreview(value, 80);
933
- return {
934
- kind: "geometry",
935
- data: display,
936
- displayData: display,
937
- readonly: false
938
- };
939
- }
940
- var geometrySheetsCellFactory = { canHandle: canHandle3, create: create3 };
941
-
942
- // src/cell-model/factories/image.ts
943
- function resolveMediaUrl(value) {
944
- if (typeof value === "string") return value;
945
- if (typeof value === "object" && value) {
946
- const obj = value;
947
- return obj.url || obj.src || obj.href || obj.path || "";
948
- }
949
- return "";
950
- }
951
- var imageSheetsCellFactory = {
952
- canHandle(cellType) {
953
- return MEDIA_TYPES.has(cellType);
954
- },
955
- create(value, metadata) {
956
- const url = value === null || value === void 0 || value === "" ? "" : resolveMediaUrl(value);
957
- const data = [url];
958
- return {
959
- kind: "image",
960
- data,
961
- displayData: JSON.stringify(data),
962
- readonly: false,
963
- meta: { cellType: metadata.cellType }
964
- };
965
- }
966
- };
967
-
968
- // src/cell-model/factories/interval.ts
969
- function formatIntervalForDisplay(value) {
970
- if (value === null || value === void 0) return "";
971
- let interval;
972
- if (typeof value === "string") {
973
- try {
974
- interval = JSON.parse(value);
975
- } catch {
976
- if (/\d+[yMwdhms]/.test(value)) {
977
- return value;
978
- }
979
- return value;
980
- }
981
- } else if (typeof value === "object") {
982
- interval = value;
983
- } else {
984
- return String(value);
985
- }
986
- const parts = [];
987
- if (interval.years && interval.years !== 0) {
988
- parts.push(`${interval.years}y`);
989
- }
990
- if (interval.months && interval.months !== 0) {
991
- parts.push(`${interval.months}mo`);
992
- }
993
- if (interval.days && interval.days !== 0) {
994
- parts.push(`${interval.days}d`);
995
- }
996
- if (interval.hours && interval.hours !== 0) {
997
- parts.push(`${interval.hours}h`);
998
- }
999
- if (interval.minutes && interval.minutes !== 0) {
1000
- parts.push(`${interval.minutes}m`);
1001
- }
1002
- if (interval.seconds && interval.seconds !== 0) {
1003
- const secs = interval.seconds;
1004
- if (Number.isInteger(secs)) {
1005
- parts.push(`${secs}s`);
1006
- } else {
1007
- parts.push(`${secs.toFixed(1)}s`);
1008
- }
1009
- }
1010
- if (parts.length === 0) {
1011
- return "0s";
1012
- }
1013
- return parts.join(" ");
1014
- }
1015
- function canHandle4(cellType, _value) {
1016
- return cellType === "interval";
1017
- }
1018
- function create4(value, metadata) {
1019
- if (value === null || value === void 0) {
1020
- return {
1021
- kind: "text",
1022
- data: "",
1023
- displayData: "",
1024
- readonly: false,
1025
- meta: { cellType: metadata.cellType }
1026
- };
1027
- }
1028
- const displayValue = formatIntervalForDisplay(value);
1029
- const dataValue = typeof value === "string" ? value : JSON.stringify(value);
1030
- return {
1031
- kind: "text",
1032
- data: dataValue,
1033
- displayData: displayValue,
1034
- readonly: false,
1035
- meta: { cellType: metadata.cellType }
1036
- };
1037
- }
1038
- var intervalSheetsCellFactory = { canHandle: canHandle4, create: create4 };
1039
-
1040
- // src/cell-model/factories/number.ts
1041
- function canHandle5(cellType, _value) {
1042
- return NUMBER_TYPES.has(cellType);
1043
- }
1044
- function create5(value, _metadata) {
1045
- if (value === null || value === void 0) {
1046
- return { kind: "number", data: void 0, displayData: "", readonly: false };
1047
- }
1048
- const numValue = typeof value === "number" ? value : parseFloat(value);
1049
- if (isNaN(numValue)) {
1050
- return { kind: "number", data: void 0, displayData: "", readonly: false };
1051
- }
1052
- return { kind: "number", data: numValue, displayData: String(numValue), readonly: false };
1053
- }
1054
- var numberSheetsCellFactory = { canHandle: canHandle5, create: create5 };
1055
-
1056
- // src/cell-model/factories/relation.ts
1057
- var DEFAULT_MAX_RELATION_CHIPS = 3;
1058
- var DEFAULT_RELATION_LABEL_MAX_LEN = 24;
1059
- var RELATION_ID_KEYS = /* @__PURE__ */ new Set(["id", "uuid", "rowId", "nodeId"]);
1060
- function truncateLabel(s, max) {
1061
- if (s.length <= max) return s;
1062
- if (max <= 1) return "\u2026";
1063
- return s.slice(0, Math.max(0, max - 1)) + "\u2026";
1064
- }
1065
- function deriveRelationLabel(relationValue, metadata, maxLength) {
1066
- if (relationValue == null) return "";
1067
- if (typeof relationValue === "string" && relationValue.startsWith("draft:")) return "";
1068
- if (typeof relationValue === "object" && !Array.isArray(relationValue) && typeof relationValue.id === "string" && relationValue.id.startsWith("draft:"))
1069
- return "";
1070
- const ensureString = (val) => {
1071
- if (val == null) return "";
1072
- const str = String(val).trim();
1073
- if (!str || str.toLowerCase() === "null") return "";
1074
- return str;
1075
- };
1076
- if (typeof relationValue === "string" || typeof relationValue === "number") {
1077
- return truncateLabel(ensureString(relationValue), maxLength);
1078
- }
1079
- if (Array.isArray(relationValue)) {
1080
- const labels = relationValue.map((item) => deriveRelationLabel(item, metadata, maxLength)).filter((label) => label.length > 0);
1081
- return labels.join(", ");
1082
- }
1083
- if (typeof relationValue !== "object") {
1084
- return truncateLabel(ensureString(relationValue), maxLength);
1085
- }
1086
- const relInfo = metadata.relationInfo;
1087
- const candidatesFromMeta = relInfo?.displayCandidates ?? [];
1088
- const objectValue = relationValue;
1089
- const keys = Object.keys(objectValue);
1090
- const meaningfulCandidates = candidatesFromMeta.filter((k) => !RELATION_ID_KEYS.has(k));
1091
- const heuristicKeys = Array.from(
1092
- /* @__PURE__ */ new Set([
1093
- ...meaningfulCandidates,
1094
- ...keys.filter((key) => /(name|label|title|display|email)/i.test(key)),
1095
- "displayName",
1096
- "fullName",
1097
- "name",
1098
- "title",
1099
- "label",
1100
- "description",
1101
- "username",
1102
- "email",
1103
- "code"
1104
- ])
1105
- );
1106
- for (const candidate of heuristicKeys) {
1107
- if (!candidate) continue;
1108
- const candidateValue = ensureString(objectValue[candidate]);
1109
- if (candidateValue) {
1110
- return truncateLabel(candidateValue, maxLength);
1111
- }
1112
- }
1113
- for (const idKey of ["id", "uuid"]) {
1114
- const idVal = ensureString(objectValue[idKey]);
1115
- if (idVal) {
1116
- return truncateLabel(idVal, maxLength);
1117
- }
1118
- }
1119
- const firstPrimitive = keys.map((key) => objectValue[key]).find((val) => val != null && ["string", "number", "boolean"].includes(typeof val));
1120
- if (firstPrimitive !== void 0) {
1121
- return truncateLabel(ensureString(firstPrimitive), maxLength);
1122
- }
1123
- return truncateLabel(compactJsonPreview(objectValue, 80), maxLength);
1124
- }
1125
- function canHandle6(cellType, _value) {
1126
- return cellType === "relation";
1127
- }
1128
- function create6(value, metadata, _deriveGeometry) {
1129
- const relInfo = metadata.relationInfo;
1130
- const relOptions = metadata.relationOptions;
1131
- const chipLimit = relOptions?.relationChipLimit ?? DEFAULT_MAX_RELATION_CHIPS;
1132
- const labelMax = relOptions?.relationLabelMaxLength ?? DEFAULT_RELATION_LABEL_MAX_LEN;
1133
- const isListRelation = relInfo?.kind === "hasMany" || relInfo?.kind === "manyToMany";
1134
- if (isListRelation) {
1135
- const arr = Array.isArray(value) ? value : [];
1136
- const labelsAll = arr.map((entry) => deriveRelationLabel(entry, metadata, labelMax)).filter((label2) => label2.length > 0);
1137
- const labels = labelsAll.slice(0, chipLimit);
1138
- const remaining = labelsAll.length - labels.length;
1139
- const finalData = remaining > 0 ? [...labels, `+${remaining}`] : labels;
1140
- return {
1141
- kind: "relation",
1142
- data: finalData,
1143
- displayData: "",
1144
- readonly: false
1145
- };
1146
- }
1147
- const label = deriveRelationLabel(value, metadata, labelMax);
1148
- return {
1149
- kind: "relation",
1150
- data: label,
1151
- displayData: label,
1152
- readonly: false
1153
- };
1154
- }
1155
- var relationSheetsCellFactory = { canHandle: canHandle6, create: create6 };
1156
-
1157
- // src/cell-model/factories/text.ts
1158
- function canHandle7(_cellType, _value) {
1159
- return true;
1160
- }
1161
- function create7(value, metadata) {
1162
- const meta = { cellType: metadata.cellType };
1163
- if (value === null || value === void 0) {
1164
- return { kind: "text", data: "", displayData: "", readonly: false, meta };
1165
- }
1166
- if (typeof value === "string") {
1167
- return { kind: "text", data: value, displayData: value, readonly: false, meta };
1168
- }
1169
- const display = compactJsonPreview(value, 80);
1170
- return { kind: "text", data: display, displayData: display, readonly: false, meta };
1171
- }
1172
- var textSheetsCellFactory = { canHandle: canHandle7, create: create7 };
1173
-
1174
- // src/cell-model/factories/uri.ts
1175
- function canHandle8(cellType, _value) {
1176
- return cellType === "url" || cellType === "email";
1177
- }
1178
- function create8(value, metadata) {
1179
- const cellType = metadata.cellType;
1180
- if (value === null || value === void 0 || value === "") {
1181
- return { kind: "uri", data: "", displayData: "", readonly: false, meta: { cellType } };
1182
- }
1183
- const stringValue = String(value);
1184
- const isEmail = metadata.cellType === "email";
1185
- const data = isEmail ? `mailto:${stringValue}` : stringValue;
1186
- return { kind: "uri", data, displayData: stringValue, readonly: false, meta: { cellType } };
1187
- }
1188
- var uriSheetsCellFactory = { canHandle: canHandle8, create: create8 };
1189
-
1190
- // src/cell-model/create-sheets-cell.ts
1191
- var SHEETS_CELL_FACTORIES = [
1192
- imageSheetsCellFactory,
1193
- uriSheetsCellFactory,
1194
- badgesSheetsCellFactory,
1195
- dateTimeSheetsCellFactory,
1196
- intervalSheetsCellFactory,
1197
- geometrySheetsCellFactory,
1198
- relationSheetsCellFactory,
1199
- numberSheetsCellFactory,
1200
- booleanSheetsCellFactory,
1201
- textSheetsCellFactory
1202
- // Fallback — must be last.
1203
- ];
1204
- function withTypeKey(cell, cellType) {
1205
- return { ...cell, meta: { ...cell.meta, cellType } };
1206
- }
1207
- function createSheetsCell(value, metadata, deriveGeometry) {
1208
- const { cellType } = metadata;
1209
- if (value === null || value === void 0) {
1210
- const emptyFactory = SHEETS_CELL_FACTORIES.find((f) => f.canHandle(cellType, null));
1211
- if (emptyFactory) {
1212
- return withTypeKey(emptyFactory.create(null, metadata, deriveGeometry), cellType);
1213
- }
1214
- return withTypeKey({ kind: "text", data: "", displayData: "", readonly: false }, cellType);
1215
- }
1216
- const factory = SHEETS_CELL_FACTORIES.find((f) => f.canHandle(cellType, value));
1217
- if (factory) {
1218
- return withTypeKey(factory.create(value, metadata, deriveGeometry), cellType);
1219
- }
1220
- return withTypeKey(
1221
- {
1222
- kind: "text",
1223
- data: value,
1224
- displayData: String(value),
1225
- readonly: false
1226
- },
1227
- cellType
1228
- );
1229
- }
1230
-
1231
- // src/grid/editors/overlay-viewport-guard.tsx
1232
- import React, { useLayoutEffect, useMemo as useMemo2, useRef } from "react";
1233
- import { jsx } from "react/jsx-runtime";
1234
- var OverlayMeasureContext = React.createContext({ maxHeight: 0, shouldFlip: false });
1235
- function computeOverlayGeometry(viewportHeight, targetY, targetH, marginPx, minBelowPx) {
1236
- const maxHeightPx = Math.max(0, viewportHeight - marginPx * 2);
1237
- const hasTarget = targetY != null && targetH != null;
1238
- const targetBottom = hasTarget ? targetY + targetH : 0;
1239
- const spaceBelow = viewportHeight - targetBottom - marginPx;
1240
- const shouldFlip = hasTarget && spaceBelow < minBelowPx;
1241
- const maxHeight = shouldFlip ? maxHeightPx : Math.max(0, spaceBelow);
1242
- return { shouldFlip, maxHeight, targetBottom, spaceBelow, maxHeightPx };
1243
- }
1244
- function OverlayViewportGuard({ children, debugName, marginPx = 12, minBelowPx = 320, target }) {
1245
- const ref = useRef(null);
1246
- const overlayRootRef = useRef(null);
1247
- const clipRegionRef = useRef(null);
1248
- const restoreRef = useRef(null);
1249
- const targetY = target?.y;
1250
- const targetH = target?.height;
1251
- const computed = useMemo2(() => {
1252
- const vh = typeof window !== "undefined" ? window.innerHeight : 800;
1253
- const { shouldFlip, maxHeight } = computeOverlayGeometry(vh, targetY, targetH, marginPx, minBelowPx);
1254
- return { shouldFlip, maxHeight };
1255
- }, [marginPx, minBelowPx, targetY, targetH]);
1256
- const positionRef = useRef(null);
1257
- positionRef.current = () => {
1258
- const el = ref.current;
1259
- if (!el) return;
1260
- let clipRegion = clipRegionRef.current;
1261
- if (!clipRegion?.isConnected) {
1262
- clipRegion = el.closest(".gdg-clip-region");
1263
- clipRegionRef.current = clipRegion;
1264
- }
1265
- const cachedRoot = overlayRootRef.current;
1266
- const overlayRoot = (cachedRoot?.isConnected ? cachedRoot : null) ?? clipRegion?.parentElement ?? null;
1267
- if (!overlayRoot) return;
1268
- overlayRootRef.current = overlayRoot;
1269
- if (!restoreRef.current) {
1270
- restoreRef.current = {
1271
- top: overlayRoot.style.top,
1272
- maxHeight: overlayRoot.style.maxHeight,
1273
- clipOverflow: clipRegion?.style.overflow ?? ""
1274
- };
1275
- }
1276
- if (clipRegion && clipRegion.style.overflow !== "visible") {
1277
- clipRegion.style.overflow = "visible";
1278
- }
1279
- const { shouldFlip, spaceBelow, targetBottom, maxHeightPx } = computeOverlayGeometry(
1280
- window.innerHeight,
1281
- target?.y,
1282
- target?.height,
1283
- marginPx,
1284
- minBelowPx
1285
- );
1286
- if (!shouldFlip) {
1287
- const restoreTop = restoreRef.current?.top ?? "";
1288
- if (overlayRoot.style.top !== restoreTop) {
1289
- overlayRoot.style.top = restoreTop;
1290
- }
1291
- const newMaxHeight = `${Math.max(0, spaceBelow)}px`;
1292
- if (overlayRoot.style.maxHeight !== newMaxHeight) {
1293
- overlayRoot.style.maxHeight = newMaxHeight;
1294
- }
1295
- return;
1296
- }
1297
- const newFlipMaxHeight = `${maxHeightPx}px`;
1298
- if (overlayRoot.style.maxHeight !== newFlipMaxHeight) {
1299
- overlayRoot.style.maxHeight = newFlipMaxHeight;
1300
- }
1301
- const h = overlayRoot.getBoundingClientRect().height;
1302
- let nextTop = targetBottom - h;
1303
- nextTop = Math.max(marginPx, Math.min(nextTop, window.innerHeight - marginPx - h));
1304
- if (!Number.isFinite(nextTop)) nextTop = marginPx;
1305
- const newTop = `${nextTop}px`;
1306
- if (overlayRoot.style.top !== newTop) {
1307
- overlayRoot.style.top = newTop;
1308
- }
1309
- if (typeof globalThis !== "undefined" && globalThis.__DEV__) {
1310
- sheetsLogger().debug?.("[data-grid][overlay-flip]", { debugName, shouldFlip, spaceBelow });
1311
- }
1312
- };
1313
- useLayoutEffect(() => {
1314
- positionRef.current?.();
1315
- const el = ref.current;
1316
- const overlayRoot = overlayRootRef.current;
1317
- const clipsRight = overlayRoot ? overlayRoot.getBoundingClientRect().right > window.innerWidth : false;
1318
- const animation = el?.animate(
1319
- [{ opacity: 0 }, { opacity: 1 }],
1320
- { duration: 50, delay: clipsRight ? 50 : 0, easing: "ease-out", fill: "both" }
1321
- );
1322
- const handleResize = () => positionRef.current?.();
1323
- window.addEventListener("resize", handleResize);
1324
- let ro;
1325
- let roRaf = 0;
1326
- if ("ResizeObserver" in window && el) {
1327
- ro = new ResizeObserver(() => {
1328
- cancelAnimationFrame(roRaf);
1329
- roRaf = requestAnimationFrame(() => positionRef.current?.());
1330
- });
1331
- ro.observe(el);
1332
- }
1333
- return () => {
1334
- animation?.cancel();
1335
- cancelAnimationFrame(roRaf);
1336
- window.removeEventListener("resize", handleResize);
1337
- ro?.disconnect();
1338
- const root = overlayRootRef.current;
1339
- if (root && restoreRef.current) {
1340
- root.style.top = restoreRef.current.top;
1341
- root.style.maxHeight = restoreRef.current.maxHeight;
1342
- }
1343
- const clip = clipRegionRef.current;
1344
- if (clip && restoreRef.current) {
1345
- clip.style.overflow = restoreRef.current.clipOverflow;
1346
- }
1347
- };
1348
- }, []);
1349
- return /* @__PURE__ */ jsx(OverlayMeasureContext.Provider, { value: computed, children: /* @__PURE__ */ jsx("div", { ref, children }) });
1350
- }
1351
-
1352
- // src/hooks/use-sheets-upload.ts
1353
- import { useEffect, useMemo as useMemo3, useRef as useRef2 } from "react";
1354
- import { useMutation as useMutation2, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
1355
- import { cleanTable as cleanTable2 } from "@constructive-io/data";
1356
- import {
1357
- toCamelCaseSingular as toCamelCaseSingular3,
1358
- toPatchFieldName as toPatchFieldName2,
1359
- toUpdateInputTypeName,
1360
- toUpdateMutationName as toUpdateMutationName2
1361
- } from "@constructive-io/data";
1362
- function resolveUploadNaming(tableName, table) {
1363
- return {
1364
- mutationName: toUpdateMutationName2(tableName, table),
1365
- singularName: toCamelCaseSingular3(tableName, table),
1366
- patchFieldName: toPatchFieldName2(tableName, table),
1367
- updateInputTypeName: toUpdateInputTypeName(tableName)
1368
- };
1369
- }
1370
- function resolveTransport(endpoint, getToken, options) {
1371
- if (options?.execute && options?.executeUpload) {
1372
- return { execute: options.execute, executeUpload: options.executeUpload };
1373
- }
1374
- const config = {
1375
- endpoint,
1376
- auth: { mode: "standalone" },
1377
- onAuthError: options?.onAuthError
1378
- };
1379
- return {
1380
- execute: createSheetsExecute(config, getToken),
1381
- executeUpload: createSheetsUpload(config, getToken)
1382
- };
1383
- }
1384
- async function executeFieldUpload(tableName, fieldName, recordId, file, endpoint, getToken, naming, options) {
1385
- if (!endpoint && !(options?.execute && options?.executeUpload)) {
1386
- throw new Error("No endpoint configured. Select a database API or use Direct Connect.");
1387
- }
1388
- const { execute, executeUpload } = resolveTransport(endpoint, getToken, options);
1389
- const uploadResult = await executeUpload(file, void 0, {
1390
- tableName,
1391
- fieldName,
1392
- recordId,
1393
- onProgress: options?.onProgress
1394
- });
1395
- const resolvedNaming = naming ?? resolveUploadNaming(tableName);
1396
- const patchValue = {
1397
- ...uploadResult.url != null && { url: uploadResult.url },
1398
- ...uploadResult.filename != null && { filename: uploadResult.filename },
1399
- ...uploadResult.mime != null && { mime: uploadResult.mime },
1400
- ...uploadResult.size != null && { size: uploadResult.size }
1401
- };
1402
- const mutationString = `
1403
- mutation ${resolvedNaming.mutationName}Mutation($input: ${resolvedNaming.updateInputTypeName}!) {
1404
- ${resolvedNaming.mutationName}(input: $input) {
1405
- ${resolvedNaming.singularName} {
1406
- id
1407
- ${fieldName}
1408
- }
1409
- }
1410
- }
1411
- `.trim();
1412
- const result = await execute(mutationString, {
1413
- input: {
1414
- id: recordId,
1415
- [resolvedNaming.patchFieldName]: {
1416
- [fieldName]: patchValue
1417
- }
1418
- }
1419
- });
1420
- const updatedRecord = result?.[resolvedNaming.mutationName]?.[resolvedNaming.singularName];
1421
- if (!updatedRecord) {
1422
- throw new Error("Upload succeeded but no data returned from patch");
1423
- }
1424
- const uploadedFileData = updatedRecord[fieldName];
1425
- if (!uploadedFileData) {
1426
- throw new Error(`Upload succeeded but ${fieldName} field not found in response`);
1427
- }
1428
- const fileObject = typeof uploadedFileData === "object" ? uploadedFileData : null;
1429
- return {
1430
- url: fileObject?.url || uploadedFileData,
1431
- filename: fileObject?.filename || file.name,
1432
- mime: fileObject?.mime || file.type,
1433
- size: fileObject?.size || file.size
1434
- };
1435
- }
1436
- function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
1437
- const queryClient = useQueryClient2();
1438
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
1439
- const storeApi = useSheetsStoreApi();
1440
- const { data: meta } = useSheetsMeta();
1441
- const table = useMemo3(() => {
1442
- if (!meta?._meta?.tables) return null;
1443
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
1444
- return candidate ? cleanTable2(candidate) : null;
1445
- }, [meta, tableName]);
1446
- const resolvedNaming = useMemo3(() => resolveUploadNaming(tableName, table), [tableName, table]);
1447
- const getToken = useMemo3(() => {
1448
- if (config.auth.mode === "embedded") {
1449
- return config.auth.getToken;
1450
- }
1451
- return () => storeApi.getState().accessToken;
1452
- }, [config.auth, storeApi]);
1453
- const tableRef = useRef2(tableName);
1454
- const fieldRef = useRef2(fieldName);
1455
- const idRef = useRef2(recordId);
1456
- useEffect(() => {
1457
- tableRef.current = tableName;
1458
- fieldRef.current = fieldName;
1459
- idRef.current = recordId;
1460
- }, [tableName, fieldName, recordId]);
1461
- return useMutation2({
1462
- mutationKey: ["sheets", scopeKey, "field-upload", tableName, fieldName, recordId],
1463
- mutationFn: async (file) => {
1464
- return executeFieldUpload(
1465
- tableRef.current,
1466
- fieldRef.current,
1467
- idRef.current,
1468
- file,
1469
- config.endpoint,
1470
- getToken,
1471
- resolvedNaming,
1472
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
1473
- );
1474
- },
1475
- onSuccess: (data) => {
1476
- options.onSuccess?.(data);
1477
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
1478
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
1479
- },
1480
- onError: (error) => {
1481
- options.onError?.(error);
1482
- }
1483
- });
1484
- }
1485
- function useSheetsImageUpload(tableName, fieldName, recordId, options = {}) {
1486
- const queryClient = useQueryClient2();
1487
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
1488
- const storeApi = useSheetsStoreApi();
1489
- const { data: meta } = useSheetsMeta();
1490
- const table = useMemo3(() => {
1491
- if (!meta?._meta?.tables) return null;
1492
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
1493
- return candidate ? cleanTable2(candidate) : null;
1494
- }, [meta, tableName]);
1495
- const resolvedNaming = useMemo3(() => resolveUploadNaming(tableName, table), [tableName, table]);
1496
- const getToken = useMemo3(() => {
1497
- if (config.auth.mode === "embedded") {
1498
- return config.auth.getToken;
1499
- }
1500
- return () => storeApi.getState().accessToken;
1501
- }, [config.auth, storeApi]);
1502
- const tableRef = useRef2(tableName);
1503
- const fieldRef = useRef2(fieldName);
1504
- const idRef = useRef2(recordId);
1505
- useEffect(() => {
1506
- tableRef.current = tableName;
1507
- fieldRef.current = fieldName;
1508
- idRef.current = recordId;
1509
- }, [tableName, fieldName, recordId]);
1510
- return useMutation2({
1511
- mutationKey: ["sheets", scopeKey, "image-upload", tableName, fieldName, recordId],
1512
- mutationFn: async (file) => {
1513
- if (!file.type.startsWith("image/")) {
1514
- throw new Error("Please select an image file");
1515
- }
1516
- const maxSize = 10 * 1024 * 1024;
1517
- if (file.size > maxSize) {
1518
- throw new Error("File size must be less than 10MB");
1519
- }
1520
- return executeFieldUpload(
1521
- tableRef.current,
1522
- fieldRef.current,
1523
- idRef.current,
1524
- file,
1525
- config.endpoint,
1526
- getToken,
1527
- resolvedNaming,
1528
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
1529
- );
1530
- },
1531
- onSuccess: (data) => {
1532
- options.onSuccess?.(data);
1533
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
1534
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
1535
- },
1536
- onError: (error) => {
1537
- options.onError?.(error);
1538
- }
1539
- });
1540
- }
1541
-
1542
- // src/hooks/use-sheets-table-cursor.ts
1543
- import { useMemo as useMemo4 } from "react";
1544
- import { useInfiniteQuery, useQueryClient as useQueryClient3 } from "@tanstack/react-query";
1545
- import {
1546
- cleanTable as cleanTable3
1547
- } from "@constructive-io/data";
1548
- import { createError as createError3 } from "@constructive-io/data";
1549
- import { toOrderByEnumValue as toOrderByEnumValue2 } from "@constructive-io/data";
1550
- function useSheetsTableCursor(tableName, options = {}) {
1551
- const queryClient = useQueryClient3();
1552
- const { execute, scopeKey } = useSheetsContext();
1553
- const { data: meta } = useSheetsMeta();
1554
- const adapter = useSheetsAdapter();
1555
- const tables = useMemo4(() => {
1556
- if (!meta?._meta?.tables) return [];
1557
- return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => cleanTable3(metaTable));
1558
- }, [meta]);
1559
- const table = useMemo4(
1560
- () => tables.find((candidate) => candidate.name === tableName) ?? null,
1561
- [tables, tableName]
1562
- );
1563
- const { enabled = true, select: fieldSelection, pageSize = 20, where, orderBy } = options;
1564
- const stableOptions = useMemo4(
1565
- () => ({ fieldSelection, where, orderBy }),
1566
- [fieldSelection, where, orderBy]
1567
- );
1568
- const queryOptions = useMemo4(
1569
- () => ({
1570
- fieldSelection,
1571
- where,
1572
- orderBy,
1573
- limit: pageSize,
1574
- includePageInfo: true
1575
- }),
1576
- [fieldSelection, where, orderBy, pageSize]
1577
- );
1578
- const {
1579
- data,
1580
- isLoading,
1581
- isFetchingNextPage,
1582
- hasNextPage,
1583
- fetchNextPage,
1584
- error
1585
- } = useInfiniteQuery({
1586
- queryKey: sheetsQueryKeys.cursorTable(scopeKey, tableName, stableOptions),
1587
- queryFn: async ({ pageParam }) => {
1588
- if (!table) {
1589
- throw createError3.notFound(`Table '${tableName}' not found`);
1590
- }
1591
- const cursor = pageParam;
1592
- const variableOptions = {
1593
- limit: pageSize,
1594
- where,
1595
- orderBy,
1596
- ...cursor ? { after: cursor } : {}
1597
- };
1598
- const variables = transformToPostGraphileVariables(table, variableOptions);
1599
- const [relationFieldMap] = await Promise.all([
1600
- resolveRelationFieldMap({
1601
- table,
1602
- fieldSelection,
1603
- scopeKey,
1604
- queryClient,
1605
- execute
1606
- }),
1607
- validateOrderByVariables(variables, table, scopeKey, queryClient, execute)
1608
- ]);
1609
- const validatedOrderByEnum = new Set(variables.orderBy ?? []);
1610
- const availableOrderByFields = new Set(table.fields.map((field) => field.name));
1611
- const validatedOrderBy = orderBy?.filter(
1612
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has(toOrderByEnumValue2(field, direction))
1613
- );
1614
- const res = await adapter.listRows(
1615
- { table, allTables: tables, tableName },
1616
- {
1617
- ...queryOptions,
1618
- orderBy: validatedOrderBy,
1619
- // resolveRelationFieldMap yields `string | null` (null = omit field). The
1620
- // contract narrows to `string`, but the null values are passed through to
1621
- // buildSelect unchanged at runtime — behavior is identical to before.
1622
- relationFieldMap,
1623
- ...cursor ? { after: cursor } : {}
1624
- },
1625
- execute
1626
- );
1627
- const pageInfo = res.pageInfo ?? {
1628
- hasNextPage: false,
1629
- hasPreviousPage: false
1630
- };
1631
- return {
1632
- rows: res.rows,
1633
- totalCount: res.totalCount,
1634
- pageInfo
1635
- };
1636
- },
1637
- initialPageParam: void 0,
1638
- getNextPageParam: (lastPage) => lastPage.pageInfo.hasNextPage && lastPage.pageInfo.endCursor ? lastPage.pageInfo.endCursor : void 0,
1639
- enabled: enabled && !!table,
1640
- staleTime: 5 * 60 * 1e3
1641
- });
1642
- const flatData = useMemo4(
1643
- () => data?.pages.flatMap((page) => page.rows) ?? [],
1644
- [data]
1645
- );
1646
- const totalCount = useMemo4(
1647
- () => data?.pages[data.pages.length - 1]?.totalCount ?? 0,
1648
- [data]
1649
- );
1650
- return {
1651
- data: flatData,
1652
- totalCount,
1653
- isLoading,
1654
- isFetchingNextPage,
1655
- hasNextPage: hasNextPage ?? false,
1656
- fetchNextPage,
1657
- error
1658
- };
1659
- }
1660
-
1661
- // src/grid/editors/array-editor.tsx
1662
- import { useCallback, useEffect as useEffect2, useMemo as useMemo5, useRef as useRef3, useState } from "react";
1663
- import { Badge } from "@constructive-io/ui/badge";
1664
- import { Button } from "@constructive-io/ui/button";
1665
- import { XIcon } from "lucide-react";
1666
- import { jsx as jsx2, jsxs } from "react/jsx-runtime";
1667
- var MAC_UA_RE = /Mac|iPod|iPhone|iPad/;
1668
- function parsePendingItems(input) {
1669
- if (!input) return [];
1670
- return input.split(/[\n,]/g).map((token) => token.trim()).filter((token) => token.length > 0);
1671
- }
1672
- function mergeArrayEditorValues(list, pendingInput) {
1673
- const pendingItems = parsePendingItems(pendingInput);
1674
- if (!pendingItems.length) return list;
1675
- return [...list, ...pendingItems];
1676
- }
1677
- function ArrayEditor({ value, onChange, onFinished }) {
1678
- const items = useMemo5(() => Array.isArray(value) ? value : [], [value]);
1679
- const [list, setList] = useState(items);
1680
- const [input, setInput] = useState("");
1681
- const inputRef = useRef3(null);
1682
- const keyContainerRef = useRef3(null);
1683
- const handleCancel = useCallback(() => onFinished(void 0), [onFinished]);
1684
- const handleSave = useCallback(() => {
1685
- const next = mergeArrayEditorValues(list, input);
1686
- setList(next);
1687
- setInput("");
1688
- onChange(next);
1689
- onFinished(next);
1690
- }, [input, list, onChange, onFinished]);
1691
- const add = useCallback(() => {
1692
- const next = mergeArrayEditorValues(list, input);
1693
- if (next.length === list.length) return;
1694
- setList(next);
1695
- setInput("");
1696
- onChange(next);
1697
- }, [input, list, onChange]);
1698
- const remove = useCallback(
1699
- (idx) => {
1700
- const next = list.filter((_, i) => i !== idx);
1701
- setList(next);
1702
- onChange(next);
1703
- inputRef.current?.focus();
1704
- },
1705
- [list, onChange]
1706
- );
1707
- const actionsRef = useRef3({ add, handleSave, remove, handleCancel });
1708
- actionsRef.current = { add, handleSave, remove, handleCancel };
1709
- const stateRef = useRef3({ input, listLength: list.length });
1710
- stateRef.current = { input, listLength: list.length };
1711
- useEffect2(() => {
1712
- const el = keyContainerRef.current;
1713
- if (!el) return;
1714
- const handler = (e) => {
1715
- const { add: add2, handleSave: handleSave2, remove: remove2, handleCancel: handleCancel2 } = actionsRef.current;
1716
- const { input: input2, listLength } = stateRef.current;
1717
- if (e.key === "Escape") {
1718
- e.preventDefault();
1719
- e.stopPropagation();
1720
- handleCancel2();
1721
- return;
1722
- }
1723
- if (e.key === "Backspace" && !input2 && listLength > 0) {
1724
- e.preventDefault();
1725
- e.stopPropagation();
1726
- remove2(listLength - 1);
1727
- return;
1728
- }
1729
- if (e.key === "Enter" && !e.metaKey && !e.ctrlKey) {
1730
- e.preventDefault();
1731
- e.stopPropagation();
1732
- add2();
1733
- return;
1734
- }
1735
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey) || e.key === "s" && (e.metaKey || e.ctrlKey)) {
1736
- e.preventDefault();
1737
- e.stopPropagation();
1738
- handleSave2();
1739
- return;
1740
- }
1741
- if (e.key === "Tab") {
1742
- e.stopPropagation();
1743
- }
1744
- };
1745
- el.addEventListener("keydown", handler);
1746
- return () => el.removeEventListener("keydown", handler);
1747
- }, []);
1748
- const isMac = typeof navigator !== "undefined" && MAC_UA_RE.test(navigator.userAgent);
1749
- const modKey = isMac ? "\u2318" : "Ctrl";
1750
- return /* @__PURE__ */ jsx2(
1751
- EditorFocusTrap,
1752
- {
1753
- onEscape: handleCancel,
1754
- className: `bg-popover ${OVERLAY.sm} rounded-lg border p-2.5 shadow-lg`,
1755
- children: /* @__PURE__ */ jsxs("div", { ref: keyContainerRef, children: [
1756
- /* @__PURE__ */ jsxs(
1757
- "div",
1758
- {
1759
- className: "flex min-h-[2.5rem] cursor-text flex-wrap items-center gap-2 rounded-md px-1 py-1",
1760
- onClick: () => inputRef.current?.focus(),
1761
- children: [
1762
- list.map((item, i) => /* @__PURE__ */ jsxs(
1763
- Badge,
1764
- {
1765
- variant: "outline",
1766
- size: "sm",
1767
- className: "group/tag !animate-none !transition-none gap-0.5 pe-0.5",
1768
- children: [
1769
- /* @__PURE__ */ jsx2("span", { className: "max-w-[180px] truncate", children: String(item) }),
1770
- /* @__PURE__ */ jsx2(
1771
- "button",
1772
- {
1773
- className: "text-muted-foreground/60 hover:bg-muted hover:text-foreground -me-px inline-flex size-4 items-center justify-center rounded-xs transition-colors",
1774
- onClick: (e) => {
1775
- e.stopPropagation();
1776
- remove(i);
1777
- },
1778
- "aria-label": `Remove ${String(item)}`,
1779
- tabIndex: -1,
1780
- children: /* @__PURE__ */ jsx2(XIcon, { className: "size-3" })
1781
- }
1782
- )
1783
- ]
1784
- },
1785
- i
1786
- )),
1787
- /* @__PURE__ */ jsx2(
1788
- "input",
1789
- {
1790
- ref: inputRef,
1791
- value: input,
1792
- onChange: (e) => setInput(e.target.value),
1793
- placeholder: list.length === 0 ? "Type and press Enter..." : "Add more...",
1794
- className: "placeholder:text-muted-foreground/50 min-w-[80px] flex-1 bg-transparent py-0.5 text-sm outline-none"
1795
- }
1796
- )
1797
- ]
1798
- }
1799
- ),
1800
- /* @__PURE__ */ jsxs("div", { className: "mt-3 flex items-center justify-between gap-4 border-t px-1 pt-2.5", children: [
1801
- /* @__PURE__ */ jsxs("div", { className: "text-muted-foreground flex items-center gap-3 text-xs", children: [
1802
- /* @__PURE__ */ jsxs("span", { className: "inline-flex shrink-0 items-center gap-1", children: [
1803
- /* @__PURE__ */ jsx2("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight", children: "Enter" }),
1804
- /* @__PURE__ */ jsx2("span", { children: "add" })
1805
- ] }),
1806
- /* @__PURE__ */ jsx2("span", { className: "text-border", children: "|" }),
1807
- /* @__PURE__ */ jsxs("span", { className: "inline-flex shrink-0 items-center gap-1", children: [
1808
- /* @__PURE__ */ jsx2("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight", children: modKey }),
1809
- /* @__PURE__ */ jsx2("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight", children: "\u21B5" }),
1810
- /* @__PURE__ */ jsx2("span", { children: "save" })
1811
- ] }),
1812
- /* @__PURE__ */ jsxs("span", { className: "inline-flex shrink-0 items-center gap-1", children: [
1813
- /* @__PURE__ */ jsx2("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight", children: "\u232B" }),
1814
- /* @__PURE__ */ jsx2("span", { children: "remove" })
1815
- ] })
1816
- ] }),
1817
- /* @__PURE__ */ jsx2(Button, { onClick: handleSave, size: "xs", variant: "default", className: "shrink-0", children: "Save" })
1818
- ] })
1819
- ] })
1820
- }
1821
- );
1822
- }
1823
-
1824
- // src/grid-dom/editors/array-editor.tsx
1825
- import { jsx as jsx3 } from "react/jsx-runtime";
1826
- function ArrayEditorDom({ value, onCommit, onCancel }) {
1827
- const initial = Array.isArray(value) ? value : [];
1828
- return /* @__PURE__ */ jsx3("div", { "data-slot": "array-editor", children: /* @__PURE__ */ jsx3(
1829
- ArrayEditor,
1830
- {
1831
- value: initial,
1832
- onChange: () => {
1833
- },
1834
- onFinished: (next) => next === void 0 ? onCancel() : onCommit(next)
1835
- }
1836
- ) });
1837
- }
1838
-
1839
- // src/grid-dom/editors/date-editor.tsx
1840
- import { lazy, Suspense } from "react";
1841
- import { jsx as jsx4 } from "react/jsx-runtime";
1842
- var DateEditor = lazy(() => import("./date-editor-ZFNDKYBD.js").then((m) => ({ default: m.DateEditor })));
1843
- function DateEditorDom({ value, cell, onCommit, onCancel }) {
1844
- const cellType = cell.meta?.cellType;
1845
- const dateType = cellType && DATE_TIME_TYPES.has(cellType) ? cellType : void 0;
1846
- return /* @__PURE__ */ jsx4("div", { "data-slot": "date-editor", children: /* @__PURE__ */ jsx4(Suspense, { fallback: /* @__PURE__ */ jsx4("div", { className: "h-9 w-full min-w-[320px] animate-pulse rounded-sm bg-muted" }), children: /* @__PURE__ */ jsx4(
1847
- DateEditor,
1848
- {
1849
- value,
1850
- dateType,
1851
- onFinishedEditing: (next) => next === void 0 ? onCancel() : onCommit(next)
1852
- }
1853
- ) }) });
1854
- }
1855
-
1856
- // src/grid-dom/editors/geometry-editor.tsx
1857
- import { Suspense as Suspense3 } from "react";
1858
-
1859
- // src/grid/editors/geometry-editor.tsx
1860
- import { lazy as lazy2, Suspense as Suspense2, useCallback as useCallback2, useContext, useLayoutEffect as useLayoutEffect2, useMemo as useMemo6, useRef as useRef4, useState as useState2 } from "react";
1861
- import { AlertCircle, FileText, Loader2, Map as Map2, MapPin, Shuffle } from "lucide-react";
1862
- import { Button as Button2 } from "@constructive-io/ui/button";
1863
- import { Tabs, TabsContent, TabsList, TabsTrigger } from "@constructive-io/ui/tabs";
1864
- import { Textarea } from "@constructive-io/ui/textarea";
1865
- import { Fragment, jsx as jsx5, jsxs as jsxs2 } from "react/jsx-runtime";
1866
- var MapPicker = lazy2(
1867
- () => import("./map-picker-ZUGGOIZS.js").then((m) => ({ default: m.MapPicker }))
1868
- );
1869
- function MapPickerLoading() {
1870
- return /* @__PURE__ */ jsx5("div", { className: "flex h-[280px] w-full items-center justify-center rounded-lg border bg-muted/30", children: /* @__PURE__ */ jsx5(Loader2, { className: "h-6 w-6 animate-spin text-muted-foreground" }) });
1871
- }
1872
- var VALID_GEOJSON_TYPES = [
1873
- "Point",
1874
- "LineString",
1875
- "Polygon",
1876
- "MultiPoint",
1877
- "MultiLineString",
1878
- "MultiPolygon",
1879
- "GeometryCollection"
1880
- ];
1881
- function isValidGeoJSON(obj) {
1882
- if (!obj || typeof obj !== "object") return false;
1883
- if (!obj.type || typeof obj.type !== "string") return false;
1884
- if (obj.type === "Feature" || obj.type === "FeatureCollection") return false;
1885
- if (!VALID_GEOJSON_TYPES.includes(obj.type)) return false;
1886
- switch (obj.type) {
1887
- case "Point":
1888
- return Array.isArray(obj.coordinates) && obj.coordinates.length >= 2;
1889
- case "LineString":
1890
- return Array.isArray(obj.coordinates) && obj.coordinates.length >= 2 && obj.coordinates.every((coord) => Array.isArray(coord) && coord.length >= 2);
1891
- case "Polygon":
1892
- return Array.isArray(obj.coordinates) && obj.coordinates.length >= 1 && obj.coordinates.every((ring) => Array.isArray(ring) && ring.length >= 4);
1893
- default:
1894
- return true;
1895
- }
1896
- }
1897
- function getGeoJSONHint(obj) {
1898
- if (!obj || typeof obj !== "object" || typeof obj.type !== "string") return void 0;
1899
- if (obj.type === "Feature") return "Feature type is not supported by PostGIS. Extract the geometry property first.";
1900
- if (obj.type === "FeatureCollection") return "FeatureCollection type is not supported by PostGIS. Extract individual geometries first.";
1901
- return void 0;
1902
- }
1903
- function isValidGeometry(obj) {
1904
- if (!obj || typeof obj !== "object") return false;
1905
- if (!("geojson" in obj) || !("srid" in obj) || !("x" in obj) || !("y" in obj)) {
1906
- return false;
1907
- }
1908
- if (!isValidGeoJSON(obj.geojson)) return false;
1909
- if (!Number.isInteger(obj.srid)) return false;
1910
- if (!Number.isFinite(obj.x) || !Number.isFinite(obj.y)) return false;
1911
- return true;
1912
- }
1913
- function isWrappedGeoJSON(obj) {
1914
- if (!obj || typeof obj !== "object") return false;
1915
- if (!("geojson" in obj)) return false;
1916
- return isValidGeoJSON(obj.geojson);
1917
- }
1918
- function isBarePoint(obj) {
1919
- return obj && typeof obj === "object" && "x" in obj && "y" in obj && typeof obj.x === "number" && typeof obj.y === "number" && !("type" in obj) && !("geojson" in obj);
1920
- }
1921
- function extractRawGeoJSON(obj) {
1922
- if (isValidGeoJSON(obj)) return obj;
1923
- if (obj?.geojson && isValidGeoJSON(obj.geojson)) return obj.geojson;
1924
- if (isBarePoint(obj)) return { type: "Point", coordinates: [obj.x, obj.y] };
1925
- return null;
1926
- }
1927
- function extractPointCoords(geojson) {
1928
- if (geojson?.type === "Point" && Array.isArray(geojson.coordinates)) {
1929
- return { x: Number(geojson.coordinates[0]), y: Number(geojson.coordinates[1]) };
1930
- }
1931
- return { x: 0, y: 0 };
1932
- }
1933
- function validateGeometry(jsonString, expectedType) {
1934
- if (!jsonString.trim()) return true;
1935
- try {
1936
- const parsed = JSON.parse(jsonString);
1937
- if (!isValidGeometry(parsed) && !isValidGeoJSON(parsed) && !isWrappedGeoJSON(parsed) && !isBarePoint(parsed)) {
1938
- const hint = getGeoJSONHint(parsed?.geojson ?? parsed);
1939
- if (hint) return hint;
1940
- return 'Invalid geometry. Expected GeoJSON (e.g., {"type": "Point", "coordinates": [0, 0]}).';
1941
- }
1942
- if (expectedType) {
1943
- const geojson = extractRawGeoJSON(parsed) ?? parsed;
1944
- const actualType = geojson?.type;
1945
- if (actualType && actualType !== expectedType) {
1946
- return `Column expects ${expectedType} but got ${actualType}.`;
1947
- }
1948
- }
1949
- return true;
1950
- } catch {
1951
- return "Invalid JSON format";
1952
- }
1953
- }
1954
- function isPointGeometry(geometry) {
1955
- return !!(geometry?.geojson?.type === "Point" && Array.isArray(geometry.geojson.coordinates));
1956
- }
1957
- function formatGeometry(val) {
1958
- if (val == null) return "";
1959
- try {
1960
- const obj = typeof val === "string" ? JSON.parse(val) : val;
1961
- return JSON.stringify(obj, null, 2);
1962
- } catch {
1963
- return String(val);
1964
- }
1965
- }
1966
- function parseGeometryValue(value) {
1967
- if (!value) return null;
1968
- try {
1969
- const parsed = typeof value === "string" ? JSON.parse(value) : value;
1970
- if (isValidGeometry(parsed)) return parsed;
1971
- if (isValidGeoJSON(parsed)) {
1972
- return { geojson: parsed, srid: 4326, ...extractPointCoords(parsed) };
1973
- }
1974
- if (isWrappedGeoJSON(parsed)) {
1975
- const gj = parsed.geojson;
1976
- return { geojson: gj, srid: Number(parsed.srid) || 4326, ...extractPointCoords(gj) };
1977
- }
1978
- if (isBarePoint(parsed)) {
1979
- const geojson = { type: "Point", coordinates: [parsed.x, parsed.y] };
1980
- return { geojson, srid: 4326, x: parsed.x, y: parsed.y };
1981
- }
1982
- return null;
1983
- } catch {
1984
- return null;
1985
- }
1986
- }
1987
- var GEOMETRY_PLACEHOLDERS = {
1988
- Point: JSON.stringify({ type: "Point", coordinates: [0, 0] }, null, 2),
1989
- Polygon: JSON.stringify({ type: "Polygon", coordinates: [[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]] }, null, 2),
1990
- LineString: JSON.stringify({ type: "LineString", coordinates: [[0, 0], [1, 1], [2, 0]] }, null, 2),
1991
- MultiPoint: JSON.stringify({ type: "MultiPoint", coordinates: [[0, 0], [1, 1]] }, null, 2),
1992
- MultiPolygon: JSON.stringify({ type: "MultiPolygon", coordinates: [[[[0, 0], [1, 0], [1, 1], [0, 1], [0, 0]]]] }, null, 2),
1993
- MultiLineString: JSON.stringify({ type: "MultiLineString", coordinates: [[[0, 0], [1, 1]], [[2, 2], [3, 3]]] }, null, 2)
1994
- };
1995
- var DEFAULT_GEOMETRY_PLACEHOLDER = GEOMETRY_PLACEHOLDERS.Point;
1996
- var IS_MAC = typeof navigator !== "undefined" && /Mac|iPod|iPhone|iPad/.test(navigator.userAgent);
1997
- var MOD_KEY = IS_MAC ? "\u2318" : "Ctrl";
1998
- var RANDOMIZABLE_TYPES = ["Point", "LineString", "Polygon"];
1999
- function generateRandomGeometry(constrainedType) {
2000
- const sampleLocations = [
2001
- { name: "Times Square, NYC", lng: -73.985, lat: 40.758 },
2002
- { name: "Eiffel Tower, Paris", lng: 2.294, lat: 48.858 },
2003
- { name: "Big Ben, London", lng: -0.124, lat: 51.499 },
2004
- { name: "Golden Gate Bridge, SF", lng: -122.478, lat: 37.819 },
2005
- { name: "Sydney Opera House", lng: 151.215, lat: -33.857 }
2006
- ];
2007
- const randomType = constrainedType && RANDOMIZABLE_TYPES.includes(constrainedType) ? constrainedType : RANDOMIZABLE_TYPES[Math.floor(Math.random() * RANDOMIZABLE_TYPES.length)];
2008
- const baseLocation = sampleLocations[Math.floor(Math.random() * sampleLocations.length)];
2009
- const baseLng = baseLocation.lng;
2010
- const baseLat = baseLocation.lat;
2011
- let geojson;
2012
- switch (randomType) {
2013
- case "Point":
2014
- geojson = {
2015
- type: "Point",
2016
- coordinates: [baseLng, baseLat]
2017
- };
2018
- break;
2019
- case "LineString": {
2020
- const pathPoints = [];
2021
- for (let i = 0; i < 4; i++) {
2022
- pathPoints.push([
2023
- baseLng + (Math.random() - 0.5) * 0.01,
2024
- baseLat + (Math.random() - 0.5) * 0.01
2025
- ]);
2026
- }
2027
- geojson = {
2028
- type: "LineString",
2029
- coordinates: pathPoints
2030
- };
2031
- break;
2032
- }
2033
- case "Polygon": {
2034
- const offset = 5e-3;
2035
- geojson = {
2036
- type: "Polygon",
2037
- coordinates: [
2038
- [
2039
- [baseLng - offset, baseLat - offset],
2040
- [baseLng + offset, baseLat - offset],
2041
- [baseLng + offset, baseLat + offset],
2042
- [baseLng - offset, baseLat + offset],
2043
- [baseLng - offset, baseLat - offset]
2044
- ]
2045
- ]
2046
- };
2047
- break;
2048
- }
2049
- }
2050
- let x = baseLng, y = baseLat;
2051
- if (geojson.type === "Point") {
2052
- x = geojson.coordinates[0];
2053
- y = geojson.coordinates[1];
2054
- }
2055
- return { geojson, srid: 4326, x, y };
2056
- }
2057
- var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
2058
- const currentGeometryData = value;
2059
- const geometryValue = useMemo6(() => parseGeometryValue(currentGeometryData), [currentGeometryData]);
2060
- const [editingValue, setEditingValue] = useState2(() => {
2061
- if (!currentGeometryData) return "";
2062
- const geo = parseGeometryValue(currentGeometryData);
2063
- if (geo?.geojson) return JSON.stringify(geo.geojson, null, 2);
2064
- return formatGeometry(currentGeometryData);
2065
- });
2066
- const canShowMap = expectedType === "Point" || !expectedType && geometryValue != null && isPointGeometry(geometryValue);
2067
- const validationResult = useMemo6(() => validateGeometry(editingValue, expectedType), [editingValue, expectedType]);
2068
- const isValid = validationResult === true;
2069
- const validationError = typeof validationResult === "string" ? validationResult : void 0;
2070
- const [activeTab, setActiveTab] = useState2(() => canShowMap ? "map" : "json");
2071
- const handleMapChange = useCallback2((mapValue) => {
2072
- if (mapValue?.geojson?.type) {
2073
- setEditingValue(JSON.stringify(mapValue.geojson, null, 2));
2074
- } else {
2075
- setEditingValue("");
2076
- }
2077
- }, []);
2078
- const handleRandomize = useCallback2(() => {
2079
- setEditingValue(JSON.stringify(generateRandomGeometry(expectedType).geojson, null, 2));
2080
- }, [expectedType]);
2081
- const handleSave = useCallback2(() => {
2082
- if (!isValid) return;
2083
- let finalValue;
2084
- if (!editingValue.trim()) {
2085
- finalValue = "";
2086
- } else {
2087
- try {
2088
- const parsed = JSON.parse(editingValue);
2089
- finalValue = JSON.stringify(extractRawGeoJSON(parsed) ?? parsed);
2090
- } catch {
2091
- finalValue = editingValue;
2092
- }
2093
- }
2094
- onFinishedEditing(finalValue);
2095
- }, [editingValue, isValid, onFinishedEditing]);
2096
- const handleCancel = useCallback2(() => {
2097
- onFinishedEditing();
2098
- }, [onFinishedEditing]);
2099
- const handleEditorKeyDown = useCallback2(
2100
- (e) => {
2101
- if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
2102
- e.preventDefault();
2103
- if (isValid) handleSave();
2104
- }
2105
- },
2106
- [isValid, handleSave]
2107
- );
2108
- const mapPickerValue = useMemo6(() => {
2109
- try {
2110
- if (editingValue) {
2111
- const raw = extractRawGeoJSON(JSON.parse(editingValue));
2112
- if (raw) return raw;
2113
- }
2114
- } catch {
2115
- }
2116
- if (geometryValue && isPointGeometry(geometryValue)) {
2117
- return geometryValue.geojson;
2118
- }
2119
- return void 0;
2120
- }, [editingValue, geometryValue]);
2121
- const { maxHeight: overlayMaxHeight } = useContext(OverlayMeasureContext);
2122
- const editorRef = useRef4(null);
2123
- const contentRef = useRef4(null);
2124
- const [scrollBudget, setScrollBudget] = useState2();
2125
- useLayoutEffect2(() => {
2126
- const editor = editorRef.current;
2127
- const content = contentRef.current;
2128
- if (!editor || !content || overlayMaxHeight <= 0) return;
2129
- const fixedUI = editor.scrollHeight - content.scrollHeight;
2130
- setScrollBudget(Math.max(0, overlayMaxHeight - fixedUI));
2131
- }, [overlayMaxHeight]);
2132
- const header = /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between px-3 py-2", children: [
2133
- /* @__PURE__ */ jsxs2("div", { className: "flex items-center gap-2", children: [
2134
- /* @__PURE__ */ jsx5(MapPin, { className: "text-muted-foreground h-3.5 w-3.5" }),
2135
- /* @__PURE__ */ jsx5("span", { className: "text-sm font-medium", children: "Geometry" }),
2136
- expectedType && /* @__PURE__ */ jsx5("span", { className: "bg-muted text-muted-foreground rounded px-1.5 py-0.5 text-xs", children: expectedType })
2137
- ] }),
2138
- canShowMap && /* @__PURE__ */ jsxs2(TabsList, { className: "h-7", children: [
2139
- /* @__PURE__ */ jsxs2(TabsTrigger, { value: "map", className: "flex items-center gap-1.5 px-2.5 text-xs", children: [
2140
- /* @__PURE__ */ jsx5(Map2, { className: "h-3 w-3" }),
2141
- "Map"
2142
- ] }),
2143
- /* @__PURE__ */ jsxs2(TabsTrigger, { value: "json", className: "flex items-center gap-1.5 px-2.5 text-xs", children: [
2144
- /* @__PURE__ */ jsx5(FileText, { className: "h-3 w-3" }),
2145
- "JSON"
2146
- ] })
2147
- ] })
2148
- ] });
2149
- const jsonContent = /* @__PURE__ */ jsxs2("div", { className: "space-y-3 p-3", children: [
2150
- /* @__PURE__ */ jsx5(
2151
- Textarea,
2152
- {
2153
- id: "geometry-json",
2154
- value: editingValue,
2155
- onChange: (e) => setEditingValue(e.target.value),
2156
- className: cn("min-h-[200px] resize-none font-mono text-sm", !isValid && "border-destructive"),
2157
- placeholder: GEOMETRY_PLACEHOLDERS[expectedType ?? ""] ?? DEFAULT_GEOMETRY_PLACEHOLDER,
2158
- autoFocus: !canShowMap || activeTab === "json"
2159
- }
2160
- ),
2161
- validationError && /* @__PURE__ */ jsxs2("div", { className: "text-destructive flex items-center gap-2 text-sm", children: [
2162
- /* @__PURE__ */ jsx5(AlertCircle, { className: "h-4 w-4 shrink-0" }),
2163
- validationError
2164
- ] }),
2165
- (!expectedType || RANDOMIZABLE_TYPES.includes(expectedType)) && /* @__PURE__ */ jsxs2(Button2, { variant: "ghost", size: "xs", onClick: handleRandomize, title: "Generate random geometry", children: [
2166
- /* @__PURE__ */ jsx5(Shuffle, { className: "mr-1 h-3 w-3" }),
2167
- "Randomize"
2168
- ] })
2169
- ] });
2170
- const footer = /* @__PURE__ */ jsxs2("div", { className: "flex items-center justify-between border-t px-3 py-2", children: [
2171
- /* @__PURE__ */ jsxs2("div", { className: "text-muted-foreground flex items-center gap-3 text-xs", children: [
2172
- isValid ? /* @__PURE__ */ jsx5("span", { className: "text-muted-foreground/60 shrink-0", children: "Valid" }) : /* @__PURE__ */ jsx5("span", { className: "text-destructive shrink-0", children: "Invalid" }),
2173
- /* @__PURE__ */ jsx5("span", { className: "text-border", children: "|" }),
2174
- /* @__PURE__ */ jsxs2("span", { className: "inline-flex shrink-0 items-center gap-1", children: [
2175
- /* @__PURE__ */ jsx5("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight", children: MOD_KEY }),
2176
- /* @__PURE__ */ jsx5("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight", children: "\u21B5" }),
2177
- /* @__PURE__ */ jsx5("span", { children: "save" })
2178
- ] }),
2179
- /* @__PURE__ */ jsxs2("span", { className: "inline-flex shrink-0 items-center gap-1", children: [
2180
- /* @__PURE__ */ jsx5("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight", children: "Esc" }),
2181
- /* @__PURE__ */ jsx5("span", { children: "cancel" })
2182
- ] })
2183
- ] }),
2184
- /* @__PURE__ */ jsx5(Button2, { onClick: handleSave, size: "xs", variant: "default", className: "shrink-0", disabled: !isValid, children: "Save" })
2185
- ] });
2186
- return /* @__PURE__ */ jsx5(
2187
- EditorFocusTrap,
2188
- {
2189
- onEscape: handleCancel,
2190
- className: `bg-popover flex w-full ${OVERLAY.xl} flex-col overflow-hidden rounded-lg border shadow-lg`,
2191
- children: /* @__PURE__ */ jsx5("div", { ref: editorRef, onKeyDown: handleEditorKeyDown, className: "flex min-h-0 flex-1 flex-col", children: canShowMap ? /* @__PURE__ */ jsxs2(Tabs, { value: activeTab, onValueChange: (v) => setActiveTab(v), className: "flex min-h-0 flex-1 flex-col", children: [
2192
- header,
2193
- /* @__PURE__ */ jsxs2("div", { ref: contentRef, className: "min-h-0 flex-1 overflow-y-auto border-t", style: { maxHeight: scrollBudget }, children: [
2194
- /* @__PURE__ */ jsx5(TabsContent, { value: "map", className: "mt-0 p-3", children: /* @__PURE__ */ jsx5(Suspense2, { fallback: /* @__PURE__ */ jsx5(MapPickerLoading, {}), children: /* @__PURE__ */ jsx5(
2195
- MapPicker,
2196
- {
2197
- value: mapPickerValue,
2198
- onChange: handleMapChange,
2199
- height: 280,
2200
- placeholder: "Search for a location or click on the map..."
2201
- }
2202
- ) }) }),
2203
- /* @__PURE__ */ jsx5(TabsContent, { value: "json", className: "mt-0", children: jsonContent })
2204
- ] }),
2205
- footer
2206
- ] }) : /* @__PURE__ */ jsxs2(Fragment, { children: [
2207
- header,
2208
- /* @__PURE__ */ jsx5("div", { ref: contentRef, className: "min-h-0 flex-1 overflow-y-auto border-t", style: { maxHeight: scrollBudget }, children: jsonContent }),
2209
- footer
2210
- ] }) })
2211
- }
2212
- );
2213
- };
2214
-
2215
- // src/grid-dom/editors/geometry-editor.tsx
2216
- import { jsx as jsx6 } from "react/jsx-runtime";
2217
- function GeometryEditorDom({ value, fieldMeta, onCommit, onCancel }) {
2218
- const expectedType = fieldMeta?.type?.subtype || void 0;
2219
- return /* @__PURE__ */ jsx6("div", { "data-slot": "geometry-editor", children: /* @__PURE__ */ jsx6(Suspense3, { fallback: /* @__PURE__ */ jsx6("div", { className: "h-80 w-full min-w-[600px] animate-pulse rounded-lg bg-muted" }), children: /* @__PURE__ */ jsx6(
2220
- GeometryEditor,
2221
- {
2222
- value,
2223
- expectedType,
2224
- onFinishedEditing: (next) => next === void 0 ? onCancel() : onCommit(next)
2225
- }
2226
- ) }) });
2227
- }
2228
-
2229
- // src/grid-dom/editors/image-editor.tsx
2230
- import { Suspense as Suspense4 } from "react";
2231
-
2232
- // src/grid/editors/image-editor.tsx
2233
- import { useCallback as useCallback3, useContext as useContext2, useEffect as useEffect4, useMemo as useMemo8, useRef as useRef5, useState as useState5 } from "react";
2234
- import { AlertCircleIcon, FileIcon, ImageIcon, ImageOff, Loader2 as Loader22, UploadIcon, XIcon as XIcon2 } from "lucide-react";
2235
- import { AnimatePresence, motion } from "motion/react";
2236
- import { toast } from "@constructive-io/ui/toast";
2237
-
2238
- // src/utils/file.utils.ts
2239
- var getImageUrl = (imageValue) => {
2240
- if (!imageValue) return null;
2241
- if (typeof imageValue === "string") {
2242
- return imageValue;
2243
- }
2244
- if (typeof imageValue === "object" && imageValue !== null) {
2245
- const urlCandidates = ["url", "src", "href", "link", "path"];
2246
- for (const candidate of urlCandidates) {
2247
- const obj = imageValue;
2248
- if (obj[candidate] && typeof obj[candidate] === "string") {
2249
- return obj[candidate];
2250
- }
2251
- }
2252
- }
2253
- return null;
2254
- };
2255
- var getImageMetadata = (imageValue) => {
2256
- if (!imageValue || typeof imageValue !== "object") return null;
2257
- const obj = imageValue;
2258
- return {
2259
- filename: obj.filename || obj.name || "Unknown",
2260
- size: obj.size || obj.fileSize || 0,
2261
- mime: obj.mime || obj.type || obj.contentType || "unknown",
2262
- url: getImageUrl(imageValue) || ""
2263
- };
2264
- };
2265
- var formatFileSize = (bytes) => {
2266
- if (bytes === 0) return "0 B";
2267
- const k = 1024;
2268
- const sizes = ["B", "KB", "MB", "GB"];
2269
- const i = Math.floor(Math.log(bytes) / Math.log(k));
2270
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
2271
- };
2272
-
2273
- // src/utils/use-image-status.ts
2274
- import { useEffect as useEffect3, useState as useState3 } from "react";
2275
- function useImageStatus(src) {
2276
- const [status, setStatus] = useState3("idle");
2277
- useEffect3(() => {
2278
- if (!src) return setStatus("idle");
2279
- setStatus("loading");
2280
- const img = new Image();
2281
- img.src = src;
2282
- const onLoad = () => setStatus("loaded");
2283
- const onError = () => setStatus("error");
2284
- img.addEventListener("load", onLoad);
2285
- img.addEventListener("error", onError);
2286
- return () => {
2287
- img.removeEventListener("load", onLoad);
2288
- img.removeEventListener("error", onError);
2289
- };
2290
- }, [src]);
2291
- return status;
2292
- }
2293
-
2294
- // src/grid/editors/image-editor.tsx
2295
- import { Button as Button3 } from "@constructive-io/ui/button";
2296
- import { Skeleton } from "@constructive-io/ui/skeleton";
2297
-
2298
- // src/utils/image-with-fallback.tsx
2299
- import { useMemo as useMemo7, useState as useState4 } from "react";
2300
- import { jsx as jsx7 } from "react/jsx-runtime";
2301
- function ImageWithFallback({
2302
- src,
2303
- alt = "",
2304
- fallback,
2305
- fallbackElement,
2306
- loadingElement,
2307
- wrapperClassName,
2308
- className,
2309
- ...imgProps
2310
- }) {
2311
- const fallbacks = useMemo7(() => {
2312
- const legacyFallbacks = [];
2313
- if (loadingElement) legacyFallbacks.push(loadingElement);
2314
- if (fallbackElement) legacyFallbacks.push(fallbackElement);
2315
- const primaryFallbacks = fallback === void 0 ? [] : Array.isArray(fallback) ? fallback : [fallback];
2316
- return [...primaryFallbacks, ...legacyFallbacks];
2317
- }, [fallback, fallbackElement, loadingElement]);
2318
- const [currentSrcIndex, setCurrentSrcIndex] = useState4(0);
2319
- const currentSrc = currentSrcIndex === 0 ? src : fallbacks[currentSrcIndex - 1];
2320
- const status = useImageStatus(typeof currentSrc === "string" ? currentSrc : void 0);
2321
- if (status === "error" && currentSrcIndex < fallbacks.length) {
2322
- if (typeof fallbacks[currentSrcIndex] === "string") {
2323
- setCurrentSrcIndex((i) => i + 1);
2324
- }
2325
- }
2326
- const renderContent = () => {
2327
- switch (status) {
2328
- case "idle":
2329
- case "loading": {
2330
- const maybeJSX = fallbacks.find((f) => typeof f !== "string");
2331
- return maybeJSX ?? /* @__PURE__ */ jsx7("div", { className: "bg-muted h-full w-full animate-pulse rounded-md" });
2332
- }
2333
- case "loaded": {
2334
- return /* @__PURE__ */ jsx7(
2335
- "img",
2336
- {
2337
- src: currentSrc,
2338
- alt,
2339
- className: cn(
2340
- "object-cover outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10",
2341
- className
2342
- ),
2343
- ...imgProps
2344
- }
2345
- );
2346
- }
2347
- case "error": {
2348
- const jsxFallback = fallbacks.find((f) => typeof f !== "string");
2349
- return jsxFallback ?? /* @__PURE__ */ jsx7("div", { className: "bg-muted flex h-full w-full items-center justify-center rounded-md text-sm", children: alt?.[0] ?? "?" });
2350
- }
2351
- }
2352
- };
2353
- return /* @__PURE__ */ jsx7("div", { className: cn("relative overflow-hidden", wrapperClassName), children: renderContent() });
2354
- }
2355
-
2356
- // src/grid/editors/image-editor.tsx
2357
- import { Fragment as Fragment2, jsx as jsx8, jsxs as jsxs3 } from "react/jsx-runtime";
2358
- function normalizeUploadResponse(data) {
2359
- return { url: data.url, filename: data.filename, size: data.size, mime: data.mime };
2360
- }
2361
- var dropzoneTransition = { duration: 0.15, ease: [0.2, 0, 0, 1] };
2362
- function RemoveButton({ onClick, label }) {
2363
- return /* @__PURE__ */ jsx8("div", { className: "absolute top-2 right-2", children: /* @__PURE__ */ jsx8(
2364
- "button",
2365
- {
2366
- type: "button",
2367
- className: "flex size-7 cursor-pointer items-center justify-center rounded-full\n border border-black/10 bg-white/70 text-black/50 shadow-xs backdrop-blur-sm\n transition-[color,background-color,border-color,box-shadow] outline-hidden hover:bg-white/90 hover:text-black/70\n dark:border-white/10 dark:bg-black/50 dark:text-white/70\n dark:hover:bg-black/70 dark:hover:text-white/90\n focus-visible:ring-ring/50 focus-visible:ring-[3px]",
2368
- onClick: (e) => {
2369
- e.stopPropagation();
2370
- onClick();
2371
- },
2372
- "aria-label": label,
2373
- children: /* @__PURE__ */ jsx8(XIcon2, { className: "size-3.5", "aria-hidden": "true" })
2374
- }
2375
- ) });
2376
- }
2377
- function FilePreview({ name, size, mime }) {
2378
- const hasMime = !!mime && mime !== "unknown";
2379
- return /* @__PURE__ */ jsxs3("div", { className: "flex size-full flex-col items-center justify-center gap-2 p-4 text-center", children: [
2380
- /* @__PURE__ */ jsx8("div", { className: "bg-muted/60 flex size-12 shrink-0 items-center justify-center rounded-lg", "aria-hidden": "true", children: /* @__PURE__ */ jsx8(FileIcon, { className: "text-muted-foreground size-6" }) }),
2381
- /* @__PURE__ */ jsxs3("div", { className: "min-w-0 max-w-full", children: [
2382
- /* @__PURE__ */ jsx8("p", { className: "truncate text-sm font-medium", title: name, children: name || "File" }),
2383
- (size || hasMime) && /* @__PURE__ */ jsxs3("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
2384
- size ? formatFileSize(size) : null,
2385
- size && hasMime ? " \u2022 " : null,
2386
- hasMime ? /* @__PURE__ */ jsx8("span", { className: "uppercase", children: mime }) : null
2387
- ] })
2388
- ] })
2389
- ] });
2390
- }
2391
- var ImageEditor = ({
2392
- value,
2393
- onFinishedEditing,
2394
- tableName,
2395
- fieldName,
2396
- recordId,
2397
- onSaveComplete,
2398
- isDraftRow = false,
2399
- onSubmitDraft,
2400
- onDraftUploadComplete,
2401
- acceptAnyFile = false
2402
- }) => {
2403
- const noun = acceptAnyFile ? "file" : "image";
2404
- const Noun = acceptAnyFile ? "File" : "Image";
2405
- const [uploadState, setUploadState] = useState5("idle");
2406
- const { config } = useSheetsContext();
2407
- const storeApi = useSheetsStoreApi();
2408
- const { maxHeight: overlayMaxHeight } = useContext2(OverlayMeasureContext);
2409
- const getToken = useMemo8(() => {
2410
- if (config.auth.mode === "embedded") return config.auth.getToken;
2411
- return () => storeApi.getState().accessToken;
2412
- }, [config.auth, storeApi]);
2413
- const fileInputRef = useRef5(null);
2414
- const previewUrlRef = useRef5(null);
2415
- const committedRecordIdRef = useRef5(null);
2416
- const currentImageData = value ?? null;
2417
- const [imageValue, setImageValue] = useState5(currentImageData);
2418
- const [selectedFile, setSelectedFile] = useState5(null);
2419
- const [previewUrl, setPreviewUrl] = useState5(null);
2420
- const [uploadProgress, setUploadProgress] = useState5(null);
2421
- const [isDragging, setIsDragging] = useState5(false);
2422
- const [dragErrors, setDragErrors] = useState5([]);
2423
- const isSubmittingDraft = uploadState === "submitting-draft";
2424
- const isUploading = uploadState === "uploading";
2425
- const isBusy = uploadState !== "idle";
2426
- const imageUrl = useMemo8(() => getImageUrl(imageValue), [imageValue]);
2427
- const imageMetadata = useMemo8(() => getImageMetadata(imageValue), [imageValue]);
2428
- const storedMime = imageMetadata?.mime;
2429
- const storedIsImage = !acceptAnyFile || !!storedMime && storedMime.startsWith("image/");
2430
- const imageStatus = useImageStatus(storedIsImage ? imageUrl || void 0 : void 0);
2431
- const imageLoadFailed = storedIsImage && imageUrl != null && imageStatus === "error";
2432
- const hasImage = imageUrl != null && !imageLoadFailed && storedIsImage;
2433
- const revokePreviewUrl = useCallback3(() => {
2434
- if (previewUrlRef.current) {
2435
- URL.revokeObjectURL(previewUrlRef.current);
2436
- previewUrlRef.current = null;
2437
- }
2438
- }, []);
2439
- const resetFileState = useCallback3(() => {
2440
- revokePreviewUrl();
2441
- setUploadProgress(null);
2442
- setSelectedFile(null);
2443
- setPreviewUrl(null);
2444
- setUploadState("idle");
2445
- }, [revokePreviewUrl]);
2446
- const handleUploadSuccess = useCallback3((data) => {
2447
- const normalized = normalizeUploadResponse(data);
2448
- resetFileState();
2449
- setImageValue(normalized);
2450
- onSaveComplete?.({ imageData: normalized });
2451
- onFinishedEditing();
2452
- toast.success({ message: `${Noun} uploaded successfully` });
2453
- }, [resetFileState, onSaveComplete, onFinishedEditing, Noun]);
2454
- const handleUploadError = useCallback3((error) => {
2455
- setUploadState("idle");
2456
- sheetsLogger().error("[image-editor] upload failed:", error);
2457
- toast.error({ message: error.message || "Upload failed" });
2458
- }, []);
2459
- const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId || "", {
2460
- onProgress: setUploadProgress,
2461
- onSuccess: handleUploadSuccess,
2462
- onError: handleUploadError,
2463
- showToast: false
2464
- });
2465
- const handleRemoveImage = useCallback3(() => {
2466
- setImageValue(null);
2467
- setSelectedFile(null);
2468
- setPreviewUrl(null);
2469
- }, []);
2470
- const handleFileSelection = useCallback3((acceptedFiles) => {
2471
- if (acceptedFiles.length === 0) return;
2472
- const file = acceptedFiles[0];
2473
- if (!acceptAnyFile) {
2474
- if (!file.type.startsWith("image/")) {
2475
- toast.error({ message: "Please select an image file" });
2476
- return;
2477
- }
2478
- if (file.size > 10 * 1024 * 1024) {
2479
- toast.error({ message: "File size must be less than 10MB" });
2480
- return;
2481
- }
2482
- }
2483
- revokePreviewUrl();
2484
- setSelectedFile(file);
2485
- const url = URL.createObjectURL(file);
2486
- previewUrlRef.current = url;
2487
- setPreviewUrl(url);
2488
- }, [revokePreviewUrl, acceptAnyFile]);
2489
- const handleDragEnter = useCallback3((e) => {
2490
- e.preventDefault();
2491
- e.stopPropagation();
2492
- setIsDragging(true);
2493
- }, []);
2494
- const handleDragLeave = useCallback3((e) => {
2495
- e.preventDefault();
2496
- e.stopPropagation();
2497
- setIsDragging(false);
2498
- }, []);
2499
- const handleDragOver = useCallback3((e) => {
2500
- e.preventDefault();
2501
- e.stopPropagation();
2502
- }, []);
2503
- const handleDrop = useCallback3((e) => {
2504
- e.preventDefault();
2505
- e.stopPropagation();
2506
- setIsDragging(false);
2507
- setDragErrors([]);
2508
- const files = Array.from(e.dataTransfer.files);
2509
- if (files.length > 0) handleFileSelection(files);
2510
- }, [handleFileSelection]);
2511
- const openFileDialog = useCallback3(() => fileInputRef.current?.click(), []);
2512
- const removeFile = useCallback3(() => {
2513
- revokePreviewUrl();
2514
- setSelectedFile(null);
2515
- setPreviewUrl(null);
2516
- setDragErrors([]);
2517
- }, [revokePreviewUrl]);
2518
- const handleConfirmUpload = useCallback3(async () => {
2519
- if (!tableName || !fieldName || !selectedFile) return;
2520
- const committedId = committedRecordIdRef.current ?? recordId;
2521
- if (committedRecordIdRef.current != null) {
2522
- try {
2523
- toast.info({ message: `Uploading ${noun}...` });
2524
- setUploadState("uploading");
2525
- const uploadResult = await executeFieldUpload(
2526
- tableName,
2527
- fieldName,
2528
- committedRecordIdRef.current,
2529
- selectedFile,
2530
- config.endpoint,
2531
- getToken,
2532
- void 0,
2533
- { onAuthError: config.onAuthError }
2534
- );
2535
- const normalized = normalizeUploadResponse(uploadResult);
2536
- resetFileState();
2537
- setImageValue(normalized);
2538
- onDraftUploadComplete?.();
2539
- toast.success({ message: `${Noun} uploaded successfully` });
2540
- onFinishedEditing();
2541
- } catch (error) {
2542
- onDraftUploadComplete?.();
2543
- setUploadState("idle");
2544
- toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
2545
- }
2546
- return;
2547
- }
2548
- if (isDraftRow) {
2549
- if (!onSubmitDraft) {
2550
- toast.error({ message: "Cannot upload to draft row - save the row first" });
2551
- return;
2552
- }
2553
- try {
2554
- toast.info({ message: "Creating row..." });
2555
- setUploadState("submitting-draft");
2556
- const result = await onSubmitDraft();
2557
- const createdId = result.createdRow?.id;
2558
- if (typeof createdId !== "string" && typeof createdId !== "number") {
2559
- throw new Error("Image uploads require a scalar id primary key.");
2560
- }
2561
- committedRecordIdRef.current = createdId;
2562
- toast.info({ message: `Uploading ${noun}...` });
2563
- setUploadState("uploading");
2564
- const uploadResult = await executeFieldUpload(
2565
- tableName,
2566
- fieldName,
2567
- createdId,
2568
- selectedFile,
2569
- config.endpoint,
2570
- getToken,
2571
- void 0,
2572
- { onAuthError: config.onAuthError }
2573
- );
2574
- const normalized = normalizeUploadResponse(uploadResult);
2575
- resetFileState();
2576
- setImageValue(normalized);
2577
- onDraftUploadComplete?.();
2578
- toast.success({ message: `Row created and ${noun} uploaded` });
2579
- onFinishedEditing();
2580
- } catch (error) {
2581
- onDraftUploadComplete?.();
2582
- setUploadState("idle");
2583
- toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
2584
- }
2585
- return;
2586
- }
2587
- if (!committedId) {
2588
- toast.error({ message: "Missing record context for upload" });
2589
- return;
2590
- }
2591
- setUploadState("uploading");
2592
- uploadMutation.mutate(selectedFile);
2593
- }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing, noun, Noun]);
2594
- const handleSave = useCallback3(() => {
2595
- if (!imageValue) {
2596
- onFinishedEditing(null);
2597
- return;
2598
- }
2599
- const url = getImageUrl(imageValue);
2600
- const originalUrl = getImageUrl(value);
2601
- if (url && originalUrl === url) {
2602
- onFinishedEditing();
2603
- return;
2604
- }
2605
- onFinishedEditing(url ?? value);
2606
- }, [imageValue, value, onFinishedEditing]);
2607
- const handleCancel = useCallback3(() => {
2608
- revokePreviewUrl();
2609
- onFinishedEditing();
2610
- }, [revokePreviewUrl, onFinishedEditing]);
2611
- useEffect4(() => () => revokePreviewUrl(), [revokePreviewUrl]);
2612
- const handleEditorKeyDown = useCallback3((e) => {
2613
- if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
2614
- e.preventDefault();
2615
- handleSave();
2616
- }
2617
- }, [handleSave]);
2618
- const hasStoredFile = acceptAnyFile && !!imageUrl && !storedIsImage;
2619
- const dropzoneKey = isBusy ? "busy" : previewUrl ? "preview" : hasImage ? "loaded" : hasStoredFile ? "file" : imageLoadFailed ? "broken" : "empty";
2620
- const renderDropzoneContent = () => {
2621
- if (isBusy) {
2622
- return /* @__PURE__ */ jsxs3("div", { "data-state": uploadState, className: "text-muted-foreground flex w-full flex-col items-center justify-center p-6", children: [
2623
- /* @__PURE__ */ jsx8(Loader22, { className: "mb-2 size-6 animate-spin" }),
2624
- /* @__PURE__ */ jsx8("p", { className: "text-sm", children: isSubmittingDraft ? "Creating row..." : `Uploading ${noun}...` }),
2625
- isUploading && uploadProgress && /* @__PURE__ */ jsxs3("div", { className: "mt-3 w-full max-w-xs", children: [
2626
- /* @__PURE__ */ jsx8("div", { className: "bg-muted h-1.5 overflow-hidden rounded-full", children: /* @__PURE__ */ jsx8(
2627
- "div",
2628
- {
2629
- className: "bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)",
2630
- style: { width: `${uploadProgress.percentage}%` }
2631
- }
2632
- ) }),
2633
- /* @__PURE__ */ jsxs3("p", { className: "text-muted-foreground mt-1.5 text-center text-xs", children: [
2634
- Math.round(uploadProgress.percentage),
2635
- "%"
2636
- ] })
2637
- ] })
2638
- ] });
2639
- }
2640
- if (previewUrl) {
2641
- const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
2642
- return /* @__PURE__ */ jsxs3("div", { className: "relative w-full", style: { height: "13rem" }, children: [
2643
- selectedIsImage ? /* @__PURE__ */ jsx8("img", { src: previewUrl, alt: selectedFile?.name || "Selected file", className: "size-full object-contain p-2" }) : /* @__PURE__ */ jsx8(FilePreview, { name: selectedFile?.name, size: selectedFile?.size, mime: selectedFile?.type }),
2644
- /* @__PURE__ */ jsx8(RemoveButton, { onClick: removeFile, label: "Remove selected file" })
2645
- ] });
2646
- }
2647
- if (hasImage) {
2648
- return /* @__PURE__ */ jsxs3("div", { className: "relative w-full", style: { height: "13rem" }, children: [
2649
- /* @__PURE__ */ jsx8(
2650
- ImageWithFallback,
2651
- {
2652
- src: imageUrl,
2653
- alt: imageMetadata?.filename || "Preview",
2654
- className: "size-full object-contain p-2",
2655
- wrapperClassName: "w-full h-full",
2656
- loadingElement: /* @__PURE__ */ jsx8(Skeleton, { className: "absolute inset-0 h-full w-full rounded-md" })
2657
- }
2658
- ),
2659
- /* @__PURE__ */ jsx8(RemoveButton, { onClick: handleRemoveImage, label: "Remove image" })
2660
- ] });
2661
- }
2662
- if (hasStoredFile) {
2663
- return /* @__PURE__ */ jsxs3("div", { className: "relative w-full", style: { height: "13rem" }, children: [
2664
- /* @__PURE__ */ jsx8(FilePreview, { name: imageMetadata?.filename, size: imageMetadata?.size, mime: imageMetadata?.mime }),
2665
- /* @__PURE__ */ jsx8(RemoveButton, { onClick: handleRemoveImage, label: "Remove file" })
2666
- ] });
2667
- }
2668
- if (imageLoadFailed) {
2669
- return /* @__PURE__ */ jsxs3("div", { className: "flex w-full flex-col items-center justify-center px-4 py-6 text-center", children: [
2670
- /* @__PURE__ */ jsx8(
2671
- "div",
2672
- {
2673
- className: "mb-3 flex size-10 shrink-0 items-center justify-center rounded-full\n border border-dashed border-amber-500/25 bg-amber-500/[0.06]",
2674
- "aria-hidden": "true",
2675
- children: /* @__PURE__ */ jsx8(ImageOff, { className: "size-4 text-amber-500/50" })
2676
- }
2677
- ),
2678
- /* @__PURE__ */ jsx8("p", { className: "text-sm font-medium", children: "Image unavailable" }),
2679
- imageUrl && /* @__PURE__ */ jsx8(
2680
- "p",
2681
- {
2682
- className: "text-muted-foreground mt-1 max-w-full truncate font-mono text-[11px] opacity-50",
2683
- title: imageUrl,
2684
- children: imageUrl
2685
- }
2686
- ),
2687
- /* @__PURE__ */ jsxs3("div", { className: "mt-3 flex items-center gap-2", children: [
2688
- /* @__PURE__ */ jsxs3(
2689
- Button3,
2690
- {
2691
- variant: "outline",
2692
- size: "sm",
2693
- onClick: (e) => {
2694
- e.stopPropagation();
2695
- openFileDialog();
2696
- },
2697
- children: [
2698
- /* @__PURE__ */ jsx8(UploadIcon, { className: "-ms-0.5 opacity-60", "aria-hidden": "true" }),
2699
- "Replace"
2700
- ]
2701
- }
2702
- ),
2703
- /* @__PURE__ */ jsx8(
2704
- Button3,
2705
- {
2706
- variant: "ghost",
2707
- size: "sm",
2708
- className: "text-muted-foreground",
2709
- onClick: (e) => {
2710
- e.stopPropagation();
2711
- handleRemoveImage();
2712
- },
2713
- children: "Clear"
2714
- }
2715
- )
2716
- ] })
2717
- ] });
2718
- }
2719
- return /* @__PURE__ */ jsxs3("div", { className: "flex w-full flex-col items-center justify-center px-4 py-6 text-center", children: [
2720
- /* @__PURE__ */ jsx8("div", { className: "bg-muted/60 mb-3 flex size-10 shrink-0 items-center justify-center rounded-full", "aria-hidden": "true", children: /* @__PURE__ */ jsx8(UploadIcon, { className: "text-muted-foreground size-4" }) }),
2721
- /* @__PURE__ */ jsxs3("p", { className: "text-sm font-medium", children: [
2722
- "Drop ",
2723
- noun,
2724
- " here or browse"
2725
- ] }),
2726
- /* @__PURE__ */ jsx8("p", { className: "text-muted-foreground mt-1 text-xs", children: acceptAnyFile ? "Any file type" : "SVG, PNG, JPG or GIF (max. 10MB)" }),
2727
- /* @__PURE__ */ jsxs3(
2728
- Button3,
2729
- {
2730
- variant: "outline",
2731
- size: "sm",
2732
- className: "mt-3",
2733
- onClick: (e) => {
2734
- e.stopPropagation();
2735
- openFileDialog();
2736
- },
2737
- disabled: isBusy,
2738
- children: [
2739
- /* @__PURE__ */ jsx8(UploadIcon, { className: "-ms-0.5 opacity-60", "aria-hidden": "true" }),
2740
- "Select ",
2741
- noun
2742
- ]
2743
- }
2744
- )
2745
- ] });
2746
- };
2747
- const saveLabel = isSubmittingDraft ? "Creating..." : isUploading ? "Uploading..." : imageUrl ? "Save" : "Done";
2748
- return /* @__PURE__ */ jsx8(
2749
- EditorFocusTrap,
2750
- {
2751
- onEscape: handleCancel,
2752
- className: `bg-popover flex ${OVERLAY.lg} flex-col gap-0 overflow-hidden rounded-lg border p-0 shadow-lg`,
2753
- style: overlayMaxHeight > 0 ? { maxHeight: overlayMaxHeight } : void 0,
2754
- children: /* @__PURE__ */ jsxs3("div", { onKeyDown: handleEditorKeyDown, className: "flex min-h-0 flex-1 flex-col", children: [
2755
- /* @__PURE__ */ jsxs3("div", { className: "flex shrink-0 items-center gap-2 border-b px-6 py-3", children: [
2756
- acceptAnyFile ? /* @__PURE__ */ jsx8(FileIcon, { className: "text-muted-foreground size-4" }) : /* @__PURE__ */ jsx8(ImageIcon, { className: "text-muted-foreground size-4" }),
2757
- /* @__PURE__ */ jsx8("h3", { className: "text-sm font-medium", children: imageUrl ? `Edit ${Noun}` : `Add ${Noun}` })
2758
- ] }),
2759
- /* @__PURE__ */ jsx8(
2760
- "input",
2761
- {
2762
- ref: fileInputRef,
2763
- type: "file",
2764
- accept: acceptAnyFile ? void 0 : "image/*",
2765
- className: "hidden",
2766
- "aria-label": `Upload ${noun}`,
2767
- tabIndex: -1,
2768
- onChange: (e) => {
2769
- const files = Array.from(e.target.files || []);
2770
- if (files.length > 0) handleFileSelection(files);
2771
- e.target.value = "";
2772
- }
2773
- }
2774
- ),
2775
- /* @__PURE__ */ jsx8("div", { className: "min-h-0 flex-1 overflow-y-auto", children: /* @__PURE__ */ jsxs3("div", { className: "p-4", children: [
2776
- /* @__PURE__ */ jsx8(
2777
- "div",
2778
- {
2779
- onDragEnter: handleDragEnter,
2780
- onDragLeave: handleDragLeave,
2781
- onDragOver: handleDragOver,
2782
- onDrop: handleDrop,
2783
- "data-dragging": isDragging || void 0,
2784
- className: "bg-muted/20 hover:bg-muted/30 data-[dragging=true]:bg-accent/50 data-[dragging=true]:border-primary/40\n relative flex cursor-pointer flex-col items-center justify-center overflow-hidden rounded-lg\n border border-dashed border-border/60 transition-colors",
2785
- style: { height: "13rem" },
2786
- onClick: isBusy ? void 0 : openFileDialog,
2787
- children: /* @__PURE__ */ jsx8(AnimatePresence, { mode: "wait", initial: false, children: /* @__PURE__ */ jsx8(
2788
- motion.div,
2789
- {
2790
- initial: { opacity: 0 },
2791
- animate: { opacity: 1 },
2792
- exit: { opacity: 0 },
2793
- transition: dropzoneTransition,
2794
- className: "w-full",
2795
- children: renderDropzoneContent()
2796
- },
2797
- dropzoneKey
2798
- ) })
2799
- }
2800
- ),
2801
- dragErrors.length > 0 && /* @__PURE__ */ jsxs3("div", { className: "text-destructive mt-2 flex items-center gap-1.5 text-xs", role: "alert", children: [
2802
- /* @__PURE__ */ jsx8(AlertCircleIcon, { className: "size-3 shrink-0" }),
2803
- /* @__PURE__ */ jsx8("span", { children: dragErrors[0] })
2804
- ] }),
2805
- !isBusy && (selectedFile || imageMetadata && hasImage) && /* @__PURE__ */ jsx8("div", { className: "text-muted-foreground mt-2 text-center text-xs", children: selectedFile ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
2806
- /* @__PURE__ */ jsx8("span", { className: "font-medium", children: selectedFile.name }),
2807
- " \u2022 ",
2808
- /* @__PURE__ */ jsx8("span", { children: formatFileSize(selectedFile.size) }),
2809
- " \u2022 ",
2810
- /* @__PURE__ */ jsx8("span", { className: "uppercase", children: selectedFile.type })
2811
- ] }) : imageMetadata ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
2812
- /* @__PURE__ */ jsx8("span", { className: "font-medium", children: imageMetadata.filename }),
2813
- imageMetadata.size ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
2814
- " \u2022 ",
2815
- /* @__PURE__ */ jsx8("span", { children: formatFileSize(imageMetadata.size) })
2816
- ] }) : null,
2817
- imageMetadata.mime ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
2818
- " \u2022 ",
2819
- /* @__PURE__ */ jsx8("span", { className: "uppercase", children: imageMetadata.mime })
2820
- ] }) : null
2821
- ] }) : null })
2822
- ] }) }),
2823
- /* @__PURE__ */ jsxs3("div", { className: "flex shrink-0 justify-end gap-2 border-t px-6 py-3", children: [
2824
- /* @__PURE__ */ jsx8(Button3, { type: "button", variant: "outline", size: "sm", onClick: handleCancel, disabled: isBusy, children: "Cancel" }),
2825
- selectedFile && !isBusy ? /* @__PURE__ */ jsx8(Button3, { type: "button", size: "sm", onClick: handleConfirmUpload, children: isDraftRow ? "Create Row & Upload" : "Upload & Save" }) : /* @__PURE__ */ jsxs3(Button3, { type: "button", size: "sm", onClick: handleSave, disabled: isBusy, children: [
2826
- isBusy && /* @__PURE__ */ jsx8(Loader22, { className: "size-3.5 animate-spin" }),
2827
- saveLabel
2828
- ] })
2829
- ] })
2830
- ] })
2831
- }
2832
- );
2833
- };
2834
-
2835
- // src/grid-dom/editors/image-editor.tsx
2836
- import { jsx as jsx9 } from "react/jsx-runtime";
2837
- var DRAFT_PREFIX = "draft:";
2838
- function ImageEditorDom({
2839
- value,
2840
- cell,
2841
- colKey,
2842
- rowId,
2843
- tableName,
2844
- onCommitPatch,
2845
- onCancel,
2846
- onSubmitDraftRow,
2847
- onInvalidateData
2848
- }) {
2849
- const isDraftRow = rowId.startsWith(DRAFT_PREFIX);
2850
- const cellType = cell.meta?.cellType;
2851
- const acceptAnyFile = cellType != null && cellType !== "image";
2852
- const handleSaveComplete = onCommitPatch ? (saveData) => onCommitPatch({ [colKey]: saveData.imageData }) : void 0;
2853
- const handleSubmitDraft = isDraftRow && onSubmitDraftRow ? async () => {
2854
- const createdRow = await onSubmitDraftRow(rowId);
2855
- return { createdRow };
2856
- } : void 0;
2857
- return /* @__PURE__ */ jsx9("div", { "data-slot": "image-editor", children: /* @__PURE__ */ jsx9(Suspense4, { fallback: /* @__PURE__ */ jsx9("div", { className: "h-64 w-full min-w-[480px] animate-pulse rounded-lg bg-muted" }), children: /* @__PURE__ */ jsx9(
2858
- ImageEditor,
2859
- {
2860
- value,
2861
- acceptAnyFile,
2862
- onFinishedEditing: () => onCancel(),
2863
- tableName,
2864
- fieldName: colKey,
2865
- recordId: rowId,
2866
- onSaveComplete: handleSaveComplete,
2867
- isDraftRow,
2868
- onSubmitDraft: handleSubmitDraft,
2869
- onDraftUploadComplete: onInvalidateData
2870
- }
2871
- ) }) });
2872
- }
2873
-
2874
- // src/grid/editors/inet-editor.tsx
2875
- import { useCallback as useCallback4, useEffect as useEffect5, useRef as useRef6, useState as useState6 } from "react";
2876
- import { Button as Button4 } from "@constructive-io/ui/button";
2877
- import { jsx as jsx10, jsxs as jsxs4 } from "react/jsx-runtime";
2878
- var IPV4_RE = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/;
2879
- var IPV6_FULL_RE = /^(?:[0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$|^::1$|^::$/;
2880
- var IPV6_COMPRESSED_RE = /^([0-9a-fA-F]{1,4}:)*::([0-9a-fA-F]{1,4}:)*[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:)*::[0-9a-fA-F]{1,4}$|^([0-9a-fA-F]{1,4}:)*::$/;
2881
- var MAC_UA_RE2 = /Mac|iPod|iPhone|iPad/;
2882
- function isValidIPv4(ip) {
2883
- return IPV4_RE.test(ip);
2884
- }
2885
- function isValidIPv6(ip) {
2886
- return IPV6_FULL_RE.test(ip) || IPV6_COMPRESSED_RE.test(ip);
2887
- }
2888
- function isValidCIDR(cidr) {
2889
- const parts = cidr.split("/");
2890
- if (parts.length !== 2) return false;
2891
- const [ip, prefix] = parts;
2892
- const prefixNum = parseInt(prefix, 10);
2893
- if (isValidIPv4(ip)) {
2894
- return prefixNum >= 0 && prefixNum <= 32;
2895
- } else if (isValidIPv6(ip)) {
2896
- return prefixNum >= 0 && prefixNum <= 128;
2897
- }
2898
- return false;
2899
- }
2900
- function isValidInet(value) {
2901
- if (!value || typeof value !== "string") return false;
2902
- const trimmed = value.trim();
2903
- if (trimmed.includes("/")) {
2904
- return isValidCIDR(trimmed);
2905
- }
2906
- return isValidIPv4(trimmed) || isValidIPv6(trimmed);
2907
- }
2908
- function getInetType(value) {
2909
- if (!value) return "";
2910
- const trimmed = value.trim();
2911
- if (trimmed.includes("/")) {
2912
- const [ip] = trimmed.split("/");
2913
- if (isValidIPv4(ip)) return "IPv4 Network";
2914
- if (isValidIPv6(ip)) return "IPv6 Network";
2915
- } else {
2916
- if (isValidIPv4(trimmed)) return "IPv4 Address";
2917
- if (isValidIPv6(trimmed)) return "IPv6 Address";
2918
- }
2919
- return "Invalid";
2920
- }
2921
- var InetEditor = ({ value, onFinishedEditing }) => {
2922
- const currentInetData = typeof value === "string" ? value : "";
2923
- const [editingValue, setEditingValue] = useState6(currentInetData);
2924
- const [validationError, setValidationError] = useState6("");
2925
- const keyContainerRef = useRef6(null);
2926
- const handleSave = useCallback4(() => {
2927
- if (editingValue.trim() && !isValidInet(editingValue.trim())) {
2928
- setValidationError("Invalid IP address or CIDR");
2929
- return;
2930
- }
2931
- onFinishedEditing(editingValue.trim());
2932
- }, [editingValue, onFinishedEditing]);
2933
- const handleCancel = useCallback4(() => {
2934
- onFinishedEditing();
2935
- }, [onFinishedEditing]);
2936
- const handleInputChange = useCallback4((e) => {
2937
- setEditingValue(e.target.value);
2938
- setValidationError("");
2939
- }, []);
2940
- const actionsRef = useRef6({ handleSave, handleCancel });
2941
- actionsRef.current = { handleSave, handleCancel };
2942
- useEffect5(() => {
2943
- const el = keyContainerRef.current;
2944
- if (!el) return;
2945
- const handler = (e) => {
2946
- const { handleSave: handleSave2, handleCancel: handleCancel2 } = actionsRef.current;
2947
- if (e.key === "Escape") {
2948
- e.preventDefault();
2949
- e.stopPropagation();
2950
- handleCancel2();
2951
- return;
2952
- }
2953
- if (e.key === "Enter" && !e.metaKey && !e.ctrlKey) {
2954
- e.preventDefault();
2955
- e.stopPropagation();
2956
- handleSave2();
2957
- return;
2958
- }
2959
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey) || e.key === "s" && (e.metaKey || e.ctrlKey)) {
2960
- e.preventDefault();
2961
- e.stopPropagation();
2962
- handleSave2();
2963
- return;
2964
- }
2965
- if (e.key === "Tab") {
2966
- e.stopPropagation();
2967
- }
2968
- };
2969
- el.addEventListener("keydown", handler);
2970
- return () => el.removeEventListener("keydown", handler);
2971
- }, []);
2972
- const trimmed = editingValue.trim();
2973
- const isValid = !trimmed || isValidInet(trimmed);
2974
- const inetType = trimmed ? getInetType(trimmed) : "";
2975
- const isMac = typeof navigator !== "undefined" && MAC_UA_RE2.test(navigator.userAgent);
2976
- const modKey = isMac ? "\u2318" : "Ctrl";
2977
- return /* @__PURE__ */ jsx10(
2978
- EditorFocusTrap,
2979
- {
2980
- onEscape: handleCancel,
2981
- className: `bg-popover ${OVERLAY.sm} rounded-lg border p-2.5 shadow-lg`,
2982
- children: /* @__PURE__ */ jsxs4("div", { ref: keyContainerRef, children: [
2983
- /* @__PURE__ */ jsxs4("div", { className: "space-y-1.5", children: [
2984
- /* @__PURE__ */ jsx10("div", { className: "relative", children: /* @__PURE__ */ jsx10(
2985
- "input",
2986
- {
2987
- type: "text",
2988
- value: editingValue,
2989
- onChange: handleInputChange,
2990
- placeholder: "192.168.1.1 or 10.0.0.0/24",
2991
- className: "bg-muted/40 border-border/40 text-foreground w-full rounded-md border px-3 py-2 font-mono text-sm outline-none focus-visible:border-ring/60 focus-visible:ring-[3px] focus-visible:ring-ring/35",
2992
- autoFocus: true
2993
- }
2994
- ) }),
2995
- /* @__PURE__ */ jsx10("div", { className: "flex items-center gap-2 px-0.5", children: validationError ? /* @__PURE__ */ jsx10("span", { className: "text-destructive text-xs", children: validationError }) : trimmed && isValid && inetType ? /* @__PURE__ */ jsx10("span", { className: "text-muted-foreground text-xs tabular-nums", children: inetType }) : trimmed && !isValid ? /* @__PURE__ */ jsx10("span", { className: "text-destructive text-xs", children: "Invalid format" }) : null })
2996
- ] }),
2997
- /* @__PURE__ */ jsxs4("div", { className: "mt-3 flex items-center justify-between gap-4 border-t px-1 pt-2.5", children: [
2998
- /* @__PURE__ */ jsxs4("div", { className: "text-muted-foreground flex items-center gap-3 text-xs", children: [
2999
- /* @__PURE__ */ jsxs4("span", { className: "inline-flex shrink-0 items-center gap-1", children: [
3000
- /* @__PURE__ */ jsx10("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight", children: "Enter" }),
3001
- /* @__PURE__ */ jsx10("span", { children: "save" })
3002
- ] }),
3003
- /* @__PURE__ */ jsxs4("span", { className: "inline-flex shrink-0 items-center gap-1", children: [
3004
- /* @__PURE__ */ jsx10("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight", children: "Esc" }),
3005
- /* @__PURE__ */ jsx10("span", { children: "cancel" })
3006
- ] })
3007
- ] }),
3008
- /* @__PURE__ */ jsx10(Button4, { onClick: handleSave, size: "xs", variant: "default", className: "shrink-0", disabled: !!validationError, children: "Save" })
3009
- ] })
3010
- ] })
3011
- }
3012
- );
3013
- };
3014
-
3015
- // src/grid-dom/editors/inet-editor.tsx
3016
- import { jsx as jsx11 } from "react/jsx-runtime";
3017
- function InetEditorDom({ value, onCommit, onCancel }) {
3018
- return /* @__PURE__ */ jsx11("div", { "data-slot": "inet-editor", children: /* @__PURE__ */ jsx11(
3019
- InetEditor,
3020
- {
3021
- value,
3022
- onFinishedEditing: (next) => next === void 0 ? onCancel() : onCommit(next)
3023
- }
3024
- ) });
3025
- }
3026
-
3027
- // src/grid/editors/interval-editor.tsx
3028
- import { useCallback as useCallback5, useState as useState7 } from "react";
3029
- import { Check, Clock, X } from "lucide-react";
3030
- import { Button as Button5 } from "@constructive-io/ui/button";
3031
- import { Input } from "@constructive-io/ui/input";
3032
- import { Label } from "@constructive-io/ui/label";
3033
- import { jsx as jsx12, jsxs as jsxs5 } from "react/jsx-runtime";
3034
- var INTERVAL_PATTERNS = [
3035
- { regex: /(\d+)\s*d(ays?)?/i, key: "days" },
3036
- { regex: /(\d+)\s*h(ours?)?/i, key: "hours" },
3037
- { regex: /(\d+)\s*m(in(utes?)?)?/i, key: "minutes" },
3038
- { regex: /(\d+)\s*s(ec(onds?)?)?/i, key: "seconds" }
3039
- ];
3040
- function parseIntervalValue(data) {
3041
- if (!data || typeof data !== "string") {
3042
- return { days: 0, hours: 0, minutes: 0, seconds: 0 };
3043
- }
3044
- try {
3045
- const parsed = JSON.parse(data);
3046
- if (typeof parsed === "object" && parsed !== null) {
3047
- return {
3048
- days: parsed.days || 0,
3049
- hours: parsed.hours || 0,
3050
- minutes: parsed.minutes || 0,
3051
- seconds: parsed.seconds || 0
3052
- };
3053
- }
3054
- } catch {
3055
- const interval = { days: 0, hours: 0, minutes: 0, seconds: 0 };
3056
- INTERVAL_PATTERNS.forEach(({ regex, key }) => {
3057
- const match = data.match(regex);
3058
- if (match) {
3059
- interval[key] = parseInt(match[1], 10);
3060
- }
3061
- });
3062
- return interval;
3063
- }
3064
- return { days: 0, hours: 0, minutes: 0, seconds: 0 };
3065
- }
3066
- function formatIntervalValue(interval) {
3067
- const parts = [];
3068
- if (interval.days && interval.days > 0) parts.push(`${interval.days}d`);
3069
- if (interval.hours && interval.hours > 0) parts.push(`${interval.hours}h`);
3070
- if (interval.minutes && interval.minutes > 0) parts.push(`${interval.minutes}m`);
3071
- if (interval.seconds && interval.seconds > 0) parts.push(`${interval.seconds}s`);
3072
- return parts.join(" ") || "0s";
3073
- }
3074
- var IntervalEditor = ({ value, onFinishedEditing }) => {
3075
- const currentIntervalData = typeof value === "string" ? value : "";
3076
- const [editingValue, setEditingValue] = useState7(() => parseIntervalValue(currentIntervalData));
3077
- const handleSave = useCallback5(() => {
3078
- onFinishedEditing(JSON.stringify(editingValue));
3079
- }, [editingValue, onFinishedEditing]);
3080
- const handleCancel = useCallback5(() => {
3081
- onFinishedEditing();
3082
- }, [onFinishedEditing]);
3083
- const handleInputChange = useCallback5((field, newValue) => {
3084
- const numValue = parseInt(newValue) || 0;
3085
- setEditingValue((prev) => ({
3086
- ...prev,
3087
- [field]: Math.max(0, numValue)
3088
- // Ensure non-negative values
3089
- }));
3090
- }, []);
3091
- const handleEditorKeyDown = useCallback5(
3092
- (e) => {
3093
- if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
3094
- e.preventDefault();
3095
- handleSave();
3096
- }
3097
- },
3098
- [handleSave]
3099
- );
3100
- const previewText = formatIntervalValue(editingValue);
3101
- return /* @__PURE__ */ jsx12(EditorFocusTrap, { onEscape: handleCancel, className: `bg-popover flex ${OVERLAY.sm} flex-col gap-4 rounded-lg border p-4 shadow-lg`, children: /* @__PURE__ */ jsxs5("div", { onKeyDown: handleEditorKeyDown, children: [
3102
- /* @__PURE__ */ jsxs5("div", { className: "flex items-center gap-2", children: [
3103
- /* @__PURE__ */ jsx12(Clock, { className: "text-muted-foreground h-4 w-4" }),
3104
- /* @__PURE__ */ jsx12("h3", { className: "text-sm font-medium", children: "Edit Time Interval" })
3105
- ] }),
3106
- /* @__PURE__ */ jsxs5("div", { className: "grid grid-cols-2 gap-3", children: [
3107
- /* @__PURE__ */ jsxs5("div", { className: "space-y-1", children: [
3108
- /* @__PURE__ */ jsx12(Label, { htmlFor: "days", className: "text-muted-foreground text-xs", children: "Days" }),
3109
- /* @__PURE__ */ jsx12(
3110
- Input,
3111
- {
3112
- id: "days",
3113
- type: "number",
3114
- min: "0",
3115
- value: editingValue.days || "",
3116
- onChange: (e) => handleInputChange("days", e.target.value),
3117
- className: "h-8 text-sm",
3118
- placeholder: "0"
3119
- }
3120
- )
3121
- ] }),
3122
- /* @__PURE__ */ jsxs5("div", { className: "space-y-1", children: [
3123
- /* @__PURE__ */ jsx12(Label, { htmlFor: "hours", className: "text-muted-foreground text-xs", children: "Hours" }),
3124
- /* @__PURE__ */ jsx12(
3125
- Input,
3126
- {
3127
- id: "hours",
3128
- type: "number",
3129
- min: "0",
3130
- max: "23",
3131
- value: editingValue.hours || "",
3132
- onChange: (e) => handleInputChange("hours", e.target.value),
3133
- className: "h-8 text-sm",
3134
- placeholder: "0"
3135
- }
3136
- )
3137
- ] }),
3138
- /* @__PURE__ */ jsxs5("div", { className: "space-y-1", children: [
3139
- /* @__PURE__ */ jsx12(Label, { htmlFor: "minutes", className: "text-muted-foreground text-xs", children: "Minutes" }),
3140
- /* @__PURE__ */ jsx12(
3141
- Input,
3142
- {
3143
- id: "minutes",
3144
- type: "number",
3145
- min: "0",
3146
- max: "59",
3147
- value: editingValue.minutes || "",
3148
- onChange: (e) => handleInputChange("minutes", e.target.value),
3149
- className: "h-8 text-sm",
3150
- placeholder: "0"
3151
- }
3152
- )
3153
- ] }),
3154
- /* @__PURE__ */ jsxs5("div", { className: "space-y-1", children: [
3155
- /* @__PURE__ */ jsx12(Label, { htmlFor: "seconds", className: "text-muted-foreground text-xs", children: "Seconds" }),
3156
- /* @__PURE__ */ jsx12(
3157
- Input,
3158
- {
3159
- id: "seconds",
3160
- type: "number",
3161
- min: "0",
3162
- max: "59",
3163
- value: editingValue.seconds || "",
3164
- onChange: (e) => handleInputChange("seconds", e.target.value),
3165
- className: "h-8 text-sm",
3166
- placeholder: "0"
3167
- }
3168
- )
3169
- ] })
3170
- ] }),
3171
- /* @__PURE__ */ jsxs5("div", { className: "space-y-1", children: [
3172
- /* @__PURE__ */ jsx12(Label, { className: "text-muted-foreground text-xs", children: "Preview" }),
3173
- /* @__PURE__ */ jsx12("div", { className: "bg-muted rounded px-3 py-2 font-mono text-sm", children: previewText })
3174
- ] }),
3175
- /* @__PURE__ */ jsxs5("div", { className: "flex justify-end gap-2", children: [
3176
- /* @__PURE__ */ jsxs5(Button5, { variant: "outline", size: "sm", onClick: handleCancel, children: [
3177
- /* @__PURE__ */ jsx12(X, { className: "mr-1 h-3 w-3" }),
3178
- "Cancel"
3179
- ] }),
3180
- /* @__PURE__ */ jsxs5(Button5, { size: "sm", onClick: handleSave, children: [
3181
- /* @__PURE__ */ jsx12(Check, { className: "mr-1 h-3 w-3" }),
3182
- "Save"
3183
- ] })
3184
- ] })
3185
- ] }) });
3186
- };
3187
-
3188
- // src/grid-dom/editors/interval-editor.tsx
3189
- import { jsx as jsx13 } from "react/jsx-runtime";
3190
- function IntervalEditorDom({ value, onCommit, onCancel }) {
3191
- return /* @__PURE__ */ jsx13(
3192
- IntervalEditor,
3193
- {
3194
- value,
3195
- onFinishedEditing: (next) => next === void 0 ? onCancel() : onCommit(next)
3196
- }
3197
- );
3198
- }
3199
-
3200
- // src/grid/editors/json-editor.tsx
3201
- import { useCallback as useCallback6, useEffect as useEffect6, useMemo as useMemo9, useRef as useRef7, useState as useState8 } from "react";
3202
- import { Button as Button6 } from "@constructive-io/ui/button";
3203
- import { jsx as jsx14, jsxs as jsxs6 } from "react/jsx-runtime";
3204
- var MAC_UA_RE3 = /Mac|iPod|iPhone|iPad/;
3205
- var JSON_HIGHLIGHT_STYLES = `
3206
- .json-highlight .jh-key { color: var(--color-foreground); }
3207
- .json-highlight .jh-str { color: oklch(0.72 0.14 168); }
3208
- .json-highlight .jh-num { color: oklch(0.7 0.14 250); }
3209
- .json-highlight .jh-bool { color: oklch(0.75 0.14 55); }
3210
- .json-highlight .jh-punct { color: var(--color-muted-foreground); }
3211
- @media (prefers-color-scheme: light) {
3212
- .json-highlight .jh-str { color: oklch(0.5 0.16 168); }
3213
- .json-highlight .jh-num { color: oklch(0.48 0.16 250); }
3214
- .json-highlight .jh-bool { color: oklch(0.55 0.16 55); }
3215
- }
3216
- `;
3217
- function highlightJson(json) {
3218
- const escaped = json.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
3219
- return escaped.replace(
3220
- // Match JSON tokens: strings, numbers, booleans, null, structural chars
3221
- /("(?:[^"\\]|\\.)*")\s*(?=:)|("(?:[^"\\]|\\.)*")|(-?\d+(?:\.\d+)?(?:[eE][+-]?\d+)?)\b|(true|false|null)\b|([{}[\]:,])/g,
3222
- (match, key, str, num, bool, punct) => {
3223
- if (key !== void 0) return `<span class="jh-key">${key}</span>`;
3224
- if (str !== void 0) return `<span class="jh-str">${str}</span>`;
3225
- if (num !== void 0) return `<span class="jh-num">${num}</span>`;
3226
- if (bool !== void 0) return `<span class="jh-bool">${bool}</span>`;
3227
- if (punct !== void 0) return `<span class="jh-punct">${punct}</span>`;
3228
- return match;
3229
- }
3230
- );
3231
- }
3232
- function JsonEditor({ value, onChange, onFinished }) {
3233
- const [text, setText] = useState8(() => typeof value === "string" ? value : JSON.stringify(value, null, 2));
3234
- const textareaRef = useRef7(null);
3235
- const preRef = useRef7(null);
3236
- const keyContainerRef = useRef7(null);
3237
- const { parsed, valid } = useMemo9(() => {
3238
- try {
3239
- return { parsed: JSON.parse(text), valid: true };
3240
- } catch {
3241
- return { parsed: text, valid: false };
3242
- }
3243
- }, [text]);
3244
- const handleChange = useCallback6(
3245
- (e) => {
3246
- const next = e.target.value;
3247
- setText(next);
3248
- try {
3249
- onChange(JSON.parse(next));
3250
- } catch {
3251
- }
3252
- },
3253
- [onChange]
3254
- );
3255
- const handleCancel = useCallback6(() => onFinished(void 0), [onFinished]);
3256
- const handleSave = useCallback6(() => {
3257
- if (valid) onFinished(parsed);
3258
- }, [onFinished, parsed, valid]);
3259
- const handleScroll = useCallback6(() => {
3260
- const ta = textareaRef.current;
3261
- const pre = preRef.current;
3262
- if (ta && pre) {
3263
- pre.scrollTop = ta.scrollTop;
3264
- pre.scrollLeft = ta.scrollLeft;
3265
- }
3266
- }, []);
3267
- const actionsRef = useRef7({ handleSave, handleCancel });
3268
- actionsRef.current = { handleSave, handleCancel };
3269
- useEffect6(() => {
3270
- const el = keyContainerRef.current;
3271
- if (!el) return;
3272
- const handler = (e) => {
3273
- const { handleSave: handleSave2, handleCancel: handleCancel2 } = actionsRef.current;
3274
- if (e.key === "Escape") {
3275
- e.preventDefault();
3276
- e.stopPropagation();
3277
- handleCancel2();
3278
- return;
3279
- }
3280
- if (e.key === "Enter" && (e.metaKey || e.ctrlKey) || e.key === "s" && (e.metaKey || e.ctrlKey)) {
3281
- e.preventDefault();
3282
- e.stopPropagation();
3283
- handleSave2();
3284
- return;
3285
- }
3286
- if (e.key === "Tab") {
3287
- e.stopPropagation();
3288
- e.preventDefault();
3289
- const ta = textareaRef.current;
3290
- if (ta) {
3291
- const start = ta.selectionStart;
3292
- const end = ta.selectionEnd;
3293
- const val = ta.value;
3294
- const newVal = val.substring(0, start) + " " + val.substring(end);
3295
- ta.value = newVal;
3296
- ta.selectionStart = ta.selectionEnd = start + 2;
3297
- ta.dispatchEvent(new Event("input", { bubbles: true }));
3298
- }
3299
- }
3300
- };
3301
- el.addEventListener("keydown", handler);
3302
- return () => el.removeEventListener("keydown", handler);
3303
- }, []);
3304
- const highlighted = useMemo9(() => highlightJson(text), [text]);
3305
- const isMac = typeof navigator !== "undefined" && MAC_UA_RE3.test(navigator.userAgent);
3306
- const modKey = isMac ? "\u2318" : "Ctrl";
3307
- return /* @__PURE__ */ jsx14(EditorFocusTrap, { onEscape: handleCancel, className: `bg-popover ${OVERLAY.lg} rounded-lg border p-2.5 shadow-lg`, children: /* @__PURE__ */ jsxs6("div", { ref: keyContainerRef, children: [
3308
- /* @__PURE__ */ jsxs6(
3309
- "div",
3310
- {
3311
- className: "bg-muted/40 grid cursor-text overflow-hidden rounded-md border border-border/40",
3312
- style: { height: 300 },
3313
- onClick: () => textareaRef.current?.focus(),
3314
- children: [
3315
- /* @__PURE__ */ jsx14(
3316
- "pre",
3317
- {
3318
- ref: preRef,
3319
- className: "json-highlight pointer-events-none col-start-1 row-start-1 m-0 overflow-hidden whitespace-pre-wrap break-words bg-transparent p-3 font-mono text-sm leading-relaxed [word-break:break-all]",
3320
- "aria-hidden": "true",
3321
- dangerouslySetInnerHTML: { __html: highlighted + "\n" }
3322
- }
3323
- ),
3324
- /* @__PURE__ */ jsx14(
3325
- "textarea",
3326
- {
3327
- ref: textareaRef,
3328
- value: text,
3329
- onChange: handleChange,
3330
- onScroll: handleScroll,
3331
- spellCheck: false,
3332
- className: "col-start-1 row-start-1 m-0 resize-none overflow-auto whitespace-pre-wrap break-words bg-transparent p-3 font-mono text-sm leading-relaxed text-transparent outline-none [word-break:break-all]",
3333
- style: { caretColor: "var(--color-foreground)" },
3334
- autoFocus: true
3335
- }
3336
- )
3337
- ]
3338
- }
3339
- ),
3340
- /* @__PURE__ */ jsxs6("div", { className: "mt-3 flex items-center justify-between gap-4 border-t px-1 pt-2.5", children: [
3341
- /* @__PURE__ */ jsxs6("div", { className: "text-muted-foreground flex items-center gap-3 text-xs", children: [
3342
- valid ? /* @__PURE__ */ jsx14("span", { className: "text-muted-foreground/60 shrink-0 text-xs", children: "Valid" }) : /* @__PURE__ */ jsx14("span", { className: "text-destructive shrink-0 text-xs", children: "Invalid" }),
3343
- /* @__PURE__ */ jsx14("span", { className: "text-border", children: "|" }),
3344
- /* @__PURE__ */ jsxs6("span", { className: "inline-flex shrink-0 items-center gap-1", children: [
3345
- /* @__PURE__ */ jsx14("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight", children: modKey }),
3346
- /* @__PURE__ */ jsx14("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 min-w-5 items-center justify-center rounded border font-sans text-[11px] leading-tight", children: "\u21B5" }),
3347
- /* @__PURE__ */ jsx14("span", { children: "save" })
3348
- ] }),
3349
- /* @__PURE__ */ jsxs6("span", { className: "inline-flex shrink-0 items-center gap-1", children: [
3350
- /* @__PURE__ */ jsx14("kbd", { className: "bg-muted/60 border-border/40 inline-flex min-h-5 items-center justify-center rounded border px-1.5 font-sans text-[11px] leading-tight", children: "Esc" }),
3351
- /* @__PURE__ */ jsx14("span", { children: "cancel" })
3352
- ] })
3353
- ] }),
3354
- /* @__PURE__ */ jsx14(Button6, { onClick: handleSave, size: "xs", variant: "default", className: "shrink-0", disabled: !valid, children: "Save" })
3355
- ] }),
3356
- /* @__PURE__ */ jsx14("style", { children: JSON_HIGHLIGHT_STYLES })
3357
- ] }) });
3358
- }
3359
-
3360
- // src/grid-dom/editors/json-editor.tsx
3361
- import { jsx as jsx15 } from "react/jsx-runtime";
3362
- function JsonEditorDom({ value, onCommit, onCancel }) {
3363
- return /* @__PURE__ */ jsx15(
3364
- JsonEditor,
3365
- {
3366
- value,
3367
- onChange: () => {
3368
- },
3369
- onFinished: (next) => next === void 0 ? onCancel() : onCommit(next)
3370
- }
3371
- );
3372
- }
3373
-
3374
- // src/grid-dom/editors/number-editor.tsx
3375
- import { useRef as useRef8, useState as useState9 } from "react";
3376
- import { Button as Button7 } from "@constructive-io/ui/button";
3377
- import { jsx as jsx16, jsxs as jsxs7 } from "react/jsx-runtime";
3378
- function seedText(value) {
3379
- if (value === null || value === void 0) return "";
3380
- if (typeof value === "number") return Number.isFinite(value) ? String(value) : "";
3381
- return String(value);
3382
- }
3383
- function parseValue(text) {
3384
- const trimmed = text.trim();
3385
- if (trimmed === "") return null;
3386
- return Number(trimmed);
3387
- }
3388
- function NumberEditorDom({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
3389
- const [text, setText] = useState9(() => initialText != null ? initialText : seedText(value));
3390
- const escapedRef = useRef8(false);
3391
- const parsed = parseValue(text);
3392
- const canSave = parsed === null || Number.isFinite(parsed);
3393
- function commit() {
3394
- if (!canSave) return;
3395
- onCommit(parsed);
3396
- }
3397
- function handleKeyDown(e) {
3398
- if (e.key === "Enter") {
3399
- e.preventDefault();
3400
- commit();
3401
- return;
3402
- }
3403
- if (e.key === "Escape") {
3404
- e.preventDefault();
3405
- escapedRef.current = true;
3406
- onCancel();
3407
- }
3408
- }
3409
- function handleBlur(e) {
3410
- if (escapedRef.current) return;
3411
- const root = e.currentTarget.closest('[role="dialog"]') ?? e.currentTarget.closest('[data-slot="number-editor"]');
3412
- const landed = e.relatedTarget ?? document.activeElement;
3413
- if (root && landed && root.contains(landed)) return;
3414
- commit();
3415
- }
3416
- return /* @__PURE__ */ jsxs7(
3417
- "div",
3418
- {
3419
- "data-slot": "number-editor",
3420
- className: cn("bg-popover flex items-center gap-2 rounded-lg border p-2.5 shadow-lg", OVERLAY_SM),
3421
- children: [
3422
- /* @__PURE__ */ jsx16(
3423
- "input",
3424
- {
3425
- "aria-label": `Edit ${fieldMeta?.name ?? colKey}`,
3426
- value: text,
3427
- onChange: (e) => setText(e.target.value),
3428
- onKeyDown: handleKeyDown,
3429
- onBlur: handleBlur,
3430
- inputMode: "decimal",
3431
- spellCheck: false,
3432
- className: "bg-muted/40 border-border/40 min-w-0 flex-1 rounded-md border px-2.5 py-1.5 font-sans text-sm outline-none",
3433
- autoFocus: true
3434
- }
3435
- ),
3436
- /* @__PURE__ */ jsx16(Button7, { onClick: commit, disabled: !canSave, size: "xs", variant: "default", className: "shrink-0", children: "Save" })
3437
- ]
3438
- }
3439
- );
3440
- }
3441
- NumberEditorDom.commitsOnBlur = true;
3442
-
3443
- // src/grid/editors/relation-editor.tsx
3444
- import { useCallback as useCallback7, useContext as useContext3, useEffect as useEffect7, useLayoutEffect as useLayoutEffect3, useMemo as useMemo10, useRef as useRef10, useState as useState11 } from "react";
3445
- import { Check as Check2, Link, Loader2 as Loader23, Search, X as X2 } from "lucide-react";
3446
- import { useQueryClient as useQueryClient4 } from "@tanstack/react-query";
3447
- import { Badge as Badge2 } from "@constructive-io/ui/badge";
3448
- import { Button as Button8 } from "@constructive-io/ui/button";
3449
- import { InputGroup, InputGroupAddon, InputGroupInput } from "@constructive-io/ui/input-group";
3450
- import { Label as Label2 } from "@constructive-io/ui/label";
3451
- import { toast as toast2 } from "@constructive-io/ui/toast";
3452
-
3453
- // src/grid/editors/relation-record-tooltip.tsx
3454
- import { useRef as useRef9, useState as useState10 } from "react";
3455
- import { RiCodeLine } from "@remixicon/react";
3456
- import { Popover, PopoverContent, PopoverTrigger } from "@constructive-io/ui/popover";
3457
- import { jsx as jsx17, jsxs as jsxs8 } from "react/jsx-runtime";
3458
- function RelationRecordTooltip({ record }) {
3459
- const [open, setOpen] = useState10(false);
3460
- const closeTimeoutRef = useRef9(null);
3461
- if (!record || typeof record !== "object") {
3462
- return null;
3463
- }
3464
- const entries = Object.entries(record).filter(
3465
- ([, value]) => value !== null && value !== void 0
3466
- );
3467
- const MAX_VISIBLE_FIELDS = 12;
3468
- const visibleEntries = entries.slice(0, MAX_VISIBLE_FIELDS);
3469
- const hiddenCount = entries.length - visibleEntries.length;
3470
- const handleMouseEnter = () => {
3471
- if (closeTimeoutRef.current) {
3472
- clearTimeout(closeTimeoutRef.current);
3473
- closeTimeoutRef.current = null;
3474
- }
3475
- setOpen(true);
3476
- };
3477
- const handleMouseLeave = () => {
3478
- closeTimeoutRef.current = setTimeout(() => {
3479
- setOpen(false);
3480
- }, 100);
3481
- };
3482
- return /* @__PURE__ */ jsxs8(Popover, { open, onOpenChange: setOpen, children: [
3483
- /* @__PURE__ */ jsx17(PopoverTrigger, { asChild: true, children: /* @__PURE__ */ jsx17(
3484
- "button",
3485
- {
3486
- type: "button",
3487
- className: "text-muted-foreground/50 hover:text-muted-foreground relative flex shrink-0 cursor-help items-center justify-center rounded p-1 transition-colors before:absolute before:-inset-2 before:content-['']",
3488
- onMouseEnter: handleMouseEnter,
3489
- onMouseLeave: handleMouseLeave,
3490
- onClick: (e) => e.stopPropagation(),
3491
- children: /* @__PURE__ */ jsx17(RiCodeLine, { className: "h-3.5 w-3.5" })
3492
- }
3493
- ) }),
3494
- /* @__PURE__ */ jsxs8(
3495
- PopoverContent,
3496
- {
3497
- side: "right",
3498
- align: "start",
3499
- sideOffset: 4,
3500
- className: "z-[10000] w-[300px] max-h-[min(50vh,320px)] overflow-hidden p-0 shadow-lg",
3501
- onMouseEnter: handleMouseEnter,
3502
- onMouseLeave: handleMouseLeave,
3503
- onOpenAutoFocus: (e) => e.preventDefault(),
3504
- onCloseAutoFocus: (e) => e.preventDefault(),
3505
- children: [
3506
- /* @__PURE__ */ jsxs8("div", { className: "border-border/40 flex items-center gap-2 border-b px-3 py-2", children: [
3507
- /* @__PURE__ */ jsx17(RiCodeLine, { className: "text-muted-foreground h-4 w-4" }),
3508
- /* @__PURE__ */ jsx17("span", { className: "text-sm font-medium", children: "Record Data" }),
3509
- /* @__PURE__ */ jsxs8("span", { className: "text-muted-foreground bg-muted/40 ml-auto rounded px-1.5 py-0.5 text-xs", children: [
3510
- entries.length,
3511
- " fields"
3512
- ] })
3513
- ] }),
3514
- /* @__PURE__ */ jsx17("div", { className: "max-h-[240px] overflow-y-auto overscroll-contain", children: /* @__PURE__ */ jsxs8("div", { className: "space-y-0", children: [
3515
- visibleEntries.map(([key, value]) => /* @__PURE__ */ jsxs8("div", { className: "border-border/20 border-b px-3 py-2 last:border-b-0", children: [
3516
- /* @__PURE__ */ jsx17("div", { className: "text-muted-foreground text-xs", children: key }),
3517
- /* @__PURE__ */ jsx17("div", { className: cn(
3518
- "text-sm break-all line-clamp-3",
3519
- value === null || value === void 0 ? "text-muted-foreground/50 italic" : "text-foreground"
3520
- ), children: formatValue(value) })
3521
- ] }, key)),
3522
- hiddenCount > 0 && /* @__PURE__ */ jsxs8("div", { className: "text-muted-foreground px-3 py-2 text-xs italic", children: [
3523
- "... and ",
3524
- hiddenCount,
3525
- " more field",
3526
- hiddenCount > 1 ? "s" : ""
3527
- ] })
3528
- ] }) })
3529
- ]
3530
- }
3531
- )
3532
- ] });
3533
- }
3534
- var MAX_VALUE_LENGTH = 120;
3535
- function formatValue(value) {
3536
- if (value === null || value === void 0) return "null";
3537
- const str = typeof value === "object" ? JSON.stringify(value) : String(value);
3538
- return str.length > MAX_VALUE_LENGTH ? str.slice(0, MAX_VALUE_LENGTH) + "\u2026" : str;
3539
- }
3540
-
3541
- // src/grid/editors/relation-editor.tsx
3542
- import { jsx as jsx18, jsxs as jsxs9 } from "react/jsx-runtime";
3543
- function coerceToArray(v) {
3544
- if (v == null) return [];
3545
- if (Array.isArray(v)) return v;
3546
- if (typeof v === "object") {
3547
- const obj = v;
3548
- if (Array.isArray(obj.nodes)) return obj.nodes;
3549
- return [v];
3550
- }
3551
- if (typeof v === "string" && v) return [{ id: v }];
3552
- return [];
3553
- }
3554
- var DISPLAY_FIELDS = ["name", "title", "label", "displayName", "fullName", "email", "username", "description", "code"];
3555
- function getRelationDisplayText(relation) {
3556
- if (!relation || typeof relation !== "object") {
3557
- return String(relation || "");
3558
- }
3559
- for (const field of DISPLAY_FIELDS) {
3560
- if (relation[field] != null && String(relation[field]).trim()) {
3561
- return String(relation[field]);
3562
- }
3563
- }
3564
- if (relation.id != null) {
3565
- return `Record ${relation.id}`;
3566
- }
3567
- return "Unknown Record";
3568
- }
3569
- var RelationEditor = ({
3570
- onFinishedEditing,
3571
- tableName,
3572
- recordId,
3573
- fieldName,
3574
- currentValue,
3575
- onSaveComplete
3576
- }) => {
3577
- const { data: meta } = useSheetsMeta();
3578
- const { scopeKey } = useSheetsContext();
3579
- const queryClient = useQueryClient4();
3580
- const ensureRelationInfo = useSheetsStore((s) => s.ensureRelationInfo);
3581
- const relationInfoForTable = useSheetsStore((s) => tableName ? s.relationInfoCache[tableName] : void 0);
3582
- const relationEntry = relationInfoForTable?.[fieldName];
3583
- const isDraft = typeof recordId === "string" && recordId.startsWith("draft:");
3584
- useEffect7(() => {
3585
- if (!tableName) return;
3586
- if (relationInfoForTable?.[fieldName]) return;
3587
- ensureRelationInfo(tableName, meta);
3588
- }, [tableName, fieldName, meta, ensureRelationInfo, relationInfoForTable]);
3589
- const relationDef = useMemo10(() => {
3590
- const entry = relationEntry;
3591
- if (!entry) return null;
3592
- return { kind: entry.kind, relatedTable: entry.relatedTable };
3593
- }, [relationEntry]);
3594
- const isMulti = relationDef?.kind === "hasMany" || relationDef?.kind === "manyToMany";
3595
- const relatedTableName = relationDef?.relatedTable;
3596
- const isManyToMany = relationDef?.kind === "manyToMany";
3597
- const requiredMetaMissing = useMemo10(() => {
3598
- if (!relationEntry) return true;
3599
- if (isDraft) {
3600
- if (relationEntry.kind !== "belongsTo") return true;
3601
- return !relationEntry.relatedTable || !relationEntry.foreignKeyField;
3602
- }
3603
- if (recordId == null) return true;
3604
- if (!relationEntry.relatedTable) return true;
3605
- switch (relationEntry.kind) {
3606
- case "belongsTo":
3607
- return !relationEntry.foreignKeyField;
3608
- case "hasOne":
3609
- case "hasMany":
3610
- return !relationEntry.foreignKeyField;
3611
- case "manyToMany":
3612
- return !(relationEntry.junctionTable && relationEntry.junctionLeftKeyField && relationEntry.junctionRightKeyField);
3613
- default:
3614
- return true;
3615
- }
3616
- }, [relationEntry, recordId, isDraft]);
3617
- const canPersist = Boolean(relationEntry && !requiredMetaMissing);
3618
- const { maxHeight: overlayMaxHeight } = useContext3(OverlayMeasureContext);
3619
- const editorRef = useRef10(null);
3620
- const currentScrollRef = useRef10(null);
3621
- const [scrollBudgets, setScrollBudgets] = useState11({});
3622
- useLayoutEffect3(() => {
3623
- const editor = editorRef.current;
3624
- const currentScroll = currentScrollRef.current;
3625
- const addFromScroll = scrollContainerRef.current;
3626
- if (!editor || !currentScroll || !addFromScroll || overlayMaxHeight <= 0) return;
3627
- const measuredFixedUI = editor.scrollHeight - currentScroll.scrollHeight - addFromScroll.scrollHeight;
3628
- const budget = Math.max(0, overlayMaxHeight - measuredFixedUI);
3629
- setScrollBudgets({
3630
- current: Math.floor(budget * 0.35),
3631
- addFrom: Math.floor(budget * 0.65)
3632
- });
3633
- }, [overlayMaxHeight]);
3634
- const initialSelection = useMemo10(() => coerceToArray(currentValue), [currentValue]);
3635
- const [editingValue, setEditingValue] = useState11(initialSelection);
3636
- const [searchQuery, setSearchQuery] = useState11("");
3637
- const editingValueRef = useRef10(editingValue);
3638
- editingValueRef.current = editingValue;
3639
- const initialSelectionRef = useRef10(initialSelection);
3640
- initialSelectionRef.current = initialSelection;
3641
- const onFinishedEditingRef = useRef10(onFinishedEditing);
3642
- onFinishedEditingRef.current = onFinishedEditing;
3643
- const initialRecordIdRef = useRef10(recordId);
3644
- useEffect7(() => {
3645
- if (initialRecordIdRef.current != null && recordId != null && initialRecordIdRef.current !== recordId) {
3646
- onFinishedEditingRef.current();
3647
- }
3648
- }, [recordId]);
3649
- const selectedIdSet = useMemo10(() => {
3650
- const set = /* @__PURE__ */ new Set();
3651
- for (const r of editingValue) {
3652
- const id = r?.id;
3653
- if (id != null) set.add(id);
3654
- }
3655
- return set;
3656
- }, [editingValue]);
3657
- const displayCandidates = useMemo10(() => {
3658
- const entry = relationEntry;
3659
- return entry?.displayCandidates?.length ? entry.displayCandidates : ["name", "displayName", "fullName", "title"];
3660
- }, [relationEntry]);
3661
- const whereFilter = useMemo10(() => {
3662
- if (!searchQuery.trim() || displayCandidates.length === 0) return void 0;
3663
- const includesFilters = displayCandidates.map((f) => ({ [f]: { includesInsensitive: searchQuery } }));
3664
- return { or: includesFilters };
3665
- }, [searchQuery, displayCandidates]);
3666
- const {
3667
- data: options = [],
3668
- isLoading,
3669
- isFetchingNextPage,
3670
- hasNextPage,
3671
- fetchNextPage,
3672
- totalCount: optionsTotalCount
3673
- } = useSheetsTableCursor(relatedTableName || "", {
3674
- enabled: !!relatedTableName,
3675
- select: "all",
3676
- pageSize: 20,
3677
- where: whereFilter
3678
- });
3679
- const { data: junctionRows = [], isLoading: isJunctionLoading } = useSheetsTable(relationEntry?.junctionTable || "", {
3680
- enabled: canPersist && isManyToMany && recordId != null && !!relationEntry?.junctionTable && !!relationEntry?.junctionLeftKeyField,
3681
- select: relationEntry?.junctionLeftKeyField && relationEntry?.junctionRightKeyField ? {
3682
- select: ["id", relationEntry.junctionLeftKeyField, relationEntry.junctionRightKeyField]
3683
- } : "minimal",
3684
- limit: 500,
3685
- where: relationEntry?.junctionLeftKeyField && recordId != null ? { [relationEntry.junctionLeftKeyField]: { equalTo: recordId } } : void 0
3686
- });
3687
- const parentTable = useSheetsTable(tableName, { enabled: false });
3688
- const relatedTable = useSheetsTable(relatedTableName || "", { enabled: false });
3689
- const junctionTable = useSheetsTable(relationEntry?.junctionTable || "", { enabled: false });
3690
- const [isSaving, setIsSaving] = useState11(false);
3691
- const sentinelRef = useRef10(null);
3692
- const scrollContainerRef = useRef10(null);
3693
- useEffect7(() => {
3694
- const sentinel = sentinelRef.current;
3695
- const root = scrollContainerRef.current;
3696
- if (!sentinel || !root || !hasNextPage || isFetchingNextPage) return;
3697
- const observer = new IntersectionObserver(
3698
- ([entry]) => {
3699
- if (entry.isIntersecting) fetchNextPage();
3700
- },
3701
- { root, rootMargin: "100px", threshold: 0 }
3702
- );
3703
- observer.observe(sentinel);
3704
- return () => observer.disconnect();
3705
- }, [hasNextPage, isFetchingNextPage, fetchNextPage]);
3706
- const junctionRowsRef = useRef10(junctionRows);
3707
- junctionRowsRef.current = junctionRows;
3708
- const handleSave = useCallback7(() => {
3709
- void (async () => {
3710
- if (!relationEntry || recordId == null) {
3711
- onFinishedEditing();
3712
- return;
3713
- }
3714
- if (!canPersist) {
3715
- onFinishedEditing();
3716
- return;
3717
- }
3718
- const getRecordId = (r) => {
3719
- if (r == null) return null;
3720
- if (typeof r === "string" || typeof r === "number") return r;
3721
- if (typeof r === "object" && (typeof r.id === "string" || typeof r.id === "number")) return r.id;
3722
- return null;
3723
- };
3724
- const currentEditing = editingValueRef.current;
3725
- const currentInitial = initialSelectionRef.current;
3726
- setIsSaving(true);
3727
- try {
3728
- const initialIds = new Set(currentInitial.map(getRecordId).filter((id) => id != null));
3729
- const nextIds = new Set(currentEditing.map(getRecordId).filter((id) => id != null));
3730
- if (relationEntry.kind === "belongsTo") {
3731
- const selectedId = Array.from(nextIds)[0] ?? null;
3732
- const fkField = relationEntry.foreignKeyField;
3733
- if (!fkField) throw new Error("Missing foreignKeyField for belongsTo relation");
3734
- if (isDraft) {
3735
- onSaveComplete?.({ relationData: currentEditing[0] ?? null, foreignKeyValue: selectedId });
3736
- onFinishedEditing();
3737
- return;
3738
- }
3739
- await parentTable.update(recordId, { [fkField]: selectedId });
3740
- onSaveComplete?.({
3741
- relationData: currentEditing[0] ?? null,
3742
- foreignKeyValue: selectedId
3743
- });
3744
- onFinishedEditing();
3745
- return;
3746
- }
3747
- if (relationEntry.kind === "hasOne") {
3748
- const fkField = relationEntry.foreignKeyField;
3749
- if (!fkField) throw new Error("Missing foreignKeyField for hasOne relation");
3750
- const prevId = Array.from(initialIds)[0] ?? null;
3751
- const nextId = Array.from(nextIds)[0] ?? null;
3752
- const mutations = [];
3753
- if (prevId && prevId !== nextId) {
3754
- mutations.push(relatedTable.update(prevId, { [fkField]: null }));
3755
- }
3756
- if (nextId && nextId !== prevId) {
3757
- mutations.push(relatedTable.update(nextId, { [fkField]: recordId }));
3758
- }
3759
- if (mutations.length > 0) await Promise.all(mutations);
3760
- await Promise.all([
3761
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) }),
3762
- queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.cursorTable(scopeKey, relatedTableName || "") })
3763
- ]);
3764
- onSaveComplete?.({
3765
- relationData: currentEditing[0] ?? null,
3766
- foreignKeyValue: null
3767
- });
3768
- onFinishedEditing();
3769
- return;
3770
- }
3771
- if (relationEntry.kind === "hasMany") {
3772
- const fkField = relationEntry.foreignKeyField;
3773
- if (!fkField) throw new Error("Missing foreignKeyField for hasMany relation");
3774
- const toAdd = Array.from(nextIds).filter((id) => !initialIds.has(id));
3775
- const toRemove = Array.from(initialIds).filter((id) => !nextIds.has(id));
3776
- await Promise.all([
3777
- ...toAdd.map((id) => relatedTable.update(id, { [fkField]: recordId })),
3778
- ...toRemove.map((id) => relatedTable.update(id, { [fkField]: null }))
3779
- ]);
3780
- await Promise.all([
3781
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) }),
3782
- queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.cursorTable(scopeKey, relatedTableName || "") })
3783
- ]);
3784
- onSaveComplete?.({
3785
- relationData: currentEditing,
3786
- foreignKeyValue: null
3787
- });
3788
- onFinishedEditing();
3789
- return;
3790
- }
3791
- if (relationEntry.kind === "manyToMany") {
3792
- const jt = relationEntry.junctionTable;
3793
- const leftFk = relationEntry.junctionLeftKeyField;
3794
- const rightFk = relationEntry.junctionRightKeyField;
3795
- if (!jt || !leftFk || !rightFk) throw new Error("Missing junction metadata for manyToMany relation");
3796
- const toAdd = Array.from(nextIds).filter((id) => !initialIds.has(id));
3797
- const toRemove = Array.from(initialIds).filter((id) => !nextIds.has(id));
3798
- const rows = Array.isArray(junctionRowsRef.current) ? junctionRowsRef.current : [];
3799
- const byRight = /* @__PURE__ */ new Map();
3800
- rows.forEach((r) => {
3801
- const rightId = r?.[rightFk];
3802
- if (rightId != null) byRight.set(rightId, r);
3803
- });
3804
- await Promise.all([
3805
- ...toAdd.map((id) => junctionTable.create({ [leftFk]: recordId, [rightFk]: id })),
3806
- ...toRemove.map((id) => byRight.get(id)).filter((row) => row && (row.id != null || row[leftFk] != null && row[rightFk] != null)).map(
3807
- (row) => row.id != null ? junctionTable.delete(row.id) : junctionTable.delete({ [leftFk]: row[leftFk], [rightFk]: row[rightFk] })
3808
- )
3809
- ]);
3810
- await Promise.all([
3811
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableName) }),
3812
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, jt) }),
3813
- queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.cursorTable(scopeKey, relatedTableName || "") })
3814
- ]);
3815
- onSaveComplete?.({
3816
- relationData: currentEditing,
3817
- foreignKeyValue: null
3818
- });
3819
- onFinishedEditing();
3820
- return;
3821
- }
3822
- onFinishedEditing();
3823
- } catch (err) {
3824
- sheetsLogger().error("[relation-editor] save failed:", err);
3825
- toast2.error({ message: err instanceof Error ? err.message : "Failed to save relation" });
3826
- } finally {
3827
- setIsSaving(false);
3828
- }
3829
- })();
3830
- }, [
3831
- canPersist,
3832
- onFinishedEditing,
3833
- onSaveComplete,
3834
- recordId,
3835
- relationEntry,
3836
- relatedTable,
3837
- junctionTable,
3838
- parentTable,
3839
- queryClient,
3840
- tableName,
3841
- scopeKey,
3842
- isDraft
3843
- ]);
3844
- const handleCancel = useCallback7(() => {
3845
- onFinishedEditing();
3846
- }, [onFinishedEditing]);
3847
- const handleRemoveRelation = useCallback7(
3848
- (index) => {
3849
- if (!canPersist || isSaving) return;
3850
- setEditingValue((prev) => prev.filter((_, i) => i !== index));
3851
- },
3852
- [canPersist, isSaving]
3853
- );
3854
- const togglePick = useCallback7(
3855
- (record) => {
3856
- if (!canPersist || isSaving) return;
3857
- setEditingValue((prev) => {
3858
- const id = record?.id;
3859
- if (id != null) {
3860
- const exists = prev.some((r) => r?.id === id);
3861
- if (exists) return prev.filter((r) => r?.id !== id);
3862
- } else {
3863
- const key = JSON.stringify(record);
3864
- const exists = prev.some((r) => JSON.stringify(r) === key);
3865
- if (exists) return prev.filter((r) => JSON.stringify(r) !== key);
3866
- }
3867
- if (isMulti) return [...prev, record];
3868
- return [record];
3869
- });
3870
- },
3871
- [canPersist, isMulti, isSaving]
3872
- );
3873
- const handleEditorKeyDown = useCallback7(
3874
- (e) => {
3875
- if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
3876
- e.preventDefault();
3877
- if (canPersist && !isSaving) handleSave();
3878
- }
3879
- },
3880
- [canPersist, handleSave, isSaving]
3881
- );
3882
- return /* @__PURE__ */ jsx18("div", { ref: editorRef, children: /* @__PURE__ */ jsxs9(
3883
- EditorFocusTrap,
3884
- {
3885
- onEscape: handleCancel,
3886
- onKeyDown: handleEditorKeyDown,
3887
- className: `bg-popover flex ${OVERLAY.md} flex-col gap-4 rounded-lg border p-4 shadow-lg`,
3888
- children: [
3889
- /* @__PURE__ */ jsxs9("div", { className: "flex items-center gap-2", children: [
3890
- /* @__PURE__ */ jsx18(Link, { className: "text-muted-foreground h-4 w-4" }),
3891
- /* @__PURE__ */ jsx18("h3", { className: "text-sm font-medium", children: canPersist ? "Edit Relations" : "Related Records" }),
3892
- isMulti && editingValue.length > 0 && /* @__PURE__ */ jsx18(Badge2, { variant: "secondary", size: "sm", className: "ml-auto tabular-nums", children: editingValue.length })
3893
- ] }),
3894
- /* @__PURE__ */ jsxs9("div", { className: "space-y-2", children: [
3895
- /* @__PURE__ */ jsxs9("div", { className: "flex items-center gap-2", children: [
3896
- /* @__PURE__ */ jsx18(Label2, { className: "text-muted-foreground text-xs", children: "Current Relations" }),
3897
- editingValue.length > 0 && /* @__PURE__ */ jsx18(Badge2, { variant: "outline", size: "sm", className: "tabular-nums", children: editingValue.length })
3898
- ] }),
3899
- /* @__PURE__ */ jsx18("div", { ref: currentScrollRef, className: "rounded-md border", style: { maxHeight: scrollBudgets.current, overflowY: "auto" }, children: /* @__PURE__ */ jsx18("div", { className: "space-y-2 p-2", children: editingValue.length === 0 ? /* @__PURE__ */ jsx18("div", { className: "text-muted-foreground py-4 text-center text-sm", children: "No relations linked" }) : editingValue.map((relation, index) => {
3900
- const displayText = getRelationDisplayText(relation);
3901
- return /* @__PURE__ */ jsxs9("div", { className: "bg-muted flex items-center gap-2 rounded-md p-2", children: [
3902
- /* @__PURE__ */ jsx18(RelationRecordTooltip, { record: relation }),
3903
- /* @__PURE__ */ jsx18("span", { className: "min-w-0 flex-1 truncate text-sm", children: displayText }),
3904
- /* @__PURE__ */ jsx18(Badge2, { variant: "outline", className: "text-2xs shrink-0", children: String(relation.id || index + 1).slice(0, 8) }),
3905
- /* @__PURE__ */ jsx18(
3906
- Button8,
3907
- {
3908
- variant: "ghost",
3909
- size: "sm",
3910
- onClick: () => handleRemoveRelation(index),
3911
- disabled: !canPersist,
3912
- className: "text-muted-foreground hover:text-destructive h-6 w-6 shrink-0 p-0",
3913
- children: /* @__PURE__ */ jsx18(X2, { className: "h-3 w-3" })
3914
- }
3915
- )
3916
- ] }, index);
3917
- }) }) })
3918
- ] }),
3919
- /* @__PURE__ */ jsxs9("div", { className: "flex flex-col space-y-2", children: [
3920
- /* @__PURE__ */ jsxs9(Label2, { htmlFor: "search", className: "flex items-center gap-1 text-muted-foreground text-xs", children: [
3921
- /* @__PURE__ */ jsx18("span", { children: "Add from" }),
3922
- /* @__PURE__ */ jsx18(Badge2, { variant: "outline", size: "sm", className: "px-1", children: relationEntry?.displayName || relatedTableName || "related" }),
3923
- optionsTotalCount > 0 && /* @__PURE__ */ jsxs9(Badge2, { variant: "secondary", size: "sm", className: "ml-auto tabular-nums", children: [
3924
- options.length,
3925
- " / ",
3926
- optionsTotalCount
3927
- ] })
3928
- ] }),
3929
- /* @__PURE__ */ jsxs9(InputGroup, { children: [
3930
- /* @__PURE__ */ jsx18(InputGroupAddon, { children: /* @__PURE__ */ jsx18(Search, {}) }),
3931
- /* @__PURE__ */ jsx18(
3932
- InputGroupInput,
3933
- {
3934
- id: "search",
3935
- value: searchQuery,
3936
- onChange: (e) => setSearchQuery(e.target.value),
3937
- placeholder: "Type to search...",
3938
- size: "sm"
3939
- }
3940
- )
3941
- ] }),
3942
- /* @__PURE__ */ jsx18("div", { ref: scrollContainerRef, className: "rounded-md border", style: { maxHeight: scrollBudgets.addFrom, overflowY: "auto" }, children: /* @__PURE__ */ jsxs9("div", { "data-testid": "relation-options", className: "space-y-1 p-2", children: [
3943
- (isLoading || isManyToMany && isJunctionLoading) && /* @__PURE__ */ jsx18("div", { className: "text-muted-foreground py-6 text-center text-sm", children: "Loading..." }),
3944
- !isLoading && options.length === 0 && /* @__PURE__ */ jsx18("div", { className: "text-muted-foreground py-6 text-center text-sm", children: "No records found" }),
3945
- options.map((row) => {
3946
- const id = row?.id ?? JSON.stringify(row);
3947
- const label = getRelationDisplayTextFromCandidates(row, displayCandidates);
3948
- const active = row?.id != null ? selectedIdSet.has(row.id) : editingValue.some((r) => JSON.stringify(r) === id);
3949
- const disabled = !canPersist || isSaving;
3950
- return /* @__PURE__ */ jsx18(
3951
- "div",
3952
- {
3953
- role: "button",
3954
- tabIndex: disabled ? -1 : 0,
3955
- "aria-disabled": disabled,
3956
- onClick: () => {
3957
- if (disabled) return;
3958
- togglePick(row);
3959
- },
3960
- onKeyDown: (e) => {
3961
- if (disabled) return;
3962
- if (e.key !== "Enter" && e.key !== " ") return;
3963
- e.preventDefault();
3964
- togglePick(row);
3965
- },
3966
- className: cn(
3967
- "w-full rounded-md px-2 py-1.5 text-left",
3968
- !disabled && "hover:bg-accent/50 cursor-pointer",
3969
- disabled && "cursor-not-allowed opacity-64",
3970
- active && "bg-accent/60"
3971
- ),
3972
- children: /* @__PURE__ */ jsxs9("div", { className: "flex items-center gap-2", children: [
3973
- /* @__PURE__ */ jsx18(RelationRecordTooltip, { record: row }),
3974
- /* @__PURE__ */ jsx18("span", { className: "min-w-0 flex-1 truncate text-sm", children: label }),
3975
- active && /* @__PURE__ */ jsx18(Check2, { className: "text-primary h-3.5 w-3.5 shrink-0" }),
3976
- /* @__PURE__ */ jsx18(Badge2, { variant: "outline", className: cn("text-2xs shrink-0", active && "border-primary/40 text-link"), children: String(row?.id ?? "\u2014").slice(0, 8) })
3977
- ] })
3978
- },
3979
- id
3980
- );
3981
- }),
3982
- hasNextPage && /* @__PURE__ */ jsx18("div", { ref: sentinelRef, className: "flex justify-center py-2", children: isFetchingNextPage ? /* @__PURE__ */ jsx18(Loader23, { className: "text-muted-foreground h-4 w-4 animate-spin" }) : /* @__PURE__ */ jsx18("span", { className: "text-muted-foreground text-xs", children: "Scroll for more" }) })
3983
- ] }) })
3984
- ] }),
3985
- /* @__PURE__ */ jsxs9("div", { className: "flex justify-end gap-2", children: [
3986
- /* @__PURE__ */ jsxs9(Button8, { variant: "outline", size: "sm", onClick: handleCancel, disabled: isSaving, children: [
3987
- /* @__PURE__ */ jsx18(X2, { className: "mr-1 h-3 w-3" }),
3988
- canPersist ? "Cancel" : "Close"
3989
- ] }),
3990
- canPersist && /* @__PURE__ */ jsxs9(Button8, { size: "sm", onClick: handleSave, disabled: isSaving || isLoading || isManyToMany && isJunctionLoading, children: [
3991
- /* @__PURE__ */ jsx18(Check2, { className: "mr-1 h-3 w-3" }),
3992
- "Save"
3993
- ] })
3994
- ] })
3995
- ]
3996
- }
3997
- ) });
3998
- };
3999
- function getRelationDisplayTextFromCandidates(row, candidates) {
4000
- if (!row || typeof row !== "object") return String(row ?? "");
4001
- for (const c of candidates) {
4002
- if (row[c] != null && String(row[c]).trim()) return String(row[c]);
4003
- }
4004
- if ("id" in row) return `Record ${row.id}`;
4005
- return "Unknown Record";
4006
- }
4007
-
4008
- // src/grid-dom/editors/relation-editor.tsx
4009
- import { jsx as jsx19 } from "react/jsx-runtime";
4010
- var DRAFT_PREFIX2 = "draft:";
4011
- function resolveCurrentValue(value) {
4012
- if (typeof value === "string" && value && !value.startsWith(DRAFT_PREFIX2)) {
4013
- return { id: value };
4014
- }
4015
- return value;
4016
- }
4017
- function RelationEditorDom({
4018
- value,
4019
- colKey,
4020
- rowId,
4021
- tableName,
4022
- relationInfo,
4023
- onCommitPatch,
4024
- onCancel
4025
- }) {
4026
- const handleSaveComplete = onCommitPatch ? (saveData) => {
4027
- const patch = {};
4028
- if (relationInfo?.kind === "belongsTo" && relationInfo.foreignKeyField) {
4029
- patch[relationInfo.foreignKeyField] = saveData.foreignKeyValue;
4030
- }
4031
- const displayField = relationInfo?.relationField || colKey;
4032
- patch[displayField] = saveData.relationData;
4033
- onCommitPatch(patch);
4034
- } : void 0;
4035
- return /* @__PURE__ */ jsx19("div", { "data-slot": "relation-editor", children: /* @__PURE__ */ jsx19(
4036
- RelationEditor,
4037
- {
4038
- onFinishedEditing: () => onCancel(),
4039
- tableName: tableName ?? "",
4040
- recordId: rowId,
4041
- fieldName: colKey,
4042
- currentValue: resolveCurrentValue(value),
4043
- onSaveComplete: handleSaveComplete
4044
- }
4045
- ) });
4046
- }
4047
-
4048
- // src/grid-dom/editors/text-editor.tsx
4049
- import { useRef as useRef11, useState as useState12 } from "react";
4050
- import { Button as Button9 } from "@constructive-io/ui/button";
4051
- import { jsx as jsx20, jsxs as jsxs10 } from "react/jsx-runtime";
4052
- function TextEditor({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
4053
- const [text, setText] = useState12(() => initialText != null ? initialText : String(value ?? ""));
4054
- const escapedRef = useRef11(false);
4055
- function handleKeyDown(e) {
4056
- if (e.key === "Enter") {
4057
- e.preventDefault();
4058
- onCommit(text);
4059
- return;
4060
- }
4061
- if (e.key === "Escape") {
4062
- e.preventDefault();
4063
- escapedRef.current = true;
4064
- onCancel();
4065
- }
4066
- }
4067
- function handleBlur(e) {
4068
- if (escapedRef.current) return;
4069
- const root = e.currentTarget.closest('[role="dialog"]') ?? e.currentTarget.closest('[data-slot="text-editor"]');
4070
- const landed = e.relatedTarget ?? document.activeElement;
4071
- if (root && landed && root.contains(landed)) return;
4072
- onCommit(text);
4073
- }
4074
- return /* @__PURE__ */ jsxs10("div", { "data-slot": "text-editor", className: cn("bg-popover flex items-center gap-2 rounded-lg border p-2.5 shadow-lg", OVERLAY_SM), children: [
4075
- /* @__PURE__ */ jsx20(
4076
- "input",
4077
- {
4078
- "aria-label": `Edit ${fieldMeta?.name ?? colKey}`,
4079
- value: text,
4080
- onChange: (e) => setText(e.target.value),
4081
- onKeyDown: handleKeyDown,
4082
- onBlur: handleBlur,
4083
- spellCheck: false,
4084
- className: "bg-muted/40 border-border/40 min-w-0 flex-1 rounded-md border px-2.5 py-1.5 font-sans text-sm outline-none",
4085
- autoFocus: true
4086
- }
4087
- ),
4088
- /* @__PURE__ */ jsx20(Button9, { onClick: () => onCommit(text), size: "xs", variant: "default", className: "shrink-0", children: "Save" })
4089
- ] });
4090
- }
4091
- TextEditor.commitsOnBlur = true;
4092
-
4093
- // src/grid/editors/tsvector-editor.tsx
4094
- import { useCallback as useCallback8, useMemo as useMemo11 } from "react";
4095
- import { Info, Search as Search2, X as X3 } from "lucide-react";
4096
- import { Button as Button10 } from "@constructive-io/ui/button";
4097
- import { Label as Label3 } from "@constructive-io/ui/label";
4098
- import { jsx as jsx21, jsxs as jsxs11 } from "react/jsx-runtime";
4099
- function parseTsvector(tsvectorString) {
4100
- if (!tsvectorString || typeof tsvectorString !== "string") return [];
4101
- try {
4102
- const out = [];
4103
- const regex = /'([^']+)':([0-9A-D,]+)/g;
4104
- let match;
4105
- while ((match = regex.exec(tsvectorString)) !== null) {
4106
- const lexeme = match[1];
4107
- const posStr = match[2];
4108
- const weights = Array.from(
4109
- new Set(
4110
- posStr.split(",").map((p) => p.match(/[A-D]$/)?.[0]).filter((w) => !!w)
4111
- )
4112
- ).sort();
4113
- out.push({ lexeme, weights });
4114
- }
4115
- if (out.length) return out;
4116
- } catch {
4117
- }
4118
- return tsvectorString.split(/\s+/).filter(Boolean).map((w) => ({ lexeme: w, weights: [] }));
4119
- }
4120
- var TsvectorEditor = ({ value, onFinishedEditing }) => {
4121
- const rawValue = typeof value === "string" ? value : String(value ?? "");
4122
- const parsedTokens = useMemo11(() => parseTsvector(rawValue), [rawValue]);
4123
- const handleClose = useCallback8(() => onFinishedEditing(), [onFinishedEditing]);
4124
- return /* @__PURE__ */ jsxs11(EditorFocusTrap, { onEscape: handleClose, className: `bg-popover flex ${OVERLAY.md} flex-col gap-4 rounded-lg border p-4 shadow-lg`, children: [
4125
- /* @__PURE__ */ jsxs11("div", { className: "flex items-center gap-2", children: [
4126
- /* @__PURE__ */ jsx21(Search2, { className: "text-muted-foreground h-4 w-4" }),
4127
- /* @__PURE__ */ jsx21("h3", { className: "text-sm font-medium", children: "View Text Search Vector" })
4128
- ] }),
4129
- parsedTokens.length > 0 && /* @__PURE__ */ jsxs11("div", { className: "space-y-2", children: [
4130
- /* @__PURE__ */ jsxs11(Label3, { className: "text-muted-foreground text-xs", children: [
4131
- "Parsed Tokens (",
4132
- parsedTokens.length,
4133
- ")"
4134
- ] }),
4135
- /* @__PURE__ */ jsx21("div", { className: "bg-muted flex max-h-[120px] flex-wrap gap-1 overflow-y-auto rounded p-2 text-sm", children: parsedTokens.map((t, index) => {
4136
- const weight = t.weights[0];
4137
- const color = weight === "A" ? "bg-red-100 text-red-800 dark:bg-red-900/40 dark:text-red-200" : weight === "B" ? "bg-orange-100 text-orange-800 dark:bg-orange-900/40 dark:text-orange-200" : weight === "C" ? "bg-yellow-100 text-yellow-800 dark:bg-yellow-900/40 dark:text-yellow-200" : weight === "D" ? "bg-green-100 text-green-800 dark:bg-green-900/40 dark:text-green-200" : "bg-primary/10 text-link";
4138
- return /* @__PURE__ */ jsxs11("span", { className: cn("inline-flex items-center rounded px-2 py-1 text-xs", color), children: [
4139
- t.lexeme,
4140
- t.weights.length > 0 && /* @__PURE__ */ jsx21("span", { className: "ml-1 font-mono opacity-80", children: t.weights.join(",") })
4141
- ] }, index);
4142
- }) })
4143
- ] }),
4144
- /* @__PURE__ */ jsxs11("div", { className: "space-y-2", children: [
4145
- /* @__PURE__ */ jsx21(Label3, { className: "text-muted-foreground text-xs", children: "Raw TSVector" }),
4146
- /* @__PURE__ */ jsx21("div", { className: "bg-muted/30 max-h-40 overflow-auto rounded-md p-2", children: /* @__PURE__ */ jsx21("pre", { className: "m-0 font-mono text-xs break-all whitespace-pre-wrap", children: rawValue }) })
4147
- ] }),
4148
- /* @__PURE__ */ jsxs11("div", { className: "text-muted-foreground flex items-start gap-2 text-xs", children: [
4149
- /* @__PURE__ */ jsx21(Info, { className: "mt-0.5 h-3 w-3 flex-shrink-0" }),
4150
- /* @__PURE__ */ jsxs11("div", { children: [
4151
- /* @__PURE__ */ jsx21("p", { children: "Values are generated server-side from your full-text configuration." }),
4152
- /* @__PURE__ */ jsx21("p", { className: "mt-1", children: "Weights: A (highest), B, C, D (lowest)." })
4153
- ] })
4154
- ] }),
4155
- /* @__PURE__ */ jsx21("div", { className: "flex justify-end gap-2", children: /* @__PURE__ */ jsxs11(Button10, { variant: "outline", size: "sm", onClick: handleClose, children: [
4156
- /* @__PURE__ */ jsx21(X3, { className: "mr-1 h-3 w-3" }),
4157
- "Close"
4158
- ] }) })
4159
- ] });
4160
- };
4161
-
4162
- // src/grid-dom/editors/tsvector-editor.tsx
4163
- import { jsx as jsx22 } from "react/jsx-runtime";
4164
- function TsvectorEditorDom({ value, onCancel }) {
4165
- return /* @__PURE__ */ jsx22(TsvectorEditor, { value, onFinishedEditing: () => onCancel() });
4166
- }
4167
-
4168
- // src/grid/editors/url-editor.tsx
4169
- import { useCallback as useCallback9, useState as useState13 } from "react";
4170
- import { Check as Check3, ExternalLink, Link as Link2, X as X4 } from "lucide-react";
4171
- import { Button as Button11 } from "@constructive-io/ui/button";
4172
- import { Input as Input2 } from "@constructive-io/ui/input";
4173
- import { Label as Label4 } from "@constructive-io/ui/label";
4174
- import { jsx as jsx23, jsxs as jsxs12 } from "react/jsx-runtime";
4175
- function isValidUrl(string) {
4176
- if (!string || typeof string !== "string") return false;
4177
- try {
4178
- const urlToTest = string.startsWith("http") ? string : `https://${string}`;
4179
- new URL(urlToTest);
4180
- return true;
4181
- } catch {
4182
- return false;
4183
- }
4184
- }
4185
- function formatUrl(url) {
4186
- if (!url) return "";
4187
- if (url && !url.startsWith("http://") && !url.startsWith("https://")) {
4188
- return `https://${url}`;
4189
- }
4190
- return url;
4191
- }
4192
- function displayUrl(url) {
4193
- if (!url) return "";
4194
- return url.replace(/^https?:\/\//, "");
4195
- }
4196
- var UrlEditor = ({ value, onFinishedEditing }) => {
4197
- const currentUrlData = typeof value === "string" ? value : "";
4198
- const [editingValue, setEditingValue] = useState13(currentUrlData);
4199
- const [validationError, setValidationError] = useState13("");
4200
- const handleSave = useCallback9(() => {
4201
- if (editingValue.trim() && !isValidUrl(editingValue.trim())) {
4202
- setValidationError("Please enter a valid URL");
4203
- return;
4204
- }
4205
- const formattedUrl = editingValue.trim() ? formatUrl(editingValue.trim()) : "";
4206
- onFinishedEditing(formattedUrl);
4207
- }, [editingValue, onFinishedEditing]);
4208
- const handleCancel = useCallback9(() => {
4209
- onFinishedEditing();
4210
- }, [onFinishedEditing]);
4211
- const handleInputChange = useCallback9(
4212
- (e) => {
4213
- const newValue = e.target.value;
4214
- setEditingValue(newValue);
4215
- if (validationError) {
4216
- setValidationError("");
4217
- }
4218
- },
4219
- [validationError]
4220
- );
4221
- const handleTestUrl = useCallback9(() => {
4222
- if (editingValue.trim() && isValidUrl(editingValue.trim())) {
4223
- const fullUrl = formatUrl(editingValue.trim());
4224
- window.open(fullUrl, "_blank", "noopener,noreferrer");
4225
- }
4226
- }, [editingValue]);
4227
- const handleEditorKeyDown = useCallback9(
4228
- (e) => {
4229
- if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
4230
- e.preventDefault();
4231
- handleSave();
4232
- }
4233
- },
4234
- [handleSave]
4235
- );
4236
- const isValid = !editingValue.trim() || isValidUrl(editingValue.trim());
4237
- const displayText = editingValue.trim() ? displayUrl(editingValue.trim()) : "";
4238
- return /* @__PURE__ */ jsx23(EditorFocusTrap, { onEscape: handleCancel, className: `bg-popover flex ${OVERLAY.md} flex-col gap-4 rounded-lg border p-4 shadow-lg`, children: /* @__PURE__ */ jsxs12("div", { onKeyDown: handleEditorKeyDown, children: [
4239
- /* @__PURE__ */ jsxs12("div", { className: "flex items-center gap-2", children: [
4240
- /* @__PURE__ */ jsx23(Link2, { className: "text-muted-foreground h-4 w-4" }),
4241
- /* @__PURE__ */ jsx23("h3", { className: "text-sm font-medium", children: "Edit URL" })
4242
- ] }),
4243
- /* @__PURE__ */ jsxs12("div", { className: "space-y-2", children: [
4244
- /* @__PURE__ */ jsx23(Label4, { htmlFor: "url", className: "text-muted-foreground text-xs", children: "URL" }),
4245
- /* @__PURE__ */ jsx23(
4246
- Input2,
4247
- {
4248
- id: "url",
4249
- type: "url",
4250
- value: editingValue,
4251
- onChange: handleInputChange,
4252
- placeholder: "https://example.com",
4253
- className: cn("text-sm", validationError && "border-destructive focus-visible:ring-destructive"),
4254
- autoFocus: true
4255
- }
4256
- ),
4257
- validationError && /* @__PURE__ */ jsx23("p", { className: "text-destructive text-xs", children: validationError })
4258
- ] }),
4259
- editingValue.trim() && /* @__PURE__ */ jsxs12("div", { className: "space-y-2", children: [
4260
- /* @__PURE__ */ jsx23(Label4, { className: "text-muted-foreground text-xs", children: "Preview" }),
4261
- /* @__PURE__ */ jsxs12("div", { className: "bg-muted flex items-center gap-2 rounded p-2 text-sm", children: [
4262
- /* @__PURE__ */ jsx23(Link2, { className: "text-muted-foreground h-3 w-3 flex-shrink-0" }),
4263
- isValid ? /* @__PURE__ */ jsxs12("div", { className: "flex min-w-0 flex-1 items-center gap-2", children: [
4264
- /* @__PURE__ */ jsx23("span", { className: "text-link truncate", children: displayText }),
4265
- /* @__PURE__ */ jsx23(
4266
- Button11,
4267
- {
4268
- variant: "ghost",
4269
- size: "sm",
4270
- onClick: handleTestUrl,
4271
- className: "text-muted-foreground hover:text-link h-6 w-6 p-0",
4272
- title: "Test URL",
4273
- children: /* @__PURE__ */ jsx23(ExternalLink, { className: "h-3 w-3" })
4274
- }
4275
- )
4276
- ] }) : /* @__PURE__ */ jsx23("span", { className: "text-destructive truncate", children: editingValue })
4277
- ] })
4278
- ] }),
4279
- /* @__PURE__ */ jsxs12("div", { className: "text-muted-foreground text-xs", children: [
4280
- /* @__PURE__ */ jsx23("p", { children: "Examples:" }),
4281
- /* @__PURE__ */ jsxs12("ul", { className: "mt-1 list-inside list-disc space-y-1", children: [
4282
- /* @__PURE__ */ jsx23("li", { children: "https://example.com" }),
4283
- /* @__PURE__ */ jsx23("li", { children: "example.com (https:// will be added automatically)" }),
4284
- /* @__PURE__ */ jsx23("li", { children: "subdomain.example.com/path" })
4285
- ] })
4286
- ] }),
4287
- /* @__PURE__ */ jsxs12("div", { className: "flex justify-end gap-2", children: [
4288
- /* @__PURE__ */ jsxs12(Button11, { variant: "outline", size: "sm", onClick: handleCancel, children: [
4289
- /* @__PURE__ */ jsx23(X4, { className: "mr-1 h-3 w-3" }),
4290
- "Cancel"
4291
- ] }),
4292
- /* @__PURE__ */ jsxs12(Button11, { size: "sm", onClick: handleSave, disabled: !!validationError, children: [
4293
- /* @__PURE__ */ jsx23(Check3, { className: "mr-1 h-3 w-3" }),
4294
- "Save"
4295
- ] })
4296
- ] })
4297
- ] }) });
4298
- };
4299
-
4300
- // src/grid-dom/editors/url-editor.tsx
4301
- import { jsx as jsx24 } from "react/jsx-runtime";
4302
- function UrlEditorDom({ value, onCommit, onCancel }) {
4303
- return /* @__PURE__ */ jsx24("div", { "data-slot": "url-editor", children: /* @__PURE__ */ jsx24(
4304
- UrlEditor,
4305
- {
4306
- value,
4307
- onFinishedEditing: (next) => next === void 0 ? onCancel() : onCommit(next)
4308
- }
4309
- ) });
4310
- }
4311
-
4312
- // src/grid-dom/editors/editor-registry-dom.ts
4313
- function wrapNativeEditor(Editor, presetClass) {
4314
- if (!presetClass) return Editor;
4315
- const wrapped = Editor;
4316
- wrapped.overlayPresetClass = presetClass;
4317
- return wrapped;
4318
- }
4319
- var DOM_EDITOR_REGISTRY = {
4320
- // Text types
4321
- text: TextEditor,
4322
- varchar: TextEditor,
4323
- // Number types (the whole NUMBER_TYPES family, incl. rating)
4324
- number: NumberEditorDom,
4325
- integer: NumberEditorDom,
4326
- smallint: NumberEditorDom,
4327
- decimal: NumberEditorDom,
4328
- currency: NumberEditorDom,
4329
- percentage: NumberEditorDom,
4330
- rating: NumberEditorDom,
4331
- // Media types (the whole MEDIA_TYPES family reuses the image editor, as in glide)
4332
- image: ImageEditorDom,
4333
- file: ImageEditorDom,
4334
- video: ImageEditorDom,
4335
- audio: ImageEditorDom,
4336
- upload: ImageEditorDom,
4337
- // Date/time types
4338
- date: DateEditorDom,
4339
- datetime: DateEditorDom,
4340
- timestamptz: DateEditorDom,
4341
- time: DateEditorDom,
4342
- // Geometry types
4343
- geometry: GeometryEditorDom,
4344
- "geometry-point": GeometryEditorDom,
4345
- "geometry-collection": GeometryEditorDom,
4346
- // Other complex types
4347
- interval: IntervalEditorDom,
4348
- relation: RelationEditorDom,
4349
- tsvector: TsvectorEditorDom,
4350
- inet: InetEditorDom,
4351
- url: UrlEditorDom,
4352
- // Array types
4353
- array: ArrayEditorDom,
4354
- "text-array": ArrayEditorDom,
4355
- "uuid-array": ArrayEditorDom,
4356
- "number-array": ArrayEditorDom,
4357
- "integer-array": ArrayEditorDom,
4358
- "date-array": ArrayEditorDom,
4359
- tags: ArrayEditorDom,
4360
- // JSON types
4361
- json: JsonEditorDom,
4362
- jsonb: JsonEditorDom
4363
- };
4364
- function resolveNativeEditor(typeKey, consumer) {
4365
- return consumer?.(typeKey) ?? DOM_EDITOR_REGISTRY[typeKey];
4366
- }
4367
-
4368
- export {
4369
- resolveRelationFieldMap,
4370
- validateOrderByVariables,
4371
- resolveSheetsRowIdentity,
4372
- resolveSheetsIdentifier,
4373
- sheetsIdentifierToWhere,
4374
- sheetsIdentifierCacheKey,
4375
- sheetsRowKey,
4376
- getSheetsWriteCapability,
4377
- canRunSheetsMutation,
4378
- sheetsTableQueryKeys,
4379
- transformToPostGraphileVariables,
4380
- useSheetsTable,
4381
- createPostGraphileAdapter,
4382
- useSheetsAdapter,
4383
- useSheetsMeta,
4384
- createSheetsCell,
4385
- getImageMetadata,
4386
- OverlayMeasureContext,
4387
- computeOverlayGeometry,
4388
- OverlayViewportGuard,
4389
- executeFieldUpload,
4390
- useSheetsFieldUpload,
4391
- useSheetsImageUpload,
4392
- useSheetsTableCursor,
4393
- wrapNativeEditor,
4394
- DOM_EDITOR_REGISTRY,
4395
- resolveNativeEditor
4396
- };
4397
- //# sourceMappingURL=chunk-5QPNOKMA.js.map