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