@constructive-io/sheets 0.13.1 → 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 +554 -716
  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-AYMXT3ME.js → chunk-BGL6EBTE.js} +108 -202
  12. package/dist/chunk-BGL6EBTE.js.map +1 -0
  13. package/dist/{chunk-MXVNIKES.js → chunk-BYAYBXVB.js} +2 -2
  14. package/dist/{chunk-5QPNOKMA.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 +782 -637
  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 +121 -87
  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-5QPNOKMA.js.map +0 -1
  39. package/dist/chunk-AYMXT3ME.js.map +0 -1
  40. package/dist/chunk-H5HR5HUJ.js.map +0 -1
  41. package/dist/chunk-PZL2BCWF.js.map +0 -1
  42. package/dist/chunk-ZKANUG3F.js +0 -123
  43. package/dist/chunk-ZKANUG3F.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,80 +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
- const uploadedTypeName = upload.uploadFieldName.replace(/^upload/, "");
1107
- const fileTypeName = typeByName.has(uploadedTypeName) ? uploadedTypeName : downloadById.fileTypeName;
1108
- let remove = {};
1109
- for (const field of mutationType?.fields ?? []) {
1110
- const inputArg = field.args.find((a) => a.name === "input");
1111
- const inputTypeName = namedTypeName(inputArg?.type);
1112
- const inputFields = inputTypeName ? typeByName.get(inputTypeName)?.inputFields : null;
1113
- if (!inputTypeName || !inputFields?.some((f) => f.name === PK_FIELD_NAME)) continue;
1114
- if (!inputFields.every((f) => f.name === PK_FIELD_NAME || f.name === "clientMutationId")) continue;
1115
- const payload = typeByName.get(namedTypeName(field.type) ?? "");
1116
- if (payload?.fields?.some((f) => namedTypeName(f.type) === fileTypeName)) {
1117
- remove = { deleteFieldName: field.name, deleteInputTypeName: inputTypeName };
1118
- break;
1126
+ const fileTypes = /* @__PURE__ */ new Set();
1127
+ for (const t of schema.types) {
1128
+ if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
1129
+ fileTypes.add(t.name);
1119
1130
  }
1120
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);
1121
1138
  return {
1122
- ...upload,
1123
- ...downloadById,
1124
- ...remove
1139
+ upload: upload ? { ...upload, download: uploadDownload } : null,
1140
+ download,
1141
+ batch
1125
1142
  };
1126
1143
  }
1127
- async function deleteUploadedFileRow(execute, cap, fileId) {
1128
- if (!cap.deleteFieldName || !cap.deleteInputTypeName) return;
1129
- const mutation = `
1130
- mutation SheetsUploadCleanup($input: ${cap.deleteInputTypeName}!) {
1131
- ${cap.deleteFieldName}(input: $input) { __typename }
1132
- }
1133
- `.trim();
1134
- try {
1135
- await execute(mutation, { input: { [PK_FIELD_NAME]: fileId } });
1136
- } catch {
1137
- }
1138
- }
1139
- function resolveDownloadByIdField(schema, typeByName, queryType, uploadFieldName) {
1140
- const fileTypesWithDownloadUrl = /* @__PURE__ */ new Set();
1141
- for (const t of schema.types) {
1142
- if (t.kind === "OBJECT" && t.name && t.fields?.some((f) => f.name === "downloadUrl")) {
1143
- fileTypesWithDownloadUrl.add(t.name);
1144
- }
1145
- }
1144
+ function resolveDownloadByIdField(typeByName, queryType, fileTypesWithDownloadUrl, preferred) {
1145
+ let singular = null;
1146
1146
  for (const field of queryType?.fields ?? []) {
1147
1147
  const returnTypeName = namedTypeName(field.type);
1148
1148
  if (!returnTypeName || !fileTypesWithDownloadUrl.has(returnTypeName)) continue;
1149
1149
  if (field.args.length === 1 && field.args[0].name === PK_FIELD_NAME) {
1150
- return {
1150
+ const candidate = {
1151
1151
  fileByIdField: field.name,
1152
1152
  fileByIdArgName: "id",
1153
1153
  fileTypeName: returnTypeName,
1154
1154
  idScalarName: namedTypeName(field.args[0].type) ?? void 0
1155
1155
  };
1156
+ if (returnTypeName === preferred) return candidate;
1157
+ singular ??= candidate;
1156
1158
  }
1157
1159
  }
1158
- const connection = resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName);
1159
- 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;
1160
1163
  const nodeField = queryType?.fields?.find(
1161
1164
  (f) => f.name === "node" && f.args.some((a) => a.name === "nodeId")
1162
1165
  );
1163
1166
  if (nodeField && fileTypesWithDownloadUrl.size > 0) {
1164
- const preferred = uploadFieldName.replace(/^upload/, "");
1165
1167
  const fileTypeName = fileTypesWithDownloadUrl.has(preferred) ? preferred : [...fileTypesWithDownloadUrl][0];
1166
1168
  return { fileByIdField: "node", fileByIdArgName: "nodeId", fileTypeName };
1167
1169
  }
1168
- throw import_data.createError.badRequest("Uploads are not enabled for this endpoint.");
1170
+ return null;
1169
1171
  }
1170
- function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, uploadFieldName) {
1172
+ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDownloadUrl, preferred, batch = false) {
1171
1173
  const EQUALITY_OPERATORS = ["equalTo", "eq"];
1172
1174
  const candidates = [];
1173
1175
  for (const field of queryType?.fields ?? []) {
@@ -1182,6 +1184,8 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
1182
1184
  });
1183
1185
  if (!nodesField) continue;
1184
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");
1185
1189
  for (const arg of field.args) {
1186
1190
  const filterTypeName = namedTypeName(arg.type);
1187
1191
  const filterType = filterTypeName ? typeByName.get(filterTypeName) : null;
@@ -1191,7 +1195,7 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
1191
1195
  const idFieldTypeName = namedTypeName(idField.type);
1192
1196
  const idFieldType = idFieldTypeName ? typeByName.get(idFieldTypeName) : null;
1193
1197
  if (idFieldType?.kind === "INPUT_OBJECT" && idFieldType.inputFields) {
1194
- const opField = EQUALITY_OPERATORS.map(
1198
+ const opField = batch ? idFieldType.inputFields.find((f) => f.name === "in" && isListTypeRef(f.type)) : EQUALITY_OPERATORS.map(
1195
1199
  (op) => idFieldType.inputFields.find((f) => f.name === op)
1196
1200
  ).find((f) => f != null);
1197
1201
  if (opField) {
@@ -1203,13 +1207,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
1203
1207
  connectionFilterArgName: arg.name,
1204
1208
  connectionIdField: idField.name,
1205
1209
  connectionIdOperator: opField.name,
1206
- connectionNodesField: nodesField.name
1210
+ connectionNodesField: nodesField.name,
1211
+ connectionHasFirst
1207
1212
  });
1208
1213
  break;
1209
1214
  }
1210
1215
  continue;
1211
1216
  }
1212
- if (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName) {
1217
+ if (!batch && (idFieldType?.kind === "SCALAR" || !idFieldType && idFieldTypeName)) {
1213
1218
  candidates.push({
1214
1219
  fileByIdField: field.name,
1215
1220
  fileByIdArgName: "connection",
@@ -1217,14 +1222,14 @@ function resolveConnectionDownloadField(typeByName, queryType, fileTypesWithDown
1217
1222
  idScalarName: idFieldTypeName ?? void 0,
1218
1223
  connectionFilterArgName: arg.name,
1219
1224
  connectionIdField: idField.name,
1220
- connectionNodesField: nodesField.name
1225
+ connectionNodesField: nodesField.name,
1226
+ connectionHasFirst
1221
1227
  });
1222
1228
  break;
1223
1229
  }
1224
1230
  }
1225
1231
  }
1226
1232
  if (candidates.length === 0) return null;
1227
- const preferred = uploadFieldName.replace(/^upload/, "");
1228
1233
  return candidates.find((c) => c.fileTypeName === preferred) ?? candidates[0];
1229
1234
  }
1230
1235
  async function callUploadOp(execute, cap, input) {
@@ -1235,12 +1240,13 @@ async function callUploadOp(execute, cap, input) {
1235
1240
  fileId
1236
1241
  key
1237
1242
  deduplicated
1243
+ file
1238
1244
  }
1239
1245
  }
1240
1246
  `.trim();
1241
1247
  const data = await execute(mutation, {
1242
1248
  input: {
1243
- bucketKey: input.bucketKey,
1249
+ ...input.bucketKey === void 0 ? { isPublic: true } : { bucketKey: input.bucketKey },
1244
1250
  contentHash: input.contentHash,
1245
1251
  contentType: input.contentType,
1246
1252
  size: input.size,
@@ -1251,6 +1257,10 @@ async function callUploadOp(execute, cap, input) {
1251
1257
  if (!payload) {
1252
1258
  throw import_data.createError.badRequest("Upload failed: no payload returned from upload mutation.");
1253
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
+ }
1254
1264
  return payload;
1255
1265
  }
1256
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.";
@@ -1339,7 +1349,7 @@ async function fetchDownloadUrl(execute, cap, fileId) {
1339
1349
  const filterLiteral = cap.connectionIdOperator ? `{ ${idField}: { ${cap.connectionIdOperator}: $id } }` : `{ ${idField}: $id }`;
1340
1350
  const query2 = `
1341
1351
  query SheetsDownloadUrl($id: ${idScalar2}!) {
1342
- ${cap.fileByIdField}(${filterArg}: ${filterLiteral}, first: 1) {
1352
+ ${cap.fileByIdField}(${filterArg}: ${filterLiteral}${cap.connectionHasFirst ? ", first: 1" : ""}) {
1343
1353
  ${nodesField} {
1344
1354
  downloadUrl
1345
1355
  }
@@ -1374,10 +1384,34 @@ async function fetchDownloadUrl(execute, cap, fileId) {
1374
1384
  }
1375
1385
  return url;
1376
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
+ }
1377
1411
  async function resolveDownloadUrl(execute, endpoint, fileId) {
1378
1412
  try {
1379
- const cap = await discoverUploadCapability(endpoint, execute);
1380
- return await fetchDownloadUrl(execute, cap, fileId);
1413
+ const { download } = await discoverStorageCapabilities(endpoint, execute);
1414
+ return download ? await fetchDownloadUrl(execute, download, fileId) : null;
1381
1415
  } catch {
1382
1416
  return null;
1383
1417
  }
@@ -1471,17 +1505,33 @@ function createSheetsExecute(config, getToken) {
1471
1505
  return result.data;
1472
1506
  };
1473
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
+ }
1474
1516
  function createSheetsUpload(config, getToken) {
1475
- 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) {
1476
1524
  return async (file, _path, options) => {
1477
- if (!config.endpoint) {
1525
+ if (!endpoint) {
1478
1526
  throw import_data2.createError.badRequest("No GraphQL endpoint configured.");
1479
1527
  }
1480
- 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
+ }
1481
1532
  const contentType = file.type || "application/octet-stream";
1482
1533
  const buffer = await file.arrayBuffer();
1483
1534
  const contentHash = await sha256HexFromBuffer(buffer);
1484
- const cap = await discoverUploadCapability(config.endpoint, execute);
1485
1535
  const payload = await callUploadOp(execute, cap, {
1486
1536
  bucketKey,
1487
1537
  contentHash,
@@ -1493,24 +1543,19 @@ function createSheetsUpload(config, getToken) {
1493
1543
  if (!payload.uploadUrl) {
1494
1544
  throw import_data2.createError.badRequest("Upload failed: server returned no uploadUrl for a non-deduplicated file.");
1495
1545
  }
1496
- try {
1497
- await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
1498
- } catch (error) {
1499
- await deleteUploadedFileRow(execute, cap, payload.fileId);
1500
- throw error;
1501
- }
1546
+ await presignedPut(payload.uploadUrl, buffer, contentType, options?.onProgress);
1502
1547
  } else {
1503
1548
  options?.onProgress?.({ loaded: file.size, total: file.size, percentage: 100 });
1504
1549
  }
1505
- const url = await fetchDownloadUrl(execute, cap, payload.fileId);
1506
- return {
1507
- url,
1508
- filename: file.name,
1509
- mime: file.type,
1510
- size: file.size,
1511
- key: payload.key,
1512
- fileId: payload.fileId
1550
+ const result = {
1551
+ file: { ...payload.file, filename: payload.file.filename ?? file.name }
1513
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
+ }
1514
1559
  };
1515
1560
  }
1516
1561
 
@@ -2219,6 +2264,7 @@ var sheetsQueryKeys = {
2219
2264
  root: ["sheets"],
2220
2265
  scope: (scope) => ["sheets", scope],
2221
2266
  meta: (scope) => [...sheetsQueryKeys.scope(scope), "meta"],
2267
+ mediaUrl: (scope, endpoint, id) => [...sheetsQueryKeys.scope(scope), "media-url", endpoint, id],
2222
2268
  typeFields: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "type-fields", typeName],
2223
2269
  enumValues: (scope, typeName) => [...sheetsQueryKeys.scope(scope), "enum-values", typeName],
2224
2270
  relations: (scope, tableName) => [...sheetsQueryKeys.scope(scope), "relations", tableName],
@@ -2234,6 +2280,9 @@ var sheetsQueryKeys = {
2234
2280
 
2235
2281
  // src/context/sheets-provider.tsx
2236
2282
  var import_jsx_runtime = require("react/jsx-runtime");
2283
+ var unavailableUpload = async () => {
2284
+ throw new Error("Uploads need a storage endpoint");
2285
+ };
2237
2286
  function SheetsProvider({ config, children }) {
2238
2287
  const providerInstanceId = (0, import_react3.useId)();
2239
2288
  const storeRef = (0, import_react3.useRef)(null);
@@ -2292,10 +2341,13 @@ function SheetsProvider({ config, children }) {
2292
2341
  if (config.execute) return config.execute;
2293
2342
  return createSheetsExecute(config, getToken);
2294
2343
  }, [config, getToken]);
2344
+ const storage = (0, import_react3.useMemo)(() => resolveStorageTransport(config, getToken), [config, getToken]);
2345
+ const bucketKey = config.upload?.bucketKey;
2295
2346
  const executeUpload = (0, import_react3.useMemo)(() => {
2296
2347
  if (config.executeUpload) return config.executeUpload;
2297
- return createSheetsUpload(config, getToken);
2298
- }, [config, getToken]);
2348
+ return storage ? createPresignedSheetsUpload(storage, bucketKey) : unavailableUpload;
2349
+ }, [config.executeUpload, storage, bucketKey]);
2350
+ const canUpload = Boolean(config.executeUpload || storage);
2299
2351
  const configuredIdentityKey = config.auth.mode === "embedded" ? config.auth.getIdentityKey?.() ?? null : standaloneIdentityKey;
2300
2352
  const activeToken = config.auth.mode === "embedded" ? config.auth.getToken() : standaloneAccessToken;
2301
2353
  const authGenerationRef = (0, import_react3.useRef)({ mode: config.auth.mode, token: activeToken, generation: 0 });
@@ -2321,8 +2373,8 @@ function SheetsProvider({ config, children }) {
2321
2373
  };
2322
2374
  }, [queryClient, scopeKey]);
2323
2375
  const contextValue = (0, import_react3.useMemo)(
2324
- () => ({ config, execute, executeUpload, scopeKey }),
2325
- [config, execute, executeUpload, scopeKey]
2376
+ () => ({ config, execute, executeUpload, storage, canUpload, scopeKey }),
2377
+ [config, execute, executeUpload, storage, canUpload, scopeKey]
2326
2378
  );
2327
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 }) }) });
2328
2380
  }
@@ -2334,6 +2386,19 @@ var import_react67 = require("@remixicon/react");
2334
2386
  init_cn();
2335
2387
  var import_button19 = require("@constructive-io/ui/button");
2336
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
+
2337
2402
  // src/grid/sheets.controls.tsx
2338
2403
  var import_react4 = require("react");
2339
2404
  var import_react5 = require("@remixicon/react");
@@ -3736,7 +3801,7 @@ function mapToFrontendCellType(metadata) {
3736
3801
  if (encodedType) return encodedType;
3737
3802
  if (pgAlias) {
3738
3803
  const aliasType = mapAliasToCellType(pgAlias);
3739
- if (aliasType !== "unknown") return aliasType;
3804
+ if (aliasType !== "unknown" && !(isArray && aliasType === "attachment")) return aliasType;
3740
3805
  }
3741
3806
  if (isArray) {
3742
3807
  const result = mapGraphQLTypeToCellType(gqlType, isArray, metadata.subtype, null);
@@ -3789,6 +3854,7 @@ function mapAliasToCellType(alias) {
3789
3854
  video: "video",
3790
3855
  audio: "audio",
3791
3856
  upload: "upload",
3857
+ attachment: "attachment",
3792
3858
  // Relation types
3793
3859
  relation: "relation",
3794
3860
  // Special text types
@@ -3916,6 +3982,7 @@ function mapBackendTypeToCellType(pgType) {
3916
3982
  url: "url",
3917
3983
  image: "image",
3918
3984
  upload: "upload",
3985
+ attachment: "attachment",
3919
3986
  origin: "origin",
3920
3987
  // Arrays are handled by isArray flag
3921
3988
  _text: "array",
@@ -4358,6 +4425,7 @@ var import_data14 = require("@constructive-io/data");
4358
4425
  var import_react_query3 = require("@tanstack/react-query");
4359
4426
 
4360
4427
  // src/adapter/postgraphile-adapter.ts
4428
+ var import_graphql3 = require("graphql");
4361
4429
  var import_data13 = require("@constructive-io/data");
4362
4430
 
4363
4431
  // src/hooks/use-sheets-table.ts
@@ -5059,11 +5127,17 @@ function createPostGraphileAdapter() {
5059
5127
  },
5060
5128
  async updateRow(ctx, id, patch, execute, options = {}) {
5061
5129
  const { table, allTables, tableName } = ctx;
5062
- 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, {
5063
5138
  ...options,
5064
5139
  fieldSelection: options.fieldSelection || "display"
5065
5140
  });
5066
- const patchFieldName = (0, import_data13.toPatchFieldName)(tableName, table);
5067
5141
  const sanitizedPatch = (0, import_data13.prepareUpdateInput)(patch);
5068
5142
  if (Object.keys(sanitizedPatch).length === 0) return null;
5069
5143
  const normalizedPatch = normalizeMutationEnums(ctx, sanitizedPatch, execute);
@@ -5074,8 +5148,6 @@ function createPostGraphileAdapter() {
5074
5148
  }
5075
5149
  };
5076
5150
  const result = await execute(doc, variables);
5077
- const mutationName = (0, import_data13.toUpdateMutationName)(tableName, table);
5078
- const singularName = (0, import_data13.toCamelCaseSingular)(tableName, table);
5079
5151
  const updatedRow = result[mutationName]?.[singularName] ?? null;
5080
5152
  return updatedRow;
5081
5153
  },
@@ -5505,19 +5577,6 @@ function useDataGridColumns(tableName, rows = []) {
5505
5577
  init_sheets_logger();
5506
5578
  var import_toast = require("@constructive-io/ui/toast");
5507
5579
 
5508
- // src/grid/row-model.ts
5509
- var DRAFT_META = /* @__PURE__ */ Symbol("sheets.draftMeta");
5510
- function attachDraftMeta(row, meta) {
5511
- Object.defineProperty(row, DRAFT_META, { value: meta, enumerable: false, configurable: true });
5512
- return row;
5513
- }
5514
- function getDraftMeta(row) {
5515
- return row ? row[DRAFT_META] : void 0;
5516
- }
5517
- function isDraftRow(row) {
5518
- return getDraftMeta(row)?.isDraft === true;
5519
- }
5520
-
5521
5580
  // src/cell-types/cell-type-registry.ts
5522
5581
  function createCellTypeRegistry(cellTypes, builtins) {
5523
5582
  const byKey = /* @__PURE__ */ new Map();
@@ -5659,21 +5718,53 @@ var geometrySheetsCellFactory = { canHandle: canHandle3, create: create3 };
5659
5718
 
5660
5719
  // src/cell-model/factories/image.ts
5661
5720
  init_cell_type_groups();
5662
- function resolveMediaUrl(value) {
5663
- if (typeof value === "string") return value;
5664
- if (typeof value === "object" && value) {
5665
- const obj = value;
5666
- 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;
5667
5727
  }
5668
- 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;
5669
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
5670
5762
  var imageSheetsCellFactory = {
5671
5763
  canHandle(cellType) {
5672
- return MEDIA_TYPES.has(cellType);
5764
+ return cellType !== "attachment" && MEDIA_TYPES.has(cellType);
5673
5765
  },
5674
5766
  create(value, metadata) {
5675
- const url = value === null || value === void 0 || value === "" ? "" : resolveMediaUrl(value);
5676
- const data = [url];
5767
+ const data = [getImageUrl(value) ?? ""];
5677
5768
  return {
5678
5769
  kind: "image",
5679
5770
  data,
@@ -6126,6 +6217,7 @@ function useBatchCommit({
6126
6217
  update,
6127
6218
  getRowIdentifier = legacyRowIdentifier2,
6128
6219
  readOnlyFields,
6220
+ isCellReadOnly,
6129
6221
  canUpdate = true,
6130
6222
  applyOptimisticPatch,
6131
6223
  resyncRow,
@@ -6142,6 +6234,7 @@ function useBatchCommit({
6142
6234
  for (const w of writes) {
6143
6235
  const rowData = combinedRows[w.rowIndex];
6144
6236
  if (!rowData) continue;
6237
+ if (isCellReadOnly?.(w.rowIndex, w.colKey)) continue;
6145
6238
  if (getDraftMeta(rowData)) {
6146
6239
  draftWrites.push(w);
6147
6240
  continue;
@@ -6208,7 +6301,7 @@ function useBatchCommit({
6208
6301
  }
6209
6302
  return { applied: resolved.length };
6210
6303
  },
6211
- [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]
6212
6305
  );
6213
6306
  commitRef.current = commitCells;
6214
6307
  return commitCells;
@@ -6594,12 +6687,14 @@ function useSheetsContent(args) {
6594
6687
  serverRowsReadOnly = false,
6595
6688
  serverReadOnlyFields,
6596
6689
  getRowIdentifier,
6597
- supportsScalarSelfCommit = true
6690
+ supportsScalarSelfCommit = true,
6691
+ canUpload = true,
6692
+ canCreate = true
6598
6693
  } = args;
6599
6694
  const relationFieldNamesFromMeta = (0, import_react26.useMemo)(() => buildRelationFieldNameSet(meta, tableName), [meta, tableName]);
6600
6695
  const cache2 = (0, import_react26.useMemo)(
6601
6696
  () => /* @__PURE__ */ new Map(),
6602
- [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]
6603
6698
  );
6604
6699
  const getSheetsCell = (0, import_react26.useCallback)(
6605
6700
  (rowIndex, colKey) => {
@@ -6670,9 +6765,11 @@ function useSheetsContent(args) {
6670
6765
  };
6671
6766
  const cellType = registry.resolveTypeKey(matchInput, () => route.cellType);
6672
6767
  const rowIdentifier = !isDraftRow2 ? getRowIdentifier?.(rowData) : null;
6673
- const selfCommittingEditor = isRelation || MEDIA_TYPES.has(cellType);
6674
- const lacksScalarEditorIdentity = selfCommittingEditor && (!supportsScalarSelfCommit || rowIdentifier != null && typeof rowIdentifier === "object");
6675
- 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;
6676
6773
  const metadata = {
6677
6774
  cellType,
6678
6775
  fieldName: colKey,
@@ -6695,11 +6792,20 @@ function useSheetsContent(args) {
6695
6792
  const hasCellError = Boolean(draftErrors && colKey in draftErrors);
6696
6793
  const styled = isDraftRow2 ? tagDraftStyle(displaySafe, hasCellError) : displaySafe;
6697
6794
  const component = registry.getCellComponent(cellType);
6698
- 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
+ };
6699
6805
  cache2.set(cacheKey, { value: rawValue, resolution });
6700
6806
  return resolution;
6701
6807
  },
6702
- [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]
6703
6809
  );
6704
6810
  return { getSheetsCell };
6705
6811
  }
@@ -7808,7 +7914,7 @@ function useSheets(props) {
7808
7914
  const emit = (0, import_react33.useCallback)((type, meta) => {
7809
7915
  onEventRef.current?.({ type, tableName, at: Date.now(), meta });
7810
7916
  }, [tableName]);
7811
- const { config } = useSheetsContext();
7917
+ const { config, canUpload } = useSheetsContext();
7812
7918
  const cellRegistry = (0, import_react33.useMemo)(
7813
7919
  () => createCellTypeRegistry(
7814
7920
  // Compiled cell-component slots go LAST so they win over plugins + cellTypes.
@@ -8090,7 +8196,9 @@ function useSheets(props) {
8090
8196
  serverRowsReadOnly: !canUpdate,
8091
8197
  serverReadOnlyFields: primaryKeyFields,
8092
8198
  getRowIdentifier,
8093
- supportsScalarSelfCommit
8199
+ supportsScalarSelfCommit,
8200
+ canUpload,
8201
+ canCreate
8094
8202
  });
8095
8203
  const effectiveColumnOrder = (0, import_react33.useMemo)(() => {
8096
8204
  if (columnKeys.length > 0) return columnKeys;
@@ -8220,6 +8328,7 @@ function useSheets(props) {
8220
8328
  update,
8221
8329
  getRowIdentifier,
8222
8330
  readOnlyFields: primaryKeyFields,
8331
+ isCellReadOnly: canUpload ? void 0 : (rowIndex, colKey) => Boolean(getSheetsCellContent(rowIndex, colKey).readOnlyReason),
8223
8332
  canUpdate,
8224
8333
  applyOptimisticPatch: applyOptimisticCellPatch,
8225
8334
  resyncRow,
@@ -8938,7 +9047,7 @@ function GridViewport({
8938
9047
  }
8939
9048
 
8940
9049
  // src/grid-dom/sheets-cell-host.tsx
8941
- var import_react37 = require("react");
9050
+ var import_react38 = require("react");
8942
9051
  init_cn();
8943
9052
 
8944
9053
  // src/cell-model/badge-tones.ts
@@ -9155,42 +9264,89 @@ function GeometryCellView(props) {
9155
9264
 
9156
9265
  // src/cell-model/views/image-view.tsx
9157
9266
  var import_lucide_react2 = require("lucide-react");
9158
- init_cn();
9159
9267
 
9160
- // src/utils/file.utils.ts
9161
- var getImageUrl = (imageValue) => {
9162
- if (!imageValue) return null;
9163
- if (typeof imageValue === "string") {
9164
- return imageValue;
9165
- }
9166
- if (typeof imageValue === "object" && imageValue !== null) {
9167
- const urlCandidates = ["url", "src", "href", "link", "path"];
9168
- for (const candidate of urlCandidates) {
9169
- const obj = imageValue;
9170
- if (obj[candidate] && typeof obj[candidate] === "string") {
9171
- 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);
9172
9283
  }
9284
+ } catch (error) {
9285
+ for (const request of requests) request.reject(error);
9173
9286
  }
9174
9287
  }
9175
- return null;
9176
- };
9177
- var getImageMetadata = (imageValue) => {
9178
- if (!imageValue || typeof imageValue !== "object") return null;
9179
- const obj = imageValue;
9180
- return {
9181
- filename: obj.filename || obj.name || "Unknown",
9182
- size: obj.size || obj.fileSize || 0,
9183
- mime: obj.mime || obj.type || obj.contentType || "unknown",
9184
- url: getImageUrl(imageValue) || ""
9185
- };
9186
- };
9187
- var formatFileSize = (bytes) => {
9188
- if (bytes === 0) return "0 B";
9189
- const k = 1024;
9190
- const sizes = ["B", "KB", "MB", "GB"];
9191
- const i = Math.floor(Math.log(bytes) / Math.log(k));
9192
- return parseFloat((bytes / Math.pow(k, i)).toFixed(1)) + " " + sizes[i];
9193
- };
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();
9194
9350
 
9195
9351
  // src/cell-model/image-cache.ts
9196
9352
  var CAP = 256;
@@ -9216,34 +9372,34 @@ function warmImage(url) {
9216
9372
 
9217
9373
  // src/cell-model/views/image-view.tsx
9218
9374
  var import_jsx_runtime15 = require("react/jsx-runtime");
9219
- function readUrl(data) {
9220
- if (Array.isArray(data) && typeof data[0] === "string") return data[0];
9221
- return "";
9222
- }
9223
9375
  function basename(url) {
9224
9376
  const path = url.split(/[?#]/)[0];
9225
9377
  const seg = path.slice(path.lastIndexOf("/") + 1);
9226
9378
  return seg || url;
9227
9379
  }
9228
- function isNonImageFile(cellType, value) {
9229
- if (cellType === "image" || value == null) return false;
9230
- const mime = getImageMetadata(value)?.mime;
9231
- return !(mime && mime !== "unknown" && mime.startsWith("image/"));
9232
- }
9233
9380
  function ImageCellView(props) {
9234
- const url = readUrl(props.cell.data);
9235
- if (url && isNonImageFile(props.column.cellType, props.value)) {
9236
- const meta = getImageMetadata(props.value);
9237
- 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 ");
9238
9391
  return /* @__PURE__ */ (0, import_jsx_runtime15.jsxs)(
9239
9392
  "div",
9240
9393
  {
9241
9394
  "data-slot": "file-cell",
9242
9395
  role: "gridcell",
9396
+ "aria-readonly": props.readOnlyReason ? true : void 0,
9397
+ "aria-description": props.readOnlyReason,
9243
9398
  className: cn("flex h-full w-full items-center gap-1.5 overflow-hidden px-2"),
9244
9399
  children: [
9245
9400
  /* @__PURE__ */ (0, import_jsx_runtime15.jsx)(import_lucide_react2.FileIcon, { className: "size-3.5 shrink-0 text-muted-foreground", "aria-hidden": "true" }),
9246
- /* @__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 })
9247
9403
  ]
9248
9404
  }
9249
9405
  );
@@ -9253,6 +9409,8 @@ function ImageCellView(props) {
9253
9409
  {
9254
9410
  "data-slot": "image-cell",
9255
9411
  role: "gridcell",
9412
+ "aria-readonly": props.readOnlyReason ? true : void 0,
9413
+ "aria-description": props.readOnlyReason,
9256
9414
  className: cn("flex h-full w-full items-center overflow-hidden p-1"),
9257
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)(
9258
9416
  "img",
@@ -9260,11 +9418,16 @@ function ImageCellView(props) {
9260
9418
  src: url,
9261
9419
  decoding: "async",
9262
9420
  alt: "",
9263
- onLoad: () => warmImage(url),
9421
+ onError: onImageError,
9422
+ onLoad: () => {
9423
+ onImageLoad();
9424
+ if (durableUrl) warmImage(durableUrl);
9425
+ },
9264
9426
  className: cn(
9265
9427
  "absolute inset-0 h-full w-full rounded-sm object-cover outline-1 -outline-offset-1 outline-black/10 dark:outline-white/10"
9266
9428
  )
9267
- }
9429
+ },
9430
+ url
9268
9431
  ) : null })
9269
9432
  }
9270
9433
  );
@@ -9379,7 +9542,9 @@ function TextCellView(props) {
9379
9542
  {
9380
9543
  role: "gridcell",
9381
9544
  "data-slot": "text-cell",
9382
- title: text,
9545
+ title: [text, props.readOnlyReason].filter(Boolean).join("\n"),
9546
+ "aria-readonly": props.readOnlyReason ? true : void 0,
9547
+ "aria-description": props.readOnlyReason,
9383
9548
  className: cn("flex h-full w-full items-center truncate px-3 text-sm"),
9384
9549
  children: /* @__PURE__ */ (0, import_jsx_runtime19.jsx)("span", { className: "truncate", children: text })
9385
9550
  }
@@ -9408,7 +9573,7 @@ function UriCellView(props) {
9408
9573
  }
9409
9574
 
9410
9575
  // src/grid-dom/inline-cell-editor.tsx
9411
- var import_react36 = require("react");
9576
+ var import_react37 = require("react");
9412
9577
  init_cn();
9413
9578
  var import_jsx_runtime21 = require("react/jsx-runtime");
9414
9579
  function seedText(value) {
@@ -9422,11 +9587,11 @@ function parseNumeric(text) {
9422
9587
  return Number.isFinite(n) ? { ok: true, value: n } : { ok: false, value: null };
9423
9588
  }
9424
9589
  function InlineCellEditor({ ariaLabel, value, initialText, numeric, onCommit, onCancel }) {
9425
- const [text, setText] = (0, import_react36.useState)(() => initialText != null ? initialText : seedText(value));
9426
- const inputRef = (0, import_react36.useRef)(null);
9427
- const gridRef = (0, import_react36.useRef)(null);
9428
- const doneRef = (0, import_react36.useRef)(false);
9429
- (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)(() => {
9430
9595
  const el = inputRef.current;
9431
9596
  gridRef.current = el?.closest('[role="grid"]') ?? null;
9432
9597
  if (el && initialText == null) el.select();
@@ -9530,13 +9695,14 @@ function toCellProps(props, onStartEdit) {
9530
9695
  column: { key: props.colKey, name: props.colKey, cellType: cell.meta?.cellType ?? "unknown" },
9531
9696
  isEditing: props.isEditing,
9532
9697
  onStartEdit,
9533
- disabled: false
9698
+ disabled: false,
9699
+ readOnlyReason: props.resolution.readOnlyReason
9534
9700
  };
9535
9701
  }
9536
- var SheetsCellHostInner = (0, import_react37.memo)(
9702
+ var SheetsCellHostInner = (0, import_react38.memo)(
9537
9703
  function SheetsCellHostInner2(props) {
9538
- const wrapperRef = (0, import_react37.useRef)(null);
9539
- const startEdit = (0, import_react37.useCallback)(() => {
9704
+ const wrapperRef = (0, import_react38.useRef)(null);
9705
+ const startEdit = (0, import_react38.useCallback)(() => {
9540
9706
  const open = props.openEditor;
9541
9707
  const el = wrapperRef.current;
9542
9708
  if (!open || !el || props.resolution.cell.readonly) return;
@@ -9545,18 +9711,18 @@ var SheetsCellHostInner = (0, import_react37.memo)(
9545
9711
  const onActivateCell = props.onActivateCell;
9546
9712
  const columnIndex = props.columnIndex;
9547
9713
  const cellRowIndex = props.rowIndex;
9548
- const activate = (0, import_react37.useCallback)((e) => {
9714
+ const activate = (0, import_react38.useCallback)((e) => {
9549
9715
  onActivateCell?.(columnIndex, cellRowIndex, e.shiftKey);
9550
9716
  }, [onActivateCell, columnIndex, cellRowIndex]);
9551
9717
  const onContextMenu = props.onContextMenu;
9552
- const contextMenu = (0, import_react37.useCallback)((e) => {
9718
+ const contextMenu = (0, import_react38.useCallback)((e) => {
9553
9719
  if (!onContextMenu) return;
9554
9720
  e.preventDefault();
9555
9721
  onContextMenu(columnIndex, cellRowIndex, e.clientX, e.clientY);
9556
9722
  }, [onContextMenu, columnIndex, cellRowIndex]);
9557
9723
  const onSubmitDraftRow = props.onSubmitDraftRow;
9558
9724
  const draftAction = props.draftAction;
9559
- const submitDraft = (0, import_react37.useCallback)(() => {
9725
+ const submitDraft = (0, import_react38.useCallback)(() => {
9560
9726
  if (draftAction && onSubmitDraftRow) void onSubmitDraftRow(draftAction.draftRowId);
9561
9727
  }, [draftAction, onSubmitDraftRow]);
9562
9728
  const cellProps = toCellProps(props, startEdit);
@@ -9573,6 +9739,7 @@ var SheetsCellHostInner = (0, import_react37.memo)(
9573
9739
  ref: wrapperRef,
9574
9740
  id: `sheets-cell-${props.rowIndex}-${props.columnIndex}`,
9575
9741
  "aria-selected": props.isActive || void 0,
9742
+ title: props.resolution.readOnlyReason,
9576
9743
  onClick: activate,
9577
9744
  onDoubleClick: startEdit,
9578
9745
  onContextMenu: contextMenu,
@@ -9612,7 +9779,7 @@ var SheetsCellHostInner = (0, import_react37.memo)(
9612
9779
  },
9613
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.
9614
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.
9615
- 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
9616
9783
  // unchanged (validation result arrives, save in flight), so gate on them too.
9617
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)
9618
9785
  );
@@ -9652,19 +9819,19 @@ function SheetsCellHost({ cell, ctx, getSheetsCellContent, openEditor, isEditing
9652
9819
  }
9653
9820
 
9654
9821
  // src/grid-dom/overlay/use-overlay-controller.ts
9655
- var import_react38 = require("react");
9822
+ var import_react39 = require("react");
9656
9823
  function useOverlayController() {
9657
- const [active3, setActive] = (0, import_react38.useState)(null);
9658
- const open = (0, import_react38.useCallback)((cell) => {
9824
+ const [active3, setActive] = (0, import_react39.useState)(null);
9825
+ const open = (0, import_react39.useCallback)((cell) => {
9659
9826
  setActive(cell);
9660
9827
  }, []);
9661
- const close = (0, import_react38.useCallback)(() => {
9828
+ const close = (0, import_react39.useCallback)(() => {
9662
9829
  setActive(null);
9663
9830
  }, []);
9664
- const reanchor = (0, import_react38.useCallback)((anchorRect) => {
9831
+ const reanchor = (0, import_react39.useCallback)((anchorRect) => {
9665
9832
  setActive((prev) => prev ? { ...prev, anchorRect } : prev);
9666
9833
  }, []);
9667
- const handleKeyDown = (0, import_react38.useCallback)(
9834
+ const handleKeyDown = (0, import_react39.useCallback)(
9668
9835
  (e, resolveCell) => {
9669
9836
  if (e.key === "Enter" || e.key === "F2") {
9670
9837
  const cell = resolveCell();
@@ -9684,13 +9851,13 @@ function useOverlayController() {
9684
9851
  }
9685
9852
 
9686
9853
  // src/grid-dom/overlay/overlay-manager.tsx
9687
- var import_react42 = require("react");
9854
+ var import_react43 = require("react");
9688
9855
  var import_react_dom = require("react-dom");
9689
9856
 
9690
9857
  // src/grid/editors/overlay-viewport-guard.tsx
9691
- var import_react39 = __toESM(require("react"), 1);
9858
+ var import_react40 = __toESM(require("react"), 1);
9692
9859
  var import_jsx_runtime23 = require("react/jsx-runtime");
9693
- var OverlayMeasureContext = import_react39.default.createContext({ maxHeight: 0, shouldFlip: false });
9860
+ var OverlayMeasureContext = import_react40.default.createContext({ maxHeight: 0, shouldFlip: false });
9694
9861
  function computeOverlayGeometry(viewportHeight, targetY, targetH, marginPx, minBelowPx) {
9695
9862
  const maxHeightPx = Math.max(0, viewportHeight - marginPx * 2);
9696
9863
  const hasTarget = targetY != null && targetH != null;
@@ -9705,10 +9872,10 @@ function computeOverlayGeometry(viewportHeight, targetY, targetH, marginPx, minB
9705
9872
  init_editor_focus_trap();
9706
9873
 
9707
9874
  // src/grid/feedback/editor-error-boundary.tsx
9708
- var import_react41 = require("react");
9875
+ var import_react42 = require("react");
9709
9876
  init_sheets_logger();
9710
9877
  var import_jsx_runtime25 = require("react/jsx-runtime");
9711
- var EditorErrorBoundary = class extends import_react41.Component {
9878
+ var EditorErrorBoundary = class extends import_react42.Component {
9712
9879
  state = { error: null };
9713
9880
  static getDerivedStateFromError(error) {
9714
9881
  return { error };
@@ -9745,34 +9912,84 @@ init_cn();
9745
9912
  var import_jsx_runtime26 = require("react/jsx-runtime");
9746
9913
  var MARGIN_PX = 12;
9747
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
+ }
9748
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]';
9749
9943
  function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode = "cancel", children }) {
9750
- const containerRef = (0, import_react42.useRef)(null);
9751
- 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);
9752
9952
  const targetY = anchorRect?.top;
9753
9953
  const targetH = anchorRect?.height;
9754
9954
  const vh = typeof window !== "undefined" ? window.innerHeight : 800;
9755
9955
  const { shouldFlip, maxHeight } = computeOverlayGeometry(vh, targetY, targetH, MARGIN_PX, MIN_BELOW_PX);
9756
- const overlayMeasure = (0, import_react42.useMemo)(() => ({ maxHeight, shouldFlip }), [maxHeight, shouldFlip]);
9757
- (0, import_react42.useLayoutEffect)(() => {
9956
+ const overlayMeasure = (0, import_react43.useMemo)(() => ({ maxHeight, shouldFlip }), [maxHeight, shouldFlip]);
9957
+ (0, import_react43.useLayoutEffect)(() => {
9758
9958
  if (!open || !anchorRect) {
9759
9959
  setPos(null);
9960
+ setEntered(false);
9760
9961
  return;
9761
9962
  }
9762
9963
  const el = containerRef.current;
9763
9964
  if (!el) return;
9764
- const rect = el.getBoundingClientRect();
9765
- const vw = window.innerWidth;
9766
- const vhNow = window.innerHeight;
9767
- let left = anchorRect.left;
9768
- left = Math.max(MARGIN_PX, Math.min(left, vw - MARGIN_PX - rect.width));
9769
- if (!Number.isFinite(left)) left = MARGIN_PX;
9770
- let top = shouldFlip ? anchorRect.top - rect.height : anchorRect.bottom;
9771
- top = Math.max(MARGIN_PX, Math.min(top, vhNow - MARGIN_PX - rect.height));
9772
- if (!Number.isFinite(top)) top = MARGIN_PX;
9773
- 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();
9774
9984
  }, [open, shouldFlip, anchorRect, maxHeight]);
9775
- (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)(() => {
9776
9993
  if (!open) return;
9777
9994
  const onPointerDown = (e) => {
9778
9995
  const el = containerRef.current;
@@ -9798,8 +10015,8 @@ function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode =
9798
10015
  // Pre-measure default = the ANCHOR position (below, or above when flipping), NOT a
9799
10016
  // screen corner. So an overlay that fits (the common case) renders at its FINAL spot
9800
10017
  // with zero left/top change once measured — no travel. It stays hidden until measured
9801
- // and `transition-none` keeps the rare off-screen clamp instant, so the overlay is
9802
- // 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).
9803
10020
  left: pos ? pos.left : anchorRect.left,
9804
10021
  top: pos ? pos.top : shouldFlip ? anchorRect.top : anchorRect.bottom,
9805
10022
  maxHeight,
@@ -9808,26 +10025,19 @@ function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode =
9808
10025
  // Join the shared design-system overlay layer instead of an
9809
10026
  // arbitrary z, so the editor and any popover/tooltip it opens (e.g. the relation
9810
10027
  // "Record Data" popover, which portals into #portal-root) stack coherently.
9811
- zIndex: "var(--z-layer-floating)"
10028
+ zIndex: "var(--z-layer-floating)",
10029
+ transformOrigin: `${pos?.originX ?? 0}px ${shouldFlip ? "100%" : "0"}`
9812
10030
  };
9813
10031
  const portalHost = document.getElementById("portal-root") ?? document.body;
9814
10032
  return (0, import_react_dom.createPortal)(
9815
10033
  /* @__PURE__ */ (0, import_jsx_runtime26.jsx)(
9816
10034
  "div",
9817
10035
  {
9818
- ref: containerRef,
10036
+ ref: setContainer,
10037
+ "data-slot": "sheets-editor-overlay",
10038
+ "data-state": entered ? "open" : "closed",
9819
10039
  style,
9820
- className: cn(
9821
- // `transition-none`: the entrance is an ANIMATION (scale + fade); left/top must NEVER
9822
- // transition, or measuring/clamping the position would visibly slide the overlay across
9823
- // the screen to its anchor. This keeps the position application instant.
9824
- "pointer-events-auto transition-none",
9825
- // Origin-aware entrance (DESIGN_SPEC §10 / Emil standards): subtle scale + fade from the
9826
- // cell corner, reusing the UI popover's tw-animate utilities for a consistent feel. Gated
9827
- // on `positioned` so the overlay animates only after its measured position is applied.
9828
- positioned && "animate-[fade-scale-in_var(--duration-moderate)_ease-out] motion-reduce:animate-none",
9829
- shouldFlip ? "origin-bottom-left" : "origin-top-left"
9830
- ),
10040
+ className: DROPDOWN_MOTION,
9831
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 }) }) })
9832
10042
  }
9833
10043
  ),
@@ -9839,7 +10049,7 @@ function OverlayManager({ anchorRect, open, presetClass, onCancel, dismissMode =
9839
10049
  init_cell_type_groups();
9840
10050
 
9841
10051
  // src/grid/editors/array-editor.tsx
9842
- var import_react43 = require("react");
10052
+ var import_react44 = require("react");
9843
10053
  var import_badge = require("@constructive-io/ui/badge");
9844
10054
  var import_button6 = require("@constructive-io/ui/button");
9845
10055
  var import_lucide_react3 = require("lucide-react");
@@ -9857,27 +10067,27 @@ function mergeArrayEditorValues(list, pendingInput) {
9857
10067
  return [...list, ...pendingItems];
9858
10068
  }
9859
10069
  function ArrayEditor({ value, onChange, onFinished }) {
9860
- const items = (0, import_react43.useMemo)(() => Array.isArray(value) ? value : [], [value]);
9861
- const [list, setList] = (0, import_react43.useState)(items);
9862
- const [input, setInput] = (0, import_react43.useState)("");
9863
- const inputRef = (0, import_react43.useRef)(null);
9864
- const keyContainerRef = (0, import_react43.useRef)(null);
9865
- const handleCancel = (0, import_react43.useCallback)(() => onFinished(void 0), [onFinished]);
9866
- 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)(() => {
9867
10077
  const next = mergeArrayEditorValues(list, input);
9868
10078
  setList(next);
9869
10079
  setInput("");
9870
10080
  onChange(next);
9871
10081
  onFinished(next);
9872
10082
  }, [input, list, onChange, onFinished]);
9873
- const add = (0, import_react43.useCallback)(() => {
10083
+ const add = (0, import_react44.useCallback)(() => {
9874
10084
  const next = mergeArrayEditorValues(list, input);
9875
10085
  if (next.length === list.length) return;
9876
10086
  setList(next);
9877
10087
  setInput("");
9878
10088
  onChange(next);
9879
10089
  }, [input, list, onChange]);
9880
- const remove = (0, import_react43.useCallback)(
10090
+ const remove = (0, import_react44.useCallback)(
9881
10091
  (idx) => {
9882
10092
  const next = list.filter((_, i) => i !== idx);
9883
10093
  setList(next);
@@ -9886,11 +10096,11 @@ function ArrayEditor({ value, onChange, onFinished }) {
9886
10096
  },
9887
10097
  [list, onChange]
9888
10098
  );
9889
- const actionsRef = (0, import_react43.useRef)({ add, handleSave, remove, handleCancel });
10099
+ const actionsRef = (0, import_react44.useRef)({ add, handleSave, remove, handleCancel });
9890
10100
  actionsRef.current = { add, handleSave, remove, handleCancel };
9891
- const stateRef = (0, import_react43.useRef)({ input, listLength: list.length });
10101
+ const stateRef = (0, import_react44.useRef)({ input, listLength: list.length });
9892
10102
  stateRef.current = { input, listLength: list.length };
9893
- (0, import_react43.useEffect)(() => {
10103
+ (0, import_react44.useEffect)(() => {
9894
10104
  const el = keyContainerRef.current;
9895
10105
  if (!el) return;
9896
10106
  const handler = (e) => {
@@ -10019,14 +10229,14 @@ function ArrayEditorDom({ value, onCommit, onCancel }) {
10019
10229
  }
10020
10230
 
10021
10231
  // src/grid-dom/editors/date-editor.tsx
10022
- var import_react45 = require("react");
10232
+ var import_react46 = require("react");
10023
10233
  init_cell_type_groups();
10024
10234
  var import_jsx_runtime30 = require("react/jsx-runtime");
10025
- 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 })));
10026
10236
  function DateEditorDom({ value, cell, onCommit, onCancel }) {
10027
10237
  const cellType = cell.meta?.cellType;
10028
10238
  const dateType = cellType && DATE_TIME_TYPES.has(cellType) ? cellType : void 0;
10029
- 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)(
10030
10240
  DateEditor2,
10031
10241
  {
10032
10242
  value,
@@ -10037,10 +10247,10 @@ function DateEditorDom({ value, cell, onCommit, onCancel }) {
10037
10247
  }
10038
10248
 
10039
10249
  // src/grid-dom/editors/geometry-editor.tsx
10040
- var import_react48 = require("react");
10250
+ var import_react49 = require("react");
10041
10251
 
10042
10252
  // src/grid/editors/geometry-editor.tsx
10043
- var import_react47 = require("react");
10253
+ var import_react48 = require("react");
10044
10254
  var import_lucide_react5 = require("lucide-react");
10045
10255
  init_cn();
10046
10256
  var import_button9 = require("@constructive-io/ui/button");
@@ -10049,7 +10259,7 @@ var import_textarea = require("@constructive-io/ui/textarea");
10049
10259
  init_editor_focus_trap();
10050
10260
  init_overlay_presets();
10051
10261
  var import_jsx_runtime32 = require("react/jsx-runtime");
10052
- var MapPicker2 = (0, import_react47.lazy)(
10262
+ var MapPicker2 = (0, import_react48.lazy)(
10053
10263
  () => Promise.resolve().then(() => (init_map_picker(), map_picker_exports)).then((m) => ({ default: m.MapPicker }))
10054
10264
  );
10055
10265
  function MapPickerLoading() {
@@ -10242,29 +10452,29 @@ function generateRandomGeometry(constrainedType) {
10242
10452
  }
10243
10453
  var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10244
10454
  const currentGeometryData = value;
10245
- const geometryValue = (0, import_react47.useMemo)(() => parseGeometryValue(currentGeometryData), [currentGeometryData]);
10246
- 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)(() => {
10247
10457
  if (!currentGeometryData) return "";
10248
10458
  const geo = parseGeometryValue(currentGeometryData);
10249
10459
  if (geo?.geojson) return JSON.stringify(geo.geojson, null, 2);
10250
10460
  return formatGeometry(currentGeometryData);
10251
10461
  });
10252
10462
  const canShowMap = expectedType === "Point" || !expectedType && geometryValue != null && isPointGeometry(geometryValue);
10253
- const validationResult = (0, import_react47.useMemo)(() => validateGeometry(editingValue, expectedType), [editingValue, expectedType]);
10463
+ const validationResult = (0, import_react48.useMemo)(() => validateGeometry(editingValue, expectedType), [editingValue, expectedType]);
10254
10464
  const isValid = validationResult === true;
10255
10465
  const validationError = typeof validationResult === "string" ? validationResult : void 0;
10256
- const [activeTab, setActiveTab] = (0, import_react47.useState)(() => canShowMap ? "map" : "json");
10257
- 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) => {
10258
10468
  if (mapValue?.geojson?.type) {
10259
10469
  setEditingValue(JSON.stringify(mapValue.geojson, null, 2));
10260
10470
  } else {
10261
10471
  setEditingValue("");
10262
10472
  }
10263
10473
  }, []);
10264
- const handleRandomize = (0, import_react47.useCallback)(() => {
10474
+ const handleRandomize = (0, import_react48.useCallback)(() => {
10265
10475
  setEditingValue(JSON.stringify(generateRandomGeometry(expectedType).geojson, null, 2));
10266
10476
  }, [expectedType]);
10267
- const handleSave = (0, import_react47.useCallback)(() => {
10477
+ const handleSave = (0, import_react48.useCallback)(() => {
10268
10478
  if (!isValid) return;
10269
10479
  let finalValue;
10270
10480
  if (!editingValue.trim()) {
@@ -10279,10 +10489,10 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10279
10489
  }
10280
10490
  onFinishedEditing(finalValue);
10281
10491
  }, [editingValue, isValid, onFinishedEditing]);
10282
- const handleCancel = (0, import_react47.useCallback)(() => {
10492
+ const handleCancel = (0, import_react48.useCallback)(() => {
10283
10493
  onFinishedEditing();
10284
10494
  }, [onFinishedEditing]);
10285
- const handleEditorKeyDown = (0, import_react47.useCallback)(
10495
+ const handleEditorKeyDown = (0, import_react48.useCallback)(
10286
10496
  (e) => {
10287
10497
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
10288
10498
  e.preventDefault();
@@ -10291,7 +10501,7 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10291
10501
  },
10292
10502
  [isValid, handleSave]
10293
10503
  );
10294
- const mapPickerValue = (0, import_react47.useMemo)(() => {
10504
+ const mapPickerValue = (0, import_react48.useMemo)(() => {
10295
10505
  try {
10296
10506
  if (editingValue) {
10297
10507
  const raw = extractRawGeoJSON(JSON.parse(editingValue));
@@ -10304,11 +10514,11 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10304
10514
  }
10305
10515
  return void 0;
10306
10516
  }, [editingValue, geometryValue]);
10307
- const { maxHeight: overlayMaxHeight } = (0, import_react47.useContext)(OverlayMeasureContext);
10308
- const editorRef = (0, import_react47.useRef)(null);
10309
- const contentRef = (0, import_react47.useRef)(null);
10310
- const [scrollBudget, setScrollBudget] = (0, import_react47.useState)();
10311
- (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)(() => {
10312
10522
  const editor = editorRef.current;
10313
10523
  const content = contentRef.current;
10314
10524
  if (!editor || !content || overlayMaxHeight <= 0) return;
@@ -10377,7 +10587,7 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10377
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: [
10378
10588
  header,
10379
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: [
10380
- /* @__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)(
10381
10591
  MapPicker2,
10382
10592
  {
10383
10593
  value: mapPickerValue,
@@ -10402,7 +10612,7 @@ var GeometryEditor = ({ value, onFinishedEditing, expectedType }) => {
10402
10612
  var import_jsx_runtime33 = require("react/jsx-runtime");
10403
10613
  function GeometryEditorDom({ value, fieldMeta, onCommit, onCancel }) {
10404
10614
  const expectedType = fieldMeta?.type?.subtype || void 0;
10405
- 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)(
10406
10616
  GeometryEditor,
10407
10617
  {
10408
10618
  value,
@@ -10422,188 +10632,98 @@ var import_react53 = require("motion/react");
10422
10632
  var import_toast2 = require("@constructive-io/ui/toast");
10423
10633
 
10424
10634
  // src/hooks/use-sheets-upload.ts
10425
- var import_react49 = require("react");
10426
- var import_react_query6 = require("@tanstack/react-query");
10635
+ var import_react_query7 = require("@tanstack/react-query");
10427
10636
  var import_data19 = require("@constructive-io/data");
10428
- var import_data20 = require("@constructive-io/data");
10429
- function resolveUploadNaming(tableName, table) {
10430
- return {
10431
- mutationName: (0, import_data20.toUpdateMutationName)(tableName, table),
10432
- singularName: (0, import_data20.toCamelCaseSingular)(tableName, table),
10433
- patchFieldName: (0, import_data20.toPatchFieldName)(tableName, table),
10434
- updateInputTypeName: (0, import_data20.toUpdateInputTypeName)(tableName)
10435
- };
10436
- }
10437
- function resolveTransport(endpoint, getToken, options) {
10438
- if (options?.execute && options?.executeUpload) {
10439
- return { execute: options.execute, executeUpload: options.executeUpload };
10440
- }
10441
- const config = {
10442
- endpoint,
10443
- auth: { mode: "standalone" },
10444
- onAuthError: options?.onAuthError
10445
- };
10446
- return {
10447
- execute: createSheetsExecute(config, getToken),
10448
- executeUpload: createSheetsUpload(config, getToken)
10449
- };
10450
- }
10451
- async function executeFieldUpload(tableName, fieldName, recordId, file, endpoint, getToken, naming, options) {
10452
- if (!endpoint && !(options?.execute && options?.executeUpload)) {
10453
- throw new Error("No endpoint configured. Select a database API or use Direct Connect.");
10454
- }
10455
- const { execute, executeUpload } = resolveTransport(endpoint, getToken, options);
10456
- const uploadResult = await executeUpload(file, void 0, {
10457
- tableName,
10458
- fieldName,
10459
- recordId,
10460
- onProgress: options?.onProgress
10461
- });
10462
- const resolvedNaming = naming ?? resolveUploadNaming(tableName);
10463
- const patchValue = {
10464
- ...uploadResult.url != null && { url: uploadResult.url },
10465
- ...uploadResult.filename != null && { filename: uploadResult.filename },
10466
- ...uploadResult.mime != null && { mime: uploadResult.mime },
10467
- ...uploadResult.size != null && { size: uploadResult.size }
10468
- };
10469
- const mutationString = `
10470
- mutation ${resolvedNaming.mutationName}Mutation($input: ${resolvedNaming.updateInputTypeName}!) {
10471
- ${resolvedNaming.mutationName}(input: $input) {
10472
- ${resolvedNaming.singularName} {
10473
- id
10474
- ${fieldName}
10475
- }
10476
- }
10477
- }
10478
- `.trim();
10479
- const result = await execute(mutationString, {
10480
- input: {
10481
- id: recordId,
10482
- [resolvedNaming.patchFieldName]: {
10483
- [fieldName]: patchValue
10484
- }
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
+ };
10485
10664
  }
10486
- });
10487
- const updatedRecord = result?.[resolvedNaming.mutationName]?.[resolvedNaming.singularName];
10488
- if (!updatedRecord) {
10489
- throw new Error("Upload succeeded but no data returned from patch");
10490
10665
  }
10491
- const uploadedFileData = updatedRecord[fieldName];
10492
- if (!uploadedFileData) {
10493
- 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}'.`);
10494
10675
  }
10495
- const fileObject = typeof uploadedFileData === "object" ? uploadedFileData : null;
10496
- return {
10497
- url: fileObject?.url || uploadedFileData,
10498
- filename: fileObject?.filename || file.name,
10499
- mime: fileObject?.mime || file.type,
10500
- size: fileObject?.size || file.size
10501
- };
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}'.`);
10502
10685
  }
10503
10686
  function useSheetsFieldUpload(tableName, fieldName, recordId, options = {}) {
10504
- const queryClient = (0, import_react_query6.useQueryClient)();
10505
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
10506
- const storeApi = useSheetsStoreApi();
10507
- const { data: meta } = useSheetsMeta();
10508
- const table = (0, import_react49.useMemo)(() => {
10509
- if (!meta?._meta?.tables) return null;
10510
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
10511
- return candidate ? (0, import_data19.cleanTable)(candidate) : null;
10512
- }, [meta, tableName]);
10513
- const resolvedNaming = (0, import_react49.useMemo)(() => resolveUploadNaming(tableName, table), [tableName, table]);
10514
- const getToken = (0, import_react49.useMemo)(() => {
10515
- if (config.auth.mode === "embedded") {
10516
- return config.auth.getToken;
10517
- }
10518
- return () => storeApi.getState().accessToken;
10519
- }, [config.auth, storeApi]);
10520
- const tableRef = (0, import_react49.useRef)(tableName);
10521
- const fieldRef = (0, import_react49.useRef)(fieldName);
10522
- const idRef = (0, import_react49.useRef)(recordId);
10523
- (0, import_react49.useEffect)(() => {
10524
- tableRef.current = tableName;
10525
- fieldRef.current = fieldName;
10526
- idRef.current = recordId;
10527
- }, [tableName, fieldName, recordId]);
10528
- return (0, import_react_query6.useMutation)({
10529
- mutationKey: ["sheets", scopeKey, "field-upload", tableName, fieldName, recordId],
10530
- mutationFn: async (file) => {
10531
- return executeFieldUpload(
10532
- tableRef.current,
10533
- fieldRef.current,
10534
- idRef.current,
10535
- file,
10536
- config.endpoint,
10537
- getToken,
10538
- resolvedNaming,
10539
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
10540
- );
10541
- },
10542
- onSuccess: (data) => {
10543
- options.onSuccess?.(data);
10544
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
10545
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
10546
- },
10547
- onError: (error) => {
10548
- options.onError?.(error);
10549
- }
10550
- });
10551
- }
10552
- function useSheetsImageUpload(tableName, fieldName, recordId, options = {}) {
10553
- const queryClient = (0, import_react_query6.useQueryClient)();
10554
- const { scopeKey, config, execute, executeUpload } = useSheetsContext();
10555
- const storeApi = useSheetsStoreApi();
10687
+ const queryClient = (0, import_react_query7.useQueryClient)();
10688
+ const { execute, executeUpload, scopeKey } = useSheetsContext();
10556
10689
  const { data: meta } = useSheetsMeta();
10557
- const table = (0, import_react49.useMemo)(() => {
10558
- if (!meta?._meta?.tables) return null;
10559
- const candidate = meta._meta.tables.find((item) => item?.name === tableName);
10560
- return candidate ? (0, import_data19.cleanTable)(candidate) : null;
10561
- }, [meta, tableName]);
10562
- const resolvedNaming = (0, import_react49.useMemo)(() => resolveUploadNaming(tableName, table), [tableName, table]);
10563
- const getToken = (0, import_react49.useMemo)(() => {
10564
- if (config.auth.mode === "embedded") {
10565
- return config.auth.getToken;
10566
- }
10567
- return () => storeApi.getState().accessToken;
10568
- }, [config.auth, storeApi]);
10569
- const tableRef = (0, import_react49.useRef)(tableName);
10570
- const fieldRef = (0, import_react49.useRef)(fieldName);
10571
- const idRef = (0, import_react49.useRef)(recordId);
10572
- (0, import_react49.useEffect)(() => {
10573
- tableRef.current = tableName;
10574
- fieldRef.current = fieldName;
10575
- idRef.current = recordId;
10576
- }, [tableName, fieldName, recordId]);
10577
- return (0, import_react_query6.useMutation)({
10578
- mutationKey: ["sheets", scopeKey, "image-upload", tableName, fieldName, recordId],
10579
- mutationFn: async (file) => {
10580
- if (!file.type.startsWith("image/")) {
10581
- throw new Error("Please select an image file");
10582
- }
10583
- const maxSize = 10 * 1024 * 1024;
10584
- if (file.size > maxSize) {
10585
- throw new Error("File size must be less than 10MB");
10586
- }
10587
- return executeFieldUpload(
10588
- tableRef.current,
10589
- fieldRef.current,
10590
- idRef.current,
10591
- file,
10592
- config.endpoint,
10593
- getToken,
10594
- resolvedNaming,
10595
- { onAuthError: config.onAuthError, execute, executeUpload, onProgress: options.onProgress }
10596
- );
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);
10597
10719
  },
10598
- onSuccess: (data) => {
10599
- options.onSuccess?.(data);
10600
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.table(scopeKey, tableRef.current) });
10601
- queryClient.invalidateQueries({ queryKey: sheetsTableQueryKeys.tableRow(scopeKey, tableRef.current, idRef.current) });
10720
+ onSuccess: (value) => {
10721
+ options.onSuccess?.(value);
10722
+ invalidate();
10602
10723
  },
10603
- onError: (error) => {
10604
- options.onError?.(error);
10605
- }
10724
+ onError: options.onError
10606
10725
  });
10726
+ return { ...mutation, write, resolveRowIdentifier };
10607
10727
  }
10608
10728
 
10609
10729
  // src/grid/editors/image-editor.tsx
@@ -10612,22 +10732,22 @@ init_sheets_logger();
10612
10732
  // src/utils/use-image-status.ts
10613
10733
  var import_react50 = require("react");
10614
10734
  function useImageStatus(src) {
10615
- const [status, setStatus] = (0, import_react50.useState)("idle");
10735
+ const [result, setResult] = (0, import_react50.useState)();
10616
10736
  (0, import_react50.useEffect)(() => {
10617
- if (!src) return setStatus("idle");
10618
- setStatus("loading");
10737
+ if (!src) return;
10619
10738
  const img = new Image();
10620
- img.src = src;
10621
- const onLoad = () => setStatus("loaded");
10622
- const onError = () => setStatus("error");
10739
+ const onLoad = () => setResult({ src, status: "loaded" });
10740
+ const onError = () => setResult({ src, status: "error" });
10623
10741
  img.addEventListener("load", onLoad);
10624
10742
  img.addEventListener("error", onError);
10743
+ img.src = src;
10625
10744
  return () => {
10626
10745
  img.removeEventListener("load", onLoad);
10627
10746
  img.removeEventListener("error", onError);
10628
10747
  };
10629
10748
  }, [src]);
10630
- return status;
10749
+ if (!src) return "idle";
10750
+ return result?.src === src ? result.status : "loading";
10631
10751
  }
10632
10752
 
10633
10753
  // src/grid/editors/image-editor.tsx
@@ -10697,9 +10817,6 @@ function ImageWithFallback({
10697
10817
  init_editor_focus_trap();
10698
10818
  init_overlay_presets();
10699
10819
  var import_jsx_runtime35 = require("react/jsx-runtime");
10700
- function normalizeUploadResponse(data) {
10701
- return { url: data.url, filename: data.filename, size: data.size, mime: data.mime };
10702
- }
10703
10820
  var dropzoneTransition = { duration: 0.15, ease: [0.2, 0, 0, 1] };
10704
10821
  function RemoveButton({ onClick, label }) {
10705
10822
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("div", { className: "absolute top-2 right-2", children: /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
@@ -10718,13 +10835,14 @@ function RemoveButton({ onClick, label }) {
10718
10835
  }
10719
10836
  function FilePreview({ name, size, mime }) {
10720
10837
  const hasMime = !!mime && mime !== "unknown";
10838
+ const hasSize = size !== void 0;
10721
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: [
10722
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" }) }),
10723
10841
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "min-w-0 max-w-full", children: [
10724
10842
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("p", { className: "truncate text-sm font-medium", title: name, children: name || "File" }),
10725
- (size || hasMime) && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("p", { className: "text-muted-foreground mt-0.5 text-xs", children: [
10726
- size ? formatFileSize(size) : null,
10727
- 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,
10728
10846
  hasMime ? /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { className: "uppercase", children: mime }) : null
10729
10847
  ] })
10730
10848
  ] })
@@ -10745,13 +10863,7 @@ var ImageEditor = ({
10745
10863
  const noun = acceptAnyFile ? "file" : "image";
10746
10864
  const Noun = acceptAnyFile ? "File" : "Image";
10747
10865
  const [uploadState, setUploadState] = (0, import_react52.useState)("idle");
10748
- const { config } = useSheetsContext();
10749
- const storeApi = useSheetsStoreApi();
10750
10866
  const { maxHeight: overlayMaxHeight } = (0, import_react52.useContext)(OverlayMeasureContext);
10751
- const getToken = (0, import_react52.useMemo)(() => {
10752
- if (config.auth.mode === "embedded") return config.auth.getToken;
10753
- return () => storeApi.getState().accessToken;
10754
- }, [config.auth, storeApi]);
10755
10867
  const fileInputRef = (0, import_react52.useRef)(null);
10756
10868
  const previewUrlRef = (0, import_react52.useRef)(null);
10757
10869
  const committedRecordIdRef = (0, import_react52.useRef)(null);
@@ -10764,14 +10876,23 @@ var ImageEditor = ({
10764
10876
  const [dragErrors, setDragErrors] = (0, import_react52.useState)([]);
10765
10877
  const isSubmittingDraft = uploadState === "submitting-draft";
10766
10878
  const isUploading = uploadState === "uploading";
10879
+ const isClearing = uploadState === "clearing";
10767
10880
  const isBusy = uploadState !== "idle";
10768
- const imageUrl = (0, import_react52.useMemo)(() => getImageUrl(imageValue), [imageValue]);
10769
10881
  const imageMetadata = (0, import_react52.useMemo)(() => getImageMetadata(imageValue), [imageValue]);
10770
10882
  const storedMime = imageMetadata?.mime;
10771
10883
  const storedIsImage = !acceptAnyFile || !!storedMime && storedMime.startsWith("image/");
10884
+ const { url: imageUrl, durableUrl, id: storedFileId, isLoading: isResolvingImage, onImageError, onImageLoad } = useSheetsMediaUrl(imageValue, storedIsImage);
10772
10885
  const imageStatus = useImageStatus(storedIsImage ? imageUrl || void 0 : void 0);
10773
- const imageLoadFailed = storedIsImage && imageUrl != null && imageStatus === "error";
10774
- 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);
10775
10896
  const revokePreviewUrl = (0, import_react52.useCallback)(() => {
10776
10897
  if (previewUrlRef.current) {
10777
10898
  URL.revokeObjectURL(previewUrlRef.current);
@@ -10785,23 +10906,27 @@ var ImageEditor = ({
10785
10906
  setPreviewUrl(null);
10786
10907
  setUploadState("idle");
10787
10908
  }, [revokePreviewUrl]);
10788
- const handleUploadSuccess = (0, import_react52.useCallback)((data) => {
10789
- const normalized = normalizeUploadResponse(data);
10909
+ const finishSave = (0, import_react52.useCallback)((data, message) => {
10790
10910
  resetFileState();
10791
- setImageValue(normalized);
10792
- onSaveComplete?.({ imageData: normalized });
10911
+ setImageValue(data);
10912
+ if (committedRecordIdRef.current == null) {
10913
+ onSaveComplete?.({ imageData: data });
10914
+ } else {
10915
+ onDraftUploadComplete?.();
10916
+ }
10793
10917
  onFinishedEditing();
10794
- import_toast2.toast.success({ message: `${Noun} uploaded successfully` });
10795
- }, [resetFileState, onSaveComplete, onFinishedEditing, Noun]);
10796
- 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) => {
10797
10921
  setUploadState("idle");
10798
- sheetsLogger().error("[image-editor] upload failed:", error);
10799
- 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" });
10800
10925
  }, []);
10801
- const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId || "", {
10926
+ const uploadMutation = useSheetsFieldUpload(tableName || "", fieldName || "", recordId ?? null, {
10802
10927
  onProgress: setUploadProgress,
10803
- onSuccess: handleUploadSuccess,
10804
- onError: handleUploadError,
10928
+ onSuccess: (data) => finishSave(data, data === null ? `${Noun} cleared` : `${Noun} uploaded successfully`),
10929
+ onError: handleWriteError,
10805
10930
  showToast: false
10806
10931
  });
10807
10932
  const handleRemoveImage = (0, import_react52.useCallback)(() => {
@@ -10858,94 +10983,79 @@ var ImageEditor = ({
10858
10983
  setDragErrors([]);
10859
10984
  }, [revokePreviewUrl]);
10860
10985
  const handleConfirmUpload = (0, import_react52.useCallback)(async () => {
10861
- if (!tableName || !fieldName || !selectedFile) return;
10862
- const committedId = committedRecordIdRef.current ?? recordId;
10863
- if (committedRecordIdRef.current != null) {
10864
- try {
10865
- import_toast2.toast.info({ message: `Uploading ${noun}...` });
10866
- setUploadState("uploading");
10867
- const uploadResult = await executeFieldUpload(
10868
- tableName,
10869
- fieldName,
10870
- committedRecordIdRef.current,
10871
- selectedFile,
10872
- config.endpoint,
10873
- getToken,
10874
- void 0,
10875
- { onAuthError: config.onAuthError }
10876
- );
10877
- const normalized = normalizeUploadResponse(uploadResult);
10878
- resetFileState();
10879
- setImageValue(normalized);
10880
- onDraftUploadComplete?.();
10881
- import_toast2.toast.success({ message: `${Noun} uploaded successfully` });
10882
- onFinishedEditing();
10883
- } catch (error) {
10884
- onDraftUploadComplete?.();
10885
- setUploadState("idle");
10886
- 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;
10887
10991
  }
10992
+ setUploadState("uploading");
10993
+ uploadMutation.mutate(selectedFile);
10888
10994
  return;
10889
10995
  }
10890
- if (isDraftRow2) {
10891
- if (!onSubmitDraft) {
10892
- import_toast2.toast.error({ message: "Cannot upload to draft row - save the row first" });
10893
- return;
10894
- }
10895
- 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");
10896
11001
  import_toast2.toast.info({ message: "Creating row..." });
10897
11002
  setUploadState("submitting-draft");
10898
- const result = await onSubmitDraft();
10899
- const createdId = result.createdRow?.id;
10900
- if (typeof createdId !== "string" && typeof createdId !== "number") {
10901
- throw new Error("Image uploads require a scalar id primary key.");
10902
- }
10903
- committedRecordIdRef.current = createdId;
10904
- import_toast2.toast.info({ message: `Uploading ${noun}...` });
10905
- setUploadState("uploading");
10906
- const uploadResult = await executeFieldUpload(
10907
- tableName,
10908
- fieldName,
10909
- createdId,
10910
- selectedFile,
10911
- config.endpoint,
10912
- getToken,
10913
- void 0,
10914
- { onAuthError: config.onAuthError }
10915
- );
10916
- const normalized = normalizeUploadResponse(uploadResult);
10917
- resetFileState();
10918
- setImageValue(normalized);
10919
- onDraftUploadComplete?.();
10920
- import_toast2.toast.success({ message: `Row created and ${noun} uploaded` });
10921
- onFinishedEditing();
10922
- } catch (error) {
10923
- onDraftUploadComplete?.();
10924
- setUploadState("idle");
10925
- 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;
10926
11006
  }
10927
- 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"));
10928
11016
  }
10929
- if (!committedId) {
10930
- 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();
10931
11036
  return;
10932
11037
  }
10933
- setUploadState("uploading");
10934
- uploadMutation.mutate(selectedFile);
10935
- }, [selectedFile, uploadMutation, tableName, fieldName, recordId, isDraftRow2, onSubmitDraft, config.endpoint, config.onAuthError, getToken, resetFileState, onDraftUploadComplete, onFinishedEditing, noun, Noun]);
10936
- const handleSave = (0, import_react52.useCallback)(() => {
10937
- if (!imageValue) {
10938
- 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
+ }
10939
11045
  return;
10940
11046
  }
10941
- const url = getImageUrl(imageValue);
10942
- const originalUrl = getImageUrl(value);
10943
- if (url && originalUrl === url) {
10944
- onFinishedEditing();
11047
+ setUploadState("clearing");
11048
+ if (committedRecordIdRef.current == null) {
11049
+ uploadMutation.mutate(null);
10945
11050
  return;
10946
11051
  }
10947
- onFinishedEditing(url ?? value);
10948
- }, [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]);
10949
11059
  const handleCancel = (0, import_react52.useCallback)(() => {
10950
11060
  revokePreviewUrl();
10951
11061
  onFinishedEditing();
@@ -10954,25 +11064,37 @@ var ImageEditor = ({
10954
11064
  const handleEditorKeyDown = (0, import_react52.useCallback)((e) => {
10955
11065
  if (e.key === "Enter" && (e.ctrlKey || e.metaKey)) {
10956
11066
  e.preventDefault();
10957
- handleSave();
11067
+ if (selectedFile) void handleConfirmUpload();
11068
+ else void handleSave();
10958
11069
  }
10959
- }, [handleSave]);
10960
- const hasStoredFile = acceptAnyFile && !!imageUrl && !storedIsImage;
11070
+ }, [handleConfirmUpload, handleSave, selectedFile]);
11071
+ const hasStoredFile = hasStoredMedia && !hasImage && !imageLoadFailed;
10961
11072
  const dropzoneKey = isBusy ? "busy" : previewUrl ? "preview" : hasImage ? "loaded" : hasStoredFile ? "file" : imageLoadFailed ? "broken" : "empty";
10962
11073
  const renderDropzoneContent = () => {
10963
11074
  if (isBusy) {
10964
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: [
10965
11076
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react6.Loader2, { className: "mb-2 size-6 animate-spin" }),
10966
- /* @__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}...` }),
10967
11078
  isUploading && uploadProgress && /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "mt-3 w-full max-w-xs", children: [
10968
- /* @__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)(
10969
11080
  "div",
10970
11081
  {
10971
- className: "bg-primary h-1.5 rounded-full transition-[width] duration-(--duration-slow)",
10972
- 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
+ )
10973
11095
  }
10974
- ) }),
10975
- /* @__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: [
10976
11098
  Math.round(uploadProgress.percentage),
10977
11099
  "%"
10978
11100
  ] })
@@ -10980,7 +11102,6 @@ var ImageEditor = ({
10980
11102
  ] });
10981
11103
  }
10982
11104
  if (previewUrl) {
10983
- const selectedIsImage = !acceptAnyFile || (selectedFile?.type.startsWith("image/") ?? false);
10984
11105
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
10985
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 }),
10986
11107
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(RemoveButton, { onClick: removeFile, label: "Remove selected file" })
@@ -11003,7 +11124,7 @@ var ImageEditor = ({
11003
11124
  }
11004
11125
  if (hasStoredFile) {
11005
11126
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "relative w-full", style: { height: "13rem" }, children: [
11006
- /* @__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 }),
11007
11128
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(RemoveButton, { onClick: handleRemoveImage, label: "Remove file" })
11008
11129
  ] });
11009
11130
  }
@@ -11018,12 +11139,12 @@ var ImageEditor = ({
11018
11139
  }
11019
11140
  ),
11020
11141
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("p", { className: "text-sm font-medium", children: "Image unavailable" }),
11021
- imageUrl && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
11142
+ durableUrl && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
11022
11143
  "p",
11023
11144
  {
11024
11145
  className: "text-muted-foreground mt-1 max-w-full truncate font-mono text-[11px] opacity-50",
11025
- title: imageUrl,
11026
- children: imageUrl
11146
+ title: durableUrl,
11147
+ children: durableUrl
11027
11148
  }
11028
11149
  ),
11029
11150
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "mt-3 flex items-center gap-2", children: [
@@ -11086,7 +11207,7 @@ var ImageEditor = ({
11086
11207
  )
11087
11208
  ] });
11088
11209
  };
11089
- const saveLabel = isSubmittingDraft ? "Creating..." : isUploading ? "Uploading..." : imageUrl ? "Save" : "Done";
11210
+ const saveLabel = isSubmittingDraft ? "Creating..." : isClearing ? "Clearing..." : isUploading ? "Uploading..." : hasStoredMedia || clearPending ? "Save" : "Done";
11090
11211
  return /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
11091
11212
  EditorFocusTrap,
11092
11213
  {
@@ -11096,7 +11217,7 @@ var ImageEditor = ({
11096
11217
  children: /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { onKeyDown: handleEditorKeyDown, className: "flex min-h-0 flex-1 flex-col", children: [
11097
11218
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "flex shrink-0 items-center gap-2 border-b px-6 py-3", children: [
11098
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" }),
11099
- /* @__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}` })
11100
11221
  ] }),
11101
11222
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(
11102
11223
  "input",
@@ -11144,7 +11265,7 @@ var ImageEditor = ({
11144
11265
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react6.AlertCircleIcon, { className: "size-3 shrink-0" }),
11145
11266
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { children: dragErrors[0] })
11146
11267
  ] }),
11147
- !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: [
11148
11269
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { className: "font-medium", children: selectedFile.name }),
11149
11270
  " \u2022 ",
11150
11271
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)("span", { children: formatFileSize(selectedFile.size) }),
@@ -11164,7 +11285,7 @@ var ImageEditor = ({
11164
11285
  ] }) }),
11165
11286
  /* @__PURE__ */ (0, import_jsx_runtime35.jsxs)("div", { className: "flex shrink-0 justify-end gap-2 border-t px-6 py-3", children: [
11166
11287
  /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_button10.Button, { type: "button", variant: "outline", size: "sm", onClick: handleCancel, disabled: isBusy, children: "Cancel" }),
11167
- 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: [
11168
11289
  isBusy && /* @__PURE__ */ (0, import_jsx_runtime35.jsx)(import_lucide_react6.Loader2, { className: "size-3.5 animate-spin" }),
11169
11290
  saveLabel
11170
11291
  ] })
@@ -11182,20 +11303,18 @@ function ImageEditorDom({
11182
11303
  cell,
11183
11304
  colKey,
11184
11305
  rowId,
11306
+ rowIdentifier,
11185
11307
  tableName,
11186
11308
  onCommitPatch,
11187
11309
  onCancel,
11188
11310
  onSubmitDraftRow,
11189
11311
  onInvalidateData
11190
11312
  }) {
11191
- const isDraftRow2 = rowId.startsWith(DRAFT_PREFIX);
11313
+ const isDraftRow2 = rowIdentifier == null && rowId.startsWith(DRAFT_PREFIX);
11192
11314
  const cellType = cell.meta?.cellType;
11193
11315
  const acceptAnyFile = cellType != null && cellType !== "image";
11194
11316
  const handleSaveComplete = onCommitPatch ? (saveData) => onCommitPatch({ [colKey]: saveData.imageData }) : void 0;
11195
- const handleSubmitDraft = isDraftRow2 && onSubmitDraftRow ? async () => {
11196
- const createdRow = await onSubmitDraftRow(rowId);
11197
- return { createdRow };
11198
- } : void 0;
11317
+ const handleSubmitDraft = isDraftRow2 && onSubmitDraftRow ? () => onSubmitDraftRow(rowId) : void 0;
11199
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)(
11200
11319
  ImageEditor,
11201
11320
  {
@@ -11204,7 +11323,7 @@ function ImageEditorDom({
11204
11323
  onFinishedEditing: () => onCancel(),
11205
11324
  tableName,
11206
11325
  fieldName: colKey,
11207
- recordId: rowId,
11326
+ recordId: rowIdentifier ?? null,
11208
11327
  onSaveComplete: handleSaveComplete,
11209
11328
  isDraftRow: isDraftRow2,
11210
11329
  onSubmitDraft: handleSubmitDraft,
@@ -11793,22 +11912,22 @@ NumberEditorDom.commitsOnBlur = true;
11793
11912
  // src/grid/editors/relation-editor.tsx
11794
11913
  var import_react62 = require("react");
11795
11914
  var import_lucide_react8 = require("lucide-react");
11796
- var import_react_query8 = require("@tanstack/react-query");
11915
+ var import_react_query9 = require("@tanstack/react-query");
11797
11916
 
11798
11917
  // src/hooks/use-sheets-table-cursor.ts
11799
11918
  var import_react59 = require("react");
11800
- 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");
11801
11921
  var import_data21 = require("@constructive-io/data");
11802
11922
  var import_data22 = require("@constructive-io/data");
11803
- var import_data23 = require("@constructive-io/data");
11804
11923
  function useSheetsTableCursor(tableName, options = {}) {
11805
- const queryClient = (0, import_react_query7.useQueryClient)();
11924
+ const queryClient = (0, import_react_query8.useQueryClient)();
11806
11925
  const { execute, scopeKey } = useSheetsContext();
11807
11926
  const { data: meta } = useSheetsMeta();
11808
11927
  const adapter = useSheetsAdapter();
11809
11928
  const tables = (0, import_react59.useMemo)(() => {
11810
11929
  if (!meta?._meta?.tables) return [];
11811
- 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));
11812
11931
  }, [meta]);
11813
11932
  const table = (0, import_react59.useMemo)(
11814
11933
  () => tables.find((candidate) => candidate.name === tableName) ?? null,
@@ -11836,11 +11955,11 @@ function useSheetsTableCursor(tableName, options = {}) {
11836
11955
  hasNextPage,
11837
11956
  fetchNextPage,
11838
11957
  error
11839
- } = (0, import_react_query7.useInfiniteQuery)({
11958
+ } = (0, import_react_query8.useInfiniteQuery)({
11840
11959
  queryKey: sheetsQueryKeys.cursorTable(scopeKey, tableName, stableOptions),
11841
11960
  queryFn: async ({ pageParam }) => {
11842
11961
  if (!table) {
11843
- throw import_data22.createError.notFound(`Table '${tableName}' not found`);
11962
+ throw import_data21.createError.notFound(`Table '${tableName}' not found`);
11844
11963
  }
11845
11964
  const cursor = pageParam;
11846
11965
  const variableOptions = {
@@ -11863,7 +11982,7 @@ function useSheetsTableCursor(tableName, options = {}) {
11863
11982
  const validatedOrderByEnum = new Set(variables.orderBy ?? []);
11864
11983
  const availableOrderByFields = new Set(table.fields.map((field) => field.name));
11865
11984
  const validatedOrderBy = orderBy?.filter(
11866
- ({ 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))
11867
11986
  );
11868
11987
  const res = await adapter.listRows(
11869
11988
  { table, allTables: tables, tableName },
@@ -12050,7 +12169,7 @@ var RelationEditor = ({
12050
12169
  }) => {
12051
12170
  const { data: meta } = useSheetsMeta();
12052
12171
  const { scopeKey } = useSheetsContext();
12053
- const queryClient = (0, import_react_query8.useQueryClient)();
12172
+ const queryClient = (0, import_react_query9.useQueryClient)();
12054
12173
  const ensureRelationInfo = useSheetsStore((s) => s.ensureRelationInfo);
12055
12174
  const relationInfoForTable = useSheetsStore((s) => tableName ? s.relationInfoCache[tableName] : void 0);
12056
12175
  const relationEntry = relationInfoForTable?.[fieldName];
@@ -12810,6 +12929,7 @@ var DOM_EDITOR_REGISTRY = {
12810
12929
  video: ImageEditorDom,
12811
12930
  audio: ImageEditorDom,
12812
12931
  upload: ImageEditorDom,
12932
+ attachment: ImageEditorDom,
12813
12933
  // Date/time types
12814
12934
  date: DateEditorDom,
12815
12935
  datetime: DateEditorDom,
@@ -13555,7 +13675,7 @@ function SheetsDomInner({
13555
13675
  } = props;
13556
13676
  const s = useSheets(props);
13557
13677
  const shell = s._shell;
13558
- const { config } = useSheetsContext();
13678
+ const { config, canUpload, scopeKey } = useSheetsContext();
13559
13679
  const viewportRef = (0, import_react66.useRef)(null);
13560
13680
  const { commands, keymap, interceptors, onCommand } = props;
13561
13681
  const registry = (0, import_react66.useMemo)(() => createGridCommandRegistry(commands), [commands]);
@@ -13729,6 +13849,11 @@ function SheetsDomInner({
13729
13849
  const overlayOpen = overlay2.open;
13730
13850
  const overlayClose = overlay2.close;
13731
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]);
13732
13857
  const getSheetsCellContent = shell.getSheetsCellContent;
13733
13858
  const submitDraftRow = shell.submitDraftRow;
13734
13859
  const commitCellValue = shell.commitCellValue;
@@ -13767,9 +13892,24 @@ function SheetsDomInner({
13767
13892
  overlayOpen({ rowIndex, colKey, anchorRect, initialText, mode: "inline" });
13768
13893
  return;
13769
13894
  }
13770
- 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
+ });
13771
13911
  },
13772
- [overlayOpen]
13912
+ [overlayOpen, tableName, scopeKey]
13773
13913
  );
13774
13914
  const openEditor = (0, import_react66.useCallback)(
13775
13915
  (rowIndex, colKey, anchorRect, initialText) => dispatch("editor.open", void 0, { rowIndex, colKey, anchorRect, initialText }),
@@ -13922,6 +14062,7 @@ function SheetsDomInner({
13922
14062
  const handleOverlayScroll = (0, import_react66.useCallback)(() => {
13923
14063
  const a = activeRef.current;
13924
14064
  if (!a) return;
14065
+ if (a.mediaDraft && getDraftMeta(combinedRowsRef.current[a.rowIndex])?.draftRowId !== a.mediaDraft.rowId) return;
13925
14066
  const colIndex = columnsRef.current.findIndex((c) => c.key === a.colKey);
13926
14067
  const node = colIndex >= 0 ? document.getElementById(`sheets-cell-${a.rowIndex}-${colIndex}`) : null;
13927
14068
  if (node) {
@@ -13934,12 +14075,13 @@ function SheetsDomInner({
13934
14075
  }, [overlayReanchor, overlayClose]);
13935
14076
  const active3 = overlay2.active;
13936
14077
  const editorNode = (() => {
13937
- if (!active3) return null;
13938
- const resolution = getSheetsCellContent(active3.rowIndex, active3.colKey);
14078
+ if (!active3 || mediaDraft && !activeMediaDraft) return null;
14079
+ const resolution = activeMediaDraft?.resolution ?? getSheetsCellContent(active3.rowIndex, active3.colKey);
13939
14080
  const intent = resolveEditIntent(resolution.typeKey, { readonly: resolution.cell.readonly }, getEditorComponent);
13940
14081
  if (intent.mode !== "overlay") return null;
13941
14082
  const Editor = intent.editor;
13942
- const rowValue = combinedRows[active3.rowIndex]?.[active3.colKey];
14083
+ const row = combinedRows[active3.rowIndex];
14084
+ const rowValue = activeMediaDraft ? activeMediaDraft.value : row?.[active3.colKey];
13943
14085
  const geom = computeOverlayGeometry(
13944
14086
  typeof window !== "undefined" ? window.innerHeight : 800,
13945
14087
  active3.anchorRect.top,
@@ -13958,7 +14100,8 @@ function SheetsDomInner({
13958
14100
  value: rowValue,
13959
14101
  cell: resolution.cell,
13960
14102
  colKey: active3.colKey,
13961
- rowId: getRowId(combinedRows[active3.rowIndex], active3.rowIndex),
14103
+ rowId: activeMediaDraft?.rowId ?? getRowId(row, active3.rowIndex),
14104
+ rowIdentifier: resolution.rowIdentifier,
13962
14105
  rowIndex: active3.rowIndex,
13963
14106
  tableName: props.tableName,
13964
14107
  fieldMeta: resolution.fieldMeta,
@@ -13969,7 +14112,9 @@ function SheetsDomInner({
13969
14112
  overlayClose();
13970
14113
  },
13971
14114
  onCommitPatch: (patch) => {
13972
- shell.commitCellPatch(active3.rowIndex, patch);
14115
+ if (!activeMediaDraft || getDraftMeta(row)?.draftRowId === activeMediaDraft.rowId) {
14116
+ shell.commitCellPatch(active3.rowIndex, patch);
14117
+ }
13973
14118
  overlayClose();
13974
14119
  },
13975
14120
  onSubmitDraftRow: shell.submitDraftRow,
@@ -14038,18 +14183,18 @@ function SheetsDomInner({
14038
14183
  toTSV: (values) => toTSV(values),
14039
14184
  emit
14040
14185
  };
14041
- if (s.dataError && shell.combinedRows.length === 0) {
14186
+ if (!activeMediaDraft && s.dataError && shell.combinedRows.length === 0) {
14042
14187
  const retry = () => s.refetch();
14043
14188
  if (slots?.error) {
14044
14189
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_jsx_runtime52.Fragment, { children: slots.error({ error: s.dataError, retry }) });
14045
14190
  }
14046
14191
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(SheetsErrorState, { error: s.dataError, onRetry: retry });
14047
14192
  }
14048
- if (s.isInitialLoading) {
14193
+ if (!activeMediaDraft && s.isInitialLoading) {
14049
14194
  if (slots?.loading) return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_jsx_runtime52.Fragment, { children: slots.loading });
14050
14195
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(SheetsLoadingState, {});
14051
14196
  }
14052
- if (s.isEmpty) {
14197
+ if (!activeMediaDraft && s.isEmpty) {
14053
14198
  if (slots?.empty) {
14054
14199
  return /* @__PURE__ */ (0, import_jsx_runtime52.jsx)(import_jsx_runtime52.Fragment, { children: typeof slots.empty === "function" ? slots.empty({ tableName }) : slots.empty });
14055
14200
  }
@@ -14913,7 +15058,7 @@ function useDynamicUpdate(tableName, rowId) {
14913
15058
  var import_react74 = require("react");
14914
15059
 
14915
15060
  // src/auth/hooks/use-login.ts
14916
- var import_react_query9 = require("@tanstack/react-query");
15061
+ var import_react_query10 = require("@tanstack/react-query");
14917
15062
 
14918
15063
  // src/auth/utils/auth-errors.ts
14919
15064
  var ERROR_CODES = {
@@ -15155,10 +15300,10 @@ var SIGN_IN_MUTATION = (
15155
15300
  `
15156
15301
  );
15157
15302
  function useSheetsLogin() {
15158
- const queryClient = (0, import_react_query9.useQueryClient)();
15303
+ const queryClient = (0, import_react_query10.useQueryClient)();
15159
15304
  const { config } = useSheetsContext();
15160
15305
  const storeApi = useSheetsStoreApi();
15161
- return (0, import_react_query9.useMutation)({
15306
+ return (0, import_react_query10.useMutation)({
15162
15307
  mutationKey: ["sheets", "auth", "signIn"],
15163
15308
  mutationFn: async (credentials) => {
15164
15309
  const result = await executeAuthMutation(
@@ -15192,7 +15337,7 @@ function useSheetsLogin() {
15192
15337
  }
15193
15338
 
15194
15339
  // src/auth/hooks/use-register.ts
15195
- var import_react_query10 = require("@tanstack/react-query");
15340
+ var import_react_query11 = require("@tanstack/react-query");
15196
15341
  var SIGN_UP_MUTATION = (
15197
15342
  /* GraphQL */
15198
15343
  `
@@ -15204,10 +15349,10 @@ var SIGN_UP_MUTATION = (
15204
15349
  `
15205
15350
  );
15206
15351
  function useSheetsRegister() {
15207
- const queryClient = (0, import_react_query10.useQueryClient)();
15352
+ const queryClient = (0, import_react_query11.useQueryClient)();
15208
15353
  const { config } = useSheetsContext();
15209
15354
  const storeApi = useSheetsStoreApi();
15210
- return (0, import_react_query10.useMutation)({
15355
+ return (0, import_react_query11.useMutation)({
15211
15356
  mutationKey: ["sheets", "auth", "signUp"],
15212
15357
  mutationFn: async (formData) => {
15213
15358
  await executeAuthMutation(
@@ -15232,7 +15377,7 @@ function useSheetsRegister() {
15232
15377
  }
15233
15378
 
15234
15379
  // src/auth/hooks/use-forgot-password.ts
15235
- var import_react_query11 = require("@tanstack/react-query");
15380
+ var import_react_query12 = require("@tanstack/react-query");
15236
15381
  var FORGOT_PASSWORD_MUTATION = (
15237
15382
  /* GraphQL */
15238
15383
  `
@@ -15245,7 +15390,7 @@ var FORGOT_PASSWORD_MUTATION = (
15245
15390
  );
15246
15391
  function useSheetsForgotPassword() {
15247
15392
  const { config } = useSheetsContext();
15248
- return (0, import_react_query11.useMutation)({
15393
+ return (0, import_react_query12.useMutation)({
15249
15394
  mutationKey: ["sheets", "auth", "forgotPassword"],
15250
15395
  mutationFn: async ({ email }) => {
15251
15396
  await executeAuthMutation(
@@ -15261,7 +15406,7 @@ function useSheetsForgotPassword() {
15261
15406
  }
15262
15407
 
15263
15408
  // src/auth/hooks/use-reset-password.ts
15264
- var import_react_query12 = require("@tanstack/react-query");
15409
+ var import_react_query13 = require("@tanstack/react-query");
15265
15410
  var RESET_PASSWORD_MUTATION = (
15266
15411
  /* GraphQL */
15267
15412
  `
@@ -15274,9 +15419,9 @@ var RESET_PASSWORD_MUTATION = (
15274
15419
  `
15275
15420
  );
15276
15421
  function useSheetsResetPassword() {
15277
- const queryClient = (0, import_react_query12.useQueryClient)();
15422
+ const queryClient = (0, import_react_query13.useQueryClient)();
15278
15423
  const { config } = useSheetsContext();
15279
- return (0, import_react_query12.useMutation)({
15424
+ return (0, import_react_query13.useMutation)({
15280
15425
  mutationKey: ["sheets", "auth", "resetPassword"],
15281
15426
  mutationFn: async (input) => {
15282
15427
  const result = await executeAuthMutation(