@constructive-io/sheets 0.13.0 → 0.14.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/README.md +10 -1
  2. package/dist/advanced.cjs +555 -680
  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 +4 -4
  7. package/dist/auth.cjs.map +1 -1
  8. package/dist/auth.js +2 -2
  9. package/dist/{chunk-PZL2BCWF.js → chunk-6Y7CZ5VS.js} +2 -2
  10. package/dist/chunk-6Y7CZ5VS.js.map +1 -0
  11. package/dist/{chunk-26J3DVW7.js → chunk-BGL6EBTE.js} +116 -173
  12. package/dist/chunk-BGL6EBTE.js.map +1 -0
  13. package/dist/{chunk-MXVNIKES.js → chunk-BYAYBXVB.js} +2 -2
  14. package/dist/{chunk-CBXNKMN6.js → chunk-ER3FIDK7.js} +444 -458
  15. package/dist/chunk-ER3FIDK7.js.map +1 -0
  16. package/dist/chunk-GZM2CSTR.js +279 -0
  17. package/dist/chunk-GZM2CSTR.js.map +1 -0
  18. package/dist/{chunk-H5HR5HUJ.js → chunk-YJZFHL2D.js} +1 -1
  19. package/dist/chunk-YJZFHL2D.js.map +1 -0
  20. package/dist/{date-editor-ZFNDKYBD.js → date-editor-G26WKILO.js} +2 -2
  21. package/dist/{grid-cell-types-Pbe2m2tE.d.ts → grid-cell-types-C2-ocDS7.d.cts} +45 -5
  22. package/dist/{grid-cell-types-Pbe2m2tE.d.cts → grid-cell-types-C2-ocDS7.d.ts} +45 -5
  23. package/dist/index.cjs +789 -607
  24. package/dist/index.cjs.map +1 -1
  25. package/dist/index.d.cts +106 -112
  26. package/dist/index.d.ts +106 -112
  27. package/dist/index.js +234 -134
  28. package/dist/index.js.map +1 -1
  29. package/dist/{sheets-context-Cu3Ec_ca.d.ts → sheets-context-CHUVJCff.d.ts} +32 -31
  30. package/dist/{sheets-context-CY1RmDKL.d.cts → sheets-context-C_MkTxXm.d.cts} +32 -31
  31. package/dist/testing.cjs +128 -57
  32. package/dist/testing.cjs.map +1 -1
  33. package/dist/testing.d.cts +2 -2
  34. package/dist/testing.d.ts +2 -2
  35. package/dist/testing.js +16 -4
  36. package/dist/testing.js.map +1 -1
  37. package/package.json +5 -4
  38. package/dist/chunk-26J3DVW7.js.map +0 -1
  39. package/dist/chunk-CBXNKMN6.js.map +0 -1
  40. package/dist/chunk-H5HR5HUJ.js.map +0 -1
  41. package/dist/chunk-HETVHNMD.js +0 -123
  42. package/dist/chunk-HETVHNMD.js.map +0 -1
  43. package/dist/chunk-PZL2BCWF.js.map +0 -1
  44. /package/dist/{chunk-MXVNIKES.js.map → chunk-BYAYBXVB.js.map} +0 -0
  45. /package/dist/{date-editor-ZFNDKYBD.js.map → date-editor-G26WKILO.js.map} +0 -0
@@ -1,15 +1,13 @@
1
1
  "use client";
2
2
  import {
3
- createSheetsExecute,
4
- createSheetsUpload,
3
+ fetchMediaDownloadUrls,
5
4
  reuseSheetsPlaceholderData,
6
5
  sheetsQueryKeys
7
- } from "./chunk-26J3DVW7.js";
6
+ } from "./chunk-BGL6EBTE.js";
8
7
  import {
9
8
  useSheetsContext,
10
- useSheetsStore,
11
- useSheetsStoreApi
12
- } from "./chunk-H5HR5HUJ.js";
9
+ useSheetsStore
10
+ } from "./chunk-YJZFHL2D.js";
13
11
  import {
14
12
  BOOLEAN_TYPES,
15
13
  DATE_TIME_TYPES,
@@ -20,7 +18,7 @@ import {
20
18
  OVERLAY,
21
19
  OVERLAY_SM,
22
20
  isArrayCellType
23
- } from "./chunk-PZL2BCWF.js";
21
+ } from "./chunk-6Y7CZ5VS.js";
24
22
  import {
25
23
  cn
26
24
  } from "./chunk-YDQQA46V.js";
@@ -104,6 +102,7 @@ import { useMutation, useQuery as useQuery2, useQueryClient } from "@tanstack/re
104
102
  import { useQuery } from "@tanstack/react-query";
105
103
 
106
104
  // src/adapter/postgraphile-adapter.ts
105
+ import { print } from "graphql";
107
106
  import {
108
107
  META_CONTRACT_INTROSPECTION_DOCUMENT,
109
108
  META_DOCUMENT,
@@ -116,6 +115,7 @@ import {
116
115
  buildPostGraphileUpdate,
117
116
  buildSelect,
118
117
  createError,
118
+ getCustomAstForCleanField,
119
119
  normalizeSchemaEnumInputValues,
120
120
  prepareCreateInput,
121
121
  prepareUpdateInput,
@@ -241,11 +241,17 @@ function createPostGraphileAdapter() {
241
241
  },
242
242
  async updateRow(ctx, id, patch, execute, options = {}) {
243
243
  const { table, allTables, tableName } = ctx;
244
- const doc = buildPostGraphileUpdate(table, allTables, {
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, {
245
252
  ...options,
246
253
  fieldSelection: options.fieldSelection || "display"
247
254
  });
248
- const patchFieldName = toPatchFieldName(tableName, table);
249
255
  const sanitizedPatch = prepareUpdateInput(patch);
250
256
  if (Object.keys(sanitizedPatch).length === 0) return null;
251
257
  const normalizedPatch = normalizeMutationEnums(ctx, sanitizedPatch, execute);
@@ -256,8 +262,6 @@ function createPostGraphileAdapter() {
256
262
  }
257
263
  };
258
264
  const result = await execute(doc, variables);
259
- const mutationName = toUpdateMutationName(tableName, table);
260
- const singularName = toCamelCaseSingular(tableName, table);
261
265
  const updatedRow = result[mutationName]?.[singularName] ?? null;
262
266
  return updatedRow;
263
267
  },
@@ -939,22 +943,52 @@ function create3(value, _metadata, deriveGeometry) {
939
943
  }
940
944
  var geometrySheetsCellFactory = { canHandle: canHandle3, create: create3 };
941
945
 
942
- // src/cell-model/factories/image.ts
943
- function resolveMediaUrl(value) {
944
- if (typeof value === "string") return value;
945
- if (typeof value === "object" && value) {
946
- const obj = value;
947
- return obj.url || obj.src || obj.href || obj.path || "";
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
+ }
948
960
  }
949
- return "";
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;
950
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
951
986
  var imageSheetsCellFactory = {
952
987
  canHandle(cellType) {
953
- return MEDIA_TYPES.has(cellType);
988
+ return cellType !== "attachment" && MEDIA_TYPES.has(cellType);
954
989
  },
955
990
  create(value, metadata) {
956
- const url = value === null || value === void 0 || value === "" ? "" : resolveMediaUrl(value);
957
- const data = [url];
991
+ const data = [getImageUrl(value) ?? ""];
958
992
  return {
959
993
  kind: "image",
960
994
  data,
@@ -1350,197 +1384,102 @@ function OverlayViewportGuard({ children, debugName, marginPx = 12, minBelowPx =
1350
1384
  }
1351
1385
 
1352
1386
  // src/hooks/use-sheets-upload.ts
1353
- import { useEffect, useMemo as useMemo3, useRef as useRef2 } from "react";
1354
1387
  import { useMutation as useMutation2, useQueryClient as useQueryClient2 } from "@tanstack/react-query";
1355
1388
  import { cleanTable as cleanTable2 } from "@constructive-io/data";
1356
- import {
1357
- toCamelCaseSingular as toCamelCaseSingular3,
1358
- toPatchFieldName as toPatchFieldName2,
1359
- toUpdateInputTypeName,
1360
- toUpdateMutationName as toUpdateMutationName2
1361
- } from "@constructive-io/data";
1362
- function resolveUploadNaming(tableName, table) {
1363
- return {
1364
- mutationName: toUpdateMutationName2(tableName, table),
1365
- singularName: toCamelCaseSingular3(tableName, table),
1366
- patchFieldName: toPatchFieldName2(tableName, table),
1367
- updateInputTypeName: toUpdateInputTypeName(tableName)
1368
- };
1369
- }
1370
- function resolveTransport(endpoint, getToken, options) {
1371
- if (options?.execute && options?.executeUpload) {
1372
- return { execute: options.execute, executeUpload: options.executeUpload };
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}'.`);
1373
1394
  }
1374
- const config = {
1375
- endpoint,
1376
- auth: { mode: "standalone" },
1377
- onAuthError: options?.onAuthError
1378
- };
1379
- return {
1380
- execute: createSheetsExecute(config, getToken),
1381
- executeUpload: createSheetsUpload(config, getToken)
1382
- };
1383
- }
1384
- async function executeFieldUpload(tableName, fieldName, recordId, file, endpoint, getToken, naming, options) {
1385
- if (!endpoint && !(options?.execute && options?.executeUpload)) {
1386
- throw new Error("No endpoint configured. Select a database API or use Direct Connect.");
1387
- }
1388
- const { execute, executeUpload } = resolveTransport(endpoint, getToken, options);
1389
- const uploadResult = await executeUpload(file, void 0, {
1390
- tableName,
1391
- fieldName,
1392
- recordId,
1393
- onProgress: options?.onProgress
1394
- });
1395
- const resolvedNaming = naming ?? resolveUploadNaming(tableName);
1396
- const patchValue = {
1397
- ...uploadResult.url != null && { url: uploadResult.url },
1398
- ...uploadResult.filename != null && { filename: uploadResult.filename },
1399
- ...uploadResult.mime != null && { mime: uploadResult.mime },
1400
- ...uploadResult.size != null && { size: uploadResult.size }
1401
- };
1402
- const mutationString = `
1403
- mutation ${resolvedNaming.mutationName}Mutation($input: ${resolvedNaming.updateInputTypeName}!) {
1404
- ${resolvedNaming.mutationName}(input: $input) {
1405
- ${resolvedNaming.singularName} {
1406
- id
1407
- ${fieldName}
1408
- }
1409
- }
1410
- }
1411
- `.trim();
1412
- const result = await execute(mutationString, {
1413
- input: {
1414
- id: recordId,
1415
- [resolvedNaming.patchFieldName]: {
1416
- [fieldName]: patchValue
1417
- }
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
+ };
1418
1416
  }
1419
- });
1420
- const updatedRecord = result?.[resolvedNaming.mutationName]?.[resolvedNaming.singularName];
1421
- if (!updatedRecord) {
1422
- throw new Error("Upload succeeded but no data returned from patch");
1423
1417
  }
1424
- const uploadedFileData = updatedRecord[fieldName];
1425
- if (!uploadedFileData) {
1426
- throw new Error(`Upload succeeded but ${fieldName} field not found in response`);
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
1427
  }
1428
- const fileObject = typeof uploadedFileData === "object" ? uploadedFileData : null;
1429
- return {
1430
- url: fileObject?.url || uploadedFileData,
1431
- filename: fileObject?.filename || file.name,
1432
- mime: fileObject?.mime || file.type,
1433
- size: fileObject?.size || file.size
1434
- };
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}'.`);
1435
1437
  }
1436
1438
  function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
1437
1439
  const queryClient = useQueryClient2();
1438
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
1439
- const storeApi = useSheetsStoreApi();
1440
- const { data: meta } = useSheetsMeta();
1441
- const table = useMemo3(() => {
1442
- if (!meta?._meta?.tables) return null;
1443
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
1444
- return candidate ? cleanTable2(candidate) : null;
1445
- }, [meta, tableName]);
1446
- const resolvedNaming = useMemo3(() => resolveUploadNaming(tableName, table), [tableName, table]);
1447
- const getToken = useMemo3(() => {
1448
- if (config.auth.mode === "embedded") {
1449
- return config.auth.getToken;
1450
- }
1451
- return () => storeApi.getState().accessToken;
1452
- }, [config.auth, storeApi]);
1453
- const tableRef = useRef2(tableName);
1454
- const fieldRef = useRef2(fieldName);
1455
- const idRef = useRef2(recordId);
1456
- useEffect(() => {
1457
- tableRef.current = tableName;
1458
- fieldRef.current = fieldName;
1459
- idRef.current = recordId;
1460
- }, [tableName, fieldName, recordId]);
1461
- return useMutation2({
1462
- mutationKey: ["sheets", scopeKey, "field-upload", tableName, fieldName, recordId],
1463
- mutationFn: async (file) => {
1464
- return executeFieldUpload(
1465
- tableRef.current,
1466
- fieldRef.current,
1467
- idRef.current,
1468
- file,
1469
- config.endpoint,
1470
- getToken,
1471
- resolvedNaming,
1472
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
1473
- );
1474
- },
1475
- onSuccess: (data) => {
1476
- options.onSuccess?.(data);
1477
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
1478
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
1479
- },
1480
- onError: (error) => {
1481
- options.onError?.(error);
1482
- }
1483
- });
1484
- }
1485
- function useSheetsImageUpload(tableName, fieldName, recordId, options = {}) {
1486
- const queryClient = useQueryClient2();
1487
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
1488
- const storeApi = useSheetsStoreApi();
1440
+ const { execute, executeUpload, scopeKey } = useSheetsContext();
1489
1441
  const { data: meta } = useSheetsMeta();
1490
- const table = useMemo3(() => {
1491
- if (!meta?._meta?.tables) return null;
1492
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
1493
- return candidate ? cleanTable2(candidate) : null;
1494
- }, [meta, tableName]);
1495
- const resolvedNaming = useMemo3(() => resolveUploadNaming(tableName, table), [tableName, table]);
1496
- const getToken = useMemo3(() => {
1497
- if (config.auth.mode === "embedded") {
1498
- return config.auth.getToken;
1499
- }
1500
- return () => storeApi.getState().accessToken;
1501
- }, [config.auth, storeApi]);
1502
- const tableRef = useRef2(tableName);
1503
- const fieldRef = useRef2(fieldName);
1504
- const idRef = useRef2(recordId);
1505
- useEffect(() => {
1506
- tableRef.current = tableName;
1507
- fieldRef.current = fieldName;
1508
- idRef.current = recordId;
1509
- }, [tableName, fieldName, recordId]);
1510
- return useMutation2({
1511
- mutationKey: ["sheets", scopeKey, "image-upload", tableName, fieldName, recordId],
1512
- mutationFn: async (file) => {
1513
- if (!file.type.startsWith("image/")) {
1514
- throw new Error("Please select an image file");
1515
- }
1516
- const maxSize = 10 * 1024 * 1024;
1517
- if (file.size > maxSize) {
1518
- throw new Error("File size must be less than 10MB");
1519
- }
1520
- return executeFieldUpload(
1521
- tableRef.current,
1522
- fieldRef.current,
1523
- idRef.current,
1524
- file,
1525
- config.endpoint,
1526
- getToken,
1527
- resolvedNaming,
1528
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
1529
- );
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);
1530
1471
  },
1531
- onSuccess: (data) => {
1532
- options.onSuccess?.(data);
1533
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
1534
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
1472
+ onSuccess: (value) => {
1473
+ options.onSuccess?.(value);
1474
+ invalidate();
1535
1475
  },
1536
- onError: (error) => {
1537
- options.onError?.(error);
1538
- }
1476
+ onError: options.onError
1539
1477
  });
1478
+ return { ...mutation, write, resolveRowIdentifier };
1540
1479
  }
1541
1480
 
1542
1481
  // src/hooks/use-sheets-table-cursor.ts
1543
- import { useMemo as useMemo4 } from "react";
1482
+ import { useMemo as useMemo3 } from "react";
1544
1483
  import { useInfiniteQuery, useQueryClient as useQueryClient3 } from "@tanstack/react-query";
1545
1484
  import {
1546
1485
  cleanTable as cleanTable3
@@ -1552,20 +1491,20 @@ function useSheetsTableCursor(tableName, options = {}) {
1552
1491
  const { execute, scopeKey } = useSheetsContext();
1553
1492
  const { data: meta } = useSheetsMeta();
1554
1493
  const adapter = useSheetsAdapter();
1555
- const tables = useMemo4(() => {
1494
+ const tables = useMemo3(() => {
1556
1495
  if (!meta?._meta?.tables) return [];
1557
1496
  return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => cleanTable3(metaTable));
1558
1497
  }, [meta]);
1559
- const table = useMemo4(
1498
+ const table = useMemo3(
1560
1499
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
1561
1500
  [tables, tableName]
1562
1501
  );
1563
1502
  const { enabled = true, select: fieldSelection, pageSize = 20, where, orderBy } = options;
1564
- const stableOptions = useMemo4(
1503
+ const stableOptions = useMemo3(
1565
1504
  () => ({ fieldSelection, where, orderBy }),
1566
1505
  [fieldSelection, where, orderBy]
1567
1506
  );
1568
- const queryOptions = useMemo4(
1507
+ const queryOptions = useMemo3(
1569
1508
  () => ({
1570
1509
  fieldSelection,
1571
1510
  where,
@@ -1639,11 +1578,11 @@ function useSheetsTableCursor(tableName, options = {}) {
1639
1578
  enabled: enabled && !!table,
1640
1579
  staleTime: 5 * 60 * 1e3
1641
1580
  });
1642
- const flatData = useMemo4(
1581
+ const flatData = useMemo3(
1643
1582
  () => data?.pages.flatMap((page) => page.rows) ?? [],
1644
1583
  [data]
1645
1584
  );
1646
- const totalCount = useMemo4(
1585
+ const totalCount = useMemo3(
1647
1586
  () => data?.pages[data.pages.length - 1]?.totalCount ?? 0,
1648
1587
  [data]
1649
1588
  );
@@ -1659,7 +1598,7 @@ function useSheetsTableCursor(tableName, options = {}) {
1659
1598
  }
1660
1599
 
1661
1600
  // src/grid/editors/array-editor.tsx
1662
- import { useCallback, useEffect as useEffect2, useMemo as useMemo5, useRef as useRef3, useState } from "react";
1601
+ import { useCallback, useEffect, useMemo as useMemo4, useRef as useRef2, useState } from "react";
1663
1602
  import { Badge } from "@constructive-io/ui/badge";
1664
1603
  import { Button } from "@constructive-io/ui/button";
1665
1604
  import { XIcon } from "lucide-react";
@@ -1675,11 +1614,11 @@ function mergeArrayEditorValues(list, pendingInput) {
1675
1614
  return [...list, ...pendingItems];
1676
1615
  }
1677
1616
  function ArrayEditor({ value, onChange, onFinished }) {
1678
- const items = useMemo5(() => Array.isArray(value) ? value : [], [value]);
1617
+ const items = useMemo4(() => Array.isArray(value) ? value : [], [value]);
1679
1618
  const [list, setList] = useState(items);
1680
1619
  const [input, setInput] = useState("");
1681
- const inputRef = useRef3(null);
1682
- const keyContainerRef = useRef3(null);
1620
+ const inputRef = useRef2(null);
1621
+ const keyContainerRef = useRef2(null);
1683
1622
  const handleCancel = useCallback(() => onFinished(void 0), [onFinished]);
1684
1623
  const handleSave = useCallback(() => {
1685
1624
  const next = mergeArrayEditorValues(list, input);
@@ -1704,11 +1643,11 @@ function ArrayEditor({ value, onChange, onFinished }) {
1704
1643
  },
1705
1644
  [list, onChange]
1706
1645
  );
1707
- const actionsRef = useRef3({ add, handleSave, remove, handleCancel });
1646
+ const actionsRef = useRef2({ add, handleSave, remove, handleCancel });
1708
1647
  actionsRef.current = { add, handleSave, remove, handleCancel };
1709
- const stateRef = useRef3({ input, listLength: list.length });
1648
+ const stateRef = useRef2({ input, listLength: list.length });
1710
1649
  stateRef.current = { input, listLength: list.length };
1711
- useEffect2(() => {
1650
+ useEffect(() => {
1712
1651
  const el = keyContainerRef.current;
1713
1652
  if (!el) return;
1714
1653
  const handler = (e) => {
@@ -1839,7 +1778,7 @@ function ArrayEditorDom({ value, onCommit, onCancel }) {
1839
1778
  // src/grid-dom/editors/date-editor.tsx
1840
1779
  import { lazy, Suspense } from "react";
1841
1780
  import { jsx as jsx4 } from "react/jsx-runtime";
1842
- var DateEditor = lazy(() => import("./date-editor-ZFNDKYBD.js").then((m) => ({ default: m.DateEditor })));
1781
+ var DateEditor = lazy(() => import("./date-editor-G26WKILO.js").then((m) => ({ default: m.DateEditor })));
1843
1782
  function DateEditorDom({ value, cell, onCommit, onCancel }) {
1844
1783
  const cellType = cell.meta?.cellType;
1845
1784
  const dateType = cellType && DATE_TIME_TYPES.has(cellType) ? cellType : void 0;
@@ -1857,7 +1796,7 @@ function DateEditorDom({ value, cell, onCommit, onCancel }) {
1857
1796
  import { Suspense as Suspense3 } from "react";
1858
1797
 
1859
1798
  // src/grid/editors/geometry-editor.tsx
1860
- import { lazy as lazy2, Suspense as Suspense2, useCallback as useCallback2, useContext, useLayoutEffect as useLayoutEffect2, useMemo as useMemo6, useRef as useRef4, useState as useState2 } from "react";
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";
1861
1800
  import { AlertCircle, FileText, Loader2, Map as Map2, MapPin, Shuffle } from "lucide-react";
1862
1801
  import { Button as Button2 } from "@constructive-io/ui/button";
1863
1802
  import { Tabs, TabsContent, TabsList, TabsTrigger } from "@constructive-io/ui/tabs";
@@ -2056,7 +1995,7 @@ function generateRandomGeometry(constrainedType) {
2056
1995
  }
2057
1996
  var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
2058
1997
  const currentGeometryData = value;
2059
- const geometryValue = useMemo6(() => parseGeometryValue(currentGeometryData), [currentGeometryData]);
1998
+ const geometryValue = useMemo5(() => parseGeometryValue(currentGeometryData), [currentGeometryData]);
2060
1999
  const [editingValue, setEditingValue] = useState2(() => {
2061
2000
  if (!currentGeometryData) return "";
2062
2001
  const geo = parseGeometryValue(currentGeometryData);
@@ -2064,7 +2003,7 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
2064
2003
  return formatGeometry(currentGeometryData);
2065
2004
  });
2066
2005
  const canShowMap = expectedType === "Point" || !expectedType && geometryValue != null && isPointGeometry(geometryValue);
2067
- const validationResult = useMemo6(() => validateGeometry(editingValue, expectedType), [editingValue, expectedType]);
2006
+ const validationResult = useMemo5(() => validateGeometry(editingValue, expectedType), [editingValue, expectedType]);
2068
2007
  const isValid = validationResult === true;
2069
2008
  const validationError = typeof validationResult === "string" ? validationResult : void 0;
2070
2009
  const [activeTab, setActiveTab] = useState2(() => canShowMap ? "map" : "json");
@@ -2105,7 +2044,7 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
2105
2044
  },
2106
2045
  [isValid, handleSave]
2107
2046
  );
2108
- const mapPickerValue = useMemo6(() => {
2047
+ const mapPickerValue = useMemo5(() => {
2109
2048
  try {
2110
2049
  if (editingValue) {
2111
2050
  const raw = extractRawGeoJSON(JSON.parse(editingValue));
@@ -2119,8 +2058,8 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
2119
2058
  return void 0;
2120
2059
  }, [editingValue, geometryValue]);
2121
2060
  const { maxHeight: overlayMaxHeight } = useContext(OverlayMeasureContext);
2122
- const editorRef = useRef4(null);
2123
- const contentRef = useRef4(null);
2061
+ const editorRef = useRef3(null);
2062
+ const contentRef = useRef3(null);
2124
2063
  const [scrollBudget, setScrollBudget] = useState2();
2125
2064
  useLayoutEffect2(() => {
2126
2065
  const editor = editorRef.current;
@@ -2230,65 +2169,110 @@ function GeometryEditorDom({ value, fieldMeta, onCommit, onCancel }) {
2230
2169
  import { Suspense as Suspense4 } from "react";
2231
2170
 
2232
2171
  // src/grid/editors/image-editor.tsx
2233
- import { useCallback as useCallback3, useContext as useContext2, useEffect as useEffect4, useMemo as useMemo8, useRef as useRef5, useState as useState5 } from "react";
2172
+ import { useCallback as useCallback4, useContext as useContext2, useEffect as useEffect3, useMemo as useMemo8, useRef as useRef5, useState as useState6 } from "react";
2234
2173
  import { AlertCircleIcon, FileIcon, ImageIcon, ImageOff, Loader2 as Loader22, UploadIcon, XIcon as XIcon2 } from "lucide-react";
2235
2174
  import { AnimatePresence, motion } from "motion/react";
2236
2175
  import { toast } from "@constructive-io/ui/toast";
2237
2176
 
2238
- // src/utils/file.utils.ts
2239
- var getImageUrl = (imageValue) => {
2240
- if (!imageValue) return null;
2241
- if (typeof imageValue === "string") {
2242
- return imageValue;
2243
- }
2244
- if (typeof imageValue === "object" && imageValue !== null) {
2245
- const urlCandidates = ["url", "src", "href", "link", "path"];
2246
- for (const candidate of urlCandidates) {
2247
- const obj = imageValue;
2248
- if (obj[candidate] && typeof obj[candidate] === "string") {
2249
- return obj[candidate];
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);
2250
2192
  }
2193
+ } catch (error) {
2194
+ for (const request of requests) request.reject(error);
2251
2195
  }
2252
2196
  }
2253
- return null;
2254
- };
2255
- var getImageMetadata = (imageValue) => {
2256
- if (!imageValue || typeof imageValue !== "object") return null;
2257
- const obj = imageValue;
2258
- return {
2259
- filename: obj.filename || obj.name || "Unknown",
2260
- size: obj.size || obj.fileSize || 0,
2261
- mime: obj.mime || obj.type || obj.contentType || "unknown",
2262
- url: getImageUrl(imageValue) || ""
2263
- };
2264
- };
2265
- var formatFileSize = (bytes) => {
2266
- if (bytes === 0) return "0 B";
2267
- const k = 1024;
2268
- const sizes = ["B", "KB", "MB", "GB"];
2269
- const i = Math.floor(Math.log(bytes) / Math.log(k));
2270
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
2271
- };
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
+ }
2272
2256
 
2273
2257
  // src/utils/use-image-status.ts
2274
- import { useEffect as useEffect3, useState as useState3 } from "react";
2258
+ import { useEffect as useEffect2, useState as useState4 } from "react";
2275
2259
  function useImageStatus(src) {
2276
- const [status, setStatus] = useState3("idle");
2277
- useEffect3(() => {
2278
- if (!src) return setStatus("idle");
2279
- setStatus("loading");
2260
+ const [result, setResult] = useState4();
2261
+ useEffect2(() => {
2262
+ if (!src) return;
2280
2263
  const img = new Image();
2281
- img.src = src;
2282
- const onLoad = () => setStatus("loaded");
2283
- const onError = () => setStatus("error");
2264
+ const onLoad = () => setResult({ src, status: "loaded" });
2265
+ const onError = () => setResult({ src, status: "error" });
2284
2266
  img.addEventListener("load", onLoad);
2285
2267
  img.addEventListener("error", onError);
2268
+ img.src = src;
2286
2269
  return () => {
2287
2270
  img.removeEventListener("load", onLoad);
2288
2271
  img.removeEventListener("error", onError);
2289
2272
  };
2290
2273
  }, [src]);
2291
- return status;
2274
+ if (!src) return "idle";
2275
+ return result?.src === src ? result.status : "loading";
2292
2276
  }
2293
2277
 
2294
2278
  // src/grid/editors/image-editor.tsx
@@ -2296,7 +2280,7 @@ import { Button as Button3 } from "@constructive-io/ui/button";
2296
2280
  import { Skeleton } from "@constructive-io/ui/skeleton";
2297
2281
 
2298
2282
  // src/utils/image-with-fallback.tsx
2299
- import { useMemo as useMemo7, useState as useState4 } from "react";
2283
+ import { useMemo as useMemo7, useState as useState5 } from "react";
2300
2284
  import { jsx as jsx7 } from "react/jsx-runtime";
2301
2285
  function ImageWithFallback({
2302
2286
  src,
@@ -2315,7 +2299,7 @@ function ImageWithFallback({
2315
2299
  const primaryFallbacks = fallback === void 0 ? [] : Array.isArray(fallback) ? fallback : [fallback];
2316
2300
  return [...primaryFallbacks, ...legacyFallbacks];
2317
2301
  }, [fallback, fallbackElement, loadingElement]);
2318
- const [currentSrcIndex, setCurrentSrcIndex] = useState4(0);
2302
+ const [currentSrcIndex, setCurrentSrcIndex] = useState5(0);
2319
2303
  const currentSrc = currentSrcIndex === 0 ? src : fallbacks[currentSrcIndex - 1];
2320
2304
  const status = useImageStatus(typeof currentSrc === "string" ? currentSrc : void 0);
2321
2305
  if (status === "error" && currentSrcIndex < fallbacks.length) {
@@ -2355,9 +2339,6 @@ function ImageWithFallback({
2355
2339
 
2356
2340
  // src/grid/editors/image-editor.tsx
2357
2341
  import { Fragment as Fragment2, jsx as jsx8, jsxs as jsxs3 } from "react/jsx-runtime";
2358
- function normalizeUploadResponse(data) {
2359
- return { url: data.url, filename: data.filename, size: data.size, mime: data.mime };
2360
- }
2361
2342
  var dropzoneTransition = { duration: 0.15, ease: [0.2, 0, 0, 1] };
2362
2343
  function RemoveButton({ onClick, label }) {
2363
2344
  return /* @__PURE__ */ jsx8("div", { className: "absolute top-2 right-2", children: /* @__PURE__ */ jsx8(
@@ -2376,13 +2357,14 @@ function RemoveButton({ onClick, label }) {
2376
2357
  }
2377
2358
  function FilePreview({ name, size, mime }) {
2378
2359
  const hasMime = !!mime && mime !== "unknown";
2360
+ const hasSize = size !== void 0;
2379
2361
  return /* @__PURE__ */ jsxs3("div", { className: "flex size-full flex-col items-center justify-center gap-2 p-4 text-center", children: [
2380
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" }) }),
2381
2363
  /* @__PURE__ */ jsxs3("div", { className: "min-w-0 max-w-full", children: [
2382
2364
  /* @__PURE__ */ jsx8("p", { className: "truncate text-sm font-medium", title: name, children: name || "File" }),
2383
- (size || hasMime) && /* @__PURE__ */ jsxs3("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
2384
- size ? formatFileSize(size) : null,
2385
- size && hasMime ? " \u2022 " : null,
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,
2386
2368
  hasMime ? /* @__PURE__ */ jsx8("span", { className: "uppercase", children: mime }) : null
2387
2369
  ] })
2388
2370
  ] })
@@ -2402,72 +2384,79 @@ var ImageEditor = ({
2402
2384
  }) => {
2403
2385
  const noun = acceptAnyFile ? "file" : "image";
2404
2386
  const Noun = acceptAnyFile ? "File" : "Image";
2405
- const [uploadState, setUploadState] = useState5("idle");
2406
- const { config } = useSheetsContext();
2407
- const storeApi = useSheetsStoreApi();
2387
+ const [uploadState, setUploadState] = useState6("idle");
2408
2388
  const { maxHeight: overlayMaxHeight } = useContext2(OverlayMeasureContext);
2409
- const getToken = useMemo8(() => {
2410
- if (config.auth.mode === "embedded") return config.auth.getToken;
2411
- return () => storeApi.getState().accessToken;
2412
- }, [config.auth, storeApi]);
2413
2389
  const fileInputRef = useRef5(null);
2414
2390
  const previewUrlRef = useRef5(null);
2415
2391
  const committedRecordIdRef = useRef5(null);
2416
2392
  const currentImageData = value ?? null;
2417
- const [imageValue, setImageValue] = useState5(currentImageData);
2418
- const [selectedFile, setSelectedFile] = useState5(null);
2419
- const [previewUrl, setPreviewUrl] = useState5(null);
2420
- const [uploadProgress, setUploadProgress] = useState5(null);
2421
- const [isDragging, setIsDragging] = useState5(false);
2422
- const [dragErrors, setDragErrors] = useState5([]);
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([]);
2423
2399
  const isSubmittingDraft = uploadState === "submitting-draft";
2424
2400
  const isUploading = uploadState === "uploading";
2401
+ const isClearing = uploadState === "clearing";
2425
2402
  const isBusy = uploadState !== "idle";
2426
- const imageUrl = useMemo8(() => getImageUrl(imageValue), [imageValue]);
2427
2403
  const imageMetadata = useMemo8(() => getImageMetadata(imageValue), [imageValue]);
2428
2404
  const storedMime = imageMetadata?.mime;
2429
2405
  const storedIsImage = !acceptAnyFile || !!storedMime && storedMime.startsWith("image/");
2406
+ const { url: imageUrl, durableUrl, id: storedFileId, isLoading: isResolvingImage, onImageError, onImageLoad } = useSheetsMediaUrl(imageValue, storedIsImage);
2430
2407
  const imageStatus = useImageStatus(storedIsImage ? imageUrl || void 0 : void 0);
2431
- const imageLoadFailed = storedIsImage && imageUrl != null && imageStatus === "error";
2432
- const hasImage = imageUrl != null && !imageLoadFailed && storedIsImage;
2433
- const revokePreviewUrl = useCallback3(() => {
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(() => {
2434
2419
  if (previewUrlRef.current) {
2435
2420
  URL.revokeObjectURL(previewUrlRef.current);
2436
2421
  previewUrlRef.current = null;
2437
2422
  }
2438
2423
  }, []);
2439
- const resetFileState = useCallback3(() => {
2424
+ const resetFileState = useCallback4(() => {
2440
2425
  revokePreviewUrl();
2441
2426
  setUploadProgress(null);
2442
2427
  setSelectedFile(null);
2443
2428
  setPreviewUrl(null);
2444
2429
  setUploadState("idle");
2445
2430
  }, [revokePreviewUrl]);
2446
- const handleUploadSuccess = useCallback3((data) => {
2447
- const normalized = normalizeUploadResponse(data);
2431
+ const finishSave = useCallback4((data, message) => {
2448
2432
  resetFileState();
2449
- setImageValue(normalized);
2450
- onSaveComplete?.({ imageData: normalized });
2433
+ setImageValue(data);
2434
+ if (committedRecordIdRef.current == null) {
2435
+ onSaveComplete?.({ imageData: data });
2436
+ } else {
2437
+ onDraftUploadComplete?.();
2438
+ }
2451
2439
  onFinishedEditing();
2452
- toast.success({ message: `${Noun} uploaded successfully` });
2453
- }, [resetFileState, onSaveComplete, onFinishedEditing, Noun]);
2454
- const handleUploadError = useCallback3((error) => {
2440
+ toast.success({ message });
2441
+ }, [resetFileState, onSaveComplete, onDraftUploadComplete, onFinishedEditing]);
2442
+ const handleWriteError = useCallback4((error) => {
2455
2443
  setUploadState("idle");
2456
- sheetsLogger().error("[image-editor] upload failed:", error);
2457
- toast.error({ message: error.message || "Upload failed" });
2444
+ setUploadProgress(null);
2445
+ sheetsLogger().error("[image-editor] media update failed:", error);
2446
+ toast.error({ message: error.message || "Could not save the file" });
2458
2447
  }, []);
2459
- const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId || "", {
2448
+ const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId ?? null, {
2460
2449
  onProgress: setUploadProgress,
2461
- onSuccess: handleUploadSuccess,
2462
- onError: handleUploadError,
2450
+ onSuccess: (data) => finishSave(data, data === null ? `${Noun} cleared` : `${Noun} uploaded successfully`),
2451
+ onError: handleWriteError,
2463
2452
  showToast: false
2464
2453
  });
2465
- const handleRemoveImage = useCallback3(() => {
2454
+ const handleRemoveImage = useCallback4(() => {
2466
2455
  setImageValue(null);
2467
2456
  setSelectedFile(null);
2468
2457
  setPreviewUrl(null);
2469
2458
  }, []);
2470
- const handleFileSelection = useCallback3((acceptedFiles) => {
2459
+ const handleFileSelection = useCallback4((acceptedFiles) => {
2471
2460
  if (acceptedFiles.length === 0) return;
2472
2461
  const file = acceptedFiles[0];
2473
2462
  if (!acceptAnyFile) {
@@ -2486,21 +2475,21 @@ var ImageEditor = ({
2486
2475
  previewUrlRef.current = url;
2487
2476
  setPreviewUrl(url);
2488
2477
  }, [revokePreviewUrl, acceptAnyFile]);
2489
- const handleDragEnter = useCallback3((e) => {
2478
+ const handleDragEnter = useCallback4((e) => {
2490
2479
  e.preventDefault();
2491
2480
  e.stopPropagation();
2492
2481
  setIsDragging(true);
2493
2482
  }, []);
2494
- const handleDragLeave = useCallback3((e) => {
2483
+ const handleDragLeave = useCallback4((e) => {
2495
2484
  e.preventDefault();
2496
2485
  e.stopPropagation();
2497
2486
  setIsDragging(false);
2498
2487
  }, []);
2499
- const handleDragOver = useCallback3((e) => {
2488
+ const handleDragOver = useCallback4((e) => {
2500
2489
  e.preventDefault();
2501
2490
  e.stopPropagation();
2502
2491
  }, []);
2503
- const handleDrop = useCallback3((e) => {
2492
+ const handleDrop = useCallback4((e) => {
2504
2493
  e.preventDefault();
2505
2494
  e.stopPropagation();
2506
2495
  setIsDragging(false);
@@ -2508,129 +2497,126 @@ var ImageEditor = ({
2508
2497
  const files = Array.from(e.dataTransfer.files);
2509
2498
  if (files.length > 0) handleFileSelection(files);
2510
2499
  }, [handleFileSelection]);
2511
- const openFileDialog = useCallback3(() => fileInputRef.current?.click(), []);
2512
- const removeFile = useCallback3(() => {
2500
+ const openFileDialog = useCallback4(() => fileInputRef.current?.click(), []);
2501
+ const removeFile = useCallback4(() => {
2513
2502
  revokePreviewUrl();
2514
2503
  setSelectedFile(null);
2515
2504
  setPreviewUrl(null);
2516
2505
  setDragErrors([]);
2517
2506
  }, [revokePreviewUrl]);
2518
- const handleConfirmUpload = useCallback3(async () => {
2519
- if (!tableName || !fieldName || !selectedFile) return;
2520
- const committedId = committedRecordIdRef.current ?? recordId;
2521
- if (committedRecordIdRef.current != null) {
2522
- try {
2523
- toast.info({ message: `Uploading ${noun}...` });
2524
- setUploadState("uploading");
2525
- const uploadResult = await executeFieldUpload(
2526
- tableName,
2527
- fieldName,
2528
- committedRecordIdRef.current,
2529
- selectedFile,
2530
- config.endpoint,
2531
- getToken,
2532
- void 0,
2533
- { onAuthError: config.onAuthError }
2534
- );
2535
- const normalized = normalizeUploadResponse(uploadResult);
2536
- resetFileState();
2537
- setImageValue(normalized);
2538
- onDraftUploadComplete?.();
2539
- toast.success({ message: `${Noun} uploaded successfully` });
2540
- onFinishedEditing();
2541
- } catch (error) {
2542
- onDraftUploadComplete?.();
2543
- setUploadState("idle");
2544
- toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
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;
2545
2513
  }
2514
+ setUploadState("uploading");
2515
+ uploadMutation.mutate(selectedFile);
2546
2516
  return;
2547
2517
  }
2548
- if (isDraftRow) {
2549
- if (!onSubmitDraft) {
2550
- toast.error({ message: "Cannot upload to draft row - save the row first" });
2551
- return;
2552
- }
2553
- try {
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");
2554
2523
  toast.info({ message: "Creating row..." });
2555
2524
  setUploadState("submitting-draft");
2556
- const result = await onSubmitDraft();
2557
- const createdId = result.createdRow?.id;
2558
- if (typeof createdId !== "string" && typeof createdId !== "number") {
2559
- throw new Error("Image uploads require a scalar id primary key.");
2560
- }
2561
- committedRecordIdRef.current = createdId;
2562
- toast.info({ message: `Uploading ${noun}...` });
2563
- setUploadState("uploading");
2564
- const uploadResult = await executeFieldUpload(
2565
- tableName,
2566
- fieldName,
2567
- createdId,
2568
- selectedFile,
2569
- config.endpoint,
2570
- getToken,
2571
- void 0,
2572
- { onAuthError: config.onAuthError }
2573
- );
2574
- const normalized = normalizeUploadResponse(uploadResult);
2575
- resetFileState();
2576
- setImageValue(normalized);
2577
- onDraftUploadComplete?.();
2578
- toast.success({ message: `Row created and ${noun} uploaded` });
2579
- onFinishedEditing();
2580
- } catch (error) {
2581
- onDraftUploadComplete?.();
2582
- setUploadState("idle");
2583
- toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
2525
+ const { createdRow } = await onSubmitDraft();
2526
+ rowPersisted = true;
2527
+ committedRecordIdRef.current = createdRow ? uploadMutation.resolveRowIdentifier(createdRow) : null;
2584
2528
  }
2585
- return;
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"));
2586
2538
  }
2587
- if (!committedId) {
2588
- toast.error({ message: "Missing record context for upload" });
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();
2589
2558
  return;
2590
2559
  }
2591
- setUploadState("uploading");
2592
- uploadMutation.mutate(selectedFile);
2593
- }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing, noun, Noun]);
2594
- const handleSave = useCallback3(() => {
2595
- if (!imageValue) {
2596
- onFinishedEditing(null);
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
+ }
2597
2567
  return;
2598
2568
  }
2599
- const url = getImageUrl(imageValue);
2600
- const originalUrl = getImageUrl(value);
2601
- if (url && originalUrl === url) {
2602
- onFinishedEditing();
2569
+ setUploadState("clearing");
2570
+ if (committedRecordIdRef.current == null) {
2571
+ uploadMutation.mutate(null);
2603
2572
  return;
2604
2573
  }
2605
- onFinishedEditing(url ?? value);
2606
- }, [imageValue, value, onFinishedEditing]);
2607
- const handleCancel = useCallback3(() => {
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(() => {
2608
2582
  revokePreviewUrl();
2609
2583
  onFinishedEditing();
2610
2584
  }, [revokePreviewUrl, onFinishedEditing]);
2611
- useEffect4(() => () => revokePreviewUrl(), [revokePreviewUrl]);
2612
- const handleEditorKeyDown = useCallback3((e) => {
2585
+ useEffect3(() => () => revokePreviewUrl(), [revokePreviewUrl]);
2586
+ const handleEditorKeyDown = useCallback4((e) => {
2613
2587
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
2614
2588
  e.preventDefault();
2615
- handleSave();
2589
+ if (selectedFile) void handleConfirmUpload();
2590
+ else void handleSave();
2616
2591
  }
2617
- }, [handleSave]);
2618
- const hasStoredFile = acceptAnyFile && !!imageUrl && !storedIsImage;
2592
+ }, [handleConfirmUpload, handleSave, selectedFile]);
2593
+ const hasStoredFile = hasStoredMedia && !hasImage && !imageLoadFailed;
2619
2594
  const dropzoneKey = isBusy ? "busy" : previewUrl ? "preview" : hasImage ? "loaded" : hasStoredFile ? "file" : imageLoadFailed ? "broken" : "empty";
2620
2595
  const renderDropzoneContent = () => {
2621
2596
  if (isBusy) {
2622
2597
  return /* @__PURE__ */ jsxs3("div", { "data-state": uploadState, className: "text-muted-foreground flex w-full flex-col items-center justify-center p-6", children: [
2623
2598
  /* @__PURE__ */ jsx8(Loader22, { className: "mb-2 size-6 animate-spin" }),
2624
- /* @__PURE__ */ jsx8("p", { className: "text-sm", children: isSubmittingDraft ? "Creating row..." : `Uploading ${noun}...` }),
2599
+ /* @__PURE__ */ jsx8("p", { role: "status", className: "text-sm", children: isSubmittingDraft ? "Creating row..." : isClearing ? `Clearing ${noun}...` : `Uploading ${noun}...` }),
2625
2600
  isUploading && uploadProgress && /* @__PURE__ */ jsxs3("div", { className: "mt-3 w-full max-w-xs", children: [
2626
- /* @__PURE__ */ jsx8("div", { className: "bg-muted h-1.5 overflow-hidden rounded-full", children: /* @__PURE__ */ jsx8(
2601
+ /* @__PURE__ */ jsx8(
2627
2602
  "div",
2628
2603
  {
2629
- className: "bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)",
2630
- style: { width: `${uploadProgress.percentage}%` }
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
+ )
2631
2617
  }
2632
- ) }),
2633
- /* @__PURE__ */ jsxs3("p", { className: "text-muted-foreground mt-1.5 text-center text-xs", children: [
2618
+ ),
2619
+ /* @__PURE__ */ jsxs3("p", { "aria-hidden": "true", className: "text-muted-foreground mt-1.5 text-center text-xs tabular-nums", children: [
2634
2620
  Math.round(uploadProgress.percentage),
2635
2621
  "%"
2636
2622
  ] })
@@ -2638,7 +2624,6 @@ var ImageEditor = ({
2638
2624
  ] });
2639
2625
  }
2640
2626
  if (previewUrl) {
2641
- const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
2642
2627
  return /* @__PURE__ */ jsxs3("div", { className: "relative w-full", style: { height: "13rem" }, children: [
2643
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 }),
2644
2629
  /* @__PURE__ */ jsx8(RemoveButton, { onClick: removeFile, label: "Remove selected file" })
@@ -2661,7 +2646,7 @@ var ImageEditor = ({
2661
2646
  }
2662
2647
  if (hasStoredFile) {
2663
2648
  return /* @__PURE__ */ jsxs3("div", { className: "relative w-full", style: { height: "13rem" }, children: [
2664
- /* @__PURE__ */ jsx8(FilePreview, { name: imageMetadata?.filename, size: imageMetadata?.size, mime: imageMetadata?.mime }),
2649
+ /* @__PURE__ */ jsx8(FilePreview, { name: imageMetadata?.filename ?? durableUrl ?? void 0, size: imageMetadata?.size, mime: imageMetadata?.mime }),
2665
2650
  /* @__PURE__ */ jsx8(RemoveButton, { onClick: handleRemoveImage, label: "Remove file" })
2666
2651
  ] });
2667
2652
  }
@@ -2676,12 +2661,12 @@ var ImageEditor = ({
2676
2661
  }
2677
2662
  ),
2678
2663
  /* @__PURE__ */ jsx8("p", { className: "text-sm font-medium", children: "Image unavailable" }),
2679
- imageUrl && /* @__PURE__ */ jsx8(
2664
+ durableUrl && /* @__PURE__ */ jsx8(
2680
2665
  "p",
2681
2666
  {
2682
2667
  className: "text-muted-foreground mt-1 max-w-full truncate font-mono text-[11px] opacity-50",
2683
- title: imageUrl,
2684
- children: imageUrl
2668
+ title: durableUrl,
2669
+ children: durableUrl
2685
2670
  }
2686
2671
  ),
2687
2672
  /* @__PURE__ */ jsxs3("div", { className: "mt-3 flex items-center gap-2", children: [
@@ -2744,7 +2729,7 @@ var ImageEditor = ({
2744
2729
  )
2745
2730
  ] });
2746
2731
  };
2747
- const saveLabel = isSubmittingDraft ? "Creating..." : isUploading ? "Uploading..." : imageUrl ? "Save" : "Done";
2732
+ const saveLabel = isSubmittingDraft ? "Creating..." : isClearing ? "Clearing..." : isUploading ? "Uploading..." : hasStoredMedia || clearPending ? "Save" : "Done";
2748
2733
  return /* @__PURE__ */ jsx8(
2749
2734
  EditorFocusTrap,
2750
2735
  {
@@ -2754,7 +2739,7 @@ var ImageEditor = ({
2754
2739
  children: /* @__PURE__ */ jsxs3("div", { onKeyDown: handleEditorKeyDown, className: "flex min-h-0 flex-1 flex-col", children: [
2755
2740
  /* @__PURE__ */ jsxs3("div", { className: "flex shrink-0 items-center gap-2 border-b px-6 py-3", children: [
2756
2741
  acceptAnyFile ? /* @__PURE__ */ jsx8(FileIcon, { className: "text-muted-foreground size-4" }) : /* @__PURE__ */ jsx8(ImageIcon, { className: "text-muted-foreground size-4" }),
2757
- /* @__PURE__ */ jsx8("h3", { className: "text-sm font-medium", children: imageUrl ? `Edit ${Noun}` : `Add ${Noun}` })
2742
+ /* @__PURE__ */ jsx8("h3", { className: "text-sm font-medium", children: hasStoredMedia ? `Edit ${Noun}` : `Add ${Noun}` })
2758
2743
  ] }),
2759
2744
  /* @__PURE__ */ jsx8(
2760
2745
  "input",
@@ -2802,7 +2787,7 @@ var ImageEditor = ({
2802
2787
  /* @__PURE__ */ jsx8(AlertCircleIcon, { className: "size-3 shrink-0" }),
2803
2788
  /* @__PURE__ */ jsx8("span", { children: dragErrors[0] })
2804
2789
  ] }),
2805
- !isBusy && (selectedFile || imageMetadata && hasImage) && /* @__PURE__ */ jsx8("div", { className: "text-muted-foreground mt-2 text-center text-xs", children: selectedFile ? /* @__PURE__ */ jsxs3(Fragment2, { children: [
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: [
2806
2791
  /* @__PURE__ */ jsx8("span", { className: "font-medium", children: selectedFile.name }),
2807
2792
  " \u2022 ",
2808
2793
  /* @__PURE__ */ jsx8("span", { children: formatFileSize(selectedFile.size) }),
@@ -2822,7 +2807,7 @@ var ImageEditor = ({
2822
2807
  ] }) }),
2823
2808
  /* @__PURE__ */ jsxs3("div", { className: "flex shrink-0 justify-end gap-2 border-t px-6 py-3", children: [
2824
2809
  /* @__PURE__ */ jsx8(Button3, { type: "button", variant: "outline", size: "sm", onClick: handleCancel, disabled: isBusy, children: "Cancel" }),
2825
- selectedFile && !isBusy ? /* @__PURE__ */ jsx8(Button3, { type: "button", size: "sm", onClick: handleConfirmUpload, children: isDraftRow ? "Create Row & Upload" : "Upload & Save" }) : /* @__PURE__ */ jsxs3(Button3, { type: "button", size: "sm", onClick: handleSave, disabled: isBusy, children: [
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: [
2826
2811
  isBusy && /* @__PURE__ */ jsx8(Loader22, { className: "size-3.5 animate-spin" }),
2827
2812
  saveLabel
2828
2813
  ] })
@@ -2840,20 +2825,18 @@ function ImageEditorDom({
2840
2825
  cell,
2841
2826
  colKey,
2842
2827
  rowId,
2828
+ rowIdentifier,
2843
2829
  tableName,
2844
2830
  onCommitPatch,
2845
2831
  onCancel,
2846
2832
  onSubmitDraftRow,
2847
2833
  onInvalidateData
2848
2834
  }) {
2849
- const isDraftRow = rowId.startsWith(DRAFT_PREFIX);
2835
+ const isDraftRow = rowIdentifier == null && rowId.startsWith(DRAFT_PREFIX);
2850
2836
  const cellType = cell.meta?.cellType;
2851
2837
  const acceptAnyFile = cellType != null && cellType !== "image";
2852
2838
  const handleSaveComplete = onCommitPatch ? (saveData) => onCommitPatch({ [colKey]: saveData.imageData }) : void 0;
2853
- const handleSubmitDraft = isDraftRow && onSubmitDraftRow ? async () => {
2854
- const createdRow = await onSubmitDraftRow(rowId);
2855
- return { createdRow };
2856
- } : void 0;
2839
+ const handleSubmitDraft = isDraftRow && onSubmitDraftRow ? () => onSubmitDraftRow(rowId) : void 0;
2857
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(
2858
2841
  ImageEditor,
2859
2842
  {
@@ -2862,7 +2845,7 @@ function ImageEditorDom({
2862
2845
  onFinishedEditing: () => onCancel(),
2863
2846
  tableName,
2864
2847
  fieldName: colKey,
2865
- recordId: rowId,
2848
+ recordId: rowIdentifier ?? null,
2866
2849
  onSaveComplete: handleSaveComplete,
2867
2850
  isDraftRow,
2868
2851
  onSubmitDraft: handleSubmitDraft,
@@ -2872,7 +2855,7 @@ function ImageEditorDom({
2872
2855
  }
2873
2856
 
2874
2857
  // src/grid/editors/inet-editor.tsx
2875
- import { useCallback as useCallback4, useEffect as useEffect5, useRef as useRef6, useState as useState6 } from "react";
2858
+ import { useCallback as useCallback5, useEffect as useEffect4, useRef as useRef6, useState as useState7 } from "react";
2876
2859
  import { Button as Button4 } from "@constructive-io/ui/button";
2877
2860
  import { jsx as jsx10, jsxs as jsxs4 } from "react/jsx-runtime";
2878
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]?)$/;
@@ -2920,26 +2903,26 @@ function getInetType(value) {
2920
2903
  }
2921
2904
  var InetEditor = ({ value, onFinishedEditing }) => {
2922
2905
  const currentInetData = typeof value === "string" ? value : "";
2923
- const [editingValue, setEditingValue] = useState6(currentInetData);
2924
- const [validationError, setValidationError] = useState6("");
2906
+ const [editingValue, setEditingValue] = useState7(currentInetData);
2907
+ const [validationError, setValidationError] = useState7("");
2925
2908
  const keyContainerRef = useRef6(null);
2926
- const handleSave = useCallback4(() => {
2909
+ const handleSave = useCallback5(() => {
2927
2910
  if (editingValue.trim() && !isValidInet(editingValue.trim())) {
2928
2911
  setValidationError("Invalid IP address or CIDR");
2929
2912
  return;
2930
2913
  }
2931
2914
  onFinishedEditing(editingValue.trim());
2932
2915
  }, [editingValue, onFinishedEditing]);
2933
- const handleCancel = useCallback4(() => {
2916
+ const handleCancel = useCallback5(() => {
2934
2917
  onFinishedEditing();
2935
2918
  }, [onFinishedEditing]);
2936
- const handleInputChange = useCallback4((e) => {
2919
+ const handleInputChange = useCallback5((e) => {
2937
2920
  setEditingValue(e.target.value);
2938
2921
  setValidationError("");
2939
2922
  }, []);
2940
2923
  const actionsRef = useRef6({ handleSave, handleCancel });
2941
2924
  actionsRef.current = { handleSave, handleCancel };
2942
- useEffect5(() => {
2925
+ useEffect4(() => {
2943
2926
  const el = keyContainerRef.current;
2944
2927
  if (!el) return;
2945
2928
  const handler = (e) => {
@@ -3025,7 +3008,7 @@ function InetEditorDom({ value, onCommit, onCancel }) {
3025
3008
  }
3026
3009
 
3027
3010
  // src/grid/editors/interval-editor.tsx
3028
- import { useCallback as useCallback5, useState as useState7 } from "react";
3011
+ import { useCallback as useCallback6, useState as useState8 } from "react";
3029
3012
  import { Check, Clock, X } from "lucide-react";
3030
3013
  import { Button as Button5 } from "@constructive-io/ui/button";
3031
3014
  import { Input } from "@constructive-io/ui/input";
@@ -3073,14 +3056,14 @@ function formatIntervalValue(interval) {
3073
3056
  }
3074
3057
  var IntervalEditor = ({ value, onFinishedEditing }) => {
3075
3058
  const currentIntervalData = typeof value === "string" ? value : "";
3076
- const [editingValue, setEditingValue] = useState7(() => parseIntervalValue(currentIntervalData));
3077
- const handleSave = useCallback5(() => {
3059
+ const [editingValue, setEditingValue] = useState8(() => parseIntervalValue(currentIntervalData));
3060
+ const handleSave = useCallback6(() => {
3078
3061
  onFinishedEditing(JSON.stringify(editingValue));
3079
3062
  }, [editingValue, onFinishedEditing]);
3080
- const handleCancel = useCallback5(() => {
3063
+ const handleCancel = useCallback6(() => {
3081
3064
  onFinishedEditing();
3082
3065
  }, [onFinishedEditing]);
3083
- const handleInputChange = useCallback5((field, newValue) => {
3066
+ const handleInputChange = useCallback6((field, newValue) => {
3084
3067
  const numValue = parseInt(newValue) || 0;
3085
3068
  setEditingValue((prev) => ({
3086
3069
  ...prev,
@@ -3088,7 +3071,7 @@ var IntervalEditor = ({ value, onFinishedEditing }) => {
3088
3071
  // Ensure non-negative values
3089
3072
  }));
3090
3073
  }, []);
3091
- const handleEditorKeyDown = useCallback5(
3074
+ const handleEditorKeyDown = useCallback6(
3092
3075
  (e) => {
3093
3076
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
3094
3077
  e.preventDefault();
@@ -3198,7 +3181,7 @@ function IntervalEditorDom({ value, onCommit, onCancel }) {
3198
3181
  }
3199
3182
 
3200
3183
  // src/grid/editors/json-editor.tsx
3201
- import { useCallback as useCallback6, useEffect as useEffect6, useMemo as useMemo9, useRef as useRef7, useState as useState8 } from "react";
3184
+ import { useCallback as useCallback7, useEffect as useEffect5, useMemo as useMemo9, useRef as useRef7, useState as useState9 } from "react";
3202
3185
  import { Button as Button6 } from "@constructive-io/ui/button";
3203
3186
  import { jsx as jsx14, jsxs as jsxs6 } from "react/jsx-runtime";
3204
3187
  var MAC_UA_RE3 = /Mac|iPod|iPhone|iPad/;
@@ -3230,7 +3213,7 @@ function highlightJson(json) {
3230
3213
  );
3231
3214
  }
3232
3215
  function JsonEditor({ value, onChange, onFinished }) {
3233
- const [text, setText] = useState8(() => typeof value === "string" ? value : JSON.stringify(value, null, 2));
3216
+ const [text, setText] = useState9(() => typeof value === "string" ? value : JSON.stringify(value, null, 2));
3234
3217
  const textareaRef = useRef7(null);
3235
3218
  const preRef = useRef7(null);
3236
3219
  const keyContainerRef = useRef7(null);
@@ -3241,7 +3224,7 @@ function JsonEditor({ value, onChange, onFinished }) {
3241
3224
  return { parsed: text, valid: false };
3242
3225
  }
3243
3226
  }, [text]);
3244
- const handleChange = useCallback6(
3227
+ const handleChange = useCallback7(
3245
3228
  (e) => {
3246
3229
  const next = e.target.value;
3247
3230
  setText(next);
@@ -3252,11 +3235,11 @@ function JsonEditor({ value, onChange, onFinished }) {
3252
3235
  },
3253
3236
  [onChange]
3254
3237
  );
3255
- const handleCancel = useCallback6(() => onFinished(void 0), [onFinished]);
3256
- const handleSave = useCallback6(() => {
3238
+ const handleCancel = useCallback7(() => onFinished(void 0), [onFinished]);
3239
+ const handleSave = useCallback7(() => {
3257
3240
  if (valid) onFinished(parsed);
3258
3241
  }, [onFinished, parsed, valid]);
3259
- const handleScroll = useCallback6(() => {
3242
+ const handleScroll = useCallback7(() => {
3260
3243
  const ta = textareaRef.current;
3261
3244
  const pre = preRef.current;
3262
3245
  if (ta && pre) {
@@ -3266,7 +3249,7 @@ function JsonEditor({ value, onChange, onFinished }) {
3266
3249
  }, []);
3267
3250
  const actionsRef = useRef7({ handleSave, handleCancel });
3268
3251
  actionsRef.current = { handleSave, handleCancel };
3269
- useEffect6(() => {
3252
+ useEffect5(() => {
3270
3253
  const el = keyContainerRef.current;
3271
3254
  if (!el) return;
3272
3255
  const handler = (e) => {
@@ -3372,7 +3355,7 @@ function JsonEditorDom({ value, onCommit, onCancel }) {
3372
3355
  }
3373
3356
 
3374
3357
  // src/grid-dom/editors/number-editor.tsx
3375
- import { useRef as useRef8, useState as useState9 } from "react";
3358
+ import { useRef as useRef8, useState as useState10 } from "react";
3376
3359
  import { Button as Button7 } from "@constructive-io/ui/button";
3377
3360
  import { jsx as jsx16, jsxs as jsxs7 } from "react/jsx-runtime";
3378
3361
  function seedText(value) {
@@ -3386,7 +3369,7 @@ function parseValue(text) {
3386
3369
  return Number(trimmed);
3387
3370
  }
3388
3371
  function NumberEditorDom({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
3389
- const [text, setText] = useState9(() => initialText != null ? initialText : seedText(value));
3372
+ const [text, setText] = useState10(() => initialText != null ? initialText : seedText(value));
3390
3373
  const escapedRef = useRef8(false);
3391
3374
  const parsed = parseValue(text);
3392
3375
  const canSave = parsed === null || Number.isFinite(parsed);
@@ -3441,7 +3424,7 @@ function NumberEditorDom({ value, initialText, colKey, fieldMeta, onCommit, onCa
3441
3424
  NumberEditorDom.commitsOnBlur = true;
3442
3425
 
3443
3426
  // src/grid/editors/relation-editor.tsx
3444
- import { useCallback as useCallback7, useContext as useContext3, useEffect as useEffect7, useLayoutEffect as useLayoutEffect3, useMemo as useMemo10, useRef as useRef10, useState as useState11 } from "react";
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";
3445
3428
  import { Check as Check2, Link, Loader2 as Loader23, Search, X as X2 } from "lucide-react";
3446
3429
  import { useQueryClient as useQueryClient4 } from "@tanstack/react-query";
3447
3430
  import { Badge as Badge2 } from "@constructive-io/ui/badge";
@@ -3451,12 +3434,12 @@ import { Label as Label2 } from "@constructive-io/ui/label";
3451
3434
  import { toast as toast2 } from "@constructive-io/ui/toast";
3452
3435
 
3453
3436
  // src/grid/editors/relation-record-tooltip.tsx
3454
- import { useRef as useRef9, useState as useState10 } from "react";
3437
+ import { useRef as useRef9, useState as useState11 } from "react";
3455
3438
  import { RiCodeLine } from "@remixicon/react";
3456
3439
  import { Popover, PopoverContent, PopoverTrigger } from "@constructive-io/ui/popover";
3457
3440
  import { jsx as jsx17, jsxs as jsxs8 } from "react/jsx-runtime";
3458
3441
  function RelationRecordTooltip({ record }) {
3459
- const [open, setOpen] = useState10(false);
3442
+ const [open, setOpen] = useState11(false);
3460
3443
  const closeTimeoutRef = useRef9(null);
3461
3444
  if (!record || typeof record !== "object") {
3462
3445
  return null;
@@ -3581,7 +3564,7 @@ var RelationEditor = ({
3581
3564
  const relationInfoForTable = useSheetsStore((s) => tableName ? s.relationInfoCache[tableName] : void 0);
3582
3565
  const relationEntry = relationInfoForTable?.[fieldName];
3583
3566
  const isDraft = typeof recordId === "string" && recordId.startsWith("draft:");
3584
- useEffect7(() => {
3567
+ useEffect6(() => {
3585
3568
  if (!tableName) return;
3586
3569
  if (relationInfoForTable?.[fieldName]) return;
3587
3570
  ensureRelationInfo(tableName, meta);
@@ -3618,7 +3601,7 @@ var RelationEditor = ({
3618
3601
  const { maxHeight: overlayMaxHeight } = useContext3(OverlayMeasureContext);
3619
3602
  const editorRef = useRef10(null);
3620
3603
  const currentScrollRef = useRef10(null);
3621
- const [scrollBudgets, setScrollBudgets] = useState11({});
3604
+ const [scrollBudgets, setScrollBudgets] = useState12({});
3622
3605
  useLayoutEffect3(() => {
3623
3606
  const editor = editorRef.current;
3624
3607
  const currentScroll = currentScrollRef.current;
@@ -3632,8 +3615,8 @@ var RelationEditor = ({
3632
3615
  });
3633
3616
  }, [overlayMaxHeight]);
3634
3617
  const initialSelection = useMemo10(() => coerceToArray(currentValue), [currentValue]);
3635
- const [editingValue, setEditingValue] = useState11(initialSelection);
3636
- const [searchQuery, setSearchQuery] = useState11("");
3618
+ const [editingValue, setEditingValue] = useState12(initialSelection);
3619
+ const [searchQuery, setSearchQuery] = useState12("");
3637
3620
  const editingValueRef = useRef10(editingValue);
3638
3621
  editingValueRef.current = editingValue;
3639
3622
  const initialSelectionRef = useRef10(initialSelection);
@@ -3641,7 +3624,7 @@ var RelationEditor = ({
3641
3624
  const onFinishedEditingRef = useRef10(onFinishedEditing);
3642
3625
  onFinishedEditingRef.current = onFinishedEditing;
3643
3626
  const initialRecordIdRef = useRef10(recordId);
3644
- useEffect7(() => {
3627
+ useEffect6(() => {
3645
3628
  if (initialRecordIdRef.current != null && recordId != null && initialRecordIdRef.current !== recordId) {
3646
3629
  onFinishedEditingRef.current();
3647
3630
  }
@@ -3687,10 +3670,10 @@ var RelationEditor = ({
3687
3670
  const parentTable = useSheetsTable(tableName, { enabled: false });
3688
3671
  const relatedTable = useSheetsTable(relatedTableName || "", { enabled: false });
3689
3672
  const junctionTable = useSheetsTable(relationEntry?.junctionTable || "", { enabled: false });
3690
- const [isSaving, setIsSaving] = useState11(false);
3673
+ const [isSaving, setIsSaving] = useState12(false);
3691
3674
  const sentinelRef = useRef10(null);
3692
3675
  const scrollContainerRef = useRef10(null);
3693
- useEffect7(() => {
3676
+ useEffect6(() => {
3694
3677
  const sentinel = sentinelRef.current;
3695
3678
  const root = scrollContainerRef.current;
3696
3679
  if (!sentinel || !root || !hasNextPage || isFetchingNextPage) return;
@@ -3705,7 +3688,7 @@ var RelationEditor = ({
3705
3688
  }, [hasNextPage, isFetchingNextPage, fetchNextPage]);
3706
3689
  const junctionRowsRef = useRef10(junctionRows);
3707
3690
  junctionRowsRef.current = junctionRows;
3708
- const handleSave = useCallback7(() => {
3691
+ const handleSave = useCallback8(() => {
3709
3692
  void (async () => {
3710
3693
  if (!relationEntry || recordId == null) {
3711
3694
  onFinishedEditing();
@@ -3841,17 +3824,17 @@ var RelationEditor = ({
3841
3824
  scopeKey,
3842
3825
  isDraft
3843
3826
  ]);
3844
- const handleCancel = useCallback7(() => {
3827
+ const handleCancel = useCallback8(() => {
3845
3828
  onFinishedEditing();
3846
3829
  }, [onFinishedEditing]);
3847
- const handleRemoveRelation = useCallback7(
3830
+ const handleRemoveRelation = useCallback8(
3848
3831
  (index) => {
3849
3832
  if (!canPersist || isSaving) return;
3850
3833
  setEditingValue((prev) => prev.filter((_, i) => i !== index));
3851
3834
  },
3852
3835
  [canPersist, isSaving]
3853
3836
  );
3854
- const togglePick = useCallback7(
3837
+ const togglePick = useCallback8(
3855
3838
  (record) => {
3856
3839
  if (!canPersist || isSaving) return;
3857
3840
  setEditingValue((prev) => {
@@ -3870,7 +3853,7 @@ var RelationEditor = ({
3870
3853
  },
3871
3854
  [canPersist, isMulti, isSaving]
3872
3855
  );
3873
- const handleEditorKeyDown = useCallback7(
3856
+ const handleEditorKeyDown = useCallback8(
3874
3857
  (e) => {
3875
3858
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
3876
3859
  e.preventDefault();
@@ -4046,11 +4029,11 @@ function RelationEditorDom({
4046
4029
  }
4047
4030
 
4048
4031
  // src/grid-dom/editors/text-editor.tsx
4049
- import { useRef as useRef11, useState as useState12 } from "react";
4032
+ import { useRef as useRef11, useState as useState13 } from "react";
4050
4033
  import { Button as Button9 } from "@constructive-io/ui/button";
4051
4034
  import { jsx as jsx20, jsxs as jsxs10 } from "react/jsx-runtime";
4052
4035
  function TextEditor({ value, initialText, colKey, fieldMeta, onCommit, onCancel }) {
4053
- const [text, setText] = useState12(() => initialText != null ? initialText : String(value ?? ""));
4036
+ const [text, setText] = useState13(() => initialText != null ? initialText : String(value ?? ""));
4054
4037
  const escapedRef = useRef11(false);
4055
4038
  function handleKeyDown(e) {
4056
4039
  if (e.key === "Enter") {
@@ -4091,7 +4074,7 @@ function TextEditor({ value, initialText, colKey, fieldMeta, onCommit, onCancel
4091
4074
  TextEditor.commitsOnBlur = true;
4092
4075
 
4093
4076
  // src/grid/editors/tsvector-editor.tsx
4094
- import { useCallback as useCallback8, useMemo as useMemo11 } from "react";
4077
+ import { useCallback as useCallback9, useMemo as useMemo11 } from "react";
4095
4078
  import { Info, Search as Search2, X as X3 } from "lucide-react";
4096
4079
  import { Button as Button10 } from "@constructive-io/ui/button";
4097
4080
  import { Label as Label3 } from "@constructive-io/ui/label";
@@ -4120,7 +4103,7 @@ function parseTsvector(tsvectorString) {
4120
4103
  var TsvectorEditor = ({ value, onFinishedEditing }) => {
4121
4104
  const rawValue = typeof value === "string" ? value : String(value ?? "");
4122
4105
  const parsedTokens = useMemo11(() => parseTsvector(rawValue), [rawValue]);
4123
- const handleClose = useCallback8(() => onFinishedEditing(), [onFinishedEditing]);
4106
+ const handleClose = useCallback9(() => onFinishedEditing(), [onFinishedEditing]);
4124
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: [
4125
4108
  /* @__PURE__ */ jsxs11("div", { className: "flex items-center gap-2", children: [
4126
4109
  /* @__PURE__ */ jsx21(Search2, { className: "text-muted-foreground h-4 w-4" }),
@@ -4166,7 +4149,7 @@ function TsvectorEditorDom({ value, onCancel }) {
4166
4149
  }
4167
4150
 
4168
4151
  // src/grid/editors/url-editor.tsx
4169
- import { useCallback as useCallback9, useState as useState13 } from "react";
4152
+ import { useCallback as useCallback10, useState as useState14 } from "react";
4170
4153
  import { Check as Check3, ExternalLink, Link as Link2, X as X4 } from "lucide-react";
4171
4154
  import { Button as Button11 } from "@constructive-io/ui/button";
4172
4155
  import { Input as Input2 } from "@constructive-io/ui/input";
@@ -4195,9 +4178,9 @@ function displayUrl(url) {
4195
4178
  }
4196
4179
  var UrlEditor = ({ value, onFinishedEditing }) => {
4197
4180
  const currentUrlData = typeof value === "string" ? value : "";
4198
- const [editingValue, setEditingValue] = useState13(currentUrlData);
4199
- const [validationError, setValidationError] = useState13("");
4200
- const handleSave = useCallback9(() => {
4181
+ const [editingValue, setEditingValue] = useState14(currentUrlData);
4182
+ const [validationError, setValidationError] = useState14("");
4183
+ const handleSave = useCallback10(() => {
4201
4184
  if (editingValue.trim() && !isValidUrl(editingValue.trim())) {
4202
4185
  setValidationError("Please enter a valid URL");
4203
4186
  return;
@@ -4205,10 +4188,10 @@ var UrlEditor = ({ value, onFinishedEditing }) => {
4205
4188
  const formattedUrl = editingValue.trim() ? formatUrl(editingValue.trim()) : "";
4206
4189
  onFinishedEditing(formattedUrl);
4207
4190
  }, [editingValue, onFinishedEditing]);
4208
- const handleCancel = useCallback9(() => {
4191
+ const handleCancel = useCallback10(() => {
4209
4192
  onFinishedEditing();
4210
4193
  }, [onFinishedEditing]);
4211
- const handleInputChange = useCallback9(
4194
+ const handleInputChange = useCallback10(
4212
4195
  (e) => {
4213
4196
  const newValue = e.target.value;
4214
4197
  setEditingValue(newValue);
@@ -4218,13 +4201,13 @@ var UrlEditor = ({ value, onFinishedEditing }) => {
4218
4201
  },
4219
4202
  [validationError]
4220
4203
  );
4221
- const handleTestUrl = useCallback9(() => {
4204
+ const handleTestUrl = useCallback10(() => {
4222
4205
  if (editingValue.trim() && isValidUrl(editingValue.trim())) {
4223
4206
  const fullUrl = formatUrl(editingValue.trim());
4224
4207
  window.open(fullUrl, "_blank", "noopener,noreferrer");
4225
4208
  }
4226
4209
  }, [editingValue]);
4227
- const handleEditorKeyDown = useCallback9(
4210
+ const handleEditorKeyDown = useCallback10(
4228
4211
  (e) => {
4229
4212
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
4230
4213
  e.preventDefault();
@@ -4334,6 +4317,7 @@ var DOM_EDITOR_REGISTRY = {
4334
4317
  video: ImageEditorDom,
4335
4318
  audio: ImageEditorDom,
4336
4319
  upload: ImageEditorDom,
4320
+ attachment: ImageEditorDom,
4337
4321
  // Date/time types
4338
4322
  date: DateEditorDom,
4339
4323
  datetime: DateEditorDom,
@@ -4381,17 +4365,19 @@ export {
4381
4365
  createPostGraphileAdapter,
4382
4366
  useSheetsAdapter,
4383
4367
  useSheetsMeta,
4384
- createSheetsCell,
4385
4368
  getImageMetadata,
4369
+ formatFileSize,
4370
+ createSheetsCell,
4371
+ useSheetsMediaUrl,
4386
4372
  OverlayMeasureContext,
4387
4373
  computeOverlayGeometry,
4388
4374
  OverlayViewportGuard,
4389
4375
  executeFieldUpload,
4390
4376
  useSheetsFieldUpload,
4391
- useSheetsImageUpload,
4377
+ ImageEditorDom,
4392
4378
  useSheetsTableCursor,
4393
4379
  wrapNativeEditor,
4394
4380
  DOM_EDITOR_REGISTRY,
4395
4381
  resolveNativeEditor
4396
4382
  };
4397
- //# sourceMappingURL=chunk-CBXNKMN6.js.map
4383
+ //# sourceMappingURL=chunk-ER3FIDK7.js.map