@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
package/dist/index.cjs CHANGED
@@ -120,7 +120,7 @@ var init_cell_type_groups = __esm({
120
120
  "date-array",
121
121
  "interval"
122
122
  ]);
123
- MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file", "video", "audio", "upload"]);
123
+ MEDIA_TYPES = /* @__PURE__ */ new Set(["image", "file", "video", "audio", "upload", "attachment"]);
124
124
  ENHANCED_TYPES = /* @__PURE__ */ new Set([
125
125
  "email",
126
126
  "url",
@@ -144,9 +144,9 @@ function getVisibleFocusable(container) {
144
144
  );
145
145
  }
146
146
  function EditorFocusTrap({ children, onEscape, onKeyDown, className, style }) {
147
- const containerRef = (0, import_react40.useRef)(null);
148
- const previousActiveElement = (0, import_react40.useRef)(null);
149
- (0, import_react40.useLayoutEffect)(() => {
147
+ const containerRef = (0, import_react41.useRef)(null);
148
+ const previousActiveElement = (0, import_react41.useRef)(null);
149
+ (0, import_react41.useLayoutEffect)(() => {
150
150
  previousActiveElement.current = document.activeElement;
151
151
  if (!containerRef.current) return;
152
152
  const visibleElements = getVisibleFocusable(containerRef.current);
@@ -156,14 +156,14 @@ function EditorFocusTrap({ children, onEscape, onKeyDown, className, style }) {
156
156
  containerRef.current.focus();
157
157
  }
158
158
  }, []);
159
- (0, import_react40.useEffect)(() => {
159
+ (0, import_react41.useEffect)(() => {
160
160
  return () => {
161
161
  if (previousActiveElement.current instanceof HTMLElement && previousActiveElement.current.isConnected) {
162
162
  previousActiveElement.current.focus();
163
163
  }
164
164
  };
165
165
  }, []);
166
- const handleKeyDown = (0, import_react40.useCallback)(
166
+ const handleKeyDown = (0, import_react41.useCallback)(
167
167
  (e) => {
168
168
  onKeyDown?.(e);
169
169
  if (e.key === "Escape") {
@@ -208,11 +208,11 @@ function EditorFocusTrap({ children, onEscape, onKeyDown, className, style }) {
208
208
  }
209
209
  );
210
210
  }
211
- var import_react40, import_jsx_runtime24, FOCUSABLE_SELECTOR;
211
+ var import_react41, import_jsx_runtime24, FOCUSABLE_SELECTOR;
212
212
  var init_editor_focus_trap = __esm({
213
213
  "src/grid/editors/editor-focus-trap.tsx"() {
214
214
  "use strict";
215
- import_react40 = require("react");
215
+ import_react41 = require("react");
216
216
  import_jsx_runtime24 = require("react/jsx-runtime");
217
217
  FOCUSABLE_SELECTOR = [
218
218
  "button:not([disabled])",
@@ -290,11 +290,11 @@ function resolveDateType(value, explicitType) {
290
290
  }
291
291
  return getDateType(value);
292
292
  }
293
- var import_react44, import_date, import_button7, import_calendar_rac, import_jsx_runtime29, TIME_RE, MAC_UA_RE2, DATE_ONLY_RE, getDateType, formatDate, formatForInput, dateToDateValue, dateValueToDate, DateEditor;
293
+ var import_react45, import_date, import_button7, import_calendar_rac, import_jsx_runtime29, TIME_RE, MAC_UA_RE2, DATE_ONLY_RE, getDateType, formatDate, formatForInput, dateToDateValue, dateValueToDate, DateEditor;
294
294
  var init_date_editor = __esm({
295
295
  "src/grid/editors/date-editor.tsx"() {
296
296
  "use strict";
297
- import_react44 = require("react");
297
+ import_react45 = require("react");
298
298
  import_date = require("@internationalized/date");
299
299
  import_button7 = require("@constructive-io/ui/button");
300
300
  import_calendar_rac = require("@constructive-io/ui/calendar-rac");
@@ -423,14 +423,14 @@ var init_date_editor = __esm({
423
423
  DateEditor = ({ value, onFinishedEditing, dateType: forcedDateType }) => {
424
424
  const currentDateValue = typeof value === "string" ? value : "";
425
425
  const dateType = resolveDateType(currentDateValue, forcedDateType);
426
- const [dateValue, setDateValue] = (0, import_react44.useState)(currentDateValue);
427
- const [selectedDate, setSelectedDate] = (0, import_react44.useState)(
426
+ const [dateValue, setDateValue] = (0, import_react45.useState)(currentDateValue);
427
+ const [selectedDate, setSelectedDate] = (0, import_react45.useState)(
428
428
  dateToDateValue(currentDateValue || /* @__PURE__ */ new Date())
429
429
  );
430
- const keyContainerRef = (0, import_react44.useRef)(null);
430
+ const keyContainerRef = (0, import_react45.useRef)(null);
431
431
  const isTimeOnly = dateType === "time";
432
432
  const isDateTimeType = dateType === "datetime" || dateType === "timestamptz";
433
- const handleDateSelect = (0, import_react44.useCallback)(
433
+ const handleDateSelect = (0, import_react45.useCallback)(
434
434
  (dateValue2) => {
435
435
  if (Array.isArray(dateValue2)) return;
436
436
  const selectedValue = dateValue2;
@@ -448,7 +448,7 @@ var init_date_editor = __esm({
448
448
  },
449
449
  [isDateTimeType, currentDateValue]
450
450
  );
451
- const handleTimeChange = (0, import_react44.useCallback)(
451
+ const handleTimeChange = (0, import_react45.useCallback)(
452
452
  (timeValue) => {
453
453
  if (!timeValue) return;
454
454
  if (isTimeOnly) {
@@ -463,7 +463,7 @@ var init_date_editor = __esm({
463
463
  },
464
464
  [isTimeOnly, selectedDate, currentDateValue]
465
465
  );
466
- const handleSave = (0, import_react44.useCallback)(() => {
466
+ const handleSave = (0, import_react45.useCallback)(() => {
467
467
  let finalValue;
468
468
  if (!dateValue) {
469
469
  finalValue = "";
@@ -506,12 +506,12 @@ var init_date_editor = __esm({
506
506
  }
507
507
  onFinishedEditing(finalValue);
508
508
  }, [dateValue, dateType, onFinishedEditing]);
509
- const handleCancel = (0, import_react44.useCallback)(() => {
509
+ const handleCancel = (0, import_react45.useCallback)(() => {
510
510
  onFinishedEditing();
511
511
  }, [onFinishedEditing]);
512
- const actionsRef = (0, import_react44.useRef)({ handleSave, handleCancel });
512
+ const actionsRef = (0, import_react45.useRef)({ handleSave, handleCancel });
513
513
  actionsRef.current = { handleSave, handleCancel };
514
- (0, import_react44.useEffect)(() => {
514
+ (0, import_react45.useEffect)(() => {
515
515
  const el = keyContainerRef.current;
516
516
  if (!el) return;
517
517
  const handler = (e) => {
@@ -619,13 +619,13 @@ function MapPicker({
619
619
  height = 300,
620
620
  markerColor = "#3b82f6"
621
621
  }) {
622
- const [searchQuery, setSearchQuery] = (0, import_react46.useState)("");
623
- const [searchResults, setSearchResults] = (0, import_react46.useState)([]);
624
- const [isSearching, setIsSearching] = (0, import_react46.useState)(false);
625
- const [showResults, setShowResults] = (0, import_react46.useState)(false);
626
- const searchTimeoutRef = (0, import_react46.useRef)(null);
622
+ const [searchQuery, setSearchQuery] = (0, import_react47.useState)("");
623
+ const [searchResults, setSearchResults] = (0, import_react47.useState)([]);
624
+ const [isSearching, setIsSearching] = (0, import_react47.useState)(false);
625
+ const [showResults, setShowResults] = (0, import_react47.useState)(false);
626
+ const searchTimeoutRef = (0, import_react47.useRef)(null);
627
627
  const position = extractPosition(value);
628
- const handleMapClick = (0, import_react46.useCallback)(
628
+ const handleMapClick = (0, import_react47.useCallback)(
629
629
  (lat, lng) => {
630
630
  if (disabled) return;
631
631
  const newValue = createMapValue(lat, lng);
@@ -635,7 +635,7 @@ function MapPicker({
635
635
  },
636
636
  [disabled, onChange]
637
637
  );
638
- const handleSearchChange = (0, import_react46.useCallback)((e) => {
638
+ const handleSearchChange = (0, import_react47.useCallback)((e) => {
639
639
  const query = e.target.value;
640
640
  setSearchQuery(query);
641
641
  if (searchTimeoutRef.current) {
@@ -654,7 +654,7 @@ function MapPicker({
654
654
  }
655
655
  }, 300);
656
656
  }, []);
657
- const handleResultSelect = (0, import_react46.useCallback)(
657
+ const handleResultSelect = (0, import_react47.useCallback)(
658
658
  (result) => {
659
659
  if (disabled) return;
660
660
  const lat = parseFloat(result.lat);
@@ -666,17 +666,17 @@ function MapPicker({
666
666
  },
667
667
  [disabled, onChange]
668
668
  );
669
- const clearSearch = (0, import_react46.useCallback)(() => {
669
+ const clearSearch = (0, import_react47.useCallback)(() => {
670
670
  setSearchQuery("");
671
671
  setShowResults(false);
672
672
  setSearchResults([]);
673
673
  }, []);
674
- const clearLocation = (0, import_react46.useCallback)(() => {
674
+ const clearLocation = (0, import_react47.useCallback)(() => {
675
675
  if (disabled) return;
676
676
  onChange?.(void 0);
677
677
  setSearchQuery("");
678
678
  }, [disabled, onChange]);
679
- (0, import_react46.useEffect)(() => {
679
+ (0, import_react47.useEffect)(() => {
680
680
  return () => {
681
681
  if (searchTimeoutRef.current) {
682
682
  clearTimeout(searchTimeoutRef.current);
@@ -739,7 +739,7 @@ function MapPicker({
739
739
  ))
740
740
  ] }) })
741
741
  ] }),
742
- /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_card.Card, { className: "overflow-hidden", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_card.CardContent, { className: "p-0", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_react46.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(MapLoading, { height }), children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
742
+ /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_card.Card, { className: "overflow-hidden", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_card.CardContent, { className: "p-0", children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(import_react47.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(MapLoading, { height }), children: /* @__PURE__ */ (0, import_jsx_runtime31.jsx)(
743
743
  LeafletMapInner,
744
744
  {
745
745
  position,
@@ -760,12 +760,12 @@ function MapPicker({
760
760
  ] }) })
761
761
  ] });
762
762
  }
763
- var import_react46, import_lucide_react4, import_button8, import_card, import_input_group, import_jsx_runtime31, createMapValue, extractPosition, searchLocation, LeafletMapInner;
763
+ var import_react47, import_lucide_react4, import_button8, import_card, import_input_group, import_jsx_runtime31, createMapValue, extractPosition, searchLocation, LeafletMapInner;
764
764
  var init_map_picker = __esm({
765
765
  "src/utils/map-picker.tsx"() {
766
766
  "use strict";
767
767
  "use client";
768
- import_react46 = __toESM(require("react"), 1);
768
+ import_react47 = __toESM(require("react"), 1);
769
769
  import_lucide_react4 = require("lucide-react");
770
770
  init_cn();
771
771
  init_sheets_logger();
@@ -809,7 +809,7 @@ var init_map_picker = __esm({
809
809
  return [];
810
810
  }
811
811
  };
812
- LeafletMapInner = (0, import_react46.lazy)(
812
+ LeafletMapInner = (0, import_react47.lazy)(
813
813
  () => Promise.all([import("react-leaflet"), import("leaflet")]).then(([reactLeaflet, L]) => {
814
814
  const { MapContainer, TileLayer, Marker, useMapEvents, useMap } = reactLeaflet;
815
815
  const createCustomIcon = (color = "#3b82f6") => {
@@ -848,7 +848,7 @@ var init_map_picker = __esm({
848
848
  onMapClick(e.latlng.lat, e.latlng.lng);
849
849
  }
850
850
  });
851
- import_react46.default.useEffect(() => {
851
+ import_react47.default.useEffect(() => {
852
852
  if (position && map) {
853
853
  map.setView(position, 15);
854
854
  }
@@ -986,7 +986,6 @@ __export(src_exports, {
986
986
  useSheetsContext: () => useSheetsContext,
987
987
  useSheetsFieldUpload: () => useSheetsFieldUpload,
988
988
  useSheetsForgotPassword: () => useSheetsForgotPassword,
989
- useSheetsImageUpload: () => useSheetsImageUpload,
990
989
  useSheetsInfiniteTable: () => useSheetsInfiniteTable,
991
990
  useSheetsLogin: () => useSheetsLogin,
992
991
  useSheetsMeta: () => useSheetsMeta,
@@ -1034,9 +1033,14 @@ async function sha256HexFromBuffer(buffer) {
1034
1033
  }
1035
1034
  return hex;
1036
1035
  }
1037
- var capabilityCache = /* @__PURE__ */ new Map();
1038
- function discoverUploadCapability(endpoint, execute) {
1039
- const cached = capabilityCache.get(endpoint);
1036
+ var capabilityCache = /* @__PURE__ */ new WeakMap();
1037
+ async function discoverStorageCapabilities(endpoint, execute) {
1038
+ let endpoints = capabilityCache.get(execute);
1039
+ if (!endpoints) {
1040
+ endpoints = /* @__PURE__ */ new Map();
1041
+ capabilityCache.set(execute, endpoints);
1042
+ }
1043
+ const cached = endpoints.get(endpoint);
1040
1044
  if (cached) return cached;
1041
1045
  const promise = (async () => {
1042
1046
  const data = await execute((0, import_graphql.getIntrospectionQuery)());
@@ -1044,12 +1048,21 @@ function discoverUploadCapability(endpoint, execute) {
1044
1048
  if (!schema) {
1045
1049
  throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
1046
1050
  }
1047
- return resolveUploadCapability(schema);
1051
+ return resolveStorageCapabilities(schema);
1048
1052
  })();
1049
- promise.catch(() => capabilityCache.delete(endpoint));
1050
- capabilityCache.set(endpoint, promise);
1053
+ promise.catch(() => endpoints.delete(endpoint));
1054
+ endpoints.set(endpoint, promise);
1051
1055
  return promise;
1052
1056
  }
1057
+ async function discoverUploadCapability(endpoint, execute) {
1058
+ const { upload } = await discoverStorageCapabilities(endpoint, execute);
1059
+ if (!upload) capabilityCache.get(execute)?.delete(endpoint);
1060
+ return requireUploadCapability(upload);
1061
+ }
1062
+ function requireUploadCapability(upload) {
1063
+ if (!upload) throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
1064
+ return upload;
1065
+ }
1053
1066
  function namedTypeName(ref) {
1054
1067
  let cur = ref;
1055
1068
  while (cur && (cur.kind === "NON_NULL" || cur.kind === "LIST")) {
@@ -1065,7 +1078,7 @@ function isListTypeRef(ref) {
1065
1078
  return cur?.kind === "LIST";
1066
1079
  }
1067
1080
  var PK_FIELD_NAME = "id";
1068
- function resolveUploadCapability(schema) {
1081
+ function resolveStorageCapabilities(schema) {
1069
1082
  const typeByName = /* @__PURE__ */ new Map();
1070
1083
  for (const t of schema.types) {
1071
1084
  if (t.name) typeByName.set(t.name, t);
@@ -1084,7 +1097,7 @@ function resolveUploadCapability(schema) {
1084
1097
  const present = new Set(t.inputFields.map((f) => f.name));
1085
1098
  return names.every((n) => present.has(n));
1086
1099
  };
1087
- const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "deduplicated"];
1100
+ const PAYLOAD_FIELDS = ["uploadUrl", "fileId", "key", "deduplicated"];
1088
1101
  const INPUT_FIELDS = ["contentHash", "bucketKey", "contentType", "size"];
1089
1102
  const mutationType = schema.mutationType ? typeByName.get(schema.mutationType.name) : null;
1090
1103
  const queryType = schema.queryType ? typeByName.get(schema.queryType.name) : null;
@@ -1094,52 +1107,69 @@ function resolveUploadCapability(schema) {
1094
1107
  if (!inputArg) continue;
1095
1108
  const inputTypeName = namedTypeName(inputArg.type);
1096
1109
  const payloadTypeName = namedTypeName(field.type);
1097
- if (inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
1098
- upload = { uploadFieldName: field.name, inputTypeName };
1099
- break;
1110
+ if (inputTypeName && inputHasFields(inputTypeName, INPUT_FIELDS) && objectHasFields(payloadTypeName, PAYLOAD_FIELDS)) {
1111
+ const payloadFields = typeByName.get(payloadTypeName ?? "")?.fields;
1112
+ const candidate = {
1113
+ uploadFieldName: field.name,
1114
+ inputTypeName,
1115
+ hasFileProjection: payloadFields?.some(
1116
+ (f) => f.name === "file" && !isListTypeRef(f.type) && namedTypeName(f.type) === "JSON"
1117
+ ) ?? false
1118
+ };
1119
+ if (field.name === "uploadAppFile") {
1120
+ upload = candidate;
1121
+ break;
1122
+ }
1123
+ upload ??= candidate;
1100
1124
  }
1101
1125
  }
1102
- if (!upload) {
1103
- throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
1104
- }
1105
- const downloadById = resolveDownloadByIdField(schema, typeByName, queryType, upload.uploadFieldName);
1106
- return {
1107
- ...upload,
1108
- ...downloadById
1109
- };
1110
- }
1111
- function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
1112
- const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
1126
+ const fileTypes = /* @__PURE__ */ new Set();
1113
1127
  for (const t of schema.types) {
1114
1128
  if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
1115
- fileTypesWithDownloadUrl.add(t.name);
1129
+ fileTypes.add(t.name);
1116
1130
  }
1117
1131
  }
1132
+ const uploadType = upload?.uploadFieldName.replace(/^upload/, "") ?? "AppFile";
1133
+ const uploadDownload = resolveDownloadByIdField(typeByName, queryType, fileTypes, uploadType);
1134
+ const preferredPreviewType = fileTypes.has("AppFile") ? "AppFile" : uploadType;
1135
+ const previewType = fileTypes.has(preferredPreviewType) ? preferredPreviewType : uploadDownload?.fileTypeName ?? preferredPreviewType;
1136
+ const download = previewType === uploadType ? uploadDownload : resolveDownloadByIdField(typeByName, queryType, fileTypes, previewType);
1137
+ const batch = resolveConnectionDownloadField(typeByName, queryType, fileTypes, previewType, true);
1138
+ return {
1139
+ upload: upload ? { ...upload, download: uploadDownload } : null,
1140
+ download,
1141
+ batch
1142
+ };
1143
+ }
1144
+ function resolveDownloadByIdField(typeByName, queryType, fileTypesWithDownloadUrl, preferred) {
1145
+ let singular = null;
1118
1146
  for (const field of queryType?.fields ?? []) {
1119
1147
  const returnTypeName = namedTypeName(field.type);
1120
1148
  if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
1121
1149
  if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
1122
- return {
1150
+ const candidate = {
1123
1151
  fileByIdField: field.name,
1124
1152
  fileByIdArgName: "id",
1125
1153
  fileTypeName: returnTypeName,
1126
1154
  idScalarName: namedTypeName(field.args[0].type) ?? void 0
1127
1155
  };
1156
+ if (returnTypeName === preferred) return candidate;
1157
+ singular ??= candidate;
1128
1158
  }
1129
1159
  }
1130
- const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
1131
- if (connection) return connection;
1160
+ const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred);
1161
+ if (connection?.fileTypeName === preferred) return connection;
1162
+ if (singular || connection) return singular ?? connection;
1132
1163
  const nodeField = queryType?.fields?.find(
1133
1164
  (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
1134
1165
  );
1135
1166
  if (nodeField && fileTypesWithDownloadUrl.size > 0) {
1136
- const preferred = uploadFieldName.replace(/^upload/, "");
1137
1167
  const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
1138
1168
  return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
1139
1169
  }
1140
- throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
1170
+ return null;
1141
1171
  }
1142
- function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
1172
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred, batch = false) {
1143
1173
  const EQUALITY_OPERATORS = ["equalTo", "eq"];
1144
1174
  const candidates = [];
1145
1175
  for (const field of queryType?.fields ?? []) {
@@ -1154,6 +1184,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
1154
1184
  });
1155
1185
  if (!nodesField) continue;
1156
1186
  const fileTypeName = namedTypeName(nodesField.type);
1187
+ if (batch && (fileTypeName !== preferred || !typeByName.get(fileTypeName)?.fields?.some((field2) => field2.name === PK_FIELD_NAME))) continue;
1188
+ const connectionHasFirst = field.args.some((arg) => arg.name === "first");
1157
1189
  for (const arg of field.args) {
1158
1190
  const filterTypeName = namedTypeName(arg.type);
1159
1191
  const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
@@ -1163,7 +1195,7 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
1163
1195
  const idFieldTypeName = namedTypeName(idField.type);
1164
1196
  const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
1165
1197
  if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
1166
- const opField = EQUALITY_OPERATORS.map(
1198
+ const opField = batch ? idFieldType.inputFields.find((f) => f.name === "in" && isListTypeRef(f.type)) : EQUALITY_OPERATORS.map(
1167
1199
  (op) => idFieldType.inputFields.find((f) => f.name === op)
1168
1200
  ).find((f) => f != null);
1169
1201
  if (opField) {
@@ -1175,13 +1207,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
1175
1207
  connectionFilterArgName: arg.name,
1176
1208
  connectionIdField: idField.name,
1177
1209
  connectionIdOperator: opField.name,
1178
- connectionNodesField: nodesField.name
1210
+ connectionNodesField: nodesField.name,
1211
+ connectionHasFirst
1179
1212
  });
1180
1213
  break;
1181
1214
  }
1182
1215
  continue;
1183
1216
  }
1184
- if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
1217
+ if (!batch && (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName)) {
1185
1218
  candidates.push({
1186
1219
  fileByIdField: field.name,
1187
1220
  fileByIdArgName: "connection",
@@ -1189,14 +1222,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
1189
1222
  idScalarName: idFieldTypeName ?? void 0,
1190
1223
  connectionFilterArgName: arg.name,
1191
1224
  connectionIdField: idField.name,
1192
- connectionNodesField: nodesField.name
1225
+ connectionNodesField: nodesField.name,
1226
+ connectionHasFirst
1193
1227
  });
1194
1228
  break;
1195
1229
  }
1196
1230
  }
1197
1231
  }
1198
1232
  if (candidates.length === 0) return null;
1199
- const preferred = uploadFieldName.replace(/^upload/, "");
1200
1233
  return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
1201
1234
  }
1202
1235
  async function callUploadOp(execute, cap, input) {
@@ -1207,12 +1240,13 @@ async function callUploadOp(execute, cap, input) {
1207
1240
  fileId
1208
1241
  key
1209
1242
  deduplicated
1243
+ file
1210
1244
  }
1211
1245
  }
1212
1246
  `.trim();
1213
1247
  const data = await execute(mutation, {
1214
1248
  input: {
1215
- bucketKey: input.bucketKey,
1249
+ ...input.bucketKey === void 0 ? { isPublic: true } : { bucketKey: input.bucketKey },
1216
1250
  contentHash: input.contentHash,
1217
1251
  contentType: input.contentType,
1218
1252
  size: input.size,
@@ -1223,8 +1257,16 @@ async function callUploadOp(execute, cap, input) {
1223
1257
  if (!payload) {
1224
1258
  throw import_data.createError.badRequest("Upload failed: no payload returned from upload mutation.");
1225
1259
  }
1260
+ const file = payload.file;
1261
+ if (!file || typeof file.id !== "string" || typeof file.key !== "string" || typeof file.bucket_id !== "string" || typeof file.mime !== "string" || typeof file.size !== "number") {
1262
+ throw import_data.createError.badRequest("Upload failed: server returned an invalid file projection.");
1263
+ }
1226
1264
  return payload;
1227
1265
  }
1266
+ var STORAGE_UPLOAD_BLOCKED_MESSAGE = "Upload failed: the storage server didn't accept the upload from this site. Check the bucket's allowed origins (CORS) and your connection.";
1267
+ function storageUnreachableError() {
1268
+ return import_data.createError.graphql(STORAGE_UPLOAD_BLOCKED_MESSAGE, "STORAGE_UPLOAD_BLOCKED");
1269
+ }
1228
1270
  async function presignedPut(url, buffer, contentType, onProgress) {
1229
1271
  const total = buffer.byteLength;
1230
1272
  if (onProgress && typeof XMLHttpRequest !== "undefined") {
@@ -1238,8 +1280,8 @@ async function presignedPut(url, buffer, contentType, onProgress) {
1238
1280
  headers: { "Content-Type": contentType },
1239
1281
  body: buffer
1240
1282
  });
1241
- } catch (error) {
1242
- throw import_data.createError.network(error instanceof Error ? error : void 0);
1283
+ } catch {
1284
+ throw storageUnreachableError();
1243
1285
  }
1244
1286
  if (!response.ok) {
1245
1287
  const body = await response.text().catch(() => "");
@@ -1269,7 +1311,7 @@ function putWithXHR(url, buffer, contentType, total, onProgress) {
1269
1311
  reject(import_data.createError.badRequest(`Upload failed: ${xhr.status} ${xhr.statusText}${xhr.responseText ? ` \u2014 ${xhr.responseText}` : ""}`));
1270
1312
  }
1271
1313
  });
1272
- xhr.addEventListener("error", () => reject(import_data.createError.network()));
1314
+ xhr.addEventListener("error", () => reject(storageUnreachableError()));
1273
1315
  xhr.send(buffer);
1274
1316
  });
1275
1317
  }
@@ -1307,7 +1349,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
1307
1349
  const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
1308
1350
  const query2 = `
1309
1351
  query SheetsDownloadUrl($id: ${idScalar2}!) {
1310
- ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
1352
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ", first: 1" : ""}) {
1311
1353
  ${nodesField} {
1312
1354
  downloadUrl
1313
1355
  }
@@ -1342,10 +1384,34 @@ async function fetchDownloadUrl(execute, cap, fileId) {
1342
1384
  }
1343
1385
  return url;
1344
1386
  }
1387
+ async function fetchMediaDownloadUrls({ endpoint, execute }, getActiveIds) {
1388
+ const { batch, download } = await discoverStorageCapabilities(endpoint, execute);
1389
+ const ids = getActiveIds();
1390
+ const urls = /* @__PURE__ */ new Map();
1391
+ if (ids.length === 0) return urls;
1392
+ if (batch) {
1393
+ const first = batch.connectionHasFirst ? `, first: ${ids.length}` : "";
1394
+ const query = `query SheetsMediaDownloadUrls($ids: [${batch.idScalarName ?? "ID"}!]!) {
1395
+ ${batch.fileByIdField}(${batch.connectionFilterArgName}: {
1396
+ ${batch.connectionIdField}: { in: $ids }
1397
+ }${first}) { ${batch.connectionNodesField} { id downloadUrl } }
1398
+ }`;
1399
+ const data = await execute(query, { ids });
1400
+ for (const row of data?.[batch.fileByIdField]?.[batch.connectionNodesField] ?? []) {
1401
+ if (row?.downloadUrl) urls.set(row.id, row.downloadUrl);
1402
+ }
1403
+ } else if (download) {
1404
+ const results = await Promise.allSettled(ids.map((id) => fetchDownloadUrl(execute, download, id)));
1405
+ results.forEach((result, index) => {
1406
+ if (result.status === "fulfilled") urls.set(ids[index], result.value);
1407
+ });
1408
+ }
1409
+ return urls;
1410
+ }
1345
1411
  async function resolveDownloadUrl(execute, endpoint, fileId) {
1346
1412
  try {
1347
- const cap = await discoverUploadCapability(endpoint, execute);
1348
- return await fetchDownloadUrl(execute, cap, fileId);
1413
+ const { download } = await discoverStorageCapabilities(endpoint, execute);
1414
+ return download ? await fetchDownloadUrl(execute, download, fileId) : null;
1349
1415
  } catch {
1350
1416
  return null;
1351
1417
  }
@@ -1439,17 +1505,33 @@ function createSheetsExecute(config, getToken) {
1439
1505
  return result.data;
1440
1506
  };
1441
1507
  }
1508
+ function resolveStorageTransport(config, getToken) {
1509
+ const endpoint = config.storage?.endpoint;
1510
+ if (!endpoint) return void 0;
1511
+ return {
1512
+ endpoint,
1513
+ execute: config.storage?.execute ?? createSheetsExecute({ ...config, endpoint }, getToken)
1514
+ };
1515
+ }
1442
1516
  function createSheetsUpload(config, getToken) {
1443
- const execute = config.execute ?? createSheetsExecute(config, getToken);
1517
+ const transport = resolveStorageTransport(config, getToken) ?? {
1518
+ endpoint: config.endpoint,
1519
+ execute: config.execute ?? createSheetsExecute(config, getToken)
1520
+ };
1521
+ return createPresignedSheetsUpload(transport, config.upload?.bucketKey);
1522
+ }
1523
+ function createPresignedSheetsUpload({ endpoint, execute }, bucketKey) {
1444
1524
  return async (file, _path, options) => {
1445
- if (!config.endpoint) {
1525
+ if (!endpoint) {
1446
1526
  throw import_data2.createError.badRequest("No GraphQL endpoint configured.");
1447
1527
  }
1448
- const bucketKey = config.upload?.bucketKey ?? "public";
1528
+ const cap = await discoverUploadCapability(endpoint, execute);
1529
+ if (!cap.hasFileProjection) {
1530
+ throw import_data2.createError.badRequest("Uploads require a storage mutation that returns a file projection.");
1531
+ }
1449
1532
  const contentType = file.type || "application/octet-stream";
1450
1533
  const buffer = await file.arrayBuffer();
1451
1534
  const contentHash = await sha256HexFromBuffer(buffer);
1452
- const cap = await discoverUploadCapability(config.endpoint, execute);
1453
1535
  const payload = await callUploadOp(execute, cap, {
1454
1536
  bucketKey,
1455
1537
  contentHash,
@@ -1465,15 +1547,15 @@ function createSheetsUpload(config, getToken) {
1465
1547
  } else {
1466
1548
  options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
1467
1549
  }
1468
- const url = await fetchDownloadUrl(execute, cap, payload.fileId);
1469
- return {
1470
- url,
1471
- filename: file.name,
1472
- mime: file.type,
1473
- size: file.size,
1474
- key: payload.key,
1475
- fileId: payload.fileId
1550
+ const result = {
1551
+ file: { ...payload.file, filename: payload.file.filename ?? file.name }
1476
1552
  };
1553
+ if (!cap.download) return result;
1554
+ try {
1555
+ return { ...result, url: await fetchDownloadUrl(execute, cap.download, payload.fileId) };
1556
+ } catch {
1557
+ return result;
1558
+ }
1477
1559
  };
1478
1560
  }
1479
1561
 
@@ -2182,6 +2264,7 @@ var sheetsQueryKeys = {
2182
2264
  root: ["sheets"],
2183
2265
  scope: (scope) => ["sheets", scope],
2184
2266
  meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
2267
+ mediaUrl: (scope, endpoint, id) => [...sheetsQueryKeys.scope(scope), "media-url", endpoint, id],
2185
2268
  typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
2186
2269
  enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
2187
2270
  relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
@@ -2197,6 +2280,9 @@ var sheetsQueryKeys = {
2197
2280
 
2198
2281
  // src/context/sheets-provider.tsx
2199
2282
  var import_jsx_runtime = require("react/jsx-runtime");
2283
+ var unavailableUpload = async () => {
2284
+ throw new Error("Uploads need a storage endpoint");
2285
+ };
2200
2286
  function SheetsProvider({ config, children }) {
2201
2287
  const providerInstanceId = (0, import_react3.useId)();
2202
2288
  const storeRef = (0, import_react3.useRef)(null);
@@ -2255,10 +2341,13 @@ function SheetsProvider({ config, children }) {
2255
2341
  if (config.execute) return config.execute;
2256
2342
  return createSheetsExecute(config, getToken);
2257
2343
  }, [config, getToken]);
2344
+ const storage = (0, import_react3.useMemo)(() => resolveStorageTransport(config, getToken), [config, getToken]);
2345
+ const bucketKey = config.upload?.bucketKey;
2258
2346
  const executeUpload = (0, import_react3.useMemo)(() => {
2259
2347
  if (config.executeUpload) return config.executeUpload;
2260
- return createSheetsUpload(config, getToken);
2261
- }, [config, getToken]);
2348
+ return storage ? createPresignedSheetsUpload(storage, bucketKey) : unavailableUpload;
2349
+ }, [config.executeUpload, storage, bucketKey]);
2350
+ const canUpload = Boolean(config.executeUpload || storage);
2262
2351
  const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
2263
2352
  const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
2264
2353
  const authGenerationRef = (0, import_react3.useRef)({ mode: config.auth.mode, token: activeToken, generation: 0 });
@@ -2284,8 +2373,8 @@ function SheetsProvider({ config, children }) {
2284
2373
  };
2285
2374
  }, [queryClient, scopeKey]);
2286
2375
  const contextValue = (0, import_react3.useMemo)(
2287
- () => ({ config, execute, executeUpload, scopeKey }),
2288
- [config, execute, executeUpload, scopeKey]
2376
+ () => ({ config, execute, executeUpload, storage, canUpload, scopeKey }),
2377
+ [config, execute, executeUpload, storage, canUpload, scopeKey]
2289
2378
  );
2290
2379
  return /* @__PURE__ */ (0, import_jsx_runtime.jsx)(import_react_query.QueryClientProvider, { client: queryClient, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsStoreContext.Provider, { value: store, children: /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SheetsContext.Provider, { value: contextValue, children }) }) });
2291
2380
  }
@@ -2297,6 +2386,19 @@ var import_react67 = require("@remixicon/react");
2297
2386
  init_cn();
2298
2387
  var import_button19 = require("@constructive-io/ui/button");
2299
2388
 
2389
+ // src/grid/row-model.ts
2390
+ var DRAFT_META = /* @__PURE__ */ Symbol("sheets.draftMeta");
2391
+ function attachDraftMeta(row, meta) {
2392
+ Object.defineProperty(row, DRAFT_META, { value: meta, enumerable: false, configurable: true });
2393
+ return row;
2394
+ }
2395
+ function getDraftMeta(row) {
2396
+ return row ? row[DRAFT_META] : void 0;
2397
+ }
2398
+ function isDraftRow(row) {
2399
+ return getDraftMeta(row)?.isDraft === true;
2400
+ }
2401
+
2300
2402
  // src/grid/sheets.controls.tsx
2301
2403
  var import_react4 = require("react");
2302
2404
  var import_react5 = require("@remixicon/react");
@@ -3699,7 +3801,7 @@ function mapToFrontendCellType(metadata) {
3699
3801
  if (encodedType) return encodedType;
3700
3802
  if (pgAlias) {
3701
3803
  const aliasType = mapAliasToCellType(pgAlias);
3702
- if (aliasType !== "unknown") return aliasType;
3804
+ if (aliasType !== "unknown" && !(isArray && aliasType === "attachment")) return aliasType;
3703
3805
  }
3704
3806
  if (isArray) {
3705
3807
  const result = mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);
@@ -3752,6 +3854,7 @@ function mapAliasToCellType(alias) {
3752
3854
  video: "video",
3753
3855
  audio: "audio",
3754
3856
  upload: "upload",
3857
+ attachment: "attachment",
3755
3858
  // Relation types
3756
3859
  relation: "relation",
3757
3860
  // Special text types
@@ -3879,6 +3982,7 @@ function mapBackendTypeToCellType(pgType) {
3879
3982
  url: "url",
3880
3983
  image: "image",
3881
3984
  upload: "upload",
3985
+ attachment: "attachment",
3882
3986
  origin: "origin",
3883
3987
  // Arrays are handled by isArray flag
3884
3988
  _text: "array",
@@ -4321,6 +4425,7 @@ var import_data14 = require("@constructive-io/data");
4321
4425
  var import_react_query3 = require("@tanstack/react-query");
4322
4426
 
4323
4427
  // src/adapter/postgraphile-adapter.ts
4428
+ var import_graphql3 = require("graphql");
4324
4429
  var import_data13 = require("@constructive-io/data");
4325
4430
 
4326
4431
  // src/hooks/use-sheets-table.ts
@@ -5022,11 +5127,17 @@ function createPostGraphileAdapter() {
5022
5127
  },
5023
5128
  async updateRow(ctx, id, patch, execute, options = {}) {
5024
5129
  const { table, allTables, tableName } = ctx;
5025
- const doc = (0, import_data13.buildPostGraphileUpdate)(table, allTables, {
5130
+ const mutationName = (0, import_data13.toUpdateMutationName)(tableName, table);
5131
+ const returning = options.returning && table.fields.filter((field) => options.returning?.includes(field.name)).map((field) => (0, import_graphql3.print)((0, import_data13.getCustomAstForCleanField)(field))).join(" ");
5132
+ const payloadTable = returning && table.query ? { ...table, query: { ...table.query, one: null } } : table;
5133
+ const singularName = (0, import_data13.toCamelCaseSingular)(tableName, payloadTable);
5134
+ const patchFieldName = (0, import_data13.toPatchFieldName)(tableName, payloadTable);
5135
+ const doc = returning ? `mutation SheetsUpdateFields($input: ${mutationName[0].toUpperCase()}${mutationName.slice(1)}Input!) {
5136
+ ${mutationName}(input: $input) { ${singularName} { ${returning} } }
5137
+ }` : (0, import_data13.buildPostGraphileUpdate)(table, allTables, {
5026
5138
  ...options,
5027
5139
  fieldSelection: options.fieldSelection || "display"
5028
5140
  });
5029
- const patchFieldName = (0, import_data13.toPatchFieldName)(tableName, table);
5030
5141
  const sanitizedPatch = (0, import_data13.prepareUpdateInput)(patch);
5031
5142
  if (Object.keys(sanitizedPatch).length === 0) return null;
5032
5143
  const normalizedPatch = normalizeMutationEnums(ctx, sanitizedPatch, execute);
@@ -5037,8 +5148,6 @@ function createPostGraphileAdapter() {
5037
5148
  }
5038
5149
  };
5039
5150
  const result = await execute(doc, variables);
5040
- const mutationName = (0, import_data13.toUpdateMutationName)(tableName, table);
5041
- const singularName = (0, import_data13.toCamelCaseSingular)(tableName, table);
5042
5151
  const updatedRow = result[mutationName]?.[singularName] ?? null;
5043
5152
  return updatedRow;
5044
5153
  },
@@ -5468,19 +5577,6 @@ function useDataGridColumns(tableName, rows = []) {
5468
5577
  init_sheets_logger();
5469
5578
  var import_toast = require("@constructive-io/ui/toast");
5470
5579
 
5471
- // src/grid/row-model.ts
5472
- var DRAFT_META = /* @__PURE__ */ Symbol("sheets.draftMeta");
5473
- function attachDraftMeta(row, meta) {
5474
- Object.defineProperty(row, DRAFT_META, { value: meta, enumerable: false, configurable: true });
5475
- return row;
5476
- }
5477
- function getDraftMeta(row) {
5478
- return row ? row[DRAFT_META] : void 0;
5479
- }
5480
- function isDraftRow(row) {
5481
- return getDraftMeta(row)?.isDraft === true;
5482
- }
5483
-
5484
5580
  // src/cell-types/cell-type-registry.ts
5485
5581
  function createCellTypeRegistry(cellTypes, builtins) {
5486
5582
  const byKey = /* @__PURE__ */ new Map();
@@ -5622,21 +5718,53 @@ var geometrySheetsCellFactory = { canHandle: canHandle3, create: create3 };
5622
5718
 
5623
5719
  // src/cell-model/factories/image.ts
5624
5720
  init_cell_type_groups();
5625
- function resolveMediaUrl(value) {
5626
- if (typeof value === "string") return value;
5627
- if (typeof value === "object" && value) {
5628
- const obj = value;
5629
- return obj.url || obj.src || obj.href || obj.path || "";
5721
+
5722
+ // src/utils/file.utils.ts
5723
+ var getImageUrl = (imageValue) => {
5724
+ if (!imageValue) return null;
5725
+ if (typeof imageValue === "string") {
5726
+ return imageValue;
5630
5727
  }
5631
- return "";
5728
+ if (typeof imageValue === "object" && imageValue !== null) {
5729
+ const urlCandidates = ["url", "src", "href", "link", "path"];
5730
+ for (const candidate of urlCandidates) {
5731
+ const obj = imageValue;
5732
+ if (obj[candidate] && typeof obj[candidate] === "string") {
5733
+ return obj[candidate];
5734
+ }
5735
+ }
5736
+ }
5737
+ return null;
5738
+ };
5739
+ function getMediaFileId(value) {
5740
+ if (!value || typeof value !== "object") return null;
5741
+ const { id } = value;
5742
+ return typeof id === "string" && id ? id : null;
5632
5743
  }
5744
+ var getImageMetadata = (imageValue) => {
5745
+ if (!imageValue || typeof imageValue !== "object") return null;
5746
+ const obj = imageValue;
5747
+ return {
5748
+ filename: obj.filename || obj.name || "Unknown",
5749
+ size: typeof obj.size === "number" ? obj.size : typeof obj.fileSize === "number" ? obj.fileSize : void 0,
5750
+ mime: obj.mime || obj.type || obj.contentType || "unknown"
5751
+ };
5752
+ };
5753
+ var formatFileSize = (bytes) => {
5754
+ if (bytes === 0) return "0 B";
5755
+ const k = 1024;
5756
+ const sizes = ["B", "KB", "MB", "GB"];
5757
+ const i = Math.floor(Math.log(bytes) / Math.log(k));
5758
+ return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
5759
+ };
5760
+
5761
+ // src/cell-model/factories/image.ts
5633
5762
  var imageSheetsCellFactory = {
5634
5763
  canHandle(cellType) {
5635
- return MEDIA_TYPES.has(cellType);
5764
+ return cellType !== "attachment" && MEDIA_TYPES.has(cellType);
5636
5765
  },
5637
5766
  create(value, metadata) {
5638
- const url = value === null || value === void 0 || value === "" ? "" : resolveMediaUrl(value);
5639
- const data = [url];
5767
+ const data = [getImageUrl(value) ?? ""];
5640
5768
  return {
5641
5769
  kind: "image",
5642
5770
  data,
@@ -6089,6 +6217,7 @@ function useBatchCommit({
6089
6217
  update,
6090
6218
  getRowIdentifier = legacyRowIdentifier2,
6091
6219
  readOnlyFields,
6220
+ isCellReadOnly,
6092
6221
  canUpdate = true,
6093
6222
  applyOptimisticPatch,
6094
6223
  resyncRow,
@@ -6105,6 +6234,7 @@ function useBatchCommit({
6105
6234
  for (const w of writes) {
6106
6235
  const rowData = combinedRows[w.rowIndex];
6107
6236
  if (!rowData) continue;
6237
+ if (isCellReadOnly?.(w.rowIndex, w.colKey)) continue;
6108
6238
  if (getDraftMeta(rowData)) {
6109
6239
  draftWrites.push(w);
6110
6240
  continue;
@@ -6171,7 +6301,7 @@ function useBatchCommit({
6171
6301
  }
6172
6302
  return { applied: resolved.length };
6173
6303
  },
6174
- [combinedRows, fieldMetaMap, relationInfoByField, update, getRowIdentifier, readOnlyFields, canUpdate, applyOptimisticPatch, resyncRow, editCell, onCellEdit, record]
6304
+ [combinedRows, fieldMetaMap, relationInfoByField, update, getRowIdentifier, readOnlyFields, isCellReadOnly, canUpdate, applyOptimisticPatch, resyncRow, editCell, onCellEdit, record]
6175
6305
  );
6176
6306
  commitRef.current = commitCells;
6177
6307
  return commitCells;
@@ -6557,12 +6687,14 @@ function useSheetsContent(args) {
6557
6687
  serverRowsReadOnly = false,
6558
6688
  serverReadOnlyFields,
6559
6689
  getRowIdentifier,
6560
- supportsScalarSelfCommit = true
6690
+ supportsScalarSelfCommit = true,
6691
+ canUpload = true,
6692
+ canCreate = true
6561
6693
  } = args;
6562
6694
  const relationFieldNamesFromMeta = (0, import_react26.useMemo)(() => buildRelationFieldNameSet(meta, tableName), [meta, tableName]);
6563
6695
  const cache2 = (0, import_react26.useMemo)(
6564
6696
  () => /* @__PURE__ */ new Map(),
6565
- [data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit]
6697
+ [data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit, canUpload, canCreate]
6566
6698
  );
6567
6699
  const getSheetsCell = (0, import_react26.useCallback)(
6568
6700
  (rowIndex, colKey) => {
@@ -6633,9 +6765,11 @@ function useSheetsContent(args) {
6633
6765
  };
6634
6766
  const cellType = registry.resolveTypeKey(matchInput, () => route.cellType);
6635
6767
  const rowIdentifier = !isDraftRow2 ? getRowIdentifier?.(rowData) : null;
6636
- const selfCommittingEditor = isRelation || MEDIA_TYPES.has(cellType);
6637
- const lacksScalarEditorIdentity = selfCommittingEditor && (!supportsScalarSelfCommit || rowIdentifier != null && typeof rowIdentifier === "object");
6638
- const forcedReadOnly = tableForcedReadOnly || lacksScalarEditorIdentity;
6768
+ const isMedia = MEDIA_TYPES.has(cellType);
6769
+ const lacksScalarEditorIdentity = isRelation && (!supportsScalarSelfCommit || rowIdentifier != null && typeof rowIdentifier === "object");
6770
+ const lacksMediaTarget = isMedia && (isDraftRow2 ? !canCreate || serverRowsReadOnly : rowIdentifier == null);
6771
+ const readOnlyReason = isMedia && !canUpload ? "Uploads need a storage endpoint" : void 0;
6772
+ const forcedReadOnly = tableForcedReadOnly || lacksScalarEditorIdentity || lacksMediaTarget || !!readOnlyReason;
6639
6773
  const metadata = {
6640
6774
  cellType,
6641
6775
  fieldName: colKey,
@@ -6658,11 +6792,20 @@ function useSheetsContent(args) {
6658
6792
  const hasCellError = Boolean(draftErrors && colKey in draftErrors);
6659
6793
  const styled = isDraftRow2 ? tagDraftStyle(displaySafe, hasCellError) : displaySafe;
6660
6794
  const component = registry.getCellComponent(cellType);
6661
- const resolution = { cell: styled, component, colKey, typeKey: cellType, fieldMeta, relationInfo };
6795
+ const resolution = {
6796
+ cell: styled,
6797
+ component,
6798
+ colKey,
6799
+ typeKey: cellType,
6800
+ fieldMeta,
6801
+ relationInfo,
6802
+ rowIdentifier,
6803
+ readOnlyReason
6804
+ };
6662
6805
  cache2.set(cacheKey, { value: rawValue, resolution });
6663
6806
  return resolution;
6664
6807
  },
6665
- [data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit]
6808
+ [data, columnKeys, fieldMetaMap, registry, relationFieldNamesFromMeta, relationInfoByField, options, serverRowsReadOnly, serverReadOnlyFields, getRowIdentifier, supportsScalarSelfCommit, canUpload, canCreate]
6666
6809
  );
6667
6810
  return { getSheetsCell };
6668
6811
  }
@@ -7771,7 +7914,7 @@ function useSheets(props) {
7771
7914
  const emit = (0, import_react33.useCallback)((type, meta) => {
7772
7915
  onEventRef.current?.({ type, tableName, at: Date.now(), meta });
7773
7916
  }, [tableName]);
7774
- const { config } = useSheetsContext();
7917
+ const { config, canUpload } = useSheetsContext();
7775
7918
  const cellRegistry = (0, import_react33.useMemo)(
7776
7919
  () => createCellTypeRegistry(
7777
7920
  // Compiled cell-component slots go LAST so they win over plugins + cellTypes.
@@ -8053,7 +8196,9 @@ function useSheets(props) {
8053
8196
  serverRowsReadOnly: !canUpdate,
8054
8197
  serverReadOnlyFields: primaryKeyFields,
8055
8198
  getRowIdentifier,
8056
- supportsScalarSelfCommit
8199
+ supportsScalarSelfCommit,
8200
+ canUpload,
8201
+ canCreate
8057
8202
  });
8058
8203
  const effectiveColumnOrder = (0, import_react33.useMemo)(() => {
8059
8204
  if (columnKeys.length > 0) return columnKeys;
@@ -8183,6 +8328,7 @@ function useSheets(props) {
8183
8328
  update,
8184
8329
  getRowIdentifier,
8185
8330
  readOnlyFields: primaryKeyFields,
8331
+ isCellReadOnly: canUpload ? void 0 : (rowIndex, colKey) => Boolean(getSheetsCellContent(rowIndex, colKey).readOnlyReason),
8186
8332
  canUpdate,
8187
8333
  applyOptimisticPatch: applyOptimisticCellPatch,
8188
8334
  resyncRow,
@@ -8901,7 +9047,7 @@ function GridViewport({
8901
9047
  }
8902
9048
 
8903
9049
  // src/grid-dom/sheets-cell-host.tsx
8904
- var import_react37 = require("react");
9050
+ var import_react38 = require("react");
8905
9051
  init_cn();
8906
9052
 
8907
9053
  // src/cell-model/badge-tones.ts
@@ -9118,42 +9264,89 @@ function GeometryCellView(props) {
9118
9264
 
9119
9265
  // src/cell-model/views/image-view.tsx
9120
9266
  var import_lucide_react2 = require("lucide-react");
9121
- init_cn();
9122
9267
 
9123
- // src/utils/file.utils.ts
9124
- var getImageUrl = (imageValue) => {
9125
- if (!imageValue) return null;
9126
- if (typeof imageValue === "string") {
9127
- return imageValue;
9128
- }
9129
- if (typeof imageValue === "object" && imageValue !== null) {
9130
- const urlCandidates = ["url", "src", "href", "link", "path"];
9131
- for (const candidate of urlCandidates) {
9132
- const obj = imageValue;
9133
- if (obj[candidate] && typeof obj[candidate] === "string") {
9134
- return obj[candidate];
9268
+ // src/hooks/use-sheets-media-url.ts
9269
+ var import_react36 = require("react");
9270
+ var import_react_query6 = require("@tanstack/react-query");
9271
+ var MAX_BATCH_SIZE = 100;
9272
+ var REFRESH_INTERVAL = 50 * 60 * 1e3;
9273
+ var UNRESOLVED_STALE_TIME = 60 * 1e3;
9274
+ var loaders = /* @__PURE__ */ new WeakMap();
9275
+ function createMediaLoader(storage) {
9276
+ let pending = [];
9277
+ async function fetchBatch(requests) {
9278
+ const getActiveIds = () => [...new Set(requests.filter(({ signal }) => !signal.aborted).map(({ id }) => id))];
9279
+ try {
9280
+ const urls = getActiveIds().length ? await fetchMediaDownloadUrls(storage, getActiveIds) : null;
9281
+ for (const request of requests) {
9282
+ request.resolve(request.signal.aborted ? null : urls?.get(request.id) ?? null);
9135
9283
  }
9284
+ } catch (error) {
9285
+ for (const request of requests) request.reject(error);
9136
9286
  }
9137
9287
  }
9138
- return null;
9139
- };
9140
- var getImageMetadata = (imageValue) => {
9141
- if (!imageValue || typeof imageValue !== "object") return null;
9142
- const obj = imageValue;
9143
- return {
9144
- filename: obj.filename || obj.name || "Unknown",
9145
- size: obj.size || obj.fileSize || 0,
9146
- mime: obj.mime || obj.type || obj.contentType || "unknown",
9147
- url: getImageUrl(imageValue) || ""
9148
- };
9149
- };
9150
- var formatFileSize = (bytes) => {
9151
- if (bytes === 0) return "0 B";
9152
- const k = 1024;
9153
- const sizes = ["B", "KB", "MB", "GB"];
9154
- const i = Math.floor(Math.log(bytes) / Math.log(k));
9155
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
9156
- };
9288
+ function flush() {
9289
+ const requests = pending;
9290
+ pending = [];
9291
+ for (let start = 0; start < requests.length; start += MAX_BATCH_SIZE) {
9292
+ void fetchBatch(requests.slice(start, start + MAX_BATCH_SIZE));
9293
+ }
9294
+ }
9295
+ return (id, signal) => new Promise((resolve, reject) => {
9296
+ if (pending.length === 0) queueMicrotask(flush);
9297
+ pending.push({ id, signal, resolve, reject });
9298
+ });
9299
+ }
9300
+ function getMediaLoader(storage, scopeKey) {
9301
+ let scopes = loaders.get(storage);
9302
+ if (!scopes) {
9303
+ scopes = /* @__PURE__ */ new WeakMap();
9304
+ loaders.set(storage, scopes);
9305
+ }
9306
+ let load = scopes.get(scopeKey);
9307
+ if (!load) {
9308
+ load = createMediaLoader(storage);
9309
+ scopes.set(scopeKey, load);
9310
+ }
9311
+ return load;
9312
+ }
9313
+ function useSheetsMediaUrl(value, previewImage = true) {
9314
+ const { storage, scopeKey } = useSheetsContext();
9315
+ const durableUrl = getImageUrl(value);
9316
+ const id = getMediaFileId(value);
9317
+ const endpoint = storage?.endpoint;
9318
+ const resource = (0, import_react36.useMemo)(() => ({ scopeKey, endpoint, id }), [scopeKey, endpoint, id]);
9319
+ const query = (0, import_react_query6.useQuery)({
9320
+ queryKey: sheetsQueryKeys.mediaUrl(scopeKey, endpoint, id),
9321
+ queryFn: storage && id && previewImage && !durableUrl ? ({ signal }) => getMediaLoader(storage, scopeKey)(id, signal) : import_react_query6.skipToken,
9322
+ staleTime: (query2) => query2.state.data ? REFRESH_INTERVAL : UNRESOLVED_STALE_TIME,
9323
+ gcTime: REFRESH_INTERVAL,
9324
+ refetchInterval: (query2) => query2.state.data && query2.state.status === "success" ? REFRESH_INTERVAL : false,
9325
+ refetchOnWindowFocus: true,
9326
+ retry: false
9327
+ });
9328
+ const signedUrl = previewImage && !durableUrl && !query.isPlaceholderData ? query.data ?? null : null;
9329
+ const [failed, setFailed] = (0, import_react36.useState)(null);
9330
+ const retried = (0, import_react36.useRef)(null);
9331
+ const { refetch } = query;
9332
+ const onImageError = (0, import_react36.useCallback)(() => {
9333
+ if (!signedUrl) return;
9334
+ setFailed({ resource, url: signedUrl });
9335
+ if (retried.current === resource) return;
9336
+ retried.current = resource;
9337
+ void refetch({ cancelRefetch: false });
9338
+ }, [refetch, resource, signedUrl]);
9339
+ const onImageLoad = (0, import_react36.useCallback)(() => {
9340
+ if (retried.current !== resource) return;
9341
+ retried.current = null;
9342
+ setFailed(null);
9343
+ }, [resource]);
9344
+ const url = durableUrl ?? (failed?.resource === resource && failed.url === signedUrl ? null : signedUrl);
9345
+ return { url, durableUrl, id, isLoading: query.isFetching && !url, onImageError, onImageLoad };
9346
+ }
9347
+
9348
+ // src/cell-model/views/image-view.tsx
9349
+ init_cn();
9157
9350
 
9158
9351
  // src/cell-model/image-cache.ts
9159
9352
  var CAP = 256;
@@ -9179,34 +9372,34 @@ function warmImage(url) {
9179
9372
 
9180
9373
  // src/cell-model/views/image-view.tsx
9181
9374
  var import_jsx_runtime15 = require("react/jsx-runtime");
9182
- function readUrl(data) {
9183
- if (Array.isArray(data) && typeof data[0] === "string") return data[0];
9184
- return "";
9185
- }
9186
9375
  function basename(url) {
9187
9376
  const path = url.split(/[?#]/)[0];
9188
9377
  const seg = path.slice(path.lastIndexOf("/") + 1);
9189
9378
  return seg || url;
9190
9379
  }
9191
- function isNonImageFile(cellType, value) {
9192
- if (cellType === "image" || value == null) return false;
9193
- const mime = getImageMetadata(value)?.mime;
9194
- return !(mime && mime !== "unknown" && mime.startsWith("image/"));
9195
- }
9196
9380
  function ImageCellView(props) {
9197
- const url = readUrl(props.cell.data);
9198
- if (url && isNonImageFile(props.column.cellType, props.value)) {
9199
- const meta = getImageMetadata(props.value);
9200
- const filename = meta?.filename && meta.filename !== "Unknown" ? meta.filename : basename(url);
9381
+ const meta = getImageMetadata(props.value);
9382
+ const previewImage = props.column.cellType === "image" || Boolean(meta?.mime.startsWith("image/"));
9383
+ const { url, durableUrl, id, isLoading, onImageError, onImageLoad } = useSheetsMediaUrl(props.value, previewImage);
9384
+ if (!previewImage && (id || durableUrl) || id && !url && !isLoading) {
9385
+ const filename = meta?.filename && meta.filename !== "Unknown" ? meta.filename : durableUrl ? basename(durableUrl) : "File";
9386
+ const details = [
9387
+ filename,
9388
+ meta?.size !== void 0 ? formatFileSize(meta.size) : null,
9389
+ meta?.mime !== "unknown" ? meta?.mime : null
9390
+ ].filter(Boolean).join(" \u2022 ");
9201
9391
  return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
9202
9392
  "div",
9203
9393
  {
9204
9394
  "data-slot": "file-cell",
9205
9395
  role: "gridcell",
9396
+ "aria-readonly": props.readOnlyReason ? true : void 0,
9397
+ "aria-description": props.readOnlyReason,
9206
9398
  className: cn("flex h-full w-full items-center gap-1.5 overflow-hidden px-2"),
9207
9399
  children: [
9208
9400
  /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_lucide_react2.FileIcon, { className: "size-3.5 shrink-0 text-muted-foreground", "aria-hidden": "true" }),
9209
- /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("span", { className: "truncate text-sm", title: filename, children: filename })
9401
+ /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("span", { className: "truncate text-sm", title: props.readOnlyReason ? `${details}
9402
+ ${props.readOnlyReason}` : details, children: filename })
9210
9403
  ]
9211
9404
  }
9212
9405
  );
@@ -9216,6 +9409,8 @@ function ImageCellView(props) {
9216
9409
  {
9217
9410
  "data-slot": "image-cell",
9218
9411
  role: "gridcell",
9412
+ "aria-readonly": props.readOnlyReason ? true : void 0,
9413
+ "aria-description": props.readOnlyReason,
9219
9414
  className: cn("flex h-full w-full items-center overflow-hidden p-1"),
9220
9415
  children: /* @__PURE__ */ (0, import_jsx_runtime15.jsx)("div", { className: cn("relative aspect-square h-full max-h-full overflow-hidden rounded-sm bg-muted"), children: url ? /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(
9221
9416
  "img",
@@ -9223,11 +9418,16 @@ function ImageCellView(props) {
9223
9418
  src: url,
9224
9419
  decoding: "async",
9225
9420
  alt: "",
9226
- onLoad: () => warmImage(url),
9421
+ onError: onImageError,
9422
+ onLoad: () => {
9423
+ onImageLoad();
9424
+ if (durableUrl) warmImage(durableUrl);
9425
+ },
9227
9426
  className: cn(
9228
9427
  "absolute inset-0 h-full w-full rounded-sm object-cover outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"
9229
9428
  )
9230
- }
9429
+ },
9430
+ url
9231
9431
  ) : null })
9232
9432
  }
9233
9433
  );
@@ -9342,7 +9542,9 @@ function TextCellView(props) {
9342
9542
  {
9343
9543
  role: "gridcell",
9344
9544
  "data-slot": "text-cell",
9345
- title: text,
9545
+ title: [text, props.readOnlyReason].filter(Boolean).join("\n"),
9546
+ "aria-readonly": props.readOnlyReason ? true : void 0,
9547
+ "aria-description": props.readOnlyReason,
9346
9548
  className: cn("flex h-full w-full items-center truncate px-3 text-sm"),
9347
9549
  children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("span", { className: "truncate", children: text })
9348
9550
  }
@@ -9371,7 +9573,7 @@ function UriCellView(props) {
9371
9573
  }
9372
9574
 
9373
9575
  // src/grid-dom/inline-cell-editor.tsx
9374
- var import_react36 = require("react");
9576
+ var import_react37 = require("react");
9375
9577
  init_cn();
9376
9578
  var import_jsx_runtime21 = require("react/jsx-runtime");
9377
9579
  function seedText(value) {
@@ -9385,11 +9587,11 @@ function parseNumeric(text) {
9385
9587
  return Number.isFinite(n) ? { ok: true, value: n } : { ok: false, value: null };
9386
9588
  }
9387
9589
  function InlineCellEditor({ ariaLabel, value, initialText, numeric, onCommit, onCancel }) {
9388
- const [text, setText] = (0, import_react36.useState)(() => initialText != null ? initialText : seedText(value));
9389
- const inputRef = (0, import_react36.useRef)(null);
9390
- const gridRef = (0, import_react36.useRef)(null);
9391
- const doneRef = (0, import_react36.useRef)(false);
9392
- (0, import_react36.useLayoutEffect)(() => {
9590
+ const [text, setText] = (0, import_react37.useState)(() => initialText != null ? initialText : seedText(value));
9591
+ const inputRef = (0, import_react37.useRef)(null);
9592
+ const gridRef = (0, import_react37.useRef)(null);
9593
+ const doneRef = (0, import_react37.useRef)(false);
9594
+ (0, import_react37.useLayoutEffect)(() => {
9393
9595
  const el = inputRef.current;
9394
9596
  gridRef.current = el?.closest('[role="grid"]') ?? null;
9395
9597
  if (el && initialText == null) el.select();
@@ -9493,13 +9695,14 @@ function toCellProps(props, onStartEdit) {
9493
9695
  column: { key: props.colKey, name: props.colKey, cellType: cell.meta?.cellType ?? "unknown" },
9494
9696
  isEditing: props.isEditing,
9495
9697
  onStartEdit,
9496
- disabled: false
9698
+ disabled: false,
9699
+ readOnlyReason: props.resolution.readOnlyReason
9497
9700
  };
9498
9701
  }
9499
- var SheetsCellHostInner = (0, import_react37.memo)(
9702
+ var SheetsCellHostInner = (0, import_react38.memo)(
9500
9703
  function SheetsCellHostInner2(props) {
9501
- const wrapperRef = (0, import_react37.useRef)(null);
9502
- const startEdit = (0, import_react37.useCallback)(() => {
9704
+ const wrapperRef = (0, import_react38.useRef)(null);
9705
+ const startEdit = (0, import_react38.useCallback)(() => {
9503
9706
  const open = props.openEditor;
9504
9707
  const el = wrapperRef.current;
9505
9708
  if (!open || !el || props.resolution.cell.readonly) return;
@@ -9508,18 +9711,18 @@ var SheetsCellHostInner = (0, import_react37.memo)(
9508
9711
  const onActivateCell = props.onActivateCell;
9509
9712
  const columnIndex = props.columnIndex;
9510
9713
  const cellRowIndex = props.rowIndex;
9511
- const activate = (0, import_react37.useCallback)((e) => {
9714
+ const activate = (0, import_react38.useCallback)((e) => {
9512
9715
  onActivateCell?.(columnIndex, cellRowIndex, e.shiftKey);
9513
9716
  }, [onActivateCell, columnIndex, cellRowIndex]);
9514
9717
  const onContextMenu = props.onContextMenu;
9515
- const contextMenu = (0, import_react37.useCallback)((e) => {
9718
+ const contextMenu = (0, import_react38.useCallback)((e) => {
9516
9719
  if (!onContextMenu) return;
9517
9720
  e.preventDefault();
9518
9721
  onContextMenu(columnIndex, cellRowIndex, e.clientX, e.clientY);
9519
9722
  }, [onContextMenu, columnIndex, cellRowIndex]);
9520
9723
  const onSubmitDraftRow = props.onSubmitDraftRow;
9521
9724
  const draftAction = props.draftAction;
9522
- const submitDraft = (0, import_react37.useCallback)(() => {
9725
+ const submitDraft = (0, import_react38.useCallback)(() => {
9523
9726
  if (draftAction && onSubmitDraftRow) void onSubmitDraftRow(draftAction.draftRowId);
9524
9727
  }, [draftAction, onSubmitDraftRow]);
9525
9728
  const cellProps = toCellProps(props, startEdit);
@@ -9536,6 +9739,7 @@ var SheetsCellHostInner = (0, import_react37.memo)(
9536
9739
  ref: wrapperRef,
9537
9740
  id: `sheets-cell-${props.rowIndex}-${props.columnIndex}`,
9538
9741
  "aria-selected": props.isActive || void 0,
9742
+ title: props.resolution.readOnlyReason,
9539
9743
  onClick: activate,
9540
9744
  onDoubleClick: startEdit,
9541
9745
  onContextMenu: contextMenu,
@@ -9575,7 +9779,7 @@ var SheetsCellHostInner = (0, import_react37.memo)(
9575
9779
  },
9576
9780
  (prev, next) => prev.rowId === next.rowId && prev.colKey === next.colKey && prev.value === next.value && prev.isEditing === next.isEditing && // initialText seeds the inline editor on open; it only differs for the editing cell.
9577
9781
  prev.inlineInitialText === next.inlineInitialText && prev.onInlineCommit === next.onInlineCommit && prev.onInlineCancel === next.onInlineCancel && // isActive must gate the memo or the focus ring will not move between cells.
9578
- prev.isActive === next.isActive && prev.openEditor === next.openEditor && prev.onActivateCell === next.onActivateCell && prev.onContextMenu === next.onContextMenu && prev.onSubmitDraftRow === next.onSubmitDraftRow && // styleHint.draft/error and the draft-action status can flip while `value` is
9782
+ prev.isActive === next.isActive && prev.openEditor === next.openEditor && prev.onActivateCell === next.onActivateCell && prev.onContextMenu === next.onContextMenu && prev.onSubmitDraftRow === next.onSubmitDraftRow && prev.resolution.cell.readonly === next.resolution.cell.readonly && prev.resolution.readOnlyReason === next.resolution.readOnlyReason && // styleHint.draft/error and the draft-action status can flip while `value` is
9579
9783
  // unchanged (validation result arrives, save in flight), so gate on them too.
9580
9784
  prev.resolution.cell.styleHint?.draft === next.resolution.cell.styleHint?.draft && prev.resolution.cell.styleHint?.error === next.resolution.cell.styleHint?.error && sameDraftAction(prev.draftAction, next.draftAction)
9581
9785
  );
@@ -9615,19 +9819,19 @@ function SheetsCellHost({ cell, ctx, getSheetsCellContent, openEditor, isEditing
9615
9819
  }
9616
9820
 
9617
9821
  // src/grid-dom/overlay/use-overlay-controller.ts
9618
- var import_react38 = require("react");
9822
+ var import_react39 = require("react");
9619
9823
  function useOverlayController() {
9620
- const [active3, setActive] = (0, import_react38.useState)(null);
9621
- const open = (0, import_react38.useCallback)((cell) => {
9824
+ const [active3, setActive] = (0, import_react39.useState)(null);
9825
+ const open = (0, import_react39.useCallback)((cell) => {
9622
9826
  setActive(cell);
9623
9827
  }, []);
9624
- const close = (0, import_react38.useCallback)(() => {
9828
+ const close = (0, import_react39.useCallback)(() => {
9625
9829
  setActive(null);
9626
9830
  }, []);
9627
- const reanchor = (0, import_react38.useCallback)((anchorRect) => {
9831
+ const reanchor = (0, import_react39.useCallback)((anchorRect) => {
9628
9832
  setActive((prev) => prev ? { ...prev, anchorRect } : prev);
9629
9833
  }, []);
9630
- const handleKeyDown = (0, import_react38.useCallback)(
9834
+ const handleKeyDown = (0, import_react39.useCallback)(
9631
9835
  (e, resolveCell) => {
9632
9836
  if (e.key === "Enter" || e.key === "F2") {
9633
9837
  const cell = resolveCell();
@@ -9647,13 +9851,13 @@ function useOverlayController() {
9647
9851
  }
9648
9852
 
9649
9853
  // src/grid-dom/overlay/overlay-manager.tsx
9650
- var import_react42 = require("react");
9854
+ var import_react43 = require("react");
9651
9855
  var import_react_dom = require("react-dom");
9652
9856
 
9653
9857
  // src/grid/editors/overlay-viewport-guard.tsx
9654
- var import_react39 = __toESM(require("react"), 1);
9858
+ var import_react40 = __toESM(require("react"), 1);
9655
9859
  var import_jsx_runtime23 = require("react/jsx-runtime");
9656
- var OverlayMeasureContext = import_react39.default.createContext({ maxHeight: 0, shouldFlip: false });
9860
+ var OverlayMeasureContext = import_react40.default.createContext({ maxHeight: 0, shouldFlip: false });
9657
9861
  function computeOverlayGeometry(viewportHeight, targetY, targetH, marginPx, minBelowPx) {
9658
9862
  const maxHeightPx = Math.max(0, viewportHeight - marginPx * 2);
9659
9863
  const hasTarget = targetY != null && targetH != null;
@@ -9668,10 +9872,10 @@ function computeOverlayGeometry(viewportHeight, targetY, targetH, marginPx, minB
9668
9872
  init_editor_focus_trap();
9669
9873
 
9670
9874
  // src/grid/feedback/editor-error-boundary.tsx
9671
- var import_react41 = require("react");
9875
+ var import_react42 = require("react");
9672
9876
  init_sheets_logger();
9673
9877
  var import_jsx_runtime25 = require("react/jsx-runtime");
9674
- var EditorErrorBoundary = class extends import_react41.Component {
9878
+ var EditorErrorBoundary = class extends import_react42.Component {
9675
9879
  state = { error: null };
9676
9880
  static getDerivedStateFromError(error) {
9677
9881
  return { error };
@@ -9708,34 +9912,84 @@ init_cn();
9708
9912
  var import_jsx_runtime26 = require("react/jsx-runtime");
9709
9913
  var MARGIN_PX = 12;
9710
9914
  var MIN_BELOW_PX = 320;
9915
+ var DROPDOWN_MOTION = [
9916
+ "opacity-0 pointer-events-none will-change-[transform,opacity]",
9917
+ "[transform:scale(var(--dropdown-pre-scale,0.97))]",
9918
+ "[transition-property:transform,opacity]",
9919
+ "[transition-duration:var(--dropdown-open-dur,250ms)]",
9920
+ "[transition-timing-function:var(--dropdown-ease,cubic-bezier(0.22,1,0.36,1))]",
9921
+ "data-[state=open]:opacity-100 data-[state=open]:pointer-events-auto data-[state=open]:[transform:scale(1)]",
9922
+ "data-[state=closing]:[transform:scale(var(--dropdown-closing-scale,0.99))]",
9923
+ "data-[state=closing]:[transition-duration:var(--dropdown-close-dur,150ms)]",
9924
+ "motion-reduce:transition-none!"
9925
+ ].join(" ");
9926
+ function prefersReducedMotion() {
9927
+ return typeof window.matchMedia !== "function" || window.matchMedia("(prefers-reduced-motion: reduce)").matches;
9928
+ }
9929
+ function playCloseTransition(node) {
9930
+ if (node.dataset.state !== "open" || prefersReducedMotion()) return;
9931
+ const host = node.parentNode ?? document.getElementById("portal-root") ?? document.body;
9932
+ const ghost = node.cloneNode(true);
9933
+ for (const el of [ghost, ...ghost.querySelectorAll("[id]")]) el.removeAttribute("id");
9934
+ ghost.setAttribute("aria-hidden", "true");
9935
+ ghost.inert = true;
9936
+ host.insertBefore(ghost, node.parentNode === host ? node : null);
9937
+ void ghost.offsetWidth;
9938
+ ghost.dataset.state = "closing";
9939
+ const closeMs = parseFloat(getComputedStyle(ghost).transitionDuration) * 1e3;
9940
+ window.setTimeout(() => ghost.remove(), (Number.isFinite(closeMs) ? closeMs : 150) + 50);
9941
+ }
9711
9942
  var FLOATING_LAYER_SELECTOR = '[role="listbox"],[role="menu"],[role="dialog"],[role="tooltip"],[data-floating-ui-portal],[data-base-ui-positioner],[data-radix-popper-content-wrapper]';
9712
9943
  function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode = "cancel", children }) {
9713
- const containerRef = (0, import_react42.useRef)(null);
9714
- const [pos, setPos] = (0, import_react42.useState)(null);
9944
+ const containerRef = (0, import_react43.useRef)(null);
9945
+ const setContainer = (0, import_react43.useCallback)((node) => {
9946
+ const previous = containerRef.current;
9947
+ containerRef.current = node;
9948
+ if (!node && previous) playCloseTransition(previous);
9949
+ }, []);
9950
+ const [pos, setPos] = (0, import_react43.useState)(null);
9951
+ const [entered, setEntered] = (0, import_react43.useState)(false);
9715
9952
  const targetY = anchorRect?.top;
9716
9953
  const targetH = anchorRect?.height;
9717
9954
  const vh = typeof window !== "undefined" ? window.innerHeight : 800;
9718
9955
  const { shouldFlip, maxHeight } = computeOverlayGeometry(vh, targetY, targetH, MARGIN_PX, MIN_BELOW_PX);
9719
- const overlayMeasure = (0, import_react42.useMemo)(() => ({ maxHeight, shouldFlip }), [maxHeight, shouldFlip]);
9720
- (0, import_react42.useLayoutEffect)(() => {
9956
+ const overlayMeasure = (0, import_react43.useMemo)(() => ({ maxHeight, shouldFlip }), [maxHeight, shouldFlip]);
9957
+ (0, import_react43.useLayoutEffect)(() => {
9721
9958
  if (!open || !anchorRect) {
9722
9959
  setPos(null);
9960
+ setEntered(false);
9723
9961
  return;
9724
9962
  }
9725
9963
  const el = containerRef.current;
9726
9964
  if (!el) return;
9727
- const rect = el.getBoundingClientRect();
9728
- const vw = window.innerWidth;
9729
- const vhNow = window.innerHeight;
9730
- let left = anchorRect.left;
9731
- left = Math.max(MARGIN_PX, Math.min(left, vw - MARGIN_PX - rect.width));
9732
- if (!Number.isFinite(left)) left = MARGIN_PX;
9733
- let top = shouldFlip ? anchorRect.top - rect.height : anchorRect.bottom;
9734
- top = Math.max(MARGIN_PX, Math.min(top, vhNow - MARGIN_PX - rect.height));
9735
- if (!Number.isFinite(top)) top = MARGIN_PX;
9736
- setPos({ left, top });
9965
+ const place = () => {
9966
+ const width = el.offsetWidth;
9967
+ const height = el.offsetHeight;
9968
+ const vw = window.innerWidth;
9969
+ const vhNow = window.innerHeight;
9970
+ let left = anchorRect.left;
9971
+ left = Math.max(MARGIN_PX, Math.min(left, vw - MARGIN_PX - width));
9972
+ if (!Number.isFinite(left)) left = MARGIN_PX;
9973
+ let top = shouldFlip ? anchorRect.top - height : anchorRect.bottom;
9974
+ top = Math.max(MARGIN_PX, Math.min(top, vhNow - MARGIN_PX - height));
9975
+ if (!Number.isFinite(top)) top = MARGIN_PX;
9976
+ const originX = Math.max(0, Math.min(anchorRect.left - left, width));
9977
+ setPos((prev) => prev && prev.left === left && prev.top === top && prev.originX === originX ? prev : { left, top, originX });
9978
+ };
9979
+ place();
9980
+ if (typeof ResizeObserver === "undefined") return;
9981
+ const observer = new ResizeObserver(place);
9982
+ observer.observe(el);
9983
+ return () => observer.disconnect();
9737
9984
  }, [open, shouldFlip, anchorRect, maxHeight]);
9738
- (0, import_react42.useEffect)(() => {
9985
+ (0, import_react43.useEffect)(() => {
9986
+ if (!open || pos === null || entered) return;
9987
+ const el = containerRef.current;
9988
+ if (!el) return;
9989
+ void el.offsetWidth;
9990
+ setEntered(true);
9991
+ }, [open, pos, entered]);
9992
+ (0, import_react43.useEffect)(() => {
9739
9993
  if (!open) return;
9740
9994
  const onPointerDown = (e) => {
9741
9995
  const el = containerRef.current;
@@ -9761,8 +10015,8 @@ function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode =
9761
10015
  // Pre-measure default = the ANCHOR position (below, or above when flipping), NOT a
9762
10016
  // screen corner. So an overlay that fits (the common case) renders at its FINAL spot
9763
10017
  // with zero left/top change once measured — no travel. It stays hidden until measured
9764
- // and `transition-none` keeps the rare off-screen clamp instant, so the overlay is
9765
- // never seen sliding to the anchor (the correction happens off-screen, pre-reveal).
10018
+ // and left/top are never transitioned, so the rare off-screen clamp is instant and the
10019
+ // overlay is never seen sliding to the anchor (the correction happens pre-reveal).
9766
10020
  left: pos ? pos.left : anchorRect.left,
9767
10021
  top: pos ? pos.top : shouldFlip ? anchorRect.top : anchorRect.bottom,
9768
10022
  maxHeight,
@@ -9771,26 +10025,19 @@ function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode =
9771
10025
  // Join the shared design-system overlay layer instead of an
9772
10026
  // arbitrary z, so the editor and any popover/tooltip it opens (e.g. the relation
9773
10027
  // "Record Data" popover, which portals into #portal-root) stack coherently.
9774
- zIndex: "var(--z-layer-floating)"
10028
+ zIndex: "var(--z-layer-floating)",
10029
+ transformOrigin: `${pos?.originX ?? 0}px ${shouldFlip ? "100%" : "0"}`
9775
10030
  };
9776
10031
  const portalHost = document.getElementById("portal-root") ?? document.body;
9777
10032
  return (0, import_react_dom.createPortal)(
9778
10033
  /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
9779
10034
  "div",
9780
10035
  {
9781
- ref: containerRef,
10036
+ ref: setContainer,
10037
+ "data-slot": "sheets-editor-overlay",
10038
+ "data-state": entered ? "open" : "closed",
9782
10039
  style,
9783
- className: cn(
9784
- // `transition-none`: the entrance is an ANIMATION (scale + fade); left/top must NEVER
9785
- // transition, or measuring/clamping the position would visibly slide the overlay across
9786
- // the screen to its anchor. This keeps the position application instant.
9787
- "pointer-events-auto transition-none",
9788
- // Origin-aware entrance (DESIGN_SPEC §10 / Emil standards): subtle scale + fade from the
9789
- // cell corner, reusing the UI popover's tw-animate utilities for a consistent feel. Gated
9790
- // on `positioned` so the overlay animates only after its measured position is applied.
9791
- positioned && "animate-[fade-scale-in_var(--duration-moderate)_ease-out] motion-reduce:animate-none",
9792
- shouldFlip ? "origin-bottom-left" : "origin-top-left"
9793
- ),
10040
+ className: DROPDOWN_MOTION,
9794
10041
  children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(OverlayMeasureContext.Provider, { value: overlayMeasure, children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(EditorErrorGuard, { onClose: onCancel, children: /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(EditorFocusTrap, { onEscape: onCancel, className: cn("overflow-visible", presetClass), children }) }) })
9795
10042
  }
9796
10043
  ),
@@ -9802,7 +10049,7 @@ function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode =
9802
10049
  init_cell_type_groups();
9803
10050
 
9804
10051
  // src/grid/editors/array-editor.tsx
9805
- var import_react43 = require("react");
10052
+ var import_react44 = require("react");
9806
10053
  var import_badge = require("@constructive-io/ui/badge");
9807
10054
  var import_button6 = require("@constructive-io/ui/button");
9808
10055
  var import_lucide_react3 = require("lucide-react");
@@ -9820,27 +10067,27 @@ function mergeArrayEditorValues(list, pendingInput) {
9820
10067
  return [...list, ...pendingItems];
9821
10068
  }
9822
10069
  function ArrayEditor({ value, onChange, onFinished }) {
9823
- const items = (0, import_react43.useMemo)(() => Array.isArray(value) ? value : [], [value]);
9824
- const [list, setList] = (0, import_react43.useState)(items);
9825
- const [input, setInput] = (0, import_react43.useState)("");
9826
- const inputRef = (0, import_react43.useRef)(null);
9827
- const keyContainerRef = (0, import_react43.useRef)(null);
9828
- const handleCancel = (0, import_react43.useCallback)(() => onFinished(void 0), [onFinished]);
9829
- const handleSave = (0, import_react43.useCallback)(() => {
10070
+ const items = (0, import_react44.useMemo)(() => Array.isArray(value) ? value : [], [value]);
10071
+ const [list, setList] = (0, import_react44.useState)(items);
10072
+ const [input, setInput] = (0, import_react44.useState)("");
10073
+ const inputRef = (0, import_react44.useRef)(null);
10074
+ const keyContainerRef = (0, import_react44.useRef)(null);
10075
+ const handleCancel = (0, import_react44.useCallback)(() => onFinished(void 0), [onFinished]);
10076
+ const handleSave = (0, import_react44.useCallback)(() => {
9830
10077
  const next = mergeArrayEditorValues(list, input);
9831
10078
  setList(next);
9832
10079
  setInput("");
9833
10080
  onChange(next);
9834
10081
  onFinished(next);
9835
10082
  }, [input, list, onChange, onFinished]);
9836
- const add = (0, import_react43.useCallback)(() => {
10083
+ const add = (0, import_react44.useCallback)(() => {
9837
10084
  const next = mergeArrayEditorValues(list, input);
9838
10085
  if (next.length === list.length) return;
9839
10086
  setList(next);
9840
10087
  setInput("");
9841
10088
  onChange(next);
9842
10089
  }, [input, list, onChange]);
9843
- const remove = (0, import_react43.useCallback)(
10090
+ const remove = (0, import_react44.useCallback)(
9844
10091
  (idx) => {
9845
10092
  const next = list.filter((_, i) => i !== idx);
9846
10093
  setList(next);
@@ -9849,11 +10096,11 @@ function ArrayEditor({ value, onChange, onFinished }) {
9849
10096
  },
9850
10097
  [list, onChange]
9851
10098
  );
9852
- const actionsRef = (0, import_react43.useRef)({ add, handleSave, remove, handleCancel });
10099
+ const actionsRef = (0, import_react44.useRef)({ add, handleSave, remove, handleCancel });
9853
10100
  actionsRef.current = { add, handleSave, remove, handleCancel };
9854
- const stateRef = (0, import_react43.useRef)({ input, listLength: list.length });
10101
+ const stateRef = (0, import_react44.useRef)({ input, listLength: list.length });
9855
10102
  stateRef.current = { input, listLength: list.length };
9856
- (0, import_react43.useEffect)(() => {
10103
+ (0, import_react44.useEffect)(() => {
9857
10104
  const el = keyContainerRef.current;
9858
10105
  if (!el) return;
9859
10106
  const handler = (e) => {
@@ -9982,14 +10229,14 @@ function ArrayEditorDom({ value, onCommit, onCancel }) {
9982
10229
  }
9983
10230
 
9984
10231
  // src/grid-dom/editors/date-editor.tsx
9985
- var import_react45 = require("react");
10232
+ var import_react46 = require("react");
9986
10233
  init_cell_type_groups();
9987
10234
  var import_jsx_runtime30 = require("react/jsx-runtime");
9988
- var DateEditor2 = (0, import_react45.lazy)(() => Promise.resolve().then(() => (init_date_editor(), date_editor_exports)).then((m) => ({ default: m.DateEditor })));
10235
+ var DateEditor2 = (0, import_react46.lazy)(() => Promise.resolve().then(() => (init_date_editor(), date_editor_exports)).then((m) => ({ default: m.DateEditor })));
9989
10236
  function DateEditorDom({ value, cell, onCommit, onCancel }) {
9990
10237
  const cellType = cell.meta?.cellType;
9991
10238
  const dateType = cellType && DATE_TIME_TYPES.has(cellType) ? cellType : void 0;
9992
- return /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("div", { "data-slot": "date-editor", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_react45.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("div", { className: "h-9 w-full min-w-[320px] animate-pulse rounded-sm bg-muted" }), children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
10239
+ return /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("div", { "data-slot": "date-editor", children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(import_react46.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)("div", { className: "h-9 w-full min-w-[320px] animate-pulse rounded-sm bg-muted" }), children: /* @__PURE__ */ (0, import_jsx_runtime30.jsx)(
9993
10240
  DateEditor2,
9994
10241
  {
9995
10242
  value,
@@ -10000,10 +10247,10 @@ function DateEditorDom({ value, cell, onCommit, onCancel }) {
10000
10247
  }
10001
10248
 
10002
10249
  // src/grid-dom/editors/geometry-editor.tsx
10003
- var import_react48 = require("react");
10250
+ var import_react49 = require("react");
10004
10251
 
10005
10252
  // src/grid/editors/geometry-editor.tsx
10006
- var import_react47 = require("react");
10253
+ var import_react48 = require("react");
10007
10254
  var import_lucide_react5 = require("lucide-react");
10008
10255
  init_cn();
10009
10256
  var import_button9 = require("@constructive-io/ui/button");
@@ -10012,7 +10259,7 @@ var import_textarea = require("@constructive-io/ui/textarea");
10012
10259
  init_editor_focus_trap();
10013
10260
  init_overlay_presets();
10014
10261
  var import_jsx_runtime32 = require("react/jsx-runtime");
10015
- var MapPicker2 = (0, import_react47.lazy)(
10262
+ var MapPicker2 = (0, import_react48.lazy)(
10016
10263
  () => Promise.resolve().then(() => (init_map_picker(), map_picker_exports)).then((m) => ({ default: m.MapPicker }))
10017
10264
  );
10018
10265
  function MapPickerLoading() {
@@ -10205,29 +10452,29 @@ function generateRandomGeometry(constrainedType) {
10205
10452
  }
10206
10453
  var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10207
10454
  const currentGeometryData = value;
10208
- const geometryValue = (0, import_react47.useMemo)(() => parseGeometryValue(currentGeometryData), [currentGeometryData]);
10209
- const [editingValue, setEditingValue] = (0, import_react47.useState)(() => {
10455
+ const geometryValue = (0, import_react48.useMemo)(() => parseGeometryValue(currentGeometryData), [currentGeometryData]);
10456
+ const [editingValue, setEditingValue] = (0, import_react48.useState)(() => {
10210
10457
  if (!currentGeometryData) return "";
10211
10458
  const geo = parseGeometryValue(currentGeometryData);
10212
10459
  if (geo?.geojson) return JSON.stringify(geo.geojson, null, 2);
10213
10460
  return formatGeometry(currentGeometryData);
10214
10461
  });
10215
10462
  const canShowMap = expectedType === "Point" || !expectedType && geometryValue != null && isPointGeometry(geometryValue);
10216
- const validationResult = (0, import_react47.useMemo)(() => validateGeometry(editingValue, expectedType), [editingValue, expectedType]);
10463
+ const validationResult = (0, import_react48.useMemo)(() => validateGeometry(editingValue, expectedType), [editingValue, expectedType]);
10217
10464
  const isValid = validationResult === true;
10218
10465
  const validationError = typeof validationResult === "string" ? validationResult : void 0;
10219
- const [activeTab, setActiveTab] = (0, import_react47.useState)(() => canShowMap ? "map" : "json");
10220
- const handleMapChange = (0, import_react47.useCallback)((mapValue) => {
10466
+ const [activeTab, setActiveTab] = (0, import_react48.useState)(() => canShowMap ? "map" : "json");
10467
+ const handleMapChange = (0, import_react48.useCallback)((mapValue) => {
10221
10468
  if (mapValue?.geojson?.type) {
10222
10469
  setEditingValue(JSON.stringify(mapValue.geojson, null, 2));
10223
10470
  } else {
10224
10471
  setEditingValue("");
10225
10472
  }
10226
10473
  }, []);
10227
- const handleRandomize = (0, import_react47.useCallback)(() => {
10474
+ const handleRandomize = (0, import_react48.useCallback)(() => {
10228
10475
  setEditingValue(JSON.stringify(generateRandomGeometry(expectedType).geojson, null, 2));
10229
10476
  }, [expectedType]);
10230
- const handleSave = (0, import_react47.useCallback)(() => {
10477
+ const handleSave = (0, import_react48.useCallback)(() => {
10231
10478
  if (!isValid) return;
10232
10479
  let finalValue;
10233
10480
  if (!editingValue.trim()) {
@@ -10242,10 +10489,10 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10242
10489
  }
10243
10490
  onFinishedEditing(finalValue);
10244
10491
  }, [editingValue, isValid, onFinishedEditing]);
10245
- const handleCancel = (0, import_react47.useCallback)(() => {
10492
+ const handleCancel = (0, import_react48.useCallback)(() => {
10246
10493
  onFinishedEditing();
10247
10494
  }, [onFinishedEditing]);
10248
- const handleEditorKeyDown = (0, import_react47.useCallback)(
10495
+ const handleEditorKeyDown = (0, import_react48.useCallback)(
10249
10496
  (e) => {
10250
10497
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
10251
10498
  e.preventDefault();
@@ -10254,7 +10501,7 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10254
10501
  },
10255
10502
  [isValid, handleSave]
10256
10503
  );
10257
- const mapPickerValue = (0, import_react47.useMemo)(() => {
10504
+ const mapPickerValue = (0, import_react48.useMemo)(() => {
10258
10505
  try {
10259
10506
  if (editingValue) {
10260
10507
  const raw = extractRawGeoJSON(JSON.parse(editingValue));
@@ -10267,11 +10514,11 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10267
10514
  }
10268
10515
  return void 0;
10269
10516
  }, [editingValue, geometryValue]);
10270
- const { maxHeight: overlayMaxHeight } = (0, import_react47.useContext)(OverlayMeasureContext);
10271
- const editorRef = (0, import_react47.useRef)(null);
10272
- const contentRef = (0, import_react47.useRef)(null);
10273
- const [scrollBudget, setScrollBudget] = (0, import_react47.useState)();
10274
- (0, import_react47.useLayoutEffect)(() => {
10517
+ const { maxHeight: overlayMaxHeight } = (0, import_react48.useContext)(OverlayMeasureContext);
10518
+ const editorRef = (0, import_react48.useRef)(null);
10519
+ const contentRef = (0, import_react48.useRef)(null);
10520
+ const [scrollBudget, setScrollBudget] = (0, import_react48.useState)();
10521
+ (0, import_react48.useLayoutEffect)(() => {
10275
10522
  const editor = editorRef.current;
10276
10523
  const content = contentRef.current;
10277
10524
  if (!editor || !content || overlayMaxHeight <= 0) return;
@@ -10340,7 +10587,7 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10340
10587
  children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)("div", { ref: editorRef, onKeyDown: handleEditorKeyDown, className: "flex min-h-0 flex-1 flex-col", children: canShowMap ? /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)(import_tabs.Tabs, { value: activeTab, onValueChange: (v) => setActiveTab(v), className: "flex min-h-0 flex-1 flex-col", children: [
10341
10588
  header,
10342
10589
  /* @__PURE__ */ (0, import_jsx_runtime32.jsxs)("div", { ref: contentRef, className: "min-h-0 flex-1 overflow-y-auto border-t", style: { maxHeight: scrollBudget }, children: [
10343
- /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_tabs.TabsContent, { value: "map", className: "mt-0 p-3", children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_react47.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(MapPickerLoading, {}), children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
10590
+ /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_tabs.TabsContent, { value: "map", className: "mt-0 p-3", children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(import_react48.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(MapPickerLoading, {}), children: /* @__PURE__ */ (0, import_jsx_runtime32.jsx)(
10344
10591
  MapPicker2,
10345
10592
  {
10346
10593
  value: mapPickerValue,
@@ -10365,7 +10612,7 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10365
10612
  var import_jsx_runtime33 = require("react/jsx-runtime");
10366
10613
  function GeometryEditorDom({ value, fieldMeta, onCommit, onCancel }) {
10367
10614
  const expectedType = fieldMeta?.type?.subtype || void 0;
10368
- return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { "data-slot": "geometry-editor", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_react48.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { className: "h-80 w-full min-w-[600px] animate-pulse rounded-lg bg-muted" }), children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
10615
+ return /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { "data-slot": "geometry-editor", children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(import_react49.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)("div", { className: "h-80 w-full min-w-[600px] animate-pulse rounded-lg bg-muted" }), children: /* @__PURE__ */ (0, import_jsx_runtime33.jsx)(
10369
10616
  GeometryEditor,
10370
10617
  {
10371
10618
  value,
@@ -10385,188 +10632,98 @@ var import_react53 = require("motion/react");
10385
10632
  var import_toast2 = require("@constructive-io/ui/toast");
10386
10633
 
10387
10634
  // src/hooks/use-sheets-upload.ts
10388
- var import_react49 = require("react");
10389
- var import_react_query6 = require("@tanstack/react-query");
10635
+ var import_react_query7 = require("@tanstack/react-query");
10390
10636
  var import_data19 = require("@constructive-io/data");
10391
- var import_data20 = require("@constructive-io/data");
10392
- function resolveUploadNaming(tableName, table) {
10393
- return {
10394
- mutationName: (0, import_data20.toUpdateMutationName)(tableName, table),
10395
- singularName: (0, import_data20.toCamelCaseSingular)(tableName, table),
10396
- patchFieldName: (0, import_data20.toPatchFieldName)(tableName, table),
10397
- updateInputTypeName: (0, import_data20.toUpdateInputTypeName)(tableName)
10398
- };
10399
- }
10400
- function resolveTransport(endpoint, getToken, options) {
10401
- if (options?.execute && options?.executeUpload) {
10402
- return { execute: options.execute, executeUpload: options.executeUpload };
10403
- }
10404
- const config = {
10405
- endpoint,
10406
- auth: { mode: "standalone" },
10407
- onAuthError: options?.onAuthError
10408
- };
10409
- return {
10410
- execute: createSheetsExecute(config, getToken),
10411
- executeUpload: createSheetsUpload(config, getToken)
10412
- };
10413
- }
10414
- async function executeFieldUpload(tableName, fieldName, recordId, file, endpoint, getToken, naming, options) {
10415
- if (!endpoint && !(options?.execute && options?.executeUpload)) {
10416
- throw new Error("No endpoint configured. Select a database API or use Direct Connect.");
10417
- }
10418
- const { execute, executeUpload } = resolveTransport(endpoint, getToken, options);
10419
- const uploadResult = await executeUpload(file, void 0, {
10420
- tableName,
10421
- fieldName,
10422
- recordId,
10423
- onProgress: options?.onProgress
10424
- });
10425
- const resolvedNaming = naming ?? resolveUploadNaming(tableName);
10426
- const patchValue = {
10427
- ...uploadResult.url != null && { url: uploadResult.url },
10428
- ...uploadResult.filename != null && { filename: uploadResult.filename },
10429
- ...uploadResult.mime != null && { mime: uploadResult.mime },
10430
- ...uploadResult.size != null && { size: uploadResult.size }
10431
- };
10432
- const mutationString = `
10433
- mutation ${resolvedNaming.mutationName}Mutation($input: ${resolvedNaming.updateInputTypeName}!) {
10434
- ${resolvedNaming.mutationName}(input: $input) {
10435
- ${resolvedNaming.singularName} {
10436
- id
10437
- ${fieldName}
10438
- }
10439
- }
10440
- }
10441
- `.trim();
10442
- const result = await execute(mutationString, {
10443
- input: {
10444
- id: recordId,
10445
- [resolvedNaming.patchFieldName]: {
10446
- [fieldName]: patchValue
10447
- }
10637
+ async function executeFieldUpload({ table: meta, allTables, fieldName, recordId }, file, { execute, executeUpload, adapter, onProgress }) {
10638
+ assertSheetsMutationAllowed(meta, "update");
10639
+ const identity = resolveSheetsIdentifier(meta, recordId);
10640
+ if (identity.status !== "identified") {
10641
+ throw new Error(`Cannot resolve a primary-key identity for table '${meta.name}'.`);
10642
+ }
10643
+ const table = (0, import_data19.cleanTable)(meta);
10644
+ const field = table.fields.find(({ name }) => name === fieldName);
10645
+ if (!field) throw new Error(`Field '${fieldName}' not found in table '${meta.name}'.`);
10646
+ const isAttachment = field.type.pgAlias?.toLowerCase() === "attachment" || field.type.pgType?.toLowerCase() === "attachment";
10647
+ let value = null;
10648
+ if (file) {
10649
+ const { file: projection } = await executeUpload(file, void 0, {
10650
+ tableName: meta.name,
10651
+ fieldName,
10652
+ recordId: typeof identity.identifier === "object" ? void 0 : identity.identifier,
10653
+ onProgress
10654
+ });
10655
+ if (isAttachment) {
10656
+ if (!projection.url) throw new Error("attachment columns need a public bucket with a public URL prefix");
10657
+ value = projection.url;
10658
+ } else {
10659
+ value = {
10660
+ ...projection,
10661
+ filename: projection.filename ?? file.name,
10662
+ mime: projection.mime ?? (file.type || "application/octet-stream")
10663
+ };
10448
10664
  }
10449
- });
10450
- const updatedRecord = result?.[resolvedNaming.mutationName]?.[resolvedNaming.singularName];
10451
- if (!updatedRecord) {
10452
- throw new Error("Upload succeeded but no data returned from patch");
10453
10665
  }
10454
- const uploadedFileData = updatedRecord[fieldName];
10455
- if (!uploadedFileData) {
10456
- throw new Error(`Upload succeeded but ${fieldName} field not found in response`);
10666
+ const updatedRow = await adapter.updateRow(
10667
+ { table, tableName: meta.name, allTables: allTables?.map(import_data19.cleanTable) ?? [table] },
10668
+ identity.identifier,
10669
+ { [fieldName]: value },
10670
+ execute,
10671
+ { returning: [fieldName] }
10672
+ );
10673
+ if (!updatedRow || !Object.hasOwn(updatedRow, fieldName)) {
10674
+ throw new Error(`Update did not return '${fieldName}'.`);
10457
10675
  }
10458
- const fileObject = typeof uploadedFileData === "object" ? uploadedFileData : null;
10459
- return {
10460
- url: fileObject?.url || uploadedFileData,
10461
- filename: fileObject?.filename || file.name,
10462
- mime: fileObject?.mime || file.type,
10463
- size: fileObject?.size || file.size
10464
- };
10676
+ const saved = updatedRow[fieldName];
10677
+ if (value === null) {
10678
+ if (saved === null) return null;
10679
+ } else if (isAttachment) {
10680
+ if (typeof saved === "string" && saved) return saved;
10681
+ } else if (saved && typeof saved === "object" && !Array.isArray(saved)) {
10682
+ return saved;
10683
+ }
10684
+ throw new Error(`Update returned an unexpected value for '${fieldName}'.`);
10465
10685
  }
10466
10686
  function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
10467
- const queryClient = (0, import_react_query6.useQueryClient)();
10468
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
10469
- const storeApi = useSheetsStoreApi();
10470
- const { data: meta } = useSheetsMeta();
10471
- const table = (0, import_react49.useMemo)(() => {
10472
- if (!meta?._meta?.tables) return null;
10473
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
10474
- return candidate ? (0, import_data19.cleanTable)(candidate) : null;
10475
- }, [meta, tableName]);
10476
- const resolvedNaming = (0, import_react49.useMemo)(() => resolveUploadNaming(tableName, table), [tableName, table]);
10477
- const getToken = (0, import_react49.useMemo)(() => {
10478
- if (config.auth.mode === "embedded") {
10479
- return config.auth.getToken;
10480
- }
10481
- return () => storeApi.getState().accessToken;
10482
- }, [config.auth, storeApi]);
10483
- const tableRef = (0, import_react49.useRef)(tableName);
10484
- const fieldRef = (0, import_react49.useRef)(fieldName);
10485
- const idRef = (0, import_react49.useRef)(recordId);
10486
- (0, import_react49.useEffect)(() => {
10487
- tableRef.current = tableName;
10488
- fieldRef.current = fieldName;
10489
- idRef.current = recordId;
10490
- }, [tableName, fieldName, recordId]);
10491
- return (0, import_react_query6.useMutation)({
10492
- mutationKey: ["sheets", scopeKey, "field-upload", tableName, fieldName, recordId],
10493
- mutationFn: async (file) => {
10494
- return executeFieldUpload(
10495
- tableRef.current,
10496
- fieldRef.current,
10497
- idRef.current,
10498
- file,
10499
- config.endpoint,
10500
- getToken,
10501
- resolvedNaming,
10502
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
10503
- );
10504
- },
10505
- onSuccess: (data) => {
10506
- options.onSuccess?.(data);
10507
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
10508
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
10509
- },
10510
- onError: (error) => {
10511
- options.onError?.(error);
10512
- }
10513
- });
10514
- }
10515
- function useSheetsImageUpload(tableName, fieldName, recordId, options = {}) {
10516
- const queryClient = (0, import_react_query6.useQueryClient)();
10517
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
10518
- const storeApi = useSheetsStoreApi();
10687
+ const queryClient = (0, import_react_query7.useQueryClient)();
10688
+ const { execute, executeUpload, scopeKey } = useSheetsContext();
10519
10689
  const { data: meta } = useSheetsMeta();
10520
- const table = (0, import_react49.useMemo)(() => {
10521
- if (!meta?._meta?.tables) return null;
10522
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
10523
- return candidate ? (0, import_data19.cleanTable)(candidate) : null;
10524
- }, [meta, tableName]);
10525
- const resolvedNaming = (0, import_react49.useMemo)(() => resolveUploadNaming(tableName, table), [tableName, table]);
10526
- const getToken = (0, import_react49.useMemo)(() => {
10527
- if (config.auth.mode === "embedded") {
10528
- return config.auth.getToken;
10529
- }
10530
- return () => storeApi.getState().accessToken;
10531
- }, [config.auth, storeApi]);
10532
- const tableRef = (0, import_react49.useRef)(tableName);
10533
- const fieldRef = (0, import_react49.useRef)(fieldName);
10534
- const idRef = (0, import_react49.useRef)(recordId);
10535
- (0, import_react49.useEffect)(() => {
10536
- tableRef.current = tableName;
10537
- fieldRef.current = fieldName;
10538
- idRef.current = recordId;
10539
- }, [tableName, fieldName, recordId]);
10540
- return (0, import_react_query6.useMutation)({
10541
- mutationKey: ["sheets", scopeKey, "image-upload", tableName, fieldName, recordId],
10542
- mutationFn: async (file) => {
10543
- if (!file.type.startsWith("image/")) {
10544
- throw new Error("Please select an image file");
10545
- }
10546
- const maxSize = 10 * 1024 * 1024;
10547
- if (file.size > maxSize) {
10548
- throw new Error("File size must be less than 10MB");
10549
- }
10550
- return executeFieldUpload(
10551
- tableRef.current,
10552
- fieldRef.current,
10553
- idRef.current,
10554
- file,
10555
- config.endpoint,
10556
- getToken,
10557
- resolvedNaming,
10558
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
10559
- );
10690
+ const adapter = useSheetsAdapter();
10691
+ const allTables = meta?._meta?.tables?.filter((entry) => entry != null);
10692
+ const table = allTables?.find(({ name }) => name === tableName);
10693
+ function resolveRowIdentifier(row) {
10694
+ if (!table) return null;
10695
+ const identity = resolveSheetsRowIdentity(table, row);
10696
+ return identity.status === "identified" ? identity.identifier : null;
10697
+ }
10698
+ async function persist(id, file) {
10699
+ if (!table) throw new Error(`Table '${tableName}' not found.`);
10700
+ return executeFieldUpload(
10701
+ { table, allTables, fieldName, recordId: id },
10702
+ file,
10703
+ { execute, executeUpload, adapter, onProgress: options.onProgress }
10704
+ );
10705
+ }
10706
+ function invalidate() {
10707
+ void queryClient.invalidateQueries({ queryKey: sheetsQueryKeys.table(scopeKey, tableName) });
10708
+ }
10709
+ async function write(id, file) {
10710
+ const value = await persist(id, file);
10711
+ invalidate();
10712
+ return value;
10713
+ }
10714
+ const mutation = (0, import_react_query7.useMutation)({
10715
+ mutationKey: [...sheetsQueryKeys.table(scopeKey, tableName), "field-upload", fieldName, recordId],
10716
+ mutationFn: (file) => {
10717
+ if (recordId == null) throw new Error("Missing record context for upload");
10718
+ return persist(recordId, file);
10560
10719
  },
10561
- onSuccess: (data) => {
10562
- options.onSuccess?.(data);
10563
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
10564
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
10720
+ onSuccess: (value) => {
10721
+ options.onSuccess?.(value);
10722
+ invalidate();
10565
10723
  },
10566
- onError: (error) => {
10567
- options.onError?.(error);
10568
- }
10724
+ onError: options.onError
10569
10725
  });
10726
+ return { ...mutation, write, resolveRowIdentifier };
10570
10727
  }
10571
10728
 
10572
10729
  // src/grid/editors/image-editor.tsx
@@ -10575,22 +10732,22 @@ init_sheets_logger();
10575
10732
  // src/utils/use-image-status.ts
10576
10733
  var import_react50 = require("react");
10577
10734
  function useImageStatus(src) {
10578
- const [status, setStatus] = (0, import_react50.useState)("idle");
10735
+ const [result, setResult] = (0, import_react50.useState)();
10579
10736
  (0, import_react50.useEffect)(() => {
10580
- if (!src) return setStatus("idle");
10581
- setStatus("loading");
10737
+ if (!src) return;
10582
10738
  const img = new Image();
10583
- img.src = src;
10584
- const onLoad = () => setStatus("loaded");
10585
- const onError = () => setStatus("error");
10739
+ const onLoad = () => setResult({ src, status: "loaded" });
10740
+ const onError = () => setResult({ src, status: "error" });
10586
10741
  img.addEventListener("load", onLoad);
10587
10742
  img.addEventListener("error", onError);
10743
+ img.src = src;
10588
10744
  return () => {
10589
10745
  img.removeEventListener("load", onLoad);
10590
10746
  img.removeEventListener("error", onError);
10591
10747
  };
10592
10748
  }, [src]);
10593
- return status;
10749
+ if (!src) return "idle";
10750
+ return result?.src === src ? result.status : "loading";
10594
10751
  }
10595
10752
 
10596
10753
  // src/grid/editors/image-editor.tsx
@@ -10660,9 +10817,6 @@ function ImageWithFallback({
10660
10817
  init_editor_focus_trap();
10661
10818
  init_overlay_presets();
10662
10819
  var import_jsx_runtime35 = require("react/jsx-runtime");
10663
- function normalizeUploadResponse(data) {
10664
- return { url: data.url, filename: data.filename, size: data.size, mime: data.mime };
10665
- }
10666
10820
  var dropzoneTransition = { duration: 0.15, ease: [0.2, 0, 0, 1] };
10667
10821
  function RemoveButton({ onClick, label }) {
10668
10822
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "absolute top-2 right-2", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
@@ -10681,13 +10835,14 @@ function RemoveButton({ onClick, label }) {
10681
10835
  }
10682
10836
  function FilePreview({ name, size, mime }) {
10683
10837
  const hasMime = !!mime && mime !== "unknown";
10838
+ const hasSize = size !== void 0;
10684
10839
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "flex size-full flex-col items-center justify-center gap-2 p-4 text-center", children: [
10685
10840
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "bg-muted/60 flex size-12 shrink-0 items-center justify-center rounded-lg", "aria-hidden": "true", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react6.FileIcon, { className: "text-muted-foreground size-6" }) }),
10686
10841
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "min-w-0 max-w-full", children: [
10687
10842
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("p", { className: "truncate text-sm font-medium", title: name, children: name || "File" }),
10688
- (size || hasMime) && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
10689
- size ? formatFileSize(size) : null,
10690
- size && hasMime ? " \u2022 " : null,
10843
+ (hasSize || hasMime) && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
10844
+ hasSize ? formatFileSize(size) : null,
10845
+ hasSize && hasMime ? " \u2022 " : null,
10691
10846
  hasMime ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { className: "uppercase", children: mime }) : null
10692
10847
  ] })
10693
10848
  ] })
@@ -10708,13 +10863,7 @@ var ImageEditor = ({
10708
10863
  const noun = acceptAnyFile ? "file" : "image";
10709
10864
  const Noun = acceptAnyFile ? "File" : "Image";
10710
10865
  const [uploadState, setUploadState] = (0, import_react52.useState)("idle");
10711
- const { config } = useSheetsContext();
10712
- const storeApi = useSheetsStoreApi();
10713
10866
  const { maxHeight: overlayMaxHeight } = (0, import_react52.useContext)(OverlayMeasureContext);
10714
- const getToken = (0, import_react52.useMemo)(() => {
10715
- if (config.auth.mode === "embedded") return config.auth.getToken;
10716
- return () => storeApi.getState().accessToken;
10717
- }, [config.auth, storeApi]);
10718
10867
  const fileInputRef = (0, import_react52.useRef)(null);
10719
10868
  const previewUrlRef = (0, import_react52.useRef)(null);
10720
10869
  const committedRecordIdRef = (0, import_react52.useRef)(null);
@@ -10727,14 +10876,23 @@ var ImageEditor = ({
10727
10876
  const [dragErrors, setDragErrors] = (0, import_react52.useState)([]);
10728
10877
  const isSubmittingDraft = uploadState === "submitting-draft";
10729
10878
  const isUploading = uploadState === "uploading";
10879
+ const isClearing = uploadState === "clearing";
10730
10880
  const isBusy = uploadState !== "idle";
10731
- const imageUrl = (0, import_react52.useMemo)(() => getImageUrl(imageValue), [imageValue]);
10732
10881
  const imageMetadata = (0, import_react52.useMemo)(() => getImageMetadata(imageValue), [imageValue]);
10733
10882
  const storedMime = imageMetadata?.mime;
10734
10883
  const storedIsImage = !acceptAnyFile || !!storedMime && storedMime.startsWith("image/");
10884
+ const { url: imageUrl, durableUrl, id: storedFileId, isLoading: isResolvingImage, onImageError, onImageLoad } = useSheetsMediaUrl(imageValue, storedIsImage);
10735
10885
  const imageStatus = useImageStatus(storedIsImage ? imageUrl || void 0 : void 0);
10736
- const imageLoadFailed = storedIsImage && imageUrl != null && imageStatus === "error";
10737
- const hasImage = imageUrl != null && !imageLoadFailed && storedIsImage;
10886
+ (0, import_react52.useEffect)(() => {
10887
+ if (imageStatus === "error") onImageError();
10888
+ if (imageStatus === "loaded") onImageLoad();
10889
+ }, [imageStatus, onImageError, onImageLoad]);
10890
+ const imageLoadFailed = storedIsImage && durableUrl != null && imageStatus === "error";
10891
+ const hasImage = (imageUrl != null || isResolvingImage) && !imageLoadFailed && storedIsImage;
10892
+ const hasStoredMedia = Boolean(storedFileId || durableUrl);
10893
+ const clearPending = value != null && imageValue == null;
10894
+ const needsDraftCreation = isDraftRow2 && committedRecordIdRef.current == null;
10895
+ const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
10738
10896
  const revokePreviewUrl = (0, import_react52.useCallback)(() => {
10739
10897
  if (previewUrlRef.current) {
10740
10898
  URL.revokeObjectURL(previewUrlRef.current);
@@ -10748,23 +10906,27 @@ var ImageEditor = ({
10748
10906
  setPreviewUrl(null);
10749
10907
  setUploadState("idle");
10750
10908
  }, [revokePreviewUrl]);
10751
- const handleUploadSuccess = (0, import_react52.useCallback)((data) => {
10752
- const normalized = normalizeUploadResponse(data);
10909
+ const finishSave = (0, import_react52.useCallback)((data, message) => {
10753
10910
  resetFileState();
10754
- setImageValue(normalized);
10755
- onSaveComplete?.({ imageData: normalized });
10911
+ setImageValue(data);
10912
+ if (committedRecordIdRef.current == null) {
10913
+ onSaveComplete?.({ imageData: data });
10914
+ } else {
10915
+ onDraftUploadComplete?.();
10916
+ }
10756
10917
  onFinishedEditing();
10757
- import_toast2.toast.success({ message: `${Noun} uploaded successfully` });
10758
- }, [resetFileState, onSaveComplete, onFinishedEditing, Noun]);
10759
- const handleUploadError = (0, import_react52.useCallback)((error) => {
10918
+ import_toast2.toast.success({ message });
10919
+ }, [resetFileState, onSaveComplete, onDraftUploadComplete, onFinishedEditing]);
10920
+ const handleWriteError = (0, import_react52.useCallback)((error) => {
10760
10921
  setUploadState("idle");
10761
- sheetsLogger().error("[image-editor] upload failed:", error);
10762
- import_toast2.toast.error({ message: error.message || "Upload failed" });
10922
+ setUploadProgress(null);
10923
+ sheetsLogger().error("[image-editor] media update failed:", error);
10924
+ import_toast2.toast.error({ message: error.message || "Could not save the file" });
10763
10925
  }, []);
10764
- const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId || "", {
10926
+ const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId ?? null, {
10765
10927
  onProgress: setUploadProgress,
10766
- onSuccess: handleUploadSuccess,
10767
- onError: handleUploadError,
10928
+ onSuccess: (data) => finishSave(data, data === null ? `${Noun} cleared` : `${Noun} uploaded successfully`),
10929
+ onError: handleWriteError,
10768
10930
  showToast: false
10769
10931
  });
10770
10932
  const handleRemoveImage = (0, import_react52.useCallback)(() => {
@@ -10821,94 +10983,79 @@ var ImageEditor = ({
10821
10983
  setDragErrors([]);
10822
10984
  }, [revokePreviewUrl]);
10823
10985
  const handleConfirmUpload = (0, import_react52.useCallback)(async () => {
10824
- if (!tableName || !fieldName || !selectedFile) return;
10825
- const committedId = committedRecordIdRef.current ?? recordId;
10826
- if (committedRecordIdRef.current != null) {
10827
- try {
10828
- import_toast2.toast.info({ message: `Uploading ${noun}...` });
10829
- setUploadState("uploading");
10830
- const uploadResult = await executeFieldUpload(
10831
- tableName,
10832
- fieldName,
10833
- committedRecordIdRef.current,
10834
- selectedFile,
10835
- config.endpoint,
10836
- getToken,
10837
- void 0,
10838
- { onAuthError: config.onAuthError }
10839
- );
10840
- const normalized = normalizeUploadResponse(uploadResult);
10841
- resetFileState();
10842
- setImageValue(normalized);
10843
- onDraftUploadComplete?.();
10844
- import_toast2.toast.success({ message: `${Noun} uploaded successfully` });
10845
- onFinishedEditing();
10846
- } catch (error) {
10847
- onDraftUploadComplete?.();
10848
- setUploadState("idle");
10849
- import_toast2.toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
10986
+ if (isBusy || !tableName || !fieldName || !selectedFile) return;
10987
+ if (!isDraftRow2) {
10988
+ if (recordId == null) {
10989
+ import_toast2.toast.error({ message: "Missing record context for upload" });
10990
+ return;
10850
10991
  }
10992
+ setUploadState("uploading");
10993
+ uploadMutation.mutate(selectedFile);
10851
10994
  return;
10852
10995
  }
10853
- if (isDraftRow2) {
10854
- if (!onSubmitDraft) {
10855
- import_toast2.toast.error({ message: "Cannot upload to draft row - save the row first" });
10856
- return;
10857
- }
10858
- try {
10996
+ let rowPersisted = committedRecordIdRef.current != null;
10997
+ try {
10998
+ const createRow = committedRecordIdRef.current == null;
10999
+ if (createRow) {
11000
+ if (!onSubmitDraft) throw new Error("Cannot upload to draft row - save the row first");
10859
11001
  import_toast2.toast.info({ message: "Creating row..." });
10860
11002
  setUploadState("submitting-draft");
10861
- const result = await onSubmitDraft();
10862
- const createdId = result.createdRow?.id;
10863
- if (typeof createdId !== "string" && typeof createdId !== "number") {
10864
- throw new Error("Image uploads require a scalar id primary key.");
10865
- }
10866
- committedRecordIdRef.current = createdId;
10867
- import_toast2.toast.info({ message: `Uploading ${noun}...` });
10868
- setUploadState("uploading");
10869
- const uploadResult = await executeFieldUpload(
10870
- tableName,
10871
- fieldName,
10872
- createdId,
10873
- selectedFile,
10874
- config.endpoint,
10875
- getToken,
10876
- void 0,
10877
- { onAuthError: config.onAuthError }
10878
- );
10879
- const normalized = normalizeUploadResponse(uploadResult);
10880
- resetFileState();
10881
- setImageValue(normalized);
10882
- onDraftUploadComplete?.();
10883
- import_toast2.toast.success({ message: `Row created and ${noun} uploaded` });
10884
- onFinishedEditing();
10885
- } catch (error) {
10886
- onDraftUploadComplete?.();
10887
- setUploadState("idle");
10888
- import_toast2.toast.error({ message: error instanceof Error ? error.message : "Upload failed" });
11003
+ const { createdRow } = await onSubmitDraft();
11004
+ rowPersisted = true;
11005
+ committedRecordIdRef.current = createdRow ? uploadMutation.resolveRowIdentifier(createdRow) : null;
10889
11006
  }
10890
- return;
11007
+ const committedId = committedRecordIdRef.current;
11008
+ if (committedId == null) throw new Error("Uploads require a primary-key identity for the created row.");
11009
+ import_toast2.toast.info({ message: `Uploading ${noun}...` });
11010
+ setUploadState("uploading");
11011
+ const saved = await uploadMutation.write(committedId, selectedFile);
11012
+ finishSave(saved, createRow ? `Row created and ${noun} uploaded` : `${Noun} uploaded successfully`);
11013
+ } catch (error) {
11014
+ if (rowPersisted) onDraftUploadComplete?.();
11015
+ handleWriteError(error instanceof Error ? error : new Error("Upload failed"));
10891
11016
  }
10892
- if (!committedId) {
10893
- import_toast2.toast.error({ message: "Missing record context for upload" });
11017
+ }, [
11018
+ isBusy,
11019
+ tableName,
11020
+ fieldName,
11021
+ selectedFile,
11022
+ isDraftRow2,
11023
+ recordId,
11024
+ uploadMutation,
11025
+ onSubmitDraft,
11026
+ noun,
11027
+ Noun,
11028
+ finishSave,
11029
+ onDraftUploadComplete,
11030
+ handleWriteError
11031
+ ]);
11032
+ const handleSave = (0, import_react52.useCallback)(async () => {
11033
+ if (isBusy) return;
11034
+ if (!clearPending) {
11035
+ onFinishedEditing();
10894
11036
  return;
10895
11037
  }
10896
- setUploadState("uploading");
10897
- uploadMutation.mutate(selectedFile);
10898
- }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow2, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing, noun, Noun]);
10899
- const handleSave = (0, import_react52.useCallback)(() => {
10900
- if (!imageValue) {
10901
- onFinishedEditing(null);
11038
+ const targetId = committedRecordIdRef.current ?? recordId;
11039
+ if (targetId == null) {
11040
+ if (isDraftRow2) {
11041
+ finishSave(null, `${Noun} cleared`);
11042
+ } else {
11043
+ handleWriteError(new Error("Missing record context for clear"));
11044
+ }
10902
11045
  return;
10903
11046
  }
10904
- const url = getImageUrl(imageValue);
10905
- const originalUrl = getImageUrl(value);
10906
- if (url && originalUrl === url) {
10907
- onFinishedEditing();
11047
+ setUploadState("clearing");
11048
+ if (committedRecordIdRef.current == null) {
11049
+ uploadMutation.mutate(null);
10908
11050
  return;
10909
11051
  }
10910
- onFinishedEditing(url ?? value);
10911
- }, [imageValue, value, onFinishedEditing]);
11052
+ try {
11053
+ const saved = await uploadMutation.write(targetId, null);
11054
+ finishSave(saved, `${Noun} cleared`);
11055
+ } catch (error) {
11056
+ handleWriteError(error instanceof Error ? error : new Error("Clear failed"));
11057
+ }
11058
+ }, [isBusy, clearPending, onFinishedEditing, recordId, isDraftRow2, finishSave, Noun, handleWriteError, uploadMutation]);
10912
11059
  const handleCancel = (0, import_react52.useCallback)(() => {
10913
11060
  revokePreviewUrl();
10914
11061
  onFinishedEditing();
@@ -10917,25 +11064,37 @@ var ImageEditor = ({
10917
11064
  const handleEditorKeyDown = (0, import_react52.useCallback)((e) => {
10918
11065
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
10919
11066
  e.preventDefault();
10920
- handleSave();
11067
+ if (selectedFile) void handleConfirmUpload();
11068
+ else void handleSave();
10921
11069
  }
10922
- }, [handleSave]);
10923
- const hasStoredFile = acceptAnyFile && !!imageUrl && !storedIsImage;
11070
+ }, [handleConfirmUpload, handleSave, selectedFile]);
11071
+ const hasStoredFile = hasStoredMedia && !hasImage && !imageLoadFailed;
10924
11072
  const dropzoneKey = isBusy ? "busy" : previewUrl ? "preview" : hasImage ? "loaded" : hasStoredFile ? "file" : imageLoadFailed ? "broken" : "empty";
10925
11073
  const renderDropzoneContent = () => {
10926
11074
  if (isBusy) {
10927
11075
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { "data-state": uploadState, className: "text-muted-foreground flex w-full flex-col items-center justify-center p-6", children: [
10928
11076
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react6.Loader2, { className: "mb-2 size-6 animate-spin" }),
10929
- /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("p", { className: "text-sm", children: isSubmittingDraft ? "Creating row..." : `Uploading ${noun}...` }),
11077
+ /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("p", { role: "status", className: "text-sm", children: isSubmittingDraft ? "Creating row..." : isClearing ? `Clearing ${noun}...` : `Uploading ${noun}...` }),
10930
11078
  isUploading && uploadProgress && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "mt-3 w-full max-w-xs", children: [
10931
- /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "bg-muted h-1.5 overflow-hidden rounded-full", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
11079
+ /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
10932
11080
  "div",
10933
11081
  {
10934
- className: "bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)",
10935
- style: { width: `${uploadProgress.percentage}%` }
11082
+ role: "progressbar",
11083
+ "aria-label": `Uploading ${noun}`,
11084
+ "aria-valuemin": 0,
11085
+ "aria-valuemax": 100,
11086
+ "aria-valuenow": Math.round(uploadProgress.percentage),
11087
+ className: "bg-muted h-1.5 overflow-hidden rounded-full",
11088
+ children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
11089
+ "div",
11090
+ {
11091
+ className: "bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)",
11092
+ style: { width: `${uploadProgress.percentage}%` }
11093
+ }
11094
+ )
10936
11095
  }
10937
- ) }),
10938
- /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("p", { className: "text-muted-foreground mt-1.5 text-center text-xs", children: [
11096
+ ),
11097
+ /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("p", { "aria-hidden": "true", className: "text-muted-foreground mt-1.5 text-center text-xs tabular-nums", children: [
10939
11098
  Math.round(uploadProgress.percentage),
10940
11099
  "%"
10941
11100
  ] })
@@ -10943,7 +11102,6 @@ var ImageEditor = ({
10943
11102
  ] });
10944
11103
  }
10945
11104
  if (previewUrl) {
10946
- const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
10947
11105
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
10948
11106
  selectedIsImage ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("img", { src: previewUrl, alt: selectedFile?.name || "Selected file", className: "size-full object-contain p-2" }) : /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(FilePreview, { name: selectedFile?.name, size: selectedFile?.size, mime: selectedFile?.type }),
10949
11107
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(RemoveButton, { onClick: removeFile, label: "Remove selected file" })
@@ -10966,7 +11124,7 @@ var ImageEditor = ({
10966
11124
  }
10967
11125
  if (hasStoredFile) {
10968
11126
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
10969
- /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(FilePreview, { name: imageMetadata?.filename, size: imageMetadata?.size, mime: imageMetadata?.mime }),
11127
+ /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(FilePreview, { name: imageMetadata?.filename ?? durableUrl ?? void 0, size: imageMetadata?.size, mime: imageMetadata?.mime }),
10970
11128
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(RemoveButton, { onClick: handleRemoveImage, label: "Remove file" })
10971
11129
  ] });
10972
11130
  }
@@ -10981,12 +11139,12 @@ var ImageEditor = ({
10981
11139
  }
10982
11140
  ),
10983
11141
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("p", { className: "text-sm font-medium", children: "Image unavailable" }),
10984
- imageUrl && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
11142
+ durableUrl && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
10985
11143
  "p",
10986
11144
  {
10987
11145
  className: "text-muted-foreground mt-1 max-w-full truncate font-mono text-[11px] opacity-50",
10988
- title: imageUrl,
10989
- children: imageUrl
11146
+ title: durableUrl,
11147
+ children: durableUrl
10990
11148
  }
10991
11149
  ),
10992
11150
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "mt-3 flex items-center gap-2", children: [
@@ -11049,7 +11207,7 @@ var ImageEditor = ({
11049
11207
  )
11050
11208
  ] });
11051
11209
  };
11052
- const saveLabel = isSubmittingDraft ? "Creating..." : isUploading ? "Uploading..." : imageUrl ? "Save" : "Done";
11210
+ const saveLabel = isSubmittingDraft ? "Creating..." : isClearing ? "Clearing..." : isUploading ? "Uploading..." : hasStoredMedia || clearPending ? "Save" : "Done";
11053
11211
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
11054
11212
  EditorFocusTrap,
11055
11213
  {
@@ -11059,7 +11217,7 @@ var ImageEditor = ({
11059
11217
  children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { onKeyDown: handleEditorKeyDown, className: "flex min-h-0 flex-1 flex-col", children: [
11060
11218
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "flex shrink-0 items-center gap-2 border-b px-6 py-3", children: [
11061
11219
  acceptAnyFile ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react6.FileIcon, { className: "text-muted-foreground size-4" }) : /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react6.ImageIcon, { className: "text-muted-foreground size-4" }),
11062
- /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("h3", { className: "text-sm font-medium", children: imageUrl ? `Edit ${Noun}` : `Add ${Noun}` })
11220
+ /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("h3", { className: "text-sm font-medium", children: hasStoredMedia ? `Edit ${Noun}` : `Add ${Noun}` })
11063
11221
  ] }),
11064
11222
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
11065
11223
  "input",
@@ -11107,7 +11265,7 @@ var ImageEditor = ({
11107
11265
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react6.AlertCircleIcon, { className: "size-3 shrink-0" }),
11108
11266
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { children: dragErrors[0] })
11109
11267
  ] }),
11110
- !isBusy && (selectedFile || imageMetadata && hasImage) && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "text-muted-foreground mt-2 text-center text-xs", children: selectedFile ? /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(import_jsx_runtime35.Fragment, { children: [
11268
+ !isBusy && (selectedFile ? selectedIsImage : imageMetadata && hasImage) && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "text-muted-foreground mt-2 text-center text-xs", children: selectedFile ? /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(import_jsx_runtime35.Fragment, { children: [
11111
11269
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { className: "font-medium", children: selectedFile.name }),
11112
11270
  " \u2022 ",
11113
11271
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { children: formatFileSize(selectedFile.size) }),
@@ -11127,7 +11285,7 @@ var ImageEditor = ({
11127
11285
  ] }) }),
11128
11286
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "flex shrink-0 justify-end gap-2 border-t px-6 py-3", children: [
11129
11287
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_button10.Button, { type: "button", variant: "outline", size: "sm", onClick: handleCancel, disabled: isBusy, children: "Cancel" }),
11130
- selectedFile && !isBusy ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_button10.Button, { type: "button", size: "sm", onClick: handleConfirmUpload, children: isDraftRow2 ? "Create Row & Upload" : "Upload & Save" }) : /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(import_button10.Button, { type: "button", size: "sm", onClick: handleSave, disabled: isBusy, children: [
11288
+ selectedFile && !isBusy ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_button10.Button, { type: "button", size: "sm", onClick: handleConfirmUpload, children: needsDraftCreation ? "Create Row & Upload" : "Upload & Save" }) : /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)(import_button10.Button, { type: "button", size: "sm", onClick: handleSave, disabled: isBusy, children: [
11131
11289
  isBusy && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react6.Loader2, { className: "size-3.5 animate-spin" }),
11132
11290
  saveLabel
11133
11291
  ] })
@@ -11145,20 +11303,18 @@ function ImageEditorDom({
11145
11303
  cell,
11146
11304
  colKey,
11147
11305
  rowId,
11306
+ rowIdentifier,
11148
11307
  tableName,
11149
11308
  onCommitPatch,
11150
11309
  onCancel,
11151
11310
  onSubmitDraftRow,
11152
11311
  onInvalidateData
11153
11312
  }) {
11154
- const isDraftRow2 = rowId.startsWith(DRAFT_PREFIX);
11313
+ const isDraftRow2 = rowIdentifier == null && rowId.startsWith(DRAFT_PREFIX);
11155
11314
  const cellType = cell.meta?.cellType;
11156
11315
  const acceptAnyFile = cellType != null && cellType !== "image";
11157
11316
  const handleSaveComplete = onCommitPatch ? (saveData) => onCommitPatch({ [colKey]: saveData.imageData }) : void 0;
11158
- const handleSubmitDraft = isDraftRow2 && onSubmitDraftRow ? async () => {
11159
- const createdRow = await onSubmitDraftRow(rowId);
11160
- return { createdRow };
11161
- } : void 0;
11317
+ const handleSubmitDraft = isDraftRow2 && onSubmitDraftRow ? () => onSubmitDraftRow(rowId) : void 0;
11162
11318
  return /* @__PURE__ */ (0, import_jsx_runtime36.jsx)("div", { "data-slot": "image-editor", children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(import_react54.Suspense, { fallback: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)("div", { className: "h-64 w-full min-w-[480px] animate-pulse rounded-lg bg-muted" }), children: /* @__PURE__ */ (0, import_jsx_runtime36.jsx)(
11163
11319
  ImageEditor,
11164
11320
  {
@@ -11167,7 +11323,7 @@ function ImageEditorDom({
11167
11323
  onFinishedEditing: () => onCancel(),
11168
11324
  tableName,
11169
11325
  fieldName: colKey,
11170
- recordId: rowId,
11326
+ recordId: rowIdentifier ?? null,
11171
11327
  onSaveComplete: handleSaveComplete,
11172
11328
  isDraftRow: isDraftRow2,
11173
11329
  onSubmitDraft: handleSubmitDraft,
@@ -11756,22 +11912,22 @@ NumberEditorDom.commitsOnBlur = true;
11756
11912
  // src/grid/editors/relation-editor.tsx
11757
11913
  var import_react62 = require("react");
11758
11914
  var import_lucide_react8 = require("lucide-react");
11759
- var import_react_query8 = require("@tanstack/react-query");
11915
+ var import_react_query9 = require("@tanstack/react-query");
11760
11916
 
11761
11917
  // src/hooks/use-sheets-table-cursor.ts
11762
11918
  var import_react59 = require("react");
11763
- var import_react_query7 = require("@tanstack/react-query");
11919
+ var import_react_query8 = require("@tanstack/react-query");
11920
+ var import_data20 = require("@constructive-io/data");
11764
11921
  var import_data21 = require("@constructive-io/data");
11765
11922
  var import_data22 = require("@constructive-io/data");
11766
- var import_data23 = require("@constructive-io/data");
11767
11923
  function useSheetsTableCursor(tableName, options = {}) {
11768
- const queryClient = (0, import_react_query7.useQueryClient)();
11924
+ const queryClient = (0, import_react_query8.useQueryClient)();
11769
11925
  const { execute, scopeKey } = useSheetsContext();
11770
11926
  const { data: meta } = useSheetsMeta();
11771
11927
  const adapter = useSheetsAdapter();
11772
11928
  const tables = (0, import_react59.useMemo)(() => {
11773
11929
  if (!meta?._meta?.tables) return [];
11774
- return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data21.cleanTable)(metaTable));
11930
+ return meta._meta.tables.filter((candidate) => candidate != null).map((metaTable) => (0, import_data20.cleanTable)(metaTable));
11775
11931
  }, [meta]);
11776
11932
  const table = (0, import_react59.useMemo)(
11777
11933
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
@@ -11799,11 +11955,11 @@ function useSheetsTableCursor(tableName, options = {}) {
11799
11955
  hasNextPage,
11800
11956
  fetchNextPage,
11801
11957
  error
11802
- } = (0, import_react_query7.useInfiniteQuery)({
11958
+ } = (0, import_react_query8.useInfiniteQuery)({
11803
11959
  queryKey: sheetsQueryKeys.cursorTable(scopeKey, tableName, stableOptions),
11804
11960
  queryFn: async ({ pageParam }) => {
11805
11961
  if (!table) {
11806
- throw import_data22.createError.notFound(`Table '${tableName}' not found`);
11962
+ throw import_data21.createError.notFound(`Table '${tableName}' not found`);
11807
11963
  }
11808
11964
  const cursor = pageParam;
11809
11965
  const variableOptions = {
@@ -11826,7 +11982,7 @@ function useSheetsTableCursor(tableName, options = {}) {
11826
11982
  const validatedOrderByEnum = new Set(variables.orderBy ?? []);
11827
11983
  const availableOrderByFields = new Set(table.fields.map((field) => field.name));
11828
11984
  const validatedOrderBy = orderBy?.filter(
11829
- ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data23.toOrderByEnumValue)(field, direction))
11985
+ ({ field, direction }) => availableOrderByFields.has(field) && validatedOrderByEnum.has((0, import_data22.toOrderByEnumValue)(field, direction))
11830
11986
  );
11831
11987
  const res = await adapter.listRows(
11832
11988
  { table, allTables: tables, tableName },
@@ -12013,7 +12169,7 @@ var RelationEditor = ({
12013
12169
  }) => {
12014
12170
  const { data: meta } = useSheetsMeta();
12015
12171
  const { scopeKey } = useSheetsContext();
12016
- const queryClient = (0, import_react_query8.useQueryClient)();
12172
+ const queryClient = (0, import_react_query9.useQueryClient)();
12017
12173
  const ensureRelationInfo = useSheetsStore((s) => s.ensureRelationInfo);
12018
12174
  const relationInfoForTable = useSheetsStore((s) => tableName ? s.relationInfoCache[tableName] : void 0);
12019
12175
  const relationEntry = relationInfoForTable?.[fieldName];
@@ -12773,6 +12929,7 @@ var DOM_EDITOR_REGISTRY = {
12773
12929
  video: ImageEditorDom,
12774
12930
  audio: ImageEditorDom,
12775
12931
  upload: ImageEditorDom,
12932
+ attachment: ImageEditorDom,
12776
12933
  // Date/time types
12777
12934
  date: DateEditorDom,
12778
12935
  datetime: DateEditorDom,
@@ -13518,7 +13675,7 @@ function SheetsDomInner({
13518
13675
  } = props;
13519
13676
  const s = useSheets(props);
13520
13677
  const shell = s._shell;
13521
- const { config } = useSheetsContext();
13678
+ const { config, canUpload, scopeKey } = useSheetsContext();
13522
13679
  const viewportRef = (0, import_react66.useRef)(null);
13523
13680
  const { commands, keymap, interceptors, onCommand } = props;
13524
13681
  const registry = (0, import_react66.useMemo)(() => createGridCommandRegistry(commands), [commands]);
@@ -13692,6 +13849,11 @@ function SheetsDomInner({
13692
13849
  const overlayOpen = overlay2.open;
13693
13850
  const overlayClose = overlay2.close;
13694
13851
  const overlayReanchor = overlay2.reanchor;
13852
+ const mediaDraft = overlay2.active?.mediaDraft;
13853
+ const activeMediaDraft = canUpload && mediaDraft?.scopeKey === scopeKey && mediaDraft?.tableName === tableName ? mediaDraft : void 0;
13854
+ (0, import_react66.useEffect)(() => {
13855
+ if (mediaDraft && !activeMediaDraft) overlayClose();
13856
+ }, [mediaDraft, activeMediaDraft, overlayClose]);
13695
13857
  const getSheetsCellContent = shell.getSheetsCellContent;
13696
13858
  const submitDraftRow = shell.submitDraftRow;
13697
13859
  const commitCellValue = shell.commitCellValue;
@@ -13730,9 +13892,24 @@ function SheetsDomInner({
13730
13892
  overlayOpen({ rowIndex, colKey, anchorRect, initialText, mode: "inline" });
13731
13893
  return;
13732
13894
  }
13733
- overlayOpen({ rowIndex, colKey, anchorRect, initialText, mode: "overlay" });
13895
+ const row = combinedRowsRef.current[rowIndex];
13896
+ const draft = intent.editor === ImageEditorDom ? getDraftMeta(row) : void 0;
13897
+ overlayOpen({
13898
+ rowIndex,
13899
+ colKey,
13900
+ anchorRect,
13901
+ initialText,
13902
+ mode: "overlay",
13903
+ mediaDraft: draft ? {
13904
+ rowId: draft.draftRowId,
13905
+ tableName,
13906
+ scopeKey,
13907
+ value: row[colKey],
13908
+ resolution
13909
+ } : void 0
13910
+ });
13734
13911
  },
13735
- [overlayOpen]
13912
+ [overlayOpen, tableName, scopeKey]
13736
13913
  );
13737
13914
  const openEditor = (0, import_react66.useCallback)(
13738
13915
  (rowIndex, colKey, anchorRect, initialText) => dispatch("editor.open", void 0, { rowIndex, colKey, anchorRect, initialText }),
@@ -13885,6 +14062,7 @@ function SheetsDomInner({
13885
14062
  const handleOverlayScroll = (0, import_react66.useCallback)(() => {
13886
14063
  const a = activeRef.current;
13887
14064
  if (!a) return;
14065
+ if (a.mediaDraft && getDraftMeta(combinedRowsRef.current[a.rowIndex])?.draftRowId !== a.mediaDraft.rowId) return;
13888
14066
  const colIndex = columnsRef.current.findIndex((c) => c.key === a.colKey);
13889
14067
  const node = colIndex >= 0 ? document.getElementById(`sheets-cell-${a.rowIndex}-${colIndex}`) : null;
13890
14068
  if (node) {
@@ -13897,12 +14075,13 @@ function SheetsDomInner({
13897
14075
  }, [overlayReanchor, overlayClose]);
13898
14076
  const active3 = overlay2.active;
13899
14077
  const editorNode = (() => {
13900
- if (!active3) return null;
13901
- const resolution = getSheetsCellContent(active3.rowIndex, active3.colKey);
14078
+ if (!active3 || mediaDraft && !activeMediaDraft) return null;
14079
+ const resolution = activeMediaDraft?.resolution ?? getSheetsCellContent(active3.rowIndex, active3.colKey);
13902
14080
  const intent = resolveEditIntent(resolution.typeKey, { readonly: resolution.cell.readonly }, getEditorComponent);
13903
14081
  if (intent.mode !== "overlay") return null;
13904
14082
  const Editor = intent.editor;
13905
- const rowValue = combinedRows[active3.rowIndex]?.[active3.colKey];
14083
+ const row = combinedRows[active3.rowIndex];
14084
+ const rowValue = activeMediaDraft ? activeMediaDraft.value : row?.[active3.colKey];
13906
14085
  const geom = computeOverlayGeometry(
13907
14086
  typeof window !== "undefined" ? window.innerHeight : 800,
13908
14087
  active3.anchorRect.top,
@@ -13921,7 +14100,8 @@ function SheetsDomInner({
13921
14100
  value: rowValue,
13922
14101
  cell: resolution.cell,
13923
14102
  colKey: active3.colKey,
13924
- rowId: getRowId(combinedRows[active3.rowIndex], active3.rowIndex),
14103
+ rowId: activeMediaDraft?.rowId ?? getRowId(row, active3.rowIndex),
14104
+ rowIdentifier: resolution.rowIdentifier,
13925
14105
  rowIndex: active3.rowIndex,
13926
14106
  tableName: props.tableName,
13927
14107
  fieldMeta: resolution.fieldMeta,
@@ -13932,7 +14112,9 @@ function SheetsDomInner({
13932
14112
  overlayClose();
13933
14113
  },
13934
14114
  onCommitPatch: (patch) => {
13935
- shell.commitCellPatch(active3.rowIndex, patch);
14115
+ if (!activeMediaDraft || getDraftMeta(row)?.draftRowId === activeMediaDraft.rowId) {
14116
+ shell.commitCellPatch(active3.rowIndex, patch);
14117
+ }
13936
14118
  overlayClose();
13937
14119
  },
13938
14120
  onSubmitDraftRow: shell.submitDraftRow,
@@ -14001,18 +14183,18 @@ function SheetsDomInner({
14001
14183
  toTSV: (values) => toTSV(values),
14002
14184
  emit
14003
14185
  };
14004
- if (s.dataError && shell.combinedRows.length === 0) {
14186
+ if (!activeMediaDraft && s.dataError && shell.combinedRows.length === 0) {
14005
14187
  const retry = () => s.refetch();
14006
14188
  if (slots?.error) {
14007
14189
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_jsx_runtime52.Fragment, { children: slots.error({ error: s.dataError, retry }) });
14008
14190
  }
14009
14191
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(SheetsErrorState, { error: s.dataError, onRetry: retry });
14010
14192
  }
14011
- if (s.isInitialLoading) {
14193
+ if (!activeMediaDraft && s.isInitialLoading) {
14012
14194
  if (slots?.loading) return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_jsx_runtime52.Fragment, { children: slots.loading });
14013
14195
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(SheetsLoadingState, {});
14014
14196
  }
14015
- if (s.isEmpty) {
14197
+ if (!activeMediaDraft && s.isEmpty) {
14016
14198
  if (slots?.empty) {
14017
14199
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_jsx_runtime52.Fragment, { children: typeof slots.empty === "function" ? slots.empty({ tableName }) : slots.empty });
14018
14200
  }
@@ -14876,7 +15058,7 @@ function useDynamicUpdate(tableName, rowId) {
14876
15058
  var import_react74 = require("react");
14877
15059
 
14878
15060
  // src/auth/hooks/use-login.ts
14879
- var import_react_query9 = require("@tanstack/react-query");
15061
+ var import_react_query10 = require("@tanstack/react-query");
14880
15062
 
14881
15063
  // src/auth/utils/auth-errors.ts
14882
15064
  var ERROR_CODES = {
@@ -15118,10 +15300,10 @@ var SIGN_IN_MUTATION = (
15118
15300
  `
15119
15301
  );
15120
15302
  function useSheetsLogin() {
15121
- const queryClient = (0, import_react_query9.useQueryClient)();
15303
+ const queryClient = (0, import_react_query10.useQueryClient)();
15122
15304
  const { config } = useSheetsContext();
15123
15305
  const storeApi = useSheetsStoreApi();
15124
- return (0, import_react_query9.useMutation)({
15306
+ return (0, import_react_query10.useMutation)({
15125
15307
  mutationKey: ["sheets", "auth", "signIn"],
15126
15308
  mutationFn: async (credentials) => {
15127
15309
  const result = await executeAuthMutation(
@@ -15155,7 +15337,7 @@ function useSheetsLogin() {
15155
15337
  }
15156
15338
 
15157
15339
  // src/auth/hooks/use-register.ts
15158
- var import_react_query10 = require("@tanstack/react-query");
15340
+ var import_react_query11 = require("@tanstack/react-query");
15159
15341
  var SIGN_UP_MUTATION = (
15160
15342
  /* GraphQL */
15161
15343
  `
@@ -15167,10 +15349,10 @@ var SIGN_UP_MUTATION = (
15167
15349
  `
15168
15350
  );
15169
15351
  function useSheetsRegister() {
15170
- const queryClient = (0, import_react_query10.useQueryClient)();
15352
+ const queryClient = (0, import_react_query11.useQueryClient)();
15171
15353
  const { config } = useSheetsContext();
15172
15354
  const storeApi = useSheetsStoreApi();
15173
- return (0, import_react_query10.useMutation)({
15355
+ return (0, import_react_query11.useMutation)({
15174
15356
  mutationKey: ["sheets", "auth", "signUp"],
15175
15357
  mutationFn: async (formData) => {
15176
15358
  await executeAuthMutation(
@@ -15195,7 +15377,7 @@ function useSheetsRegister() {
15195
15377
  }
15196
15378
 
15197
15379
  // src/auth/hooks/use-forgot-password.ts
15198
- var import_react_query11 = require("@tanstack/react-query");
15380
+ var import_react_query12 = require("@tanstack/react-query");
15199
15381
  var FORGOT_PASSWORD_MUTATION = (
15200
15382
  /* GraphQL */
15201
15383
  `
@@ -15208,7 +15390,7 @@ var FORGOT_PASSWORD_MUTATION = (
15208
15390
  );
15209
15391
  function useSheetsForgotPassword() {
15210
15392
  const { config } = useSheetsContext();
15211
- return (0, import_react_query11.useMutation)({
15393
+ return (0, import_react_query12.useMutation)({
15212
15394
  mutationKey: ["sheets", "auth", "forgotPassword"],
15213
15395
  mutationFn: async ({ email }) => {
15214
15396
  await executeAuthMutation(
@@ -15224,7 +15406,7 @@ function useSheetsForgotPassword() {
15224
15406
  }
15225
15407
 
15226
15408
  // src/auth/hooks/use-reset-password.ts
15227
- var import_react_query12 = require("@tanstack/react-query");
15409
+ var import_react_query13 = require("@tanstack/react-query");
15228
15410
  var RESET_PASSWORD_MUTATION = (
15229
15411
  /* GraphQL */
15230
15412
  `
@@ -15237,9 +15419,9 @@ var RESET_PASSWORD_MUTATION = (
15237
15419
  `
15238
15420
  );
15239
15421
  function useSheetsResetPassword() {
15240
- const queryClient = (0, import_react_query12.useQueryClient)();
15422
+ const queryClient = (0, import_react_query13.useQueryClient)();
15241
15423
  const { config } = useSheetsContext();
15242
- return (0, import_react_query12.useMutation)({
15424
+ return (0, import_react_query13.useMutation)({
15243
15425
  mutationKey: ["sheets", "auth", "resetPassword"],
15244
15426
  mutationFn: async (input) => {
15245
15427
  const result = await executeAuthMutation(