@constructive-io/sheets 0.14.1 → 0.15.0

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