strapi-plugin-bulk-updater 1.5.15 → 1.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -76,10 +76,11 @@ function parseCsvRows(csvText) {
76
76
  }
77
77
  return rows;
78
78
  }
79
- function parseCsv(csvText) {
79
+ function parseCsvWithHeaders(csvText) {
80
80
  const rows = parseCsvRows(csvText);
81
- if (rows.length < 2) return [];
81
+ if (rows.length === 0) return { headers: [], records: [] };
82
82
  const headers = rows[0].map((h) => h.trim());
83
+ if (rows.length < 2) return { headers, records: [] };
83
84
  const records = [];
84
85
  for (let i = 1; i < rows.length; i++) {
85
86
  const row = rows[i];
@@ -93,7 +94,125 @@ function parseCsv(csvText) {
93
94
  });
94
95
  records.push(record);
95
96
  }
96
- return records;
97
+ return { headers, records };
98
+ }
99
+ function escapeCsvCell(val) {
100
+ if (val === null || val === void 0) return "";
101
+ let str = "";
102
+ if (val instanceof Date) {
103
+ str = val.toISOString();
104
+ } else if (typeof val === "object") {
105
+ str = JSON.stringify(val);
106
+ } else {
107
+ str = String(val);
108
+ }
109
+ str = str.replace(/\r\n/g, "\n").replace(/\r/g, "\n");
110
+ if (/^[=+@-]/.test(str)) {
111
+ str = `'${str}`;
112
+ }
113
+ if (str.includes(",") || str.includes('"') || str.includes("\n") || str.includes("\r")) {
114
+ return `"${str.replace(/"/g, '""')}"`;
115
+ }
116
+ return str;
117
+ }
118
+ function sanitizeUserErrorMessage(msg) {
119
+ if (msg === null || msg === void 0) return "Error processing row";
120
+ const raw = typeof msg === "string" ? msg : String(msg);
121
+ const cleanedLines = raw.split(/\r?\n/).filter((line) => !/^\s+at\s+.+(\(.+\)|:\d+:\d+)\s*$/.test(line)).map((line) => line.trim()).filter(Boolean);
122
+ return cleanedLines.join(" ").trim() || "Error processing row";
123
+ }
124
+ function resolveErrorColumnName(existingHeaders) {
125
+ const existingLower = new Set(
126
+ existingHeaders.map((h) => String(h || "").trim().toLowerCase())
127
+ );
128
+ if (!existingLower.has("error")) return "Error";
129
+ if (!existingLower.has("import error")) return "Import Error";
130
+ let suffix = 2;
131
+ while (existingLower.has(`import error (${suffix})`)) {
132
+ suffix++;
133
+ }
134
+ return `Import Error (${suffix})`;
135
+ }
136
+ function formatErrorCsvFilename(collectionTypeOrUid, date = /* @__PURE__ */ new Date()) {
137
+ const rawSegment = collectionTypeOrUid ? String(collectionTypeOrUid).split(".").pop() || String(collectionTypeOrUid) : "collection";
138
+ const safeType = rawSegment.replace(/[^a-zA-Z0-9_-]+/g, "_").replace(/^_+|_+$/g, "") || "collection";
139
+ const pad = (n) => String(n).padStart(2, "0");
140
+ const stamp = `${date.getFullYear()}${pad(date.getMonth() + 1)}${pad(date.getDate())}_${pad(
141
+ date.getHours()
142
+ )}${pad(date.getMinutes())}${pad(date.getSeconds())}`;
143
+ return `error_${safeType}_${stamp}.csv`;
144
+ }
145
+ function buildErrorCsv(options) {
146
+ const { headers, failedRows } = options || {};
147
+ if (!Array.isArray(failedRows) || failedRows.length === 0) {
148
+ return {
149
+ csvContent: "",
150
+ headers: headers ? [...headers] : [],
151
+ errorColumnName: "Error",
152
+ errorCount: 0
153
+ };
154
+ }
155
+ const groupedByRow = /* @__PURE__ */ new Map();
156
+ for (const item of failedRows) {
157
+ if (!item || typeof item !== "object") continue;
158
+ const rowNum = typeof item.row === "number" && !isNaN(item.row) ? item.row : groupedByRow.size + 2;
159
+ const msg = sanitizeUserErrorMessage(item.error);
160
+ const existing = groupedByRow.get(rowNum);
161
+ if (existing) {
162
+ if (!existing.messages.includes(msg)) {
163
+ existing.messages.push(msg);
164
+ }
165
+ } else {
166
+ groupedByRow.set(rowNum, {
167
+ row: rowNum,
168
+ documentId: item.documentId,
169
+ messages: [msg],
170
+ originalRow: item.originalRow && typeof item.originalRow === "object" ? item.originalRow : {}
171
+ });
172
+ }
173
+ }
174
+ const orderedEntries = Array.from(groupedByRow.values()).sort((a, b) => a.row - b.row);
175
+ if (orderedEntries.length === 0) {
176
+ return {
177
+ csvContent: "",
178
+ headers: headers ? [...headers] : [],
179
+ errorColumnName: "Error",
180
+ errorCount: 0
181
+ };
182
+ }
183
+ let baseHeaders = [];
184
+ if (Array.isArray(headers) && headers.length > 0) {
185
+ baseHeaders = [...headers];
186
+ } else {
187
+ const keySet = /* @__PURE__ */ new Set();
188
+ for (const entry of orderedEntries) {
189
+ for (const k of Object.keys(entry.originalRow || {})) {
190
+ if (!keySet.has(k)) {
191
+ keySet.add(k);
192
+ baseHeaders.push(k);
193
+ }
194
+ }
195
+ }
196
+ }
197
+ const errorColumnName = resolveErrorColumnName(baseHeaders);
198
+ const finalHeaders = [...baseHeaders, errorColumnName];
199
+ const lines = [];
200
+ lines.push(finalHeaders.map(escapeCsvCell).join(","));
201
+ for (const entry of orderedEntries) {
202
+ const cells = baseHeaders.map((h) => {
203
+ const val = entry.originalRow ? entry.originalRow[h] : "";
204
+ return escapeCsvCell(val === void 0 || val === null ? "" : val);
205
+ });
206
+ cells.push(escapeCsvCell(entry.messages.join("; ")));
207
+ lines.push(cells.join(","));
208
+ }
209
+ const csvContent = "\uFEFF" + lines.join("\r\n") + "\r\n";
210
+ return {
211
+ csvContent,
212
+ headers: finalHeaders,
213
+ errorColumnName,
214
+ errorCount: orderedEntries.length
215
+ };
97
216
  }
98
217
  const LIFECYCLE_STATUS_WORDS = /* @__PURE__ */ new Set([
99
218
  "pending review",
@@ -265,7 +384,7 @@ function CsvManagerTab() {
265
384
  const [selectedRuleId, setSelectedRuleId] = React.useState("");
266
385
  const [importMode, setImportMode] = React.useState("auto");
267
386
  const [publishOnImport, setPublishOnImport] = React.useState(true);
268
- const [csvRawText, setCsvRawText] = React.useState("");
387
+ const [originalHeaders, setOriginalHeaders] = React.useState([]);
269
388
  const [fileName, setFileName] = React.useState("");
270
389
  const [allParsedRecords, setAllParsedRecords] = React.useState([]);
271
390
  const [previewPage, setPreviewPage] = React.useState(1);
@@ -273,6 +392,8 @@ function CsvManagerTab() {
273
392
  const [importing, setImporting] = React.useState(false);
274
393
  const [importProgress, setImportProgress] = React.useState(null);
275
394
  const [importResult, setImportResult] = React.useState(null);
395
+ const [errorReport, setErrorReport] = React.useState(null);
396
+ const activeBatchIdRef = React.useRef(null);
276
397
  const [executionWindow, setExecutionWindow] = React.useState(null);
277
398
  const [preflightLoading, setPreflightLoading] = React.useState(false);
278
399
  const [preflightReport, setPreflightReport] = React.useState(null);
@@ -351,13 +472,15 @@ function CsvManagerTab() {
351
472
  if (countAbortControllerRef.current) {
352
473
  countAbortControllerRef.current.abort();
353
474
  }
475
+ activeBatchIdRef.current = null;
354
476
  setSelectedUid(newUid);
355
477
  setAllParsedRecords([]);
356
- setCsvRawText("");
478
+ setOriginalHeaders([]);
357
479
  setFileName("");
358
480
  setPreviewPage(1);
359
481
  setImportProgress(null);
360
482
  setImportResult(null);
483
+ setErrorReport(null);
361
484
  setPreflightReport(null);
362
485
  setPreflightLoading(false);
363
486
  setImporting(false);
@@ -569,43 +692,76 @@ function CsvManagerTab() {
569
692
  const handleFileUpload = (e) => {
570
693
  const file = e.target.files?.[0];
571
694
  if (!file) return;
695
+ activeBatchIdRef.current = null;
572
696
  setFileName(file.name);
573
697
  setImportResult(null);
574
698
  setImportProgress(null);
699
+ setPreflightReport(null);
700
+ setErrorReport(null);
701
+ setOriginalHeaders([]);
575
702
  const reader = new FileReader();
576
703
  reader.onload = (event) => {
577
704
  const text = event.target?.result;
578
- setCsvRawText(text);
579
705
  try {
580
- const records = parseCsv(text);
581
- const enriched = enrichCsvRowsWithLifecycle(records, collectionEntries);
582
- setAllParsedRecords(enriched);
706
+ const { headers, records } = parseCsvWithHeaders(text);
707
+ setOriginalHeaders(headers);
708
+ setAllParsedRecords(records);
583
709
  setPreviewPage(1);
584
710
  } catch (err) {
711
+ setOriginalHeaders([]);
585
712
  setAllParsedRecords([]);
586
713
  }
587
714
  };
588
715
  reader.readAsText(file);
589
716
  };
717
+ const handleDownloadErrorCsv = () => {
718
+ if (!errorReport || errorReport.uid !== selectedUid || errorReport.failedRows.length === 0) {
719
+ return;
720
+ }
721
+ const { csvContent } = buildErrorCsv({
722
+ headers: errorReport.headers,
723
+ failedRows: errorReport.failedRows
724
+ });
725
+ const targetType = selectedCol?.singularName || selectedUid;
726
+ const errFilename = formatErrorCsvFilename(targetType);
727
+ downloadCsvFile(csvContent, errFilename);
728
+ };
590
729
  const handleExecuteImport = async () => {
591
730
  if (!selectedUid || allParsedRecords.length === 0) return;
592
- let currentEntries = collectionEntries;
593
- if (currentEntries.length === 0) {
594
- currentEntries = await fetchAndEnrichEntries(selectedUid);
595
- }
596
- const enrichedRecords = enrichCsvRowsWithLifecycle(allParsedRecords, currentEntries);
597
- const totalRows = enrichedRecords.length;
598
- const CHUNK_SIZE = 100;
599
- const totalChunks = Math.ceil(totalRows / CHUNK_SIZE);
731
+ const runUid = selectedUid;
732
+ const runHeaders = originalHeaders;
733
+ const originalRecordsSnapshot = allParsedRecords;
600
734
  const batchId = `csv_batch_${Date.now()}_${Math.random().toString(36).substring(2, 7)}`;
735
+ activeBatchIdRef.current = batchId;
601
736
  try {
602
737
  setImporting(true);
603
738
  setImportResult(null);
739
+ setErrorReport(null);
740
+ let currentEntries = collectionEntries;
741
+ if (currentEntries.length === 0) {
742
+ currentEntries = await fetchAndEnrichEntries(runUid);
743
+ }
744
+ if (activeBatchIdRef.current !== batchId) return;
745
+ const enrichedRecords = enrichCsvRowsWithLifecycle(originalRecordsSnapshot, currentEntries);
746
+ const totalRows = enrichedRecords.length;
747
+ const CHUNK_SIZE = 100;
748
+ const totalChunks = Math.ceil(totalRows / CHUNK_SIZE);
604
749
  let liveCreated = 0;
605
750
  let liveUpdated = 0;
606
751
  let liveSkipped = 0;
752
+ let liveNewWithoutDocId = 0;
607
753
  let liveErrors = 0;
608
754
  let finalResultData = null;
755
+ const accumulatedErrors = [];
756
+ const accumulatedFailedRows = [];
757
+ const accumulatedDiffs = [];
758
+ const mapOriginalRowForIndex = (rowNum, backendOrigRow) => {
759
+ const idx = typeof rowNum === "number" ? rowNum - 2 : -1;
760
+ if (idx >= 0 && idx < originalRecordsSnapshot.length) {
761
+ return originalRecordsSnapshot[idx];
762
+ }
763
+ return backendOrigRow && typeof backendOrigRow === "object" ? backendOrigRow : {};
764
+ };
609
765
  setImportProgress({
610
766
  currentChunk: 0,
611
767
  totalChunks,
@@ -618,53 +774,152 @@ function CsvManagerTab() {
618
774
  liveErrors: 0
619
775
  });
620
776
  for (let chunkIdx = 0; chunkIdx < totalChunks; chunkIdx++) {
777
+ if (activeBatchIdRef.current !== batchId) return;
621
778
  const startIdx = chunkIdx * CHUNK_SIZE;
622
779
  const endIdx = Math.min(startIdx + CHUNK_SIZE, totalRows);
623
780
  const chunkRows = enrichedRecords.slice(startIdx, endIdx);
624
781
  const isFirst = chunkIdx === 0;
625
782
  const isLast = chunkIdx === totalChunks - 1;
626
783
  const startRowNumber = startIdx + 2;
627
- const res = await post("/bulk-updater/csv/import-chunk", {
628
- uid: selectedUid,
629
- rows: chunkRows,
630
- batchId,
631
- isFirstChunk: isFirst,
632
- isLastChunk: isLast,
633
- startRowNumber,
634
- mode: importMode,
635
- publish: publishOnImport,
636
- publishStrategy,
637
- unreviewedConsent
638
- });
639
- if (!res.data || !res.data.success) {
640
- throw new Error(res.data?.error || `Chunk ${chunkIdx + 1} failed to process`);
641
- }
642
- const chunkStats = res.data.chunkStats;
643
- if (chunkStats) {
644
- liveCreated += chunkStats.created || 0;
645
- liveUpdated += chunkStats.updated || 0;
646
- liveSkipped += chunkStats.skipped || 0;
647
- liveErrors += chunkStats.errors?.length || 0;
648
- }
649
- const currentProgressPercent = Math.round((chunkIdx + 1) / totalChunks * 100);
650
- setImportProgress({
651
- currentChunk: chunkIdx + 1,
652
- totalChunks,
653
- percent: currentProgressPercent,
654
- processedRows: endIdx,
655
- totalRows,
656
- liveCreated,
657
- liveUpdated,
658
- liveSkipped,
659
- liveErrors
660
- });
661
- if (isLast) {
662
- finalResultData = res.data;
784
+ try {
785
+ const res = await post("/bulk-updater/csv/import-chunk", {
786
+ uid: runUid,
787
+ rows: chunkRows,
788
+ batchId,
789
+ isFirstChunk: isFirst,
790
+ isLastChunk: isLast,
791
+ startRowNumber,
792
+ mode: importMode,
793
+ publish: publishOnImport,
794
+ publishStrategy,
795
+ unreviewedConsent,
796
+ ...isFirst && runHeaders.length > 0 ? { originalHeaders: runHeaders } : {}
797
+ });
798
+ if (activeBatchIdRef.current !== batchId) return;
799
+ if (!res.data || !res.data.success) {
800
+ throw new Error(res.data?.error || `Chunk ${chunkIdx + 1} failed to process`);
801
+ }
802
+ const chunkStats = res.data.chunkStats;
803
+ if (chunkStats) {
804
+ liveCreated += chunkStats.created || 0;
805
+ liveUpdated += chunkStats.updated || 0;
806
+ liveSkipped += chunkStats.skipped || 0;
807
+ liveNewWithoutDocId += chunkStats.newWithoutDocId || 0;
808
+ liveErrors += chunkStats.errors?.length || 0;
809
+ if (Array.isArray(chunkStats.errors)) {
810
+ accumulatedErrors.push(...chunkStats.errors);
811
+ }
812
+ if (Array.isArray(chunkStats.failedRows) && chunkStats.failedRows.length > 0) {
813
+ for (const f of chunkStats.failedRows) {
814
+ accumulatedFailedRows.push({
815
+ row: f.row,
816
+ documentId: f.documentId,
817
+ error: f.error,
818
+ originalRow: mapOriginalRowForIndex(f.row, f.originalRow)
819
+ });
820
+ }
821
+ } else if (Array.isArray(chunkStats.errors) && chunkStats.errors.length > 0) {
822
+ for (const errItem of chunkStats.errors) {
823
+ accumulatedFailedRows.push({
824
+ row: errItem.row,
825
+ documentId: errItem.documentId,
826
+ error: errItem.error,
827
+ originalRow: mapOriginalRowForIndex(errItem.row)
828
+ });
829
+ }
830
+ }
831
+ if (Array.isArray(chunkStats.diffs)) {
832
+ accumulatedDiffs.push(...chunkStats.diffs);
833
+ }
834
+ }
835
+ const currentProgressPercent = Math.round((chunkIdx + 1) / totalChunks * 100);
836
+ setImportProgress({
837
+ currentChunk: chunkIdx + 1,
838
+ totalChunks,
839
+ percent: currentProgressPercent,
840
+ processedRows: endIdx,
841
+ totalRows,
842
+ liveCreated,
843
+ liveUpdated,
844
+ liveSkipped,
845
+ liveErrors
846
+ });
847
+ if (isLast) {
848
+ finalResultData = res.data;
849
+ }
850
+ } catch (chunkErr) {
851
+ if (ValidationRulesTab.isAbortError(chunkErr)) return;
852
+ if (activeBatchIdRef.current !== batchId) return;
853
+ const apiErrMsg = sanitizeUserErrorMessage(
854
+ chunkErr?.response?.data?.error?.message || chunkErr?.response?.data?.error || chunkErr?.message || `Chunk ${chunkIdx + 1} failed to process`
855
+ );
856
+ for (let j = startIdx; j < endIdx; j++) {
857
+ const rowNum = j + 2;
858
+ const rawRow = originalRecordsSnapshot[j] || {};
859
+ const rowDocId = extractDocId(rawRow) || void 0;
860
+ accumulatedErrors.push({
861
+ row: rowNum,
862
+ ...rowDocId ? { documentId: rowDocId } : {},
863
+ error: apiErrMsg
864
+ });
865
+ accumulatedFailedRows.push({
866
+ row: rowNum,
867
+ ...rowDocId ? { documentId: rowDocId } : {},
868
+ error: apiErrMsg,
869
+ originalRow: rawRow
870
+ });
871
+ liveSkipped++;
872
+ liveErrors++;
873
+ }
874
+ setImportResult({
875
+ success: false,
876
+ batchId,
877
+ stats: {
878
+ total: totalRows,
879
+ created: liveCreated,
880
+ updated: liveUpdated,
881
+ skipped: liveSkipped,
882
+ newWithoutDocId: liveNewWithoutDocId,
883
+ errors: accumulatedErrors,
884
+ diffs: accumulatedDiffs
885
+ }
886
+ });
887
+ if (accumulatedFailedRows.length > 0) {
888
+ setErrorReport({
889
+ uid: runUid,
890
+ batchId,
891
+ headers: runHeaders,
892
+ failedRows: accumulatedFailedRows
893
+ });
894
+ }
895
+ throw new Error(apiErrMsg);
663
896
  }
664
897
  }
898
+ if (activeBatchIdRef.current !== batchId) return;
665
899
  if (finalResultData && finalResultData.stats) {
666
900
  setImportResult(finalResultData);
667
901
  const stats = finalResultData.stats;
902
+ const finalFailedRows = accumulatedFailedRows.length > 0 ? accumulatedFailedRows : Array.isArray(stats.failedRows) && stats.failedRows.length > 0 ? stats.failedRows.map((f) => ({
903
+ row: f.row,
904
+ documentId: f.documentId,
905
+ error: f.error,
906
+ originalRow: mapOriginalRowForIndex(f.row, f.originalRow)
907
+ })) : Array.isArray(stats.errors) ? stats.errors.map((errItem) => ({
908
+ row: errItem.row,
909
+ documentId: errItem.documentId,
910
+ error: errItem.error,
911
+ originalRow: mapOriginalRowForIndex(errItem.row)
912
+ })) : [];
913
+ if (finalFailedRows.length > 0) {
914
+ setErrorReport({
915
+ uid: runUid,
916
+ batchId: finalResultData.batchId || batchId,
917
+ headers: runHeaders,
918
+ failedRows: finalFailedRows
919
+ });
920
+ } else {
921
+ setErrorReport(null);
922
+ }
668
923
  let notifMsg = `CSV Import complete: ${stats.created} created, ${stats.updated} updated across ${stats.total} records.`;
669
924
  if (stats.newWithoutDocId && stats.newWithoutDocId > 0) {
670
925
  notifMsg += ` (${stats.newWithoutDocId} new entries created due to omitted documentId)`;
@@ -681,7 +936,9 @@ function CsvManagerTab() {
681
936
  message: err.message || "Error processing CSV import batch"
682
937
  });
683
938
  } finally {
684
- setImporting(false);
939
+ if (activeBatchIdRef.current === batchId || activeBatchIdRef.current === null) {
940
+ setImporting(false);
941
+ }
685
942
  }
686
943
  };
687
944
  const handleRunPreflight = async () => {
@@ -1453,6 +1710,25 @@ function CsvManagerTab() {
1453
1710
  importResult.stats.errors.length - 10,
1454
1711
  " more error",
1455
1712
  importResult.stats.errors.length - 10 > 1 ? "s" : ""
1713
+ ] }),
1714
+ errorReport && errorReport.uid === selectedUid && (!importResult.batchId || errorReport.batchId === importResult.batchId) && errorReport.failedRows.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { marginTop: 3, gap: 2, alignItems: "center", wrap: "wrap", children: [
1715
+ /* @__PURE__ */ jsxRuntime.jsxs(
1716
+ designSystem.Button,
1717
+ {
1718
+ variant: "danger-light",
1719
+ size: "S",
1720
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Download, {}),
1721
+ onClick: handleDownloadErrorCsv,
1722
+ children: [
1723
+ "Download Error CSV (",
1724
+ errorReport.failedRows.length.toLocaleString(),
1725
+ " failed row",
1726
+ errorReport.failedRows.length > 1 ? "s" : "",
1727
+ ")"
1728
+ ]
1729
+ }
1730
+ ),
1731
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: "Contains only failed rows with all original columns preserved and an Error column." })
1456
1732
  ] })
1457
1733
  ] }),
1458
1734
  importResult.stats.diffs && importResult.stats.diffs.length > 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { marginTop: 3, padding: 3, background: "neutral0", hasRadius: true, style: { border: "1px solid #dcdce4" }, children: [
@@ -2471,6 +2747,7 @@ const BulkUpdatePreviewModal = ({
2471
2747
  previewData,
2472
2748
  attribute,
2473
2749
  targetValueDisplay,
2750
+ editMode = "common",
2474
2751
  publishOnApproval = true,
2475
2752
  lifecycleStats
2476
2753
  }) => {
@@ -2485,12 +2762,14 @@ const BulkUpdatePreviewModal = ({
2485
2762
  if (searchQuery.trim()) {
2486
2763
  const q = searchQuery.toLowerCase().trim();
2487
2764
  items = items.filter(
2488
- (d) => d.label.toLowerCase().includes(q) || d.documentId.toLowerCase().includes(q) || d.collectionName.toLowerCase().includes(q) || String(d.oldDisplay || "").toLowerCase().includes(q) || String(d.newDisplay || "").toLowerCase().includes(q)
2765
+ (d) => d.label.toLowerCase().includes(q) || d.documentId.toLowerCase().includes(q) || d.collectionName.toLowerCase().includes(q) || String(d.attribute || "").toLowerCase().includes(q) || String(d.oldDisplay || "").toLowerCase().includes(q) || String(d.newDisplay || "").toLowerCase().includes(q)
2489
2766
  );
2490
2767
  }
2491
2768
  return items;
2492
2769
  }, [previewData, filterTab, searchQuery]);
2493
2770
  if (!isOpen) return null;
2771
+ const isGridMode = editMode === "grid" || previewData?.editMode === "grid";
2772
+ const willErrorCount = previewData?.summary?.willError || 0;
2494
2773
  return /* @__PURE__ */ jsxRuntime.jsx(
2495
2774
  "div",
2496
2775
  {
@@ -2514,7 +2793,7 @@ const BulkUpdatePreviewModal = ({
2514
2793
  hasRadius: true,
2515
2794
  shadow: "popupShadow",
2516
2795
  style: {
2517
- maxWidth: 1040,
2796
+ maxWidth: 1120,
2518
2797
  width: "95%",
2519
2798
  maxHeight: "calc(100vh - 48px)",
2520
2799
  display: "flex",
@@ -2541,13 +2820,16 @@ const BulkUpdatePreviewModal = ({
2541
2820
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "primary100", textColor: "primary700", children: [
2542
2821
  "Target: ",
2543
2822
  attribute
2544
- ] })
2823
+ ] }),
2824
+ isGridMode && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "secondary100", textColor: "secondary700", children: "GRID EDITING MODE" })
2545
2825
  ] }),
2546
2826
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: "Inspect exact before & after values across target records before applying changes to the database." })
2547
2827
  ] }),
2548
2828
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", wrap: "wrap", children: [
2549
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: "New Value:" }),
2550
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "success100", textColor: "success700", children: targetValueDisplay || "(empty)" }),
2829
+ !isGridMode ? /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2830
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: "New Value:" }),
2831
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "success100", textColor: "success700", children: targetValueDisplay || "(empty)" })
2832
+ ] }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "secondary100", textColor: "secondary700", children: targetValueDisplay || "Per-Record & Component Grid Edits" }),
2551
2833
  /* @__PURE__ */ jsxRuntime.jsx(
2552
2834
  designSystem.Badge,
2553
2835
  {
@@ -2575,6 +2857,13 @@ const BulkUpdatePreviewModal = ({
2575
2857
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "delta", fontWeight: "semiBold", children: "Inspecting Target Records..." }),
2576
2858
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: "Computing proposed diffs and verifying against database schema." })
2577
2859
  ] }) }) : !previewData ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { padding: 6, style: { textAlign: "center" }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral600", children: "No preview data available." }) }) : /* @__PURE__ */ jsxRuntime.jsxs(jsxRuntime.Fragment, { children: [
2860
+ willErrorCount > 0 && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { marginBottom: 4, padding: 3, background: "danger100", hasRadius: true, style: { border: "1px solid #f5c0b8" }, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
2861
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", fontWeight: "bold", textColor: "danger700", children: "⚠️ Validation / Quota Violation Detected:" }),
2862
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", textColor: "danger700", children: [
2863
+ willErrorCount,
2864
+ ' item(s) failed schema or quota validation rules. Inspect the rows marked "Validation Error" below; invalid records will be rejected during batch execution and retained for editing.'
2865
+ ] })
2866
+ ] }) }),
2578
2867
  publishOnApproval && lifecycleStats && lifecycleStats.unreviewedCount > 0 && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { marginBottom: 4, padding: 3, background: "warning100", hasRadius: true, style: { border: "1px solid #f5c0b8" }, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
2579
2868
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", fontWeight: "bold", textColor: "warning700", children: "⚠️ Safe Publishing Active:" }),
2580
2869
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", textColor: "warning700", children: [
@@ -2640,7 +2929,7 @@ const BulkUpdatePreviewModal = ({
2640
2929
  variant: "sigma",
2641
2930
  textColor: previewData.summary.skipped > 0 ? "warning700" : "neutral600",
2642
2931
  display: "block",
2643
- children: "WILL SKIP (NO FIELD)"
2932
+ children: "WILL SKIP"
2644
2933
  }
2645
2934
  ),
2646
2935
  /* @__PURE__ */ jsxRuntime.jsx(
@@ -2654,6 +2943,19 @@ const BulkUpdatePreviewModal = ({
2654
2943
  )
2655
2944
  ]
2656
2945
  }
2946
+ ),
2947
+ willErrorCount > 0 && /* @__PURE__ */ jsxRuntime.jsxs(
2948
+ designSystem.Box,
2949
+ {
2950
+ padding: 3,
2951
+ background: "danger100",
2952
+ hasRadius: true,
2953
+ style: { flex: 1, minWidth: 140, border: "1px solid #ffa39e" },
2954
+ children: [
2955
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "danger700", display: "block", children: "VALIDATION ERRORS" }),
2956
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "beta", fontWeight: "bold", textColor: "danger700", children: willErrorCount })
2957
+ ]
2958
+ }
2657
2959
  )
2658
2960
  ] }),
2659
2961
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", marginBottom: 3, wrap: "wrap", gap: 3, children: [
@@ -2666,7 +2968,7 @@ const BulkUpdatePreviewModal = ({
2666
2968
  onClick: () => setFilterTab("all"),
2667
2969
  children: [
2668
2970
  "All (",
2669
- previewData.summary.total,
2971
+ isGridMode ? previewData.diffs.length : previewData.summary.total,
2670
2972
  ")"
2671
2973
  ]
2672
2974
  }
@@ -2709,6 +3011,19 @@ const BulkUpdatePreviewModal = ({
2709
3011
  ")"
2710
3012
  ]
2711
3013
  }
3014
+ ),
3015
+ willErrorCount > 0 && /* @__PURE__ */ jsxRuntime.jsxs(
3016
+ designSystem.Button,
3017
+ {
3018
+ variant: filterTab === "will_error" ? "default" : "tertiary",
3019
+ size: "S",
3020
+ onClick: () => setFilterTab("will_error"),
3021
+ children: [
3022
+ "Errors (",
3023
+ willErrorCount,
3024
+ ")"
3025
+ ]
3026
+ }
2712
3027
  )
2713
3028
  ] }),
2714
3029
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { width: 260 }, children: /* @__PURE__ */ jsxRuntime.jsx(
@@ -2731,20 +3046,22 @@ const BulkUpdatePreviewModal = ({
2731
3046
  overflowY: "auto",
2732
3047
  overflowX: "auto"
2733
3048
  },
2734
- children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Table, { colCount: 5, rowCount: filteredDiffs.length + 1, style: { width: "100%", minWidth: 780 }, children: [
3049
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Table, { colCount: 6, rowCount: filteredDiffs.length + 1, style: { width: "100%", minWidth: 880 }, children: [
2735
3050
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Thead, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
2736
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 150 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "COLLECTION" }) }),
2737
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { minWidth: 200 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "RECORD IDENTIFIER" }) }),
2738
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { minWidth: 180 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "CURRENT VALUE (BEFORE)" }) }),
2739
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { minWidth: 180 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "NEW VALUE (AFTER)" }) }),
2740
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 140, textAlign: "right" }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "IMPACT" }) })
3051
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 140 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "COLLECTION" }) }),
3052
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { minWidth: 185 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "RECORD IDENTIFIER" }) }),
3053
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { minWidth: 165 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "ATTRIBUTE / BLOCK" }) }),
3054
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { minWidth: 170 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "CURRENT VALUE (BEFORE)" }) }),
3055
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { minWidth: 170 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "NEW VALUE (AFTER)" }) }),
3056
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 150, textAlign: "right" }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", children: "IMPACT" }) })
2741
3057
  ] }) }),
2742
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tbody, { children: filteredDiffs.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tr, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { colSpan: 5, style: { textAlign: "center", padding: "24px" }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral600", children: "No records match the current filter or search criteria." }) }) }) : filteredDiffs.map((diff) => /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
3058
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tbody, { children: filteredDiffs.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tr, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { colSpan: 6, style: { textAlign: "center", padding: "24px" }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral600", children: "No records match the current filter or search criteria." }) }) }) : filteredDiffs.map((diff, idx) => /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
2743
3059
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "neutral150", textColor: "neutral700", children: diff.collectionName }) }),
2744
3060
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { children: [
2745
3061
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "bold", display: "block", children: diff.label }),
2746
3062
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral500", children: /* @__PURE__ */ jsxRuntime.jsx("code", { children: diff.documentId }) })
2747
3063
  ] }) }),
3064
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", fontWeight: "semiBold", textColor: "primary700", children: diff.attribute || attribute }) }),
2748
3065
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(
2749
3066
  designSystem.Typography,
2750
3067
  {
@@ -2757,13 +3074,14 @@ const BulkUpdatePreviewModal = ({
2757
3074
  children: diff.oldDisplay || "(empty)"
2758
3075
  }
2759
3076
  ) }),
2760
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: diff.status === "will_skip" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "warning700", children: "— Skipped (field absent) —" }) : diff.hasChange ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "bold", textColor: "success700", style: { wordBreak: "break-all" }, children: diff.newDisplay || "(empty)" }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral600", children: diff.newDisplay || "(already matching)" }) }),
3077
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: diff.status === "will_error" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", fontWeight: "bold", children: diff.validationError || diff.message }) : diff.status === "will_skip" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "warning700", children: "— Skipped (field absent) —" }) : diff.hasChange ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "bold", textColor: "success700", style: { wordBreak: "break-all" }, children: diff.newDisplay || "(empty)" }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral600", children: diff.newDisplay || "(already matching)" }) }),
2761
3078
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Td, { style: { textAlign: "right" }, children: [
2762
3079
  diff.status === "will_update" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "success100", textColor: "success700", children: "✓ Will Update" }),
2763
3080
  diff.status === "unchanged" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "neutral150", textColor: "neutral600", children: "= Unchanged" }),
2764
- diff.status === "will_skip" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "warning100", textColor: "warning700", children: "⚠ Will Skip" })
3081
+ diff.status === "will_skip" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "warning100", textColor: "warning700", children: "⚠ Will Skip" }),
3082
+ diff.status === "will_error" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "danger100", textColor: "danger700", children: "✕ Error" })
2765
3083
  ] })
2766
- ] }, `${diff.uid}-${diff.documentId}`)) })
3084
+ ] }, `${diff.uid}-${diff.documentId}-${diff.attribute || "root"}-${idx}`)) })
2767
3085
  ] })
2768
3086
  }
2769
3087
  )
@@ -2791,7 +3109,7 @@ const BulkUpdatePreviewModal = ({
2791
3109
  onClose();
2792
3110
  onProceed();
2793
3111
  },
2794
- disabled: loading || !previewData || previewData.summary.total === 0,
3112
+ disabled: loading || !previewData || previewData.summary.total === 0 || isGridMode && previewData.summary.willUpdate === 0,
2795
3113
  children: [
2796
3114
  "Proceed to Execute (",
2797
3115
  previewData?.summary.willUpdate || 0,
@@ -3230,12 +3548,13 @@ const CheckerReviewModal = ({
3230
3548
  children: diff.oldDisplay || "(empty)"
3231
3549
  }
3232
3550
  ) }),
3233
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: diff.status === "will_create" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "bold", textColor: "success700", style: { wordBreak: "break-all" }, children: diff.newDisplay || "(new value)" }) : diff.status === "will_skip" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "warning700", children: "— Skipped —" }) : diff.hasChange ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "bold", textColor: "success700", style: { wordBreak: "break-all" }, children: diff.newDisplay || "(empty)" }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral600", children: diff.newDisplay || "(matching)" }) }),
3551
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: diff.status === "will_create" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "bold", textColor: "success700", style: { wordBreak: "break-all" }, children: diff.newDisplay || "(new value)" }) : diff.status === "will_error" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", fontWeight: "bold", children: diff.validationError || diff.message || "Validation error" }) : diff.status === "will_skip" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "warning700", children: "— Skipped —" }) : diff.hasChange ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "bold", textColor: "success700", style: { wordBreak: "break-all" }, children: diff.newDisplay || "(empty)" }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", textColor: "neutral600", children: diff.newDisplay || "(matching)" }) }),
3234
3552
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Td, { style: { textAlign: "right" }, children: [
3235
3553
  diff.status === "will_create" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "success100", textColor: "success700", children: "+ Will Create" }),
3236
3554
  diff.status === "will_update" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "warning100", textColor: "warning700", children: "✎ Will Update" }),
3237
3555
  diff.status === "unchanged" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "neutral150", textColor: "neutral600", children: "= Unchanged" }),
3238
- diff.status === "will_skip" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "danger100", textColor: "danger700", children: "⚠ Will Skip" })
3556
+ diff.status === "will_skip" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "warning100", textColor: "warning700", children: "⚠ Will Skip" }),
3557
+ diff.status === "will_error" && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "danger100", textColor: "danger700", children: "✕ Validation Error" })
3239
3558
  ] })
3240
3559
  ] }, `${diff.uid}-${diff.documentId}-${diff.attribute}-${idx}`)) })
3241
3560
  ] })
@@ -3313,14 +3632,19 @@ const CheckerReviewModal = ({
3313
3632
  }
3314
3633
  );
3315
3634
  };
3316
- function parseDynamicZonePath(path) {
3635
+ function formatComponentNameFriendly(compUid) {
3636
+ if (!compUid) return "Component";
3637
+ const name = compUid.includes(".") ? compUid.split(".")[1] : compUid;
3638
+ return name.split(/[-_]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
3639
+ }
3640
+ function parseAttrPathClient(path) {
3317
3641
  if (!path) return { cleanPath: "", rootKey: "", subPath: "" };
3318
- const bracketMatch = path.match(/^([^.[]+)\[([^\]]+)\]\.(.+)$/);
3642
+ const bracketMatch = path.match(/^([^.[]+)\[([^\]]+)\](?:\.(.+))?$/);
3319
3643
  if (bracketMatch) {
3320
3644
  const rootKey = bracketMatch[1];
3321
- const selector = bracketMatch[2];
3322
- const subPath = bracketMatch[3];
3323
- const cleanPath = `${rootKey}.${subPath}`;
3645
+ const selector = bracketMatch[2].trim();
3646
+ const subPath = bracketMatch[3] || "";
3647
+ const cleanPath = subPath ? `${rootKey}.${subPath}` : rootKey;
3324
3648
  if (/^\d+$/.test(selector)) {
3325
3649
  return { cleanPath, rootKey, subPath, targetIndex: parseInt(selector, 10) };
3326
3650
  }
@@ -3333,126 +3657,1410 @@ function parseDynamicZonePath(path) {
3333
3657
  subPath: parts.slice(1).join(".")
3334
3658
  };
3335
3659
  }
3336
- function formatComponentName(compUid) {
3337
- if (!compUid) return "Component";
3338
- const name = compUid.includes(".") ? compUid.split(".")[1] : compUid;
3339
- return name.split(/[-_]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
3660
+ function buildOccurrenceKey(segments) {
3661
+ if (!segments || segments.length === 0) return "__scalar__";
3662
+ return segments.map((seg) => {
3663
+ if (seg.index !== void 0) {
3664
+ return seg.componentId !== void 0 && seg.componentId !== null ? `${seg.key}[${seg.index}#${seg.componentId}]` : `${seg.key}[${seg.index}]`;
3665
+ }
3666
+ return seg.key;
3667
+ }).join(".");
3340
3668
  }
3341
- function getAllNestedValues(obj, path, availableAttributes) {
3342
- if (!obj || !path) return [];
3343
- const parsed = parseDynamicZonePath(path);
3344
- const parts = parsed.cleanPath.split(".");
3345
- const [head, ...tail] = parts;
3346
- const rootTarget = getPropertyValue(obj, head);
3347
- if (Array.isArray(rootTarget)) {
3348
- const results = [];
3349
- rootTarget.forEach((item, idx) => {
3350
- if (!item || typeof item !== "object") return;
3351
- if (parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) return;
3352
- if (parsed.targetComponentUid && item.__component !== parsed.targetComponentUid) return;
3353
- const subPath = tail.join(".");
3354
- const scopedPath = item.__component ? `${head}[${item.__component}].${subPath}` : "";
3355
- const isSupported = availableAttributes ? availableAttributes.includes(scopedPath) : false;
3356
- const subVal = tail.length > 0 ? getNestedValue(item, subPath) : item;
3357
- if (subVal !== void 0 || isSupported) {
3358
- results.push({
3359
- index: idx,
3360
- componentUid: item.__component,
3361
- componentName: formatComponentName(item.__component),
3362
- value: subVal !== void 0 ? subVal : null,
3363
- path: `${head}[#${idx}${item.__component ? ` ${formatComponentName(item.__component)}` : ""}].${subPath}`
3364
- });
3669
+ function buildReadablePath(segments) {
3670
+ if (!segments || segments.length === 0) return "";
3671
+ return segments.map((seg) => {
3672
+ if (seg.index !== void 0) {
3673
+ const label = seg.componentUid ? ` ${formatComponentNameFriendly(seg.componentUid)}` : "";
3674
+ return `${seg.key}[#${seg.index}${label}]`;
3675
+ }
3676
+ return seg.key;
3677
+ }).join(".");
3678
+ }
3679
+ function getDirectProp(obj, key) {
3680
+ if (!obj || typeof obj !== "object") return void 0;
3681
+ if (obj[key] !== void 0) return obj[key];
3682
+ const camel = key.replace(/_([a-z0-9])/g, (_, l) => l.toUpperCase());
3683
+ if (obj[camel] !== void 0) return obj[camel];
3684
+ const snake = key.replace(/([A-Z])/g, "_$1").toLowerCase();
3685
+ if (obj[snake] !== void 0) return obj[snake];
3686
+ return void 0;
3687
+ }
3688
+ function resolveTailExistsOrValue(obj, parts) {
3689
+ let cur = obj;
3690
+ for (const p of parts) {
3691
+ if (cur === null || cur === void 0) return void 0;
3692
+ if (Array.isArray(cur)) {
3693
+ for (const item of cur) {
3694
+ const found = resolveTailExistsOrValue(item, parts.slice(parts.indexOf(p)));
3695
+ if (found !== void 0) return found;
3365
3696
  }
3366
- });
3367
- return results;
3697
+ return void 0;
3698
+ }
3699
+ cur = getDirectProp(cur, p);
3368
3700
  }
3369
- const singleVal = getNestedValue(obj, parsed.cleanPath);
3370
- if (singleVal !== void 0) {
3701
+ return cur;
3702
+ }
3703
+ function enumerateClientOccurrences(entry, attrPath, availableAttributes, attrMeta) {
3704
+ if (!entry || !attrPath) return [];
3705
+ const parsed = parseAttrPathClient(attrPath);
3706
+ const parts = parsed.cleanPath.split(".").filter(Boolean);
3707
+ if (parts.length === 0) return [];
3708
+ if (parts.length === 1 && !parsed.targetComponentUid && parsed.targetIndex === void 0) {
3709
+ const val = getDirectProp(entry, parts[0]);
3371
3710
  return [
3372
3711
  {
3712
+ occurrenceKey: "__scalar__",
3713
+ displayPath: parts[0],
3714
+ segments: [{ key: parts[0] }],
3715
+ value: val !== void 0 ? val : null,
3373
3716
  index: 0,
3374
- value: singleVal,
3375
- path: parsed.cleanPath
3717
+ isMissingIntermediate: false
3376
3718
  }
3377
3719
  ];
3378
3720
  }
3379
- return [];
3721
+ const results = [];
3722
+ function walk(currentVal, remainingParts, segments, missingIntermediate, firstArrayIndex, resolvedCompUid, resolvedCompId, isRootLevel) {
3723
+ if (remainingParts.length === 0) return;
3724
+ const [head, ...tail] = remainingParts;
3725
+ if (tail.length === 0) {
3726
+ const val = currentVal && typeof currentVal === "object" ? getDirectProp(currentVal, head) : void 0;
3727
+ const nextSegs = [...segments, { key: head }];
3728
+ results.push({
3729
+ occurrenceKey: buildOccurrenceKey(nextSegs),
3730
+ displayPath: buildReadablePath(nextSegs),
3731
+ segments: nextSegs,
3732
+ value: val !== void 0 ? val : null,
3733
+ componentUid: resolvedCompUid,
3734
+ componentName: resolvedCompUid ? formatComponentNameFriendly(resolvedCompUid) : void 0,
3735
+ componentId: resolvedCompId,
3736
+ index: firstArrayIndex ?? 0,
3737
+ isMissingIntermediate: missingIntermediate
3738
+ });
3739
+ return;
3740
+ }
3741
+ const nextVal = currentVal && typeof currentVal === "object" ? getDirectProp(currentVal, head) : void 0;
3742
+ const isExpectingRootArray = isRootLevel && (attrMeta?.rootType === "dynamiczone" || attrMeta?.rootRepeatable);
3743
+ if (Array.isArray(nextVal)) {
3744
+ const subPath = tail.join(".");
3745
+ nextVal.forEach((item, idx) => {
3746
+ if (!item || typeof item !== "object") return;
3747
+ if (isRootLevel && parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) return;
3748
+ if (isRootLevel && parsed.targetComponentUid && item.__component !== parsed.targetComponentUid) return;
3749
+ if (item.__component && isRootLevel) {
3750
+ const scopedAttr = `${head}[${item.__component}].${subPath}`;
3751
+ const supportedBySchema = Array.isArray(availableAttributes) && availableAttributes.includes(scopedAttr);
3752
+ const presentInData = resolveTailExistsOrValue(item, tail) !== void 0;
3753
+ if (!supportedBySchema && !presentInData) {
3754
+ return;
3755
+ }
3756
+ }
3757
+ const seg2 = {
3758
+ key: head,
3759
+ index: idx,
3760
+ componentId: item.id,
3761
+ componentUid: item.__component || (isRootLevel ? attrMeta?.component : void 0)
3762
+ };
3763
+ walk(
3764
+ item,
3765
+ tail,
3766
+ [...segments, seg2],
3767
+ missingIntermediate,
3768
+ firstArrayIndex ?? idx,
3769
+ item.__component || resolvedCompUid,
3770
+ resolvedCompId ?? item.id,
3771
+ false
3772
+ );
3773
+ });
3774
+ return;
3775
+ }
3776
+ if (isExpectingRootArray) {
3777
+ return;
3778
+ }
3779
+ const isMissing = !nextVal || typeof nextVal !== "object";
3780
+ const seg = {
3781
+ key: head,
3782
+ componentId: !isMissing ? nextVal.id : void 0,
3783
+ componentUid: !isMissing && nextVal.__component ? nextVal.__component : void 0
3784
+ };
3785
+ walk(
3786
+ isMissing ? void 0 : nextVal,
3787
+ tail,
3788
+ [...segments, seg],
3789
+ missingIntermediate || isMissing,
3790
+ firstArrayIndex,
3791
+ resolvedCompUid,
3792
+ resolvedCompId,
3793
+ false
3794
+ );
3795
+ }
3796
+ walk(entry, parts, [], false, void 0, void 0, void 0, true);
3797
+ return results;
3380
3798
  }
3381
- function getPropertyValue(target, key) {
3382
- if (!target || typeof target !== "object" || !key) return void 0;
3383
- if (target[key] !== void 0 && target[key] !== null) return target[key];
3384
- const camelKey = key.replace(/_([a-z0-9])/g, (_, letter) => letter.toUpperCase());
3385
- if (target[camelKey] !== void 0 && target[camelKey] !== null) return target[camelKey];
3386
- const snakeKey = key.replace(/([A-Z])/g, "_$1").toLowerCase();
3387
- if (target[snakeKey] !== void 0 && target[snakeKey] !== null) return target[snakeKey];
3388
- const lowerKey = key.toLowerCase();
3389
- const lowerNoUnderscore = lowerKey.replace(/_/g, "");
3390
- const matchedKey = Object.keys(target).find((k) => {
3391
- const kLower = k.toLowerCase();
3392
- return kLower === lowerKey || kLower.replace(/_/g, "") === lowerNoUnderscore;
3393
- });
3394
- if (matchedKey && target[matchedKey] !== void 0 && target[matchedKey] !== null) {
3395
- return target[matchedKey];
3799
+ function normalizeDisplayCompareValue(v) {
3800
+ if (v === void 0 || v === null) return null;
3801
+ if (typeof v === "object" && v.isRelation) return v;
3802
+ return v;
3803
+ }
3804
+ function areClientValuesEqual(a, b) {
3805
+ const na = normalizeDisplayCompareValue(a);
3806
+ const nb = normalizeDisplayCompareValue(b);
3807
+ if (na === nb) return true;
3808
+ if (na === null || nb === null) return na === nb;
3809
+ if (typeof na === "object" || typeof nb === "object") {
3810
+ try {
3811
+ return JSON.stringify(na) === JSON.stringify(nb);
3812
+ } catch {
3813
+ return false;
3814
+ }
3396
3815
  }
3397
- if (key in target) return target[key];
3398
- if (camelKey in target) return target[camelKey];
3399
- if (snakeKey in target) return target[snakeKey];
3400
- return void 0;
3816
+ return String(na) === String(nb);
3401
3817
  }
3402
- function getNestedValue(obj, path) {
3403
- if (!obj || !path) return void 0;
3404
- const parsed = parseDynamicZonePath(path);
3405
- const parts = parsed.cleanPath.split(".");
3406
- function extract(current, remainingParts) {
3407
- if (current === void 0 || current === null) return void 0;
3408
- if (remainingParts.length === 0) return current;
3409
- const [head, ...tail] = remainingParts;
3410
- if (Array.isArray(current)) {
3411
- if (/^\d+$/.test(head)) {
3412
- return extract(current[parseInt(head, 10)], tail);
3413
- }
3414
- for (let idx = 0; idx < current.length; idx++) {
3415
- const item = current[idx];
3416
- if (parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) continue;
3417
- if (parsed.targetComponentUid && item?.__component !== parsed.targetComponentUid) continue;
3418
- const found = extract(getPropertyValue(item, head), tail);
3419
- if (found !== void 0 && found !== null) return found;
3818
+ function extractRelationEditCommand(rawVal, currentDisplayVal, isMulti = false) {
3819
+ if (rawVal && typeof rawVal === "object" && !Array.isArray(rawVal) && rawVal.mode) {
3820
+ return {
3821
+ mode: rawVal.mode,
3822
+ documentIds: Array.isArray(rawVal.documentIds) ? rawVal.documentIds : rawVal.documentId ? [rawVal.documentId] : [],
3823
+ label: rawVal.label || ""
3824
+ };
3825
+ }
3826
+ if (Array.isArray(rawVal)) {
3827
+ return {
3828
+ mode: "set",
3829
+ documentIds: rawVal.map((r) => r?.documentId).filter(Boolean),
3830
+ label: rawVal.map((r) => r?.name || r?.title || r?.email || r?.documentId).filter(Boolean).join(", ")
3831
+ };
3832
+ }
3833
+ if (rawVal && typeof rawVal === "object" && rawVal.documentId) {
3834
+ return {
3835
+ mode: "set",
3836
+ documentIds: [rawVal.documentId],
3837
+ label: rawVal.name || rawVal.title || rawVal.email || rawVal.documentId
3838
+ };
3839
+ }
3840
+ if (typeof rawVal === "string") {
3841
+ try {
3842
+ const parsed = JSON.parse(rawVal);
3843
+ if (parsed && typeof parsed === "object" && parsed.mode) {
3844
+ return {
3845
+ mode: parsed.mode,
3846
+ documentIds: Array.isArray(parsed.documentIds) ? parsed.documentIds : [],
3847
+ label: parsed.label || ""
3848
+ };
3420
3849
  }
3421
- return void 0;
3850
+ } catch {
3422
3851
  }
3423
- return extract(getPropertyValue(current, head), tail);
3424
3852
  }
3425
- return extract(obj, parts);
3853
+ if (currentDisplayVal) {
3854
+ return extractRelationEditCommand(currentDisplayVal, void 0, isMulti);
3855
+ }
3856
+ return { mode: "clear", documentIds: [], label: "" };
3426
3857
  }
3427
- function getAvailableColumnsForCollection(col, selectedAttribute, searchAttribute) {
3428
- const cols = [
3429
- {
3430
- key: "select",
3431
- label: "Select",
3432
- isPermanent: true,
3433
- defaultVisible: true
3434
- },
3435
- {
3436
- key: "identifier",
3437
- label: "Identifier",
3438
- sortable: !col.isSingleType,
3439
- defaultVisible: true
3858
+ function validateClientFieldValue(value, attrMeta) {
3859
+ if (!attrMeta) return null;
3860
+ const type = String(attrMeta.type || "").toLowerCase();
3861
+ const isEmpty = value === null || value === void 0 || value === "";
3862
+ if (attrMeta.required && isEmpty && type !== "boolean") {
3863
+ return "Required field";
3864
+ }
3865
+ if (attrMeta.required && type === "boolean" && (value === null || value === void 0 || value === "")) {
3866
+ return "Required boolean";
3867
+ }
3868
+ if (isEmpty) return null;
3869
+ switch (type) {
3870
+ case "integer":
3871
+ case "biginteger": {
3872
+ const s = String(value).trim();
3873
+ if (!/^-?\d+$/.test(s)) return "Must be a valid integer";
3874
+ if (type === "integer") {
3875
+ const n = Number(s);
3876
+ if (!Number.isSafeInteger(n)) return "Integer out of range";
3877
+ if (typeof attrMeta.min === "number" && n < attrMeta.min) return `Min ${attrMeta.min}`;
3878
+ if (typeof attrMeta.max === "number" && n > attrMeta.max) return `Max ${attrMeta.max}`;
3879
+ }
3880
+ return null;
3440
3881
  }
3441
- ];
3442
- const candidateAttrs = col.attributes || [];
3443
- candidateAttrs.forEach((attr) => {
3444
- if (attr === "name" || attr === "title" || attr === selectedAttribute || searchAttribute && attr === searchAttribute) {
3445
- return;
3882
+ case "float":
3883
+ case "decimal": {
3884
+ const s = String(value).trim();
3885
+ if (!/^-?\d+(\.\d+)?$/.test(s)) return "Must be a valid number";
3886
+ const n = Number(s);
3887
+ if (typeof attrMeta.min === "number" && n < attrMeta.min) return `Min ${attrMeta.min}`;
3888
+ if (typeof attrMeta.max === "number" && n > attrMeta.max) return `Max ${attrMeta.max}`;
3889
+ return null;
3446
3890
  }
3447
- let formattedLabel = attr;
3448
- if (attr === "updated_at" || attr === "updatedAt") {
3449
- formattedLabel = "Updated At";
3450
- } else if (attr === "created_at" || attr === "createdAt") {
3451
- formattedLabel = "Created At";
3452
- } else if (attr === "published_at" || attr === "publishedAt") {
3453
- formattedLabel = "Published At";
3454
- } else {
3455
- const bracketMatch = attr.match(/^([^.[]+)\[([^\]]+)\]\.(.+)$/);
3891
+ case "boolean": {
3892
+ if (typeof value === "boolean") return null;
3893
+ const lower = String(value).trim().toLowerCase();
3894
+ if (!["true", "false", "1", "0"].includes(lower)) return "Must be true or false";
3895
+ return null;
3896
+ }
3897
+ case "enumeration": {
3898
+ if (Array.isArray(attrMeta.enumOptions) && !attrMeta.enumOptions.includes(String(value))) {
3899
+ return `Must be one of: ${attrMeta.enumOptions.join(", ")}`;
3900
+ }
3901
+ return null;
3902
+ }
3903
+ case "email": {
3904
+ const s = String(value).trim();
3905
+ if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(s)) return "Invalid email";
3906
+ return null;
3907
+ }
3908
+ case "uid": {
3909
+ const s = String(value).trim();
3910
+ if (!/^[A-Za-z0-9\-_.~]*$/.test(s)) return "Invalid UID format";
3911
+ return null;
3912
+ }
3913
+ case "json":
3914
+ case "blocks": {
3915
+ if (typeof value === "string") {
3916
+ try {
3917
+ const parsed = JSON.parse(value);
3918
+ if (type === "blocks" && parsed !== null && !Array.isArray(parsed)) {
3919
+ return "Blocks must be a JSON array";
3920
+ }
3921
+ } catch (err) {
3922
+ return `Invalid JSON: ${err.message}`;
3923
+ }
3924
+ } else if (type === "blocks" && !Array.isArray(value)) {
3925
+ return "Blocks must be an array";
3926
+ }
3927
+ return null;
3928
+ }
3929
+ case "date":
3930
+ case "datetime": {
3931
+ const d = new Date(String(value).trim());
3932
+ if (isNaN(d.getTime())) return "Invalid date/datetime";
3933
+ return null;
3934
+ }
3935
+ case "time": {
3936
+ if (!/^\d{2}:\d{2}(:\d{2}(\.\d{1,3})?)?$/.test(String(value).trim())) {
3937
+ return "Invalid time (HH:mm or HH:mm:ss)";
3938
+ }
3939
+ return null;
3940
+ }
3941
+ default: {
3942
+ const str = typeof value === "object" ? JSON.stringify(value) : String(value);
3943
+ if (typeof attrMeta.minLength === "number" && str.length < attrMeta.minLength) {
3944
+ return `Min length ${attrMeta.minLength}`;
3945
+ }
3946
+ if (typeof attrMeta.maxLength === "number" && str.length > attrMeta.maxLength) {
3947
+ return `Max length ${attrMeta.maxLength}`;
3948
+ }
3949
+ if (attrMeta.regex) {
3950
+ try {
3951
+ if (!new RegExp(attrMeta.regex).test(str)) return `Must match /${attrMeta.regex}/`;
3952
+ } catch {
3953
+ }
3954
+ }
3955
+ return null;
3956
+ }
3957
+ }
3958
+ }
3959
+ function cleanRuleKey(str) {
3960
+ return (str || "").replace(/[-_]/g, "").toLowerCase().trim();
3961
+ }
3962
+ function matchesFieldRulePath(attrPath, targetField) {
3963
+ if (!attrPath || !targetField) return false;
3964
+ const cleanAttr = parseAttrPathClient(attrPath).cleanPath;
3965
+ const parts = cleanAttr.split(".").map(cleanRuleKey).filter(Boolean);
3966
+ const leaf = parts[parts.length - 1] || "";
3967
+ const targetClean = cleanRuleKey(targetField.replace(/^api::/i, ""));
3968
+ if (leaf === targetClean || cleanRuleKey(cleanAttr) === targetClean) return true;
3969
+ const tSegs = targetField.replace(/^api::/i, "").split(".").map(cleanRuleKey).filter(Boolean);
3970
+ if (tSegs.length === 1) return leaf === tSegs[0];
3971
+ return tSegs.every((t) => t === "*" || parts.includes(t));
3972
+ }
3973
+ function computeRecordQuotaUsage(entry, attrPath, excludeOccurrenceKey, recordEdits, colAttributes, attrMeta, validationRules) {
3974
+ const occs = enumerateClientOccurrences(entry, attrPath, colAttributes, attrMeta);
3975
+ const usageCounts = {};
3976
+ for (const occ of occs) {
3977
+ if (occ.occurrenceKey === excludeOccurrenceKey) continue;
3978
+ const edited = recordEdits?.occurrences?.[occ.occurrenceKey];
3979
+ const effectiveVal = edited ? edited.value : occ.value;
3980
+ if (effectiveVal !== void 0 && effectiveVal !== null && String(effectiveVal).trim() !== "") {
3981
+ const k = String(effectiveVal).toLowerCase().trim();
3982
+ usageCounts[k] = (usageCounts[k] || 0) + 1;
3983
+ }
3984
+ }
3985
+ const quotas = {};
3986
+ if (attrMeta?.options?.items) {
3987
+ for (const item of attrMeta.options.items) {
3988
+ if (typeof item.maxAllowed === "number" && item.maxAllowed > 0) {
3989
+ quotas[item.value.toLowerCase().trim()] = item.maxAllowed;
3990
+ }
3991
+ }
3992
+ }
3993
+ if (attrMeta?.options?.quotas) {
3994
+ for (const [k, v] of Object.entries(attrMeta.options.quotas)) {
3995
+ if (typeof v === "number" && v > 0) quotas[k.toLowerCase().trim()] = v;
3996
+ }
3997
+ }
3998
+ for (const rule of validationRules || []) {
3999
+ if (!rule.enabled) continue;
4000
+ if (rule.targetField && !matchesFieldRulePath(attrPath, rule.targetField)) continue;
4001
+ for (const [k, v] of Object.entries(rule.quotas || {})) {
4002
+ if (typeof v === "number" && v > 0) quotas[k.toLowerCase().trim()] = v;
4003
+ }
4004
+ }
4005
+ return { usageCounts, quotas };
4006
+ }
4007
+ function serializeGridTargets(gridEdits, selectedEntries, collectionPages = {}, attrMeta) {
4008
+ const targets = [];
4009
+ let totalEditCount = 0;
4010
+ let hasValidationErrors = false;
4011
+ for (const [key, rec] of Object.entries(gridEdits)) {
4012
+ if (!selectedEntries[key]) continue;
4013
+ const occEntries = Object.values(rec.occurrences || {});
4014
+ if (occEntries.length === 0) continue;
4015
+ for (const occ of occEntries) {
4016
+ if (occ.validationError) {
4017
+ hasValidationErrors = true;
4018
+ }
4019
+ }
4020
+ const colPage = collectionPages[rec.uid];
4021
+ const cachedEntry = colPage?.entries?.find((e) => e.documentId === rec.documentId);
4022
+ const targetObj = {
4023
+ uid: rec.uid,
4024
+ documentId: rec.documentId,
4025
+ status: cachedEntry?.status ?? rec.status,
4026
+ publishedAt: cachedEntry?.publishedAt ?? rec.publishedAt,
4027
+ locale: cachedEntry?.locale ?? rec.locale
4028
+ };
4029
+ const isScalarOnly = occEntries.length === 1 && occEntries[0].occurrenceKey === "__scalar__" && !attrMeta?.rootType;
4030
+ if (isScalarOnly) {
4031
+ targetObj.overrideValue = occEntries[0].value;
4032
+ totalEditCount += 1;
4033
+ } else {
4034
+ targetObj.occurrenceUpdates = occEntries.map((occ) => ({
4035
+ occurrenceKey: occ.occurrenceKey,
4036
+ segments: occ.segments,
4037
+ dynamicZoneIndex: occ.segments?.[0]?.index,
4038
+ componentId: occ.segments?.find((s) => s.componentId !== void 0)?.componentId,
4039
+ componentUid: occ.segments?.find((s) => s.componentUid)?.componentUid,
4040
+ value: occ.value
4041
+ }));
4042
+ totalEditCount += occEntries.length;
4043
+ }
4044
+ targets.push(targetObj);
4045
+ }
4046
+ return { targets, totalEditCount, hasValidationErrors };
4047
+ }
4048
+ const DEFAULT_HEADING_ITEMS = [
4049
+ { value: "h1", label: "H1 - Main Page Title", maxAllowed: 1 },
4050
+ { value: "h2", label: "H2 - Primary Section Heading", maxAllowed: 3 },
4051
+ { value: "h3", label: "H3 - Sub-section Heading", maxAllowed: null },
4052
+ { value: "h4", label: "H4 - Component Title", maxAllowed: null },
4053
+ { value: "h5", label: "H5 - Card / Item Heading", maxAllowed: null },
4054
+ { value: "h6", label: "H6 - Minor Heading", maxAllowed: null }
4055
+ ];
4056
+ function toTextInputString(val, type) {
4057
+ if (val === null || val === void 0) return "";
4058
+ if (type === "date" && typeof val === "string") {
4059
+ return val.slice(0, 10);
4060
+ }
4061
+ if (type === "datetime" && typeof val === "string") {
4062
+ const d = new Date(val);
4063
+ if (!isNaN(d.getTime())) {
4064
+ const pad = (n) => String(n).padStart(2, "0");
4065
+ return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
4066
+ }
4067
+ return val.slice(0, 16);
4068
+ }
4069
+ if (type === "time" && typeof val === "string") {
4070
+ return val.slice(0, 8);
4071
+ }
4072
+ if (typeof val === "object") {
4073
+ try {
4074
+ return JSON.stringify(val);
4075
+ } catch {
4076
+ return String(val);
4077
+ }
4078
+ }
4079
+ return String(val);
4080
+ }
4081
+ const GridCellEditor = React__default.default.memo(
4082
+ ({
4083
+ entry,
4084
+ attribute,
4085
+ occurrence,
4086
+ attrMeta,
4087
+ editedValue,
4088
+ isDirty,
4089
+ validationError,
4090
+ relationOptions = [],
4091
+ relationOptionsLoading = false,
4092
+ relationIsMulti = false,
4093
+ validationRules = [],
4094
+ recordEdits,
4095
+ colAttributes,
4096
+ compact = false,
4097
+ onCommit,
4098
+ onReset
4099
+ }) => {
4100
+ const { get } = admin.useFetchClient();
4101
+ const fieldType = String(attrMeta?.type || "").toLowerCase();
4102
+ const isScopedSelect = attrMeta?.customField === "plugin::bulk-updater.scoped-select" || attrMeta?.customField === "global::scoped-select";
4103
+ const isRelation = Boolean(attrMeta?.isRelation || fieldType === "relation");
4104
+ const isMultiRelation = isRelation && Boolean(relationIsMulti || ["oneToMany", "manyToMany"].includes(attrMeta?.relationType || ""));
4105
+ const effectiveValue = isDirty ? editedValue : occurrence.value;
4106
+ const [localText, setLocalText] = React.useState(() => toTextInputString(effectiveValue, fieldType));
4107
+ const [showRichModal, setShowRichModal] = React.useState(false);
4108
+ const [richDraft, setRichDraft] = React.useState("");
4109
+ const [richError, setRichError] = React.useState(null);
4110
+ const [showMultiRelModal, setShowMultiRelModal] = React.useState(false);
4111
+ const [multiRelSelected, setMultiRelSelected] = React.useState([]);
4112
+ const [multiRelMode, setMultiRelMode] = React.useState("set");
4113
+ const [multiRelSearch, setMultiRelSearch] = React.useState("");
4114
+ const [showMediaModal, setShowMediaModal] = React.useState(false);
4115
+ const [mediaOptions, setMediaOptions] = React.useState([]);
4116
+ const [mediaSearch, setMediaSearch] = React.useState("");
4117
+ const [mediaLoading, setMediaLoading] = React.useState(false);
4118
+ const [selectedMediaIds, setSelectedMediaIds] = React.useState([]);
4119
+ React.useEffect(() => {
4120
+ setLocalText(toTextInputString(effectiveValue, fieldType));
4121
+ }, [effectiveValue, fieldType, occurrence.occurrenceKey]);
4122
+ const commitTypedValue = (rawVal) => {
4123
+ if (areClientValuesEqual(rawVal, occurrence.value)) {
4124
+ onReset(occurrence.occurrenceKey);
4125
+ return;
4126
+ }
4127
+ const err = validateClientFieldValue(rawVal, attrMeta);
4128
+ onCommit(occurrence, rawVal, err);
4129
+ };
4130
+ const loadMediaLibrary = async (query = "") => {
4131
+ try {
4132
+ setMediaLoading(true);
4133
+ const res = await get(`/bulk-updater/media-options?search=${encodeURIComponent(query)}`);
4134
+ if (res.data?.success && Array.isArray(res.data.options)) {
4135
+ setMediaOptions(res.data.options);
4136
+ }
4137
+ } catch {
4138
+ setMediaOptions([]);
4139
+ } finally {
4140
+ setMediaLoading(false);
4141
+ }
4142
+ };
4143
+ const quotaContext = React.useMemo(() => {
4144
+ if (!isScopedSelect) return null;
4145
+ return computeRecordQuotaUsage(
4146
+ entry,
4147
+ attribute,
4148
+ occurrence.occurrenceKey,
4149
+ recordEdits,
4150
+ colAttributes,
4151
+ attrMeta,
4152
+ validationRules
4153
+ );
4154
+ }, [isScopedSelect, entry, attribute, occurrence.occurrenceKey, recordEdits, colAttributes, attrMeta, validationRules]);
4155
+ const scopedItems = React.useMemo(() => {
4156
+ if (!isScopedSelect) return [];
4157
+ const base = attrMeta?.options?.items && attrMeta.options.items.length > 0 ? attrMeta.options.items : DEFAULT_HEADING_ITEMS;
4158
+ const quotas = quotaContext?.quotas || {};
4159
+ return base.map((it) => {
4160
+ const key = it.value.toLowerCase().trim();
4161
+ const maxAllowed = typeof quotas[key] === "number" ? quotas[key] : it.maxAllowed;
4162
+ const usedBySiblings = quotaContext?.usageCounts?.[key] || 0;
4163
+ return {
4164
+ ...it,
4165
+ maxAllowed,
4166
+ usedBySiblings,
4167
+ atLimit: typeof maxAllowed === "number" && maxAllowed > 0 && usedBySiblings >= maxAllowed
4168
+ };
4169
+ });
4170
+ }, [isScopedSelect, attrMeta, quotaContext]);
4171
+ const wrapperStyle = {
4172
+ borderLeft: isDirty ? "3px solid #4945ff" : "3px solid transparent",
4173
+ paddingLeft: 6,
4174
+ backgroundColor: validationError ? "rgba(208, 43, 32, 0.06)" : isDirty ? "rgba(73, 69, 255, 0.05)" : "transparent",
4175
+ borderRadius: 4,
4176
+ minWidth: compact ? 180 : 210,
4177
+ maxWidth: 320
4178
+ };
4179
+ const renderResetBtn = () => isDirty ? /* @__PURE__ */ jsxRuntime.jsx(
4180
+ designSystem.Button,
4181
+ {
4182
+ variant: "ghost",
4183
+ size: "S",
4184
+ onClick: () => onReset(occurrence.occurrenceKey),
4185
+ title: "Revert this cell back to original database value",
4186
+ style: { padding: "4px 6px", minWidth: 28, height: 28 },
4187
+ children: /* @__PURE__ */ jsxRuntime.jsx(icons.ArrowClockwise, {})
4188
+ }
4189
+ ) : null;
4190
+ if (isScopedSelect) {
4191
+ const currentValStr = effectiveValue !== null && effectiveValue !== void 0 ? String(effectiveValue) : "__clear__";
4192
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: wrapperStyle, children: [
4193
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", children: [
4194
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1, minWidth: 145 }, children: /* @__PURE__ */ jsxRuntime.jsxs(
4195
+ designSystem.SingleSelect,
4196
+ {
4197
+ size: "S",
4198
+ "aria-label": `Edit ${occurrence.displayPath}`,
4199
+ value: currentValStr,
4200
+ onChange: (val) => {
4201
+ const s = String(val);
4202
+ commitTypedValue(s === "__clear__" ? null : s);
4203
+ },
4204
+ children: [
4205
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "__clear__", children: "-- Unset --" }),
4206
+ scopedItems.map((it) => {
4207
+ const isCurrentlySelected = currentValStr.toLowerCase() === it.value.toLowerCase();
4208
+ const quotaNote = typeof it.maxAllowed === "number" && it.maxAllowed > 0 ? ` (${it.usedBySiblings + (isCurrentlySelected ? 1 : 0)}/${it.maxAllowed})` : "";
4209
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.SingleSelectOption, { value: it.value, children: [
4210
+ it.label,
4211
+ quotaNote,
4212
+ it.atLimit && !isCurrentlySelected ? " [QUOTA FULL]" : ""
4213
+ ] }, it.value);
4214
+ })
4215
+ ]
4216
+ }
4217
+ ) }),
4218
+ renderResetBtn()
4219
+ ] }),
4220
+ validationError && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", display: "block", style: { fontSize: "0.7rem", marginTop: 2 }, children: validationError })
4221
+ ] });
4222
+ }
4223
+ if (fieldType === "enumeration" && Array.isArray(attrMeta?.enumOptions)) {
4224
+ const currentValStr = effectiveValue !== null && effectiveValue !== void 0 && effectiveValue !== "" ? String(effectiveValue) : "__clear__";
4225
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: wrapperStyle, children: [
4226
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", children: [
4227
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1, minWidth: 145 }, children: /* @__PURE__ */ jsxRuntime.jsxs(
4228
+ designSystem.SingleSelect,
4229
+ {
4230
+ size: "S",
4231
+ "aria-label": `Edit ${occurrence.displayPath}`,
4232
+ value: currentValStr,
4233
+ onChange: (val) => {
4234
+ const s = String(val);
4235
+ commitTypedValue(s === "__clear__" ? null : s);
4236
+ },
4237
+ children: [
4238
+ !attrMeta.required && /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "__clear__", children: "-- Clear (null) --" }),
4239
+ attrMeta.enumOptions.map((opt) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: opt, children: opt }, opt))
4240
+ ]
4241
+ }
4242
+ ) }),
4243
+ renderResetBtn()
4244
+ ] }),
4245
+ validationError && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", display: "block", style: { fontSize: "0.7rem" }, children: validationError })
4246
+ ] });
4247
+ }
4248
+ if (fieldType === "boolean") {
4249
+ const strVal = effectiveValue === true ? "true" : effectiveValue === false ? "false" : "__unset__";
4250
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: wrapperStyle, children: [
4251
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", children: [
4252
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1, minWidth: 120 }, children: /* @__PURE__ */ jsxRuntime.jsxs(
4253
+ designSystem.SingleSelect,
4254
+ {
4255
+ size: "S",
4256
+ "aria-label": `Edit ${occurrence.displayPath}`,
4257
+ value: strVal,
4258
+ onChange: (val) => {
4259
+ const s = String(val);
4260
+ commitTypedValue(s === "true" ? true : s === "false" ? false : null);
4261
+ },
4262
+ children: [
4263
+ !attrMeta?.required && /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "__unset__", children: "-- Unset --" }),
4264
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "true", children: "true" }),
4265
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "false", children: "false" })
4266
+ ]
4267
+ }
4268
+ ) }),
4269
+ renderResetBtn()
4270
+ ] }),
4271
+ validationError && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", display: "block", style: { fontSize: "0.7rem" }, children: validationError })
4272
+ ] });
4273
+ }
4274
+ if (isRelation) {
4275
+ const cmd = extractRelationEditCommand(effectiveValue, occurrence.value, isMultiRelation);
4276
+ if (!isMultiRelation) {
4277
+ const selectedDocId = cmd.mode === "clear" ? "__clear__" : cmd.documentIds[0] || "__clear__";
4278
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: wrapperStyle, children: [
4279
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", children: [
4280
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1, minWidth: 165 }, children: /* @__PURE__ */ jsxRuntime.jsxs(
4281
+ designSystem.Combobox,
4282
+ {
4283
+ autocomplete: { type: "list", filter: "contains" },
4284
+ placeholder: relationOptionsLoading ? "Loading..." : "Pick relation...",
4285
+ value: selectedDocId,
4286
+ onChange: (val) => {
4287
+ const docId = val ? String(val) : "__clear__";
4288
+ if (docId === "__clear__") {
4289
+ commitTypedValue({ mode: "clear", documentIds: [], label: "(cleared / unlinked)" });
4290
+ } else {
4291
+ const opt = relationOptions.find((o) => o.documentId === docId);
4292
+ commitTypedValue({ mode: "set", documentIds: [docId], label: opt?.label || docId });
4293
+ }
4294
+ },
4295
+ children: [
4296
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.ComboboxOption, { value: "__clear__", textValue: "Clear / Unlink Relation", children: "-- Clear / Unlink --" }),
4297
+ relationOptions.map((opt) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.ComboboxOption, { value: opt.documentId, textValue: opt.label, children: opt.label }, opt.documentId))
4298
+ ]
4299
+ }
4300
+ ) }),
4301
+ renderResetBtn()
4302
+ ] }),
4303
+ validationError && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", display: "block", style: { fontSize: "0.7rem" }, children: validationError })
4304
+ ] });
4305
+ }
4306
+ const displaySummary = cmd.mode === "clear" ? "(cleared / empty)" : cmd.label || (cmd.documentIds.length > 0 ? `${cmd.documentIds.length} linked (${cmd.mode})` : "(unlinked)");
4307
+ const filteredRelOpts = relationOptions.filter(
4308
+ (o) => !multiRelSearch.trim() || o.label.toLowerCase().includes(multiRelSearch.toLowerCase())
4309
+ );
4310
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: wrapperStyle, children: [
4311
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", children: [
4312
+ /* @__PURE__ */ jsxRuntime.jsx(
4313
+ designSystem.Button,
4314
+ {
4315
+ variant: "tertiary",
4316
+ size: "S",
4317
+ onClick: () => {
4318
+ setMultiRelSelected(cmd.documentIds || []);
4319
+ setMultiRelMode(cmd.mode === "clear" && (cmd.documentIds || []).length === 0 ? "set" : cmd.mode);
4320
+ setMultiRelSearch("");
4321
+ setShowMultiRelModal(true);
4322
+ },
4323
+ style: { maxWidth: 230, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
4324
+ children: displaySummary
4325
+ }
4326
+ ),
4327
+ renderResetBtn()
4328
+ ] }),
4329
+ showMultiRelModal && /* @__PURE__ */ jsxRuntime.jsx(
4330
+ "div",
4331
+ {
4332
+ style: {
4333
+ position: "fixed",
4334
+ inset: 0,
4335
+ backgroundColor: "rgba(20, 20, 30, 0.55)",
4336
+ zIndex: 9999,
4337
+ display: "flex",
4338
+ alignItems: "center",
4339
+ justifyContent: "center",
4340
+ padding: 16
4341
+ },
4342
+ onClick: () => setShowMultiRelModal(false),
4343
+ children: /* @__PURE__ */ jsxRuntime.jsxs(
4344
+ designSystem.Box,
4345
+ {
4346
+ padding: 5,
4347
+ background: "neutral0",
4348
+ hasRadius: true,
4349
+ shadow: "popupShadow",
4350
+ style: { width: "92%", maxWidth: 520, maxHeight: "80vh", display: "flex", flexDirection: "column" },
4351
+ onClick: (e) => e.stopPropagation(),
4352
+ children: [
4353
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "delta", fontWeight: "bold", marginBottom: 2, children: [
4354
+ "Edit Multi-Relation: ",
4355
+ occurrence.displayPath
4356
+ ] }),
4357
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, marginBottom: 3, alignItems: "center", children: [
4358
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { width: 180 }, children: /* @__PURE__ */ jsxRuntime.jsxs(
4359
+ designSystem.SingleSelect,
4360
+ {
4361
+ label: "Operation",
4362
+ value: multiRelMode,
4363
+ onChange: (v) => setMultiRelMode(String(v)),
4364
+ children: [
4365
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "set", children: "Set / Replace All" }),
4366
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "connect", children: "Add / Connect" }),
4367
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "disconnect", children: "Remove / Disconnect" }),
4368
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.SingleSelectOption, { value: "clear", children: "Clear All" })
4369
+ ]
4370
+ }
4371
+ ) }),
4372
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1 }, children: /* @__PURE__ */ jsxRuntime.jsx(
4373
+ designSystem.TextInput,
4374
+ {
4375
+ label: "Filter items",
4376
+ placeholder: "Search relations...",
4377
+ value: multiRelSearch,
4378
+ onChange: (e) => setMultiRelSearch(e.target.value)
4379
+ }
4380
+ ) })
4381
+ ] }),
4382
+ multiRelMode !== "clear" && /* @__PURE__ */ jsxRuntime.jsx(
4383
+ designSystem.Box,
4384
+ {
4385
+ padding: 2,
4386
+ hasRadius: true,
4387
+ style: { border: "1px solid #eaeaef", overflowY: "auto", maxHeight: 280, marginBottom: 16 },
4388
+ children: filteredRelOpts.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: "No target entities found." }) : filteredRelOpts.map((opt) => {
4389
+ const checked = multiRelSelected.includes(opt.documentId);
4390
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { padding: 1, children: /* @__PURE__ */ jsxRuntime.jsx(
4391
+ designSystem.Checkbox,
4392
+ {
4393
+ checked,
4394
+ onCheckedChange: (isChecked) => {
4395
+ setMultiRelSelected(
4396
+ (prev) => isChecked ? [...prev, opt.documentId] : prev.filter((id) => id !== opt.documentId)
4397
+ );
4398
+ },
4399
+ children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", children: opt.label })
4400
+ }
4401
+ ) }, opt.documentId);
4402
+ })
4403
+ }
4404
+ ),
4405
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "flex-end", gap: 2, children: [
4406
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", onClick: () => setShowMultiRelModal(false), children: "Cancel" }),
4407
+ /* @__PURE__ */ jsxRuntime.jsx(
4408
+ designSystem.Button,
4409
+ {
4410
+ variant: "default",
4411
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Check, {}),
4412
+ onClick: () => {
4413
+ if (multiRelMode === "clear") {
4414
+ commitTypedValue({ mode: "clear", documentIds: [], label: "(cleared / unlinked)" });
4415
+ } else {
4416
+ const labels = relationOptions.filter((o) => multiRelSelected.includes(o.documentId)).map((o) => o.label).join(", ");
4417
+ commitTypedValue({
4418
+ mode: multiRelMode,
4419
+ documentIds: multiRelSelected,
4420
+ label: labels || `${multiRelSelected.length} selected`
4421
+ });
4422
+ }
4423
+ setShowMultiRelModal(false);
4424
+ },
4425
+ children: "Apply Relation Edit"
4426
+ }
4427
+ )
4428
+ ] })
4429
+ ]
4430
+ }
4431
+ )
4432
+ }
4433
+ )
4434
+ ] });
4435
+ }
4436
+ if (fieldType === "media") {
4437
+ const isMultiMedia = Boolean(attrMeta?.multiple);
4438
+ const currentIds = Array.isArray(effectiveValue) ? effectiveValue.map((v) => typeof v === "object" ? Number(v?.id) : Number(v)).filter((n) => !isNaN(n)) : typeof effectiveValue === "object" && effectiveValue?.id ? [Number(effectiveValue.id)] : typeof effectiveValue === "number" ? [effectiveValue] : [];
4439
+ const mediaSummary = currentIds.length === 0 ? "(no media — pick)" : Array.isArray(effectiveValue) ? `${currentIds.length} asset(s)` : effectiveValue?.name ? `${effectiveValue.name} (#${currentIds[0]})` : `Media #${currentIds[0]}`;
4440
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: wrapperStyle, children: [
4441
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", children: [
4442
+ /* @__PURE__ */ jsxRuntime.jsx(
4443
+ designSystem.Button,
4444
+ {
4445
+ variant: "tertiary",
4446
+ size: "S",
4447
+ onClick: () => {
4448
+ setSelectedMediaIds(currentIds);
4449
+ setMediaSearch("");
4450
+ setShowMediaModal(true);
4451
+ loadMediaLibrary("");
4452
+ },
4453
+ style: { maxWidth: 220, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
4454
+ children: mediaSummary
4455
+ }
4456
+ ),
4457
+ renderResetBtn()
4458
+ ] }),
4459
+ showMediaModal && /* @__PURE__ */ jsxRuntime.jsx(
4460
+ "div",
4461
+ {
4462
+ style: {
4463
+ position: "fixed",
4464
+ inset: 0,
4465
+ backgroundColor: "rgba(20, 20, 30, 0.55)",
4466
+ zIndex: 9999,
4467
+ display: "flex",
4468
+ alignItems: "center",
4469
+ justifyContent: "center",
4470
+ padding: 16
4471
+ },
4472
+ onClick: () => setShowMediaModal(false),
4473
+ children: /* @__PURE__ */ jsxRuntime.jsxs(
4474
+ designSystem.Box,
4475
+ {
4476
+ padding: 5,
4477
+ background: "neutral0",
4478
+ hasRadius: true,
4479
+ shadow: "popupShadow",
4480
+ style: { width: "92%", maxWidth: 620, maxHeight: "82vh", display: "flex", flexDirection: "column" },
4481
+ onClick: (e) => e.stopPropagation(),
4482
+ children: [
4483
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "delta", fontWeight: "bold", marginBottom: 3, children: [
4484
+ "Select Media Asset",
4485
+ isMultiMedia ? "s" : "",
4486
+ ": ",
4487
+ occurrence.displayPath
4488
+ ] }),
4489
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, marginBottom: 3, children: [
4490
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1 }, children: /* @__PURE__ */ jsxRuntime.jsx(
4491
+ designSystem.TextInput,
4492
+ {
4493
+ placeholder: "Search media filename or MIME...",
4494
+ value: mediaSearch,
4495
+ onChange: (e) => setMediaSearch(e.target.value)
4496
+ }
4497
+ ) }),
4498
+ /* @__PURE__ */ jsxRuntime.jsx(
4499
+ designSystem.Button,
4500
+ {
4501
+ variant: "secondary",
4502
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Search, {}),
4503
+ onClick: () => loadMediaLibrary(mediaSearch),
4504
+ loading: mediaLoading,
4505
+ children: "Search"
4506
+ }
4507
+ )
4508
+ ] }),
4509
+ /* @__PURE__ */ jsxRuntime.jsx(
4510
+ designSystem.Box,
4511
+ {
4512
+ padding: 2,
4513
+ hasRadius: true,
4514
+ style: { border: "1px solid #eaeaef", overflowY: "auto", maxHeight: 320, marginBottom: 16 },
4515
+ children: mediaLoading ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "center", padding: 4, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Loader, { small: true, children: "Loading Media Library..." }) }) : mediaOptions.length === 0 ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: "No media files matched." }) : mediaOptions.map((file) => {
4516
+ const isChecked = selectedMediaIds.includes(file.id);
4517
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { padding: 2, style: { borderBottom: "1px solid #f0f0f5" }, children: /* @__PURE__ */ jsxRuntime.jsx(
4518
+ designSystem.Checkbox,
4519
+ {
4520
+ checked: isChecked,
4521
+ onCheckedChange: (checked) => {
4522
+ if (isMultiMedia) {
4523
+ setSelectedMediaIds(
4524
+ (prev) => checked ? [...prev, file.id] : prev.filter((id) => id !== file.id)
4525
+ );
4526
+ } else {
4527
+ setSelectedMediaIds(checked ? [file.id] : []);
4528
+ }
4529
+ },
4530
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
4531
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "neutral150", textColor: "neutral700", size: "S", children: [
4532
+ "#",
4533
+ file.id
4534
+ ] }),
4535
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "semiBold", children: file.name }),
4536
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", textColor: "neutral500", children: [
4537
+ "(",
4538
+ file.mime,
4539
+ ")"
4540
+ ] })
4541
+ ] })
4542
+ }
4543
+ ) }, file.id);
4544
+ })
4545
+ }
4546
+ ),
4547
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", gap: 2, children: [
4548
+ /* @__PURE__ */ jsxRuntime.jsx(
4549
+ designSystem.Button,
4550
+ {
4551
+ variant: "danger-light",
4552
+ onClick: () => {
4553
+ commitTypedValue(isMultiMedia ? [] : null);
4554
+ setShowMediaModal(false);
4555
+ },
4556
+ children: "Clear Media"
4557
+ }
4558
+ ),
4559
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, children: [
4560
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", onClick: () => setShowMediaModal(false), children: "Cancel" }),
4561
+ /* @__PURE__ */ jsxRuntime.jsx(
4562
+ designSystem.Button,
4563
+ {
4564
+ variant: "default",
4565
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Check, {}),
4566
+ onClick: () => {
4567
+ commitTypedValue(isMultiMedia ? selectedMediaIds : selectedMediaIds[0] ?? null);
4568
+ setShowMediaModal(false);
4569
+ },
4570
+ children: "Apply Selection"
4571
+ }
4572
+ )
4573
+ ] })
4574
+ ] })
4575
+ ]
4576
+ }
4577
+ )
4578
+ }
4579
+ )
4580
+ ] });
4581
+ }
4582
+ if (fieldType === "richtext" || fieldType === "blocks" || fieldType === "json") {
4583
+ const isJsonOrBlocks = fieldType === "blocks" || fieldType === "json";
4584
+ const displayLabel = effectiveValue === null || effectiveValue === void 0 || effectiveValue === "" ? "(empty — edit)" : typeof effectiveValue === "object" ? JSON.stringify(effectiveValue).slice(0, 32) + (JSON.stringify(effectiveValue).length > 32 ? "…" : "") : String(effectiveValue).slice(0, 32) + (String(effectiveValue).length > 32 ? "…" : "");
4585
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: wrapperStyle, children: [
4586
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", children: [
4587
+ /* @__PURE__ */ jsxRuntime.jsx(
4588
+ designSystem.Button,
4589
+ {
4590
+ variant: "tertiary",
4591
+ size: "S",
4592
+ onClick: () => {
4593
+ const formatted = effectiveValue === null || effectiveValue === void 0 ? "" : typeof effectiveValue === "object" ? JSON.stringify(effectiveValue, null, 2) : String(effectiveValue);
4594
+ setRichDraft(formatted);
4595
+ setRichError(null);
4596
+ setShowRichModal(true);
4597
+ },
4598
+ style: { maxWidth: 230, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
4599
+ children: displayLabel
4600
+ }
4601
+ ),
4602
+ renderResetBtn()
4603
+ ] }),
4604
+ validationError && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", display: "block", style: { fontSize: "0.7rem" }, children: validationError }),
4605
+ showRichModal && /* @__PURE__ */ jsxRuntime.jsx(
4606
+ "div",
4607
+ {
4608
+ style: {
4609
+ position: "fixed",
4610
+ inset: 0,
4611
+ backgroundColor: "rgba(20, 20, 30, 0.55)",
4612
+ zIndex: 9999,
4613
+ display: "flex",
4614
+ alignItems: "center",
4615
+ justifyContent: "center",
4616
+ padding: 16
4617
+ },
4618
+ onClick: () => setShowRichModal(false),
4619
+ children: /* @__PURE__ */ jsxRuntime.jsxs(
4620
+ designSystem.Box,
4621
+ {
4622
+ padding: 5,
4623
+ background: "neutral0",
4624
+ hasRadius: true,
4625
+ shadow: "popupShadow",
4626
+ style: { width: "92%", maxWidth: 640, display: "flex", flexDirection: "column", gap: 12 },
4627
+ onClick: (e) => e.stopPropagation(),
4628
+ children: [
4629
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "delta", fontWeight: "bold", children: [
4630
+ "Edit ",
4631
+ fieldType.toUpperCase(),
4632
+ ": ",
4633
+ occurrence.displayPath
4634
+ ] }),
4635
+ /* @__PURE__ */ jsxRuntime.jsx(
4636
+ designSystem.Textarea,
4637
+ {
4638
+ name: "richDraft",
4639
+ "aria-label": "Rich content editor",
4640
+ value: richDraft,
4641
+ onChange: (e) => {
4642
+ setRichDraft(e.target.value);
4643
+ if (isJsonOrBlocks && e.target.value.trim()) {
4644
+ try {
4645
+ const parsed = JSON.parse(e.target.value);
4646
+ if (fieldType === "blocks" && !Array.isArray(parsed)) {
4647
+ setRichError("Strapi Blocks value must be a JSON array.");
4648
+ } else {
4649
+ setRichError(null);
4650
+ }
4651
+ } catch (err) {
4652
+ setRichError(`Invalid JSON: ${err.message}`);
4653
+ }
4654
+ } else {
4655
+ setRichError(null);
4656
+ }
4657
+ },
4658
+ style: { minHeight: 220, fontFamily: isJsonOrBlocks ? "monospace" : "inherit" }
4659
+ }
4660
+ ),
4661
+ richError && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", fontWeight: "bold", children: richError }),
4662
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", gap: 2, children: [
4663
+ /* @__PURE__ */ jsxRuntime.jsx(
4664
+ designSystem.Button,
4665
+ {
4666
+ variant: "danger-light",
4667
+ onClick: () => {
4668
+ commitTypedValue(isJsonOrBlocks ? null : "");
4669
+ setShowRichModal(false);
4670
+ },
4671
+ children: "Clear Value"
4672
+ }
4673
+ ),
4674
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, children: [
4675
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", onClick: () => setShowRichModal(false), children: "Cancel" }),
4676
+ /* @__PURE__ */ jsxRuntime.jsx(
4677
+ designSystem.Button,
4678
+ {
4679
+ variant: "default",
4680
+ disabled: Boolean(richError),
4681
+ startIcon: /* @__PURE__ */ jsxRuntime.jsx(icons.Check, {}),
4682
+ onClick: () => {
4683
+ if (isJsonOrBlocks) {
4684
+ if (!richDraft.trim()) {
4685
+ commitTypedValue(null);
4686
+ } else {
4687
+ commitTypedValue(JSON.parse(richDraft));
4688
+ }
4689
+ } else {
4690
+ commitTypedValue(richDraft);
4691
+ }
4692
+ setShowRichModal(false);
4693
+ },
4694
+ children: "Apply Edit"
4695
+ }
4696
+ )
4697
+ ] })
4698
+ ] })
4699
+ ]
4700
+ }
4701
+ )
4702
+ }
4703
+ )
4704
+ ] });
4705
+ }
4706
+ if (fieldType === "date" || fieldType === "time" || fieldType === "datetime") {
4707
+ const inputType = fieldType === "datetime" ? "datetime-local" : fieldType;
4708
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: wrapperStyle, children: [
4709
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", children: [
4710
+ /* @__PURE__ */ jsxRuntime.jsx(
4711
+ "input",
4712
+ {
4713
+ type: inputType,
4714
+ "aria-label": `Edit ${occurrence.displayPath}`,
4715
+ value: localText,
4716
+ step: fieldType === "time" ? 1 : void 0,
4717
+ onChange: (e) => {
4718
+ const v = e.target.value;
4719
+ setLocalText(v);
4720
+ commitTypedValue(v === "" ? null : v);
4721
+ },
4722
+ style: {
4723
+ padding: "6px 8px",
4724
+ borderRadius: 4,
4725
+ border: "1px solid #dcdce4",
4726
+ fontSize: "0.85rem",
4727
+ minWidth: 165
4728
+ }
4729
+ }
4730
+ ),
4731
+ renderResetBtn()
4732
+ ] }),
4733
+ validationError && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", display: "block", style: { fontSize: "0.7rem" }, children: validationError })
4734
+ ] });
4735
+ }
4736
+ const isNumeric = ["integer", "biginteger", "float", "decimal", "number"].includes(fieldType);
4737
+ const inputStep = fieldType === "integer" || fieldType === "biginteger" ? "1" : isNumeric ? "any" : void 0;
4738
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: wrapperStyle, children: [
4739
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", children: [
4740
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1, minWidth: 150 }, children: /* @__PURE__ */ jsxRuntime.jsx(
4741
+ designSystem.TextInput,
4742
+ {
4743
+ size: "S",
4744
+ type: isNumeric && fieldType !== "biginteger" ? "number" : "text",
4745
+ step: inputStep,
4746
+ "aria-label": `Edit ${occurrence.displayPath}`,
4747
+ placeholder: occurrence.isMissingIntermediate ? "Click to initialize..." : "(empty)",
4748
+ value: localText,
4749
+ onChange: (e) => {
4750
+ const next = e.target.value;
4751
+ setLocalText(next);
4752
+ commitTypedValue(isNumeric && next === "" ? null : next);
4753
+ }
4754
+ }
4755
+ ) }),
4756
+ renderResetBtn()
4757
+ ] }),
4758
+ validationError && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", display: "block", style: { fontSize: "0.7rem", marginTop: 2 }, children: validationError })
4759
+ ] });
4760
+ }
4761
+ );
4762
+ const ComponentOccurrencesDrawer = React__default.default.memo(
4763
+ ({
4764
+ colUid,
4765
+ rootKey,
4766
+ entry,
4767
+ selectedAttribute,
4768
+ attrMeta,
4769
+ colAttributes,
4770
+ gridEditMode,
4771
+ isSelected,
4772
+ selectedDzBlocks,
4773
+ occurrences,
4774
+ recordEdits,
4775
+ relationOptions,
4776
+ relationOptionsLoading,
4777
+ relationIsMulti,
4778
+ validationRules,
4779
+ onToggleDzBlock,
4780
+ onCommitEdit,
4781
+ onResetEdit
4782
+ }) => {
4783
+ const cleanRootKey = rootKey || (selectedAttribute || "").split("[")[0].split(".")[0];
4784
+ const selectedRootKey = selectedAttribute ? selectedAttribute.split("[")[0].split(".")[0] : "";
4785
+ const targetsThisRoot = Boolean(selectedAttribute && selectedRootKey === cleanRootKey);
4786
+ const blocks = Array.isArray(entry?.[cleanRootKey]) ? entry[cleanRootKey] : [];
4787
+ const isDynamicZone = blocks.some((b) => Boolean(b?.__component));
4788
+ if (blocks.length === 0) return null;
4789
+ const occByRootIndex = /* @__PURE__ */ new Map();
4790
+ occurrences.forEach((occ) => {
4791
+ if (occ.segments?.[0]?.key !== cleanRootKey || occ.segments?.[0]?.index === void 0) return;
4792
+ const rootIdx = occ.segments[0].index;
4793
+ const list = occByRootIndex.get(rootIdx) || [];
4794
+ list.push(occ);
4795
+ occByRootIndex.set(rootIdx, list);
4796
+ });
4797
+ const allApplicableIndexes = blocks.map((_, bIdx) => bIdx).filter((bIdx) => targetsThisRoot ? (occByRootIndex.get(bIdx) || []).length > 0 : true);
4798
+ return /* @__PURE__ */ jsxRuntime.jsxs(
4799
+ designSystem.Box,
4800
+ {
4801
+ padding: 3,
4802
+ background: "neutral0",
4803
+ hasRadius: true,
4804
+ style: { border: "1px solid rgba(73, 69, 255, 0.25)", boxShadow: "0 2px 8px rgba(0,0,0,0.05)" },
4805
+ children: [
4806
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", marginBottom: 2, children: [
4807
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
4808
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "sigma", textColor: "primary700", children: [
4809
+ isDynamicZone ? "DYNAMIC ZONE" : "REPEATABLE COMPONENT",
4810
+ ': "',
4811
+ cleanRootKey,
4812
+ '" (',
4813
+ blocks.length,
4814
+ " ",
4815
+ blocks.length === 1 ? "item" : "items",
4816
+ ")"
4817
+ ] }),
4818
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "primary100", textColor: "primary700", children: gridEditMode ? "Inline Per-Block Grid Editing" : "Selective Block Targeting" })
4819
+ ] }),
4820
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral500", children: gridEditMode ? "Edit each occurrence independently — component IDs & sibling blocks stay intact" : "Selectively choose which blocks to update for this entry" })
4821
+ ] }),
4822
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Table, { colCount: gridEditMode ? 4 : 5, rowCount: blocks.length + 1, style: { width: "100%", background: "#fff" }, children: [
4823
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Thead, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
4824
+ !gridEditMode && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 64 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Update?" }) }),
4825
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 85 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Pos / ID" }) }),
4826
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 210 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Component" }) }),
4827
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "sigma", children: [
4828
+ "Target Field Value (",
4829
+ selectedAttribute || "selected",
4830
+ ")"
4831
+ ] }) }),
4832
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Block Summary" }) })
4833
+ ] }) }),
4834
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tbody, { children: blocks.map((block, bIdx) => {
4835
+ const compUid = block?.__component || attrMeta?.component;
4836
+ const compLabel = formatComponentNameFriendly(compUid);
4837
+ const blockOccs = occByRootIndex.get(bIdx) || [];
4838
+ const hasTargetAttr = blockOccs.length > 0;
4839
+ const isBlockSelectable = targetsThisRoot ? hasTargetAttr : true;
4840
+ const isBlockChecked = !gridEditMode && isBlockSelectable && isSelected && (selectedDzBlocks !== void 0 ? selectedDzBlocks.includes(bIdx) : true);
4841
+ const hasDirtyOcc = blockOccs.some((o) => Boolean(recordEdits?.occurrences?.[o.occurrenceKey]));
4842
+ const blockSummaryText = block?.title || block?.name || block?.heading || block?.body || Object.keys(block || {}).filter((k) => !k.startsWith("_") && k !== "id").slice(0, 3).map((k) => {
4843
+ const v = block[k];
4844
+ if (v === null || v === void 0) return null;
4845
+ return `${k}: ${typeof v === "object" ? JSON.stringify(v).slice(0, 24) : String(v).slice(0, 24)}`;
4846
+ }).filter(Boolean).join(", ") || "-";
4847
+ return /* @__PURE__ */ jsxRuntime.jsxs(
4848
+ designSystem.Tr,
4849
+ {
4850
+ style: {
4851
+ backgroundColor: hasDirtyOcc || isBlockChecked ? "rgba(73, 69, 255, 0.07)" : void 0
4852
+ },
4853
+ children: [
4854
+ !gridEditMode && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(
4855
+ designSystem.Checkbox,
4856
+ {
4857
+ checked: isBlockChecked,
4858
+ disabled: !isBlockSelectable,
4859
+ onCheckedChange: () => {
4860
+ onToggleDzBlock(colUid, entry.documentId, bIdx, allApplicableIndexes);
4861
+ }
4862
+ }
4863
+ ) }),
4864
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Td, { children: [
4865
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", fontWeight: "bold", display: "block", children: [
4866
+ "#",
4867
+ bIdx
4868
+ ] }),
4869
+ block?.id !== void 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", textColor: "neutral500", style: { fontSize: "0.68rem" }, children: [
4870
+ "id:",
4871
+ block.id
4872
+ ] })
4873
+ ] }),
4874
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Td, { children: [
4875
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "neutral150", textColor: "neutral800", children: compLabel }),
4876
+ compUid && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral500", display: "block", style: { fontSize: "0.68rem", marginTop: 2 }, children: compUid })
4877
+ ] }),
4878
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: !targetsThisRoot ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral500", children: selectedAttribute ? `(targets "${selectedAttribute}")` : "(select attribute to inspect)" }) : !hasTargetAttr ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "neutral100", textColor: "neutral500", children: "Does not contain attribute" }) : gridEditMode ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", gap: 2, alignItems: "flex-start", children: blockOccs.map((occ) => {
4879
+ const editObj = recordEdits?.occurrences?.[occ.occurrenceKey];
4880
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: { width: "100%" }, children: [
4881
+ blockOccs.length > 1 && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", display: "block", style: { fontSize: "0.7rem", marginBottom: 2 }, children: occ.displayPath }),
4882
+ /* @__PURE__ */ jsxRuntime.jsx(
4883
+ GridCellEditor,
4884
+ {
4885
+ entry,
4886
+ attribute: selectedAttribute,
4887
+ occurrence: occ,
4888
+ attrMeta,
4889
+ editedValue: editObj?.value,
4890
+ isDirty: Boolean(editObj),
4891
+ validationError: editObj?.validationError,
4892
+ relationOptions,
4893
+ relationOptionsLoading,
4894
+ relationIsMulti,
4895
+ validationRules,
4896
+ recordEdits,
4897
+ colAttributes,
4898
+ onCommit: (o, val, err) => onCommitEdit(entry, colUid, o, val, err),
4899
+ onReset: (k) => onResetEdit(colUid, entry.documentId, k)
4900
+ }
4901
+ )
4902
+ ] }, occ.occurrenceKey);
4903
+ }) }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", gap: 1, alignItems: "flex-start", children: blockOccs.map((occ) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "semiBold", textColor: "primary700", children: occ.value !== null && occ.value !== void 0 && occ.value !== "" ? typeof occ.value === "object" ? JSON.stringify(occ.value) : String(occ.value) : "(empty / not set)" }, occ.occurrenceKey)) }) }),
4904
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(
4905
+ designSystem.Typography,
4906
+ {
4907
+ variant: "pi",
4908
+ textColor: "neutral600",
4909
+ style: { maxWidth: 280, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" },
4910
+ children: blockSummaryText
4911
+ }
4912
+ ) })
4913
+ ]
4914
+ },
4915
+ block?.id ? `id_${block.id}_idx_${bIdx}` : `idx_${bIdx}`
4916
+ );
4917
+ }) })
4918
+ ] })
4919
+ ]
4920
+ }
4921
+ );
4922
+ }
4923
+ );
4924
+ function parseDynamicZonePath(path) {
4925
+ if (!path) return { cleanPath: "", rootKey: "", subPath: "" };
4926
+ const bracketMatch = path.match(/^([^.[]+)\[([^\]]+)\]\.(.+)$/);
4927
+ if (bracketMatch) {
4928
+ const rootKey = bracketMatch[1];
4929
+ const selector = bracketMatch[2];
4930
+ const subPath = bracketMatch[3];
4931
+ const cleanPath = `${rootKey}.${subPath}`;
4932
+ if (/^\d+$/.test(selector)) {
4933
+ return { cleanPath, rootKey, subPath, targetIndex: parseInt(selector, 10) };
4934
+ }
4935
+ return { cleanPath, rootKey, subPath, targetComponentUid: selector };
4936
+ }
4937
+ const parts = path.split(".");
4938
+ return {
4939
+ cleanPath: path,
4940
+ rootKey: parts[0] || "",
4941
+ subPath: parts.slice(1).join(".")
4942
+ };
4943
+ }
4944
+ function formatComponentName(compUid) {
4945
+ if (!compUid) return "Component";
4946
+ const name = compUid.includes(".") ? compUid.split(".")[1] : compUid;
4947
+ return name.split(/[-_]/).map((w) => w.charAt(0).toUpperCase() + w.slice(1)).join(" ");
4948
+ }
4949
+ function getAllNestedValues(obj, path, availableAttributes) {
4950
+ if (!obj || !path) return [];
4951
+ const parsed = parseDynamicZonePath(path);
4952
+ const parts = parsed.cleanPath.split(".");
4953
+ const [head, ...tail] = parts;
4954
+ const rootTarget = getPropertyValue(obj, head);
4955
+ if (Array.isArray(rootTarget)) {
4956
+ const results = [];
4957
+ rootTarget.forEach((item, idx) => {
4958
+ if (!item || typeof item !== "object") return;
4959
+ if (parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) return;
4960
+ if (parsed.targetComponentUid && item.__component !== parsed.targetComponentUid) return;
4961
+ const subPath = tail.join(".");
4962
+ const scopedPath = item.__component ? `${head}[${item.__component}].${subPath}` : "";
4963
+ const isSupported = availableAttributes ? availableAttributes.includes(scopedPath) : false;
4964
+ const subVal = tail.length > 0 ? getNestedValue(item, subPath) : item;
4965
+ if (subVal !== void 0 || isSupported) {
4966
+ results.push({
4967
+ index: idx,
4968
+ componentUid: item.__component,
4969
+ componentName: formatComponentName(item.__component),
4970
+ value: subVal !== void 0 ? subVal : null,
4971
+ path: `${head}[#${idx}${item.__component ? ` ${formatComponentName(item.__component)}` : ""}].${subPath}`
4972
+ });
4973
+ }
4974
+ });
4975
+ return results;
4976
+ }
4977
+ const singleVal = getNestedValue(obj, parsed.cleanPath);
4978
+ if (singleVal !== void 0) {
4979
+ return [
4980
+ {
4981
+ index: 0,
4982
+ value: singleVal,
4983
+ path: parsed.cleanPath
4984
+ }
4985
+ ];
4986
+ }
4987
+ return [];
4988
+ }
4989
+ function getPropertyValue(target, key) {
4990
+ if (!target || typeof target !== "object" || !key) return void 0;
4991
+ if (target[key] !== void 0 && target[key] !== null) return target[key];
4992
+ const camelKey = key.replace(/_([a-z0-9])/g, (_, letter) => letter.toUpperCase());
4993
+ if (target[camelKey] !== void 0 && target[camelKey] !== null) return target[camelKey];
4994
+ const snakeKey = key.replace(/([A-Z])/g, "_$1").toLowerCase();
4995
+ if (target[snakeKey] !== void 0 && target[snakeKey] !== null) return target[snakeKey];
4996
+ const lowerKey = key.toLowerCase();
4997
+ const lowerNoUnderscore = lowerKey.replace(/_/g, "");
4998
+ const matchedKey = Object.keys(target).find((k) => {
4999
+ const kLower = k.toLowerCase();
5000
+ return kLower === lowerKey || kLower.replace(/_/g, "") === lowerNoUnderscore;
5001
+ });
5002
+ if (matchedKey && target[matchedKey] !== void 0 && target[matchedKey] !== null) {
5003
+ return target[matchedKey];
5004
+ }
5005
+ if (key in target) return target[key];
5006
+ if (camelKey in target) return target[camelKey];
5007
+ if (snakeKey in target) return target[snakeKey];
5008
+ return void 0;
5009
+ }
5010
+ function getNestedValue(obj, path) {
5011
+ if (!obj || !path) return void 0;
5012
+ const parsed = parseDynamicZonePath(path);
5013
+ const parts = parsed.cleanPath.split(".");
5014
+ function extract(current, remainingParts) {
5015
+ if (current === void 0 || current === null) return void 0;
5016
+ if (remainingParts.length === 0) return current;
5017
+ const [head, ...tail] = remainingParts;
5018
+ if (Array.isArray(current)) {
5019
+ if (/^\d+$/.test(head)) {
5020
+ return extract(current[parseInt(head, 10)], tail);
5021
+ }
5022
+ for (let idx = 0; idx < current.length; idx++) {
5023
+ const item = current[idx];
5024
+ if (parsed.targetIndex !== void 0 && idx !== parsed.targetIndex) continue;
5025
+ if (parsed.targetComponentUid && item?.__component !== parsed.targetComponentUid) continue;
5026
+ const found = extract(getPropertyValue(item, head), tail);
5027
+ if (found !== void 0 && found !== null) return found;
5028
+ }
5029
+ return void 0;
5030
+ }
5031
+ return extract(getPropertyValue(current, head), tail);
5032
+ }
5033
+ return extract(obj, parts);
5034
+ }
5035
+ function getAvailableColumnsForCollection(col, selectedAttribute, searchAttribute) {
5036
+ const cols = [
5037
+ {
5038
+ key: "select",
5039
+ label: "Select",
5040
+ isPermanent: true,
5041
+ defaultVisible: true
5042
+ },
5043
+ {
5044
+ key: "identifier",
5045
+ label: "Identifier",
5046
+ sortable: !col.isSingleType,
5047
+ defaultVisible: true
5048
+ }
5049
+ ];
5050
+ const candidateAttrs = col.attributes || [];
5051
+ candidateAttrs.forEach((attr) => {
5052
+ if (attr === "name" || attr === "title" || attr === selectedAttribute || searchAttribute && attr === searchAttribute) {
5053
+ return;
5054
+ }
5055
+ let formattedLabel = attr;
5056
+ if (attr === "updated_at" || attr === "updatedAt") {
5057
+ formattedLabel = "Updated At";
5058
+ } else if (attr === "created_at" || attr === "createdAt") {
5059
+ formattedLabel = "Created At";
5060
+ } else if (attr === "published_at" || attr === "publishedAt") {
5061
+ formattedLabel = "Published At";
5062
+ } else {
5063
+ const bracketMatch = attr.match(/^([^.[]+)\[([^\]]+)\]\.(.+)$/);
3456
5064
  if (bracketMatch) {
3457
5065
  const root = bracketMatch[1].charAt(0).toUpperCase() + bracketMatch[1].slice(1);
3458
5066
  const comp = formatComponentName(bracketMatch[2]);
@@ -3725,7 +5333,7 @@ function formatDisplayValue(val) {
3725
5333
  }
3726
5334
  return String(val);
3727
5335
  }
3728
- function renderCellContent(colDef, entry, col, selectedAttribute, searchAttribute, isMatch, hasAttr, isSelected, onToggleSelect, pendingBatches = [], isDzExpanded = false, onToggleExpandDz, filterQuery = "") {
5336
+ function renderCellContent(colDef, entry, col, selectedAttribute, searchAttribute, isMatch, hasAttr, isSelected, onToggleSelect, pendingBatches = [], isDzExpanded = false, onToggleExpandDz, filterQuery = "", gridCtx) {
3729
5337
  switch (colDef.key) {
3730
5338
  case "select":
3731
5339
  return /* @__PURE__ */ jsxRuntime.jsx(
@@ -3740,7 +5348,10 @@ function renderCellContent(colDef, entry, col, selectedAttribute, searchAttribut
3740
5348
  const dzField = Object.keys(entry).find(
3741
5349
  (k) => Array.isArray(entry[k]) && entry[k].length > 0 && entry[k].some((item) => item && item.__component)
3742
5350
  );
3743
- const dzItemsCount = dzField ? entry[dzField].length : 0;
5351
+ const selectedRootKey = selectedAttribute ? selectedAttribute.split("[")[0].split(".")[0] : "";
5352
+ const repeatableRoot = !dzField && gridCtx?.gridEditMode && selectedRootKey && gridCtx?.selectedAttrMeta?.rootRepeatable && Array.isArray(entry[selectedRootKey]) && entry[selectedRootKey].length > 0 ? selectedRootKey : void 0;
5353
+ const expandField = dzField || repeatableRoot;
5354
+ const dzItemsCount = expandField ? entry[expandField].length : 0;
3744
5355
  return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { children: [
3745
5356
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "semiBold", children: mainText }),
3746
5357
  entry.email && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral500", display: "block", children: entry.email }),
@@ -3758,7 +5369,7 @@ function renderCellContent(colDef, entry, col, selectedAttribute, searchAttribut
3758
5369
  backgroundColor: isDzExpanded ? "rgba(73, 69, 255, 0.08)" : "rgba(0, 0, 0, 0.04)",
3759
5370
  borderRadius: 4
3760
5371
  },
3761
- children: isDzExpanded ? `▲ Hide ${dzField} (${dzItemsCount} blocks)` : `▼ View ${dzField} (${dzItemsCount} blocks)`
5372
+ children: isDzExpanded ? `▲ Hide ${expandField} (${dzItemsCount} ${dzField ? "blocks" : "items"})` : `▼ ${gridCtx?.gridEditMode ? "Edit" : "View"} ${expandField} (${dzItemsCount} ${dzField ? "blocks" : "items"})`
3762
5373
  }
3763
5374
  ) })
3764
5375
  ] });
@@ -3825,13 +5436,95 @@ function renderCellContent(colDef, entry, col, selectedAttribute, searchAttribut
3825
5436
  children: displayStr
3826
5437
  }
3827
5438
  )
3828
- ]
3829
- },
3830
- m.index
3831
- );
3832
- }) });
3833
- }
3834
- case "target_attr": {
5439
+ ]
5440
+ },
5441
+ m.index
5442
+ );
5443
+ }) });
5444
+ }
5445
+ case "target_attr": {
5446
+ if (gridCtx?.gridEditMode) {
5447
+ if (selectedAttribute && !hasAttr) {
5448
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "neutral200", textColor: "neutral600", children: "Ignored (absent in schema)" });
5449
+ }
5450
+ const occs = enumerateClientOccurrences(
5451
+ entry,
5452
+ selectedAttribute,
5453
+ col?.attributes,
5454
+ gridCtx.selectedAttrMeta
5455
+ );
5456
+ if (occs.length === 0) {
5457
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral500", style: { fontStyle: "italic" }, children: "(no applicable block / item)" });
5458
+ }
5459
+ if (occs.length === 1 && !occs[0].segments.some((s) => s.index !== void 0)) {
5460
+ const occ = occs[0];
5461
+ const editObj = gridCtx.recordEdits?.occurrences?.[occ.occurrenceKey];
5462
+ return /* @__PURE__ */ jsxRuntime.jsx(
5463
+ GridCellEditor,
5464
+ {
5465
+ entry,
5466
+ attribute: selectedAttribute,
5467
+ occurrence: occ,
5468
+ attrMeta: gridCtx.selectedAttrMeta,
5469
+ editedValue: editObj?.value,
5470
+ isDirty: Boolean(editObj),
5471
+ validationError: editObj?.validationError,
5472
+ relationOptions: gridCtx.relationOptions,
5473
+ relationOptionsLoading: gridCtx.relationOptionsLoading,
5474
+ relationIsMulti: gridCtx.relationIsMulti,
5475
+ validationRules: gridCtx.validationRules,
5476
+ recordEdits: gridCtx.recordEdits,
5477
+ colAttributes: col?.attributes,
5478
+ onCommit: (o, val, err) => gridCtx.onCommitEdit(entry, col.uid, o, val, err),
5479
+ onReset: (k) => gridCtx.onResetEdit(col.uid, entry.documentId, k)
5480
+ }
5481
+ );
5482
+ }
5483
+ const maxInline = 3;
5484
+ const visibleOccs = occs.slice(0, maxInline);
5485
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 2, alignItems: "flex-start", children: [
5486
+ visibleOccs.map((occ) => {
5487
+ const editObj = gridCtx.recordEdits?.occurrences?.[occ.occurrenceKey];
5488
+ return /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { style: { width: "100%" }, children: [
5489
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 1, alignItems: "center", marginBottom: 1, children: [
5490
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { size: "S", backgroundColor: editObj ? "primary100" : "neutral200", textColor: editObj ? "primary700" : "neutral800", children: [
5491
+ "#",
5492
+ occ.index,
5493
+ " ",
5494
+ occ.componentName || "Item"
5495
+ ] }),
5496
+ occ.componentId !== void 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", textColor: "neutral500", style: { fontSize: "0.68rem" }, children: [
5497
+ "id:",
5498
+ occ.componentId
5499
+ ] }),
5500
+ editObj && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { size: "S", backgroundColor: "secondary100", textColor: "secondary700", children: "Edited" })
5501
+ ] }),
5502
+ /* @__PURE__ */ jsxRuntime.jsx(
5503
+ GridCellEditor,
5504
+ {
5505
+ compact: true,
5506
+ entry,
5507
+ attribute: selectedAttribute,
5508
+ occurrence: occ,
5509
+ attrMeta: gridCtx.selectedAttrMeta,
5510
+ editedValue: editObj?.value,
5511
+ isDirty: Boolean(editObj),
5512
+ validationError: editObj?.validationError,
5513
+ relationOptions: gridCtx.relationOptions,
5514
+ relationOptionsLoading: gridCtx.relationOptionsLoading,
5515
+ relationIsMulti: gridCtx.relationIsMulti,
5516
+ validationRules: gridCtx.validationRules,
5517
+ recordEdits: gridCtx.recordEdits,
5518
+ colAttributes: col?.attributes,
5519
+ onCommit: (o, val, err) => gridCtx.onCommitEdit(entry, col.uid, o, val, err),
5520
+ onReset: (k) => gridCtx.onResetEdit(col.uid, entry.documentId, k)
5521
+ }
5522
+ )
5523
+ ] }, occ.occurrenceKey);
5524
+ }),
5525
+ occs.length > maxInline && onToggleExpandDz && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", size: "S", onClick: onToggleExpandDz, children: isDzExpanded ? `▲ Collapse drawer` : `▼ Edit all ${occs.length} occurrences in drawer` })
5526
+ ] });
5527
+ }
3835
5528
  const matches = getAllNestedValues(entry, selectedAttribute, col?.attributes);
3836
5529
  if (matches.length === 0) {
3837
5530
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { textColor: "neutral500", style: { fontStyle: "italic" }, children: "(empty / not set)" });
@@ -4038,6 +5731,10 @@ const BulkUpdater = () => {
4038
5731
  const [searchAttribute, setSearchAttribute] = React.useState("");
4039
5732
  const [searchAttributeInput, setSearchAttributeInput] = React.useState("");
4040
5733
  const [attributesMeta, setAttributesMeta] = React.useState({});
5734
+ const [gridEditMode, setGridEditMode] = React.useState(false);
5735
+ const [gridEdits, setGridEdits] = React.useState({});
5736
+ const [gridFilterModifiedOnly, setGridFilterModifiedOnly] = React.useState(false);
5737
+ const [validationRules, setValidationRules] = React.useState([]);
4041
5738
  const effectiveSearchAttribute = searchAttribute || selectedAttribute;
4042
5739
  React.useEffect(() => {
4043
5740
  if (effectiveSearchAttribute && relationsMeta[effectiveSearchAttribute]) {
@@ -4352,10 +6049,20 @@ const BulkUpdater = () => {
4352
6049
  setPendingBatchesLoading(false);
4353
6050
  }
4354
6051
  };
6052
+ const fetchValidationRules = async () => {
6053
+ try {
6054
+ const res = await get("/bulk-updater/validation-rules");
6055
+ if (res.data?.success && Array.isArray(res.data.rules)) {
6056
+ setValidationRules(res.data.rules);
6057
+ }
6058
+ } catch {
6059
+ }
6060
+ };
4355
6061
  React.useEffect(() => {
4356
6062
  fetchModels();
4357
6063
  fetchAuditHistory();
4358
6064
  fetchPendingBatches();
6065
+ fetchValidationRules();
4359
6066
  }, []);
4360
6067
  React.useEffect(() => {
4361
6068
  if (activeTab === "audit") {
@@ -4373,7 +6080,17 @@ const BulkUpdater = () => {
4373
6080
  if (selectedCollectionUid) {
4374
6081
  const isFilterActiveNow = Boolean(searchAttribute && searchAttribute !== selectedAttribute) || filterOperator !== "none" && (["empty", "not_empty"].includes(filterOperator) || Boolean(filterQuery.trim())) || Boolean(entrySearch.trim()) || Boolean(useRegex && regexPattern.trim());
4375
6082
  if (isFilterActiveNow) {
4376
- setSelectedEntries({});
6083
+ if (gridEditMode) {
6084
+ setSelectedEntries((prev) => {
6085
+ const retained = {};
6086
+ Object.keys(gridEdits).forEach((k) => {
6087
+ if (prev[k]) retained[k] = true;
6088
+ });
6089
+ return retained;
6090
+ });
6091
+ } else {
6092
+ setSelectedEntries({});
6093
+ }
4377
6094
  }
4378
6095
  loadCollectionPage(
4379
6096
  selectedCollectionUid,
@@ -4396,12 +6113,131 @@ const BulkUpdater = () => {
4396
6113
  if (!collections.length || !selectedCollectionUid) return null;
4397
6114
  return collections.find((c) => c.uid === selectedCollectionUid) || null;
4398
6115
  }, [collections, selectedCollectionUid]);
6116
+ const activeAttrMeta = React.useMemo(() => {
6117
+ if (!selectedAttribute) return void 0;
6118
+ const base = selectedCol?.attributesMeta?.[selectedAttribute] || attributesMeta[selectedAttribute];
6119
+ const relMeta = selectedCol?.relations?.[selectedAttribute] || relationsMeta[selectedAttribute];
6120
+ if (!base && !relMeta) return void 0;
6121
+ if (relMeta && (!base || !base.isRelation)) {
6122
+ return {
6123
+ ...base || { depth: 0, type: "relation" },
6124
+ isRelation: true,
6125
+ relationType: relMeta.relationType,
6126
+ target: relMeta.targetUid
6127
+ };
6128
+ }
6129
+ return base;
6130
+ }, [selectedAttribute, selectedCol, attributesMeta, relationsMeta]);
6131
+ const totalDirtyRecordsCount = React.useMemo(() => Object.keys(gridEdits).length, [gridEdits]);
6132
+ const totalDirtyCellsCount = React.useMemo(
6133
+ () => Object.values(gridEdits).reduce(
6134
+ (sum, rec) => sum + Object.keys(rec.occurrences || {}).length,
6135
+ 0
6136
+ ),
6137
+ [gridEdits]
6138
+ );
6139
+ const gridSerialized = React.useMemo(
6140
+ () => serializeGridTargets(gridEdits, selectedEntries, collectionPages, activeAttrMeta),
6141
+ [gridEdits, selectedEntries, collectionPages, activeAttrMeta]
6142
+ );
6143
+ const handleGridCellCommit = React__default.default.useCallback(
6144
+ (entry, colUid, occ, newValue, validationError) => {
6145
+ const key = `${colUid}${KEY_SEP}${entry.documentId}`;
6146
+ const recordLabel = entry.name || entry.title || entry.email || `Entry #${entry.id || entry.documentId}`;
6147
+ setGridEdits((prev) => {
6148
+ const existingRec = prev[key] || {
6149
+ uid: colUid,
6150
+ documentId: entry.documentId,
6151
+ locale: entry.locale,
6152
+ status: entry.status,
6153
+ publishedAt: entry.publishedAt,
6154
+ recordLabel,
6155
+ occurrences: {}
6156
+ };
6157
+ return {
6158
+ ...prev,
6159
+ [key]: {
6160
+ ...existingRec,
6161
+ occurrences: {
6162
+ ...existingRec.occurrences,
6163
+ [occ.occurrenceKey]: {
6164
+ occurrenceKey: occ.occurrenceKey,
6165
+ displayPath: occ.displayPath,
6166
+ segments: occ.segments,
6167
+ originalValue: occ.value,
6168
+ value: newValue,
6169
+ fieldType: activeAttrMeta?.type || "string",
6170
+ validationError,
6171
+ touchedAt: Date.now()
6172
+ }
6173
+ }
6174
+ }
6175
+ };
6176
+ });
6177
+ setSelectedEntries((prev) => prev[key] ? prev : { ...prev, [key]: true });
6178
+ },
6179
+ [activeAttrMeta?.type]
6180
+ );
6181
+ const handleGridCellReset = React__default.default.useCallback((colUid, documentId, occKey) => {
6182
+ const key = `${colUid}${KEY_SEP}${documentId}`;
6183
+ setGridEdits((prev) => {
6184
+ const existingRec = prev[key];
6185
+ if (!existingRec) return prev;
6186
+ const nextOccs = { ...existingRec.occurrences };
6187
+ delete nextOccs[occKey];
6188
+ if (Object.keys(nextOccs).length === 0) {
6189
+ const next = { ...prev };
6190
+ delete next[key];
6191
+ return next;
6192
+ }
6193
+ return {
6194
+ ...prev,
6195
+ [key]: {
6196
+ ...existingRec,
6197
+ occurrences: nextOccs
6198
+ }
6199
+ };
6200
+ });
6201
+ }, []);
6202
+ const handleToggleGridEditMode = (checked) => {
6203
+ if (!checked && totalDirtyCellsCount > 0) {
6204
+ if (!window.confirm(`Disable Grid Editing Mode and discard ${totalDirtyCellsCount} unsaved edit(s)?`)) {
6205
+ return;
6206
+ }
6207
+ setGridEdits({});
6208
+ }
6209
+ setGridEditMode(checked);
6210
+ setGridFilterModifiedOnly(false);
6211
+ if (checked) {
6212
+ if (useRegex) setUseRegex(false);
6213
+ setRegexPattern("");
6214
+ if (selectedCollectionUid) {
6215
+ setCollectionColumnVisibility((prev) => {
6216
+ const existing = prev[selectedCollectionUid];
6217
+ if (existing && !existing.includes("target_attr")) {
6218
+ return { ...prev, [selectedCollectionUid]: [...existing, "target_attr"] };
6219
+ }
6220
+ return prev;
6221
+ });
6222
+ }
6223
+ }
6224
+ };
4399
6225
  const handleCollectionChange = (newUid) => {
4400
6226
  if (newUid === selectedCollectionUid) return;
6227
+ if (totalDirtyCellsCount > 0) {
6228
+ if (!window.confirm(
6229
+ `You have ${totalDirtyCellsCount} unsaved Grid Edit(s) in the current collection. Switching collections will discard them. Continue?`
6230
+ )) {
6231
+ return;
6232
+ }
6233
+ }
4401
6234
  if (abortControllersRef.current) {
4402
- Object.values(abortControllersRef.current).forEach((ctrl) => ctrl.abort());
6235
+ Object.values(abortControllersRef.current).forEach((ctrl) => ctrl?.abort());
4403
6236
  }
4404
6237
  setSelectedCollectionUid(newUid);
6238
+ setGridEdits({});
6239
+ setSelectedDzBlocks({});
6240
+ setExpandedDzEntries({});
4405
6241
  try {
4406
6242
  if (newUid) {
4407
6243
  localStorage.setItem(LAST_COLLECTION_KEY, newUid);
@@ -4435,6 +6271,14 @@ const BulkUpdater = () => {
4435
6271
  };
4436
6272
  const handleAttributeChange = (newAttr) => {
4437
6273
  if (newAttr !== selectedAttribute) {
6274
+ if (totalDirtyCellsCount > 0) {
6275
+ if (!window.confirm(
6276
+ `You have ${totalDirtyCellsCount} unsaved Grid Edit(s) for "${selectedAttribute}". Switching Target Attribute will discard them. Continue?`
6277
+ )) {
6278
+ return;
6279
+ }
6280
+ }
6281
+ setGridEdits({});
4438
6282
  setSelectedAttribute(newAttr);
4439
6283
  try {
4440
6284
  if (newAttr) {
@@ -4456,13 +6300,13 @@ const BulkUpdater = () => {
4456
6300
  const filteredCollections = React.useMemo(() => {
4457
6301
  return selectedCol ? [selectedCol] : [];
4458
6302
  }, [selectedCol]);
4459
- const getAttrDepth = (attr) => attributesMeta[attr]?.depth ?? (attr.includes(".") ? attr.split(".").length - 1 : 0);
6303
+ const getAttrDepth = (attr) => selectedCol?.attributesMeta?.[attr]?.depth ?? attributesMeta[attr]?.depth ?? (attr.includes(".") ? attr.split(".").length - 1 : 0);
4460
6304
  const availableColAttributes = React.useMemo(() => {
4461
6305
  return selectedCol?.attributes || attributes || [];
4462
6306
  }, [selectedCol, attributes]);
4463
6307
  const depthFilteredAttributes = React.useMemo(() => {
4464
6308
  return availableColAttributes.filter((attr) => getAttrDepth(attr) <= componentDepth);
4465
- }, [availableColAttributes, componentDepth, attributesMeta]);
6309
+ }, [availableColAttributes, componentDepth, attributesMeta, selectedCol]);
4466
6310
  const memoizedComboboxOptions = React.useMemo(() => {
4467
6311
  if (depthFilteredAttributes.length === 0) {
4468
6312
  return /* @__PURE__ */ jsxRuntime.jsx(designSystem.ComboboxOption, { value: "__none__", disabled: true, textValue: "No attributes available", children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: [
@@ -4643,7 +6487,10 @@ const BulkUpdater = () => {
4643
6487
  };
4644
6488
  const getVisibleEntries = (col) => {
4645
6489
  const pageState = collectionPages[col.uid];
4646
- const raw = pageState ? pageState.entries : col.entries || [];
6490
+ let raw = pageState ? pageState.entries : col.entries || [];
6491
+ if (gridEditMode && gridFilterModifiedOnly) {
6492
+ raw = raw.filter((entry) => Boolean(gridEdits[`${col.uid}${KEY_SEP}${entry.documentId}`]));
6493
+ }
4647
6494
  if (statusFilter === "all") return raw;
4648
6495
  return raw.filter((entry) => {
4649
6496
  const lifecycle = getEntryLifecycleStatus(entry, col, pendingBatches);
@@ -4657,7 +6504,7 @@ const BulkUpdater = () => {
4657
6504
  count += getVisibleEntries(col).length;
4658
6505
  });
4659
6506
  return count;
4660
- }, [filteredCollections, collectionPages, isFilterActive, statusFilter, pendingBatches]);
6507
+ }, [filteredCollections, collectionPages, isFilterActive, statusFilter, pendingBatches, gridEditMode, gridFilterModifiedOnly, gridEdits]);
4661
6508
  const selectAllMatching = () => {
4662
6509
  const updated = { ...selectedEntries };
4663
6510
  filteredCollections.forEach((col) => {
@@ -4685,7 +6532,17 @@ const BulkUpdater = () => {
4685
6532
  setEntrySearch("");
4686
6533
  setStatusFilter("all");
4687
6534
  setRegexPattern("");
4688
- setSelectedEntries({});
6535
+ if (gridEditMode) {
6536
+ setSelectedEntries((prev) => {
6537
+ const retained = {};
6538
+ Object.keys(gridEdits).forEach((k) => {
6539
+ if (prev[k]) retained[k] = true;
6540
+ });
6541
+ return retained;
6542
+ });
6543
+ } else {
6544
+ setSelectedEntries({});
6545
+ }
4689
6546
  collections.forEach((col) => {
4690
6547
  loadCollectionPage(col.uid, 1, void 0, void 0, void 0, "none", "", "", false, "");
4691
6548
  });
@@ -4730,58 +6587,71 @@ const BulkUpdater = () => {
4730
6587
  const deselectAll = () => {
4731
6588
  setSelectedEntries({});
4732
6589
  };
4733
- const getSelectedBreakdown = () => {
6590
+ const getSelectedBreakdown = (onlyKeys) => {
4734
6591
  const breakdown = {};
4735
- Object.keys(selectedEntries).forEach((key) => {
4736
- if (selectedEntries[key]) {
4737
- const parts = key.split(KEY_SEP);
4738
- if (parts.length === 2) {
4739
- const uid = parts[0];
4740
- const col = collections.find((c) => c.uid === uid);
4741
- const name = col?.displayName || uid;
4742
- breakdown[name] = (breakdown[name] || 0) + 1;
4743
- }
6592
+ const keysToCount = onlyKeys || Object.keys(selectedEntries).filter((k) => selectedEntries[k]);
6593
+ keysToCount.forEach((key) => {
6594
+ const parts = key.split(KEY_SEP);
6595
+ if (parts.length === 2) {
6596
+ const uid = parts[0];
6597
+ const col = collections.find((c) => c.uid === uid);
6598
+ const name = col?.displayName || uid;
6599
+ breakdown[name] = (breakdown[name] || 0) + 1;
4744
6600
  }
4745
6601
  });
4746
6602
  return breakdown;
4747
6603
  };
4748
- const selectedLifecycleStats = React.useMemo(() => {
4749
- let published = 0;
4750
- let modified = 0;
4751
- let draft = 0;
4752
- let pendingReview = 0;
4753
- let unknown = 0;
4754
- Object.keys(selectedEntries).forEach((key) => {
4755
- if (!selectedEntries[key]) return;
4756
- const parts = key.split(KEY_SEP);
4757
- if (parts.length !== 2) return;
4758
- const [uid, docId] = parts;
4759
- const col = collections.find((c) => c.uid === uid) || null;
4760
- const entry = collectionPages[uid]?.entries?.find((e) => e.documentId === docId || String(e.id) === docId) || col?.entries?.find((e) => e.documentId === docId || String(e.id) === docId);
4761
- if (col && col.draftAndPublish === false) {
4762
- published++;
4763
- } else if (entry) {
4764
- const { status } = getEntryLifecycleStatus(entry, col, pendingBatches);
4765
- if (status === "published") published++;
4766
- else if (status === "modified") modified++;
4767
- else if (status === "draft") draft++;
4768
- else if (status === "pending_review") pendingReview++;
4769
- else unknown++;
4770
- } else {
4771
- draft++;
4772
- }
4773
- });
4774
- const unreviewedCount = draft + modified + pendingReview + unknown;
4775
- return {
4776
- published,
4777
- modified,
4778
- draft,
4779
- pendingReview,
4780
- unknown,
4781
- unreviewedCount,
4782
- total: published + modified + draft + pendingReview + unknown
4783
- };
4784
- }, [selectedEntries, collections, collectionPages, pendingBatches]);
6604
+ const computeLifecycleStatsForKeys = React__default.default.useCallback(
6605
+ (keys) => {
6606
+ let published = 0;
6607
+ let modified = 0;
6608
+ let draft = 0;
6609
+ let pendingReview = 0;
6610
+ let unknown = 0;
6611
+ keys.forEach((key) => {
6612
+ const parts = key.split(KEY_SEP);
6613
+ if (parts.length !== 2) return;
6614
+ const [uid, docId] = parts;
6615
+ const col = collections.find((c) => c.uid === uid) || null;
6616
+ const entry = collectionPages[uid]?.entries?.find((e) => e.documentId === docId || String(e.id) === docId) || col?.entries?.find((e) => e.documentId === docId || String(e.id) === docId);
6617
+ if (col && col.draftAndPublish === false) {
6618
+ published++;
6619
+ } else if (entry) {
6620
+ const { status } = getEntryLifecycleStatus(entry, col, pendingBatches);
6621
+ if (status === "published") published++;
6622
+ else if (status === "modified") modified++;
6623
+ else if (status === "draft") draft++;
6624
+ else if (status === "pending_review") pendingReview++;
6625
+ else unknown++;
6626
+ } else {
6627
+ draft++;
6628
+ }
6629
+ });
6630
+ const unreviewedCount = draft + modified + pendingReview + unknown;
6631
+ return {
6632
+ published,
6633
+ modified,
6634
+ draft,
6635
+ pendingReview,
6636
+ unknown,
6637
+ unreviewedCount,
6638
+ total: published + modified + draft + pendingReview + unknown
6639
+ };
6640
+ },
6641
+ [collections, collectionPages, pendingBatches]
6642
+ );
6643
+ const selectedLifecycleStats = React.useMemo(
6644
+ () => computeLifecycleStatsForKeys(Object.keys(selectedEntries).filter((k) => selectedEntries[k])),
6645
+ [selectedEntries, computeLifecycleStatsForKeys]
6646
+ );
6647
+ const gridTargetKeys = React.useMemo(
6648
+ () => gridSerialized.targets.map((t) => `${t.uid}${KEY_SEP}${t.documentId}`),
6649
+ [gridSerialized]
6650
+ );
6651
+ const updateModalLifecycleStats = React.useMemo(
6652
+ () => gridEditMode ? computeLifecycleStatsForKeys(gridTargetKeys) : selectedLifecycleStats,
6653
+ [gridEditMode, gridTargetKeys, computeLifecycleStatsForKeys, selectedLifecycleStats]
6654
+ );
4785
6655
  const handleOpenConfirmModal = () => {
4786
6656
  if (!selectedAttribute) {
4787
6657
  toggleNotification({
@@ -4790,13 +6660,30 @@ const BulkUpdater = () => {
4790
6660
  });
4791
6661
  return;
4792
6662
  }
4793
- const totalSelected = Object.values(selectedEntries).filter(Boolean).length;
4794
- if (totalSelected === 0) {
4795
- toggleNotification({
4796
- type: "warning",
4797
- message: "Please select at least one collection type or entry to update"
4798
- });
4799
- return;
6663
+ if (gridEditMode) {
6664
+ if (gridSerialized.targets.length === 0) {
6665
+ toggleNotification({
6666
+ type: "warning",
6667
+ message: "Please edit at least one selected cell or block in the grid before updating"
6668
+ });
6669
+ return;
6670
+ }
6671
+ if (gridSerialized.hasValidationErrors) {
6672
+ toggleNotification({
6673
+ type: "danger",
6674
+ message: "Please resolve inline validation errors highlighted in red before updating"
6675
+ });
6676
+ return;
6677
+ }
6678
+ } else {
6679
+ const totalSelected = Object.values(selectedEntries).filter(Boolean).length;
6680
+ if (totalSelected === 0) {
6681
+ toggleNotification({
6682
+ type: "warning",
6683
+ message: "Please select at least one collection type or entry to update"
6684
+ });
6685
+ return;
6686
+ }
4800
6687
  }
4801
6688
  setPublishStrategy("safe");
4802
6689
  setUnreviewedConsent(false);
@@ -4810,44 +6697,63 @@ const BulkUpdater = () => {
4810
6697
  });
4811
6698
  return;
4812
6699
  }
4813
- const targets = [];
4814
- Object.keys(selectedEntries).forEach((key) => {
4815
- if (selectedEntries[key]) {
4816
- const parts = key.split(KEY_SEP);
4817
- if (parts.length === 2) {
4818
- const colUid = parts[0];
4819
- const docId = parts[1];
4820
- const targetObj = { uid: colUid, documentId: docId };
4821
- if (selectedDzBlocks[key] && selectedDzBlocks[key].length > 0) {
4822
- targetObj.dynamicZoneIndexes = selectedDzBlocks[key];
4823
- }
4824
- const colPage = collectionPages[colUid];
4825
- const cachedEntry = colPage?.entries?.find((e) => e.documentId === docId);
4826
- if (cachedEntry) {
4827
- if (cachedEntry.status) targetObj.status = cachedEntry.status;
4828
- if (cachedEntry.publishedAt) targetObj.publishedAt = cachedEntry.publishedAt;
4829
- if (cachedEntry.locale) targetObj.locale = cachedEntry.locale;
6700
+ let targets = [];
6701
+ if (gridEditMode) {
6702
+ if (gridSerialized.hasValidationErrors) {
6703
+ toggleNotification({
6704
+ type: "danger",
6705
+ message: "Please fix inline validation errors before previewing changes"
6706
+ });
6707
+ return;
6708
+ }
6709
+ targets = gridSerialized.targets;
6710
+ if (targets.length === 0) {
6711
+ toggleNotification({
6712
+ type: "warning",
6713
+ message: "Please modify and select at least one grid cell or block to preview"
6714
+ });
6715
+ return;
6716
+ }
6717
+ } else {
6718
+ Object.keys(selectedEntries).forEach((key) => {
6719
+ if (selectedEntries[key]) {
6720
+ const parts = key.split(KEY_SEP);
6721
+ if (parts.length === 2) {
6722
+ const colUid = parts[0];
6723
+ const docId = parts[1];
6724
+ const targetObj = { uid: colUid, documentId: docId };
6725
+ if (selectedDzBlocks[key] && selectedDzBlocks[key].length > 0) {
6726
+ targetObj.dynamicZoneIndexes = selectedDzBlocks[key];
6727
+ }
6728
+ const colPage = collectionPages[colUid];
6729
+ const cachedEntry = colPage?.entries?.find((e) => e.documentId === docId);
6730
+ if (cachedEntry) {
6731
+ if (cachedEntry.status) targetObj.status = cachedEntry.status;
6732
+ if (cachedEntry.publishedAt) targetObj.publishedAt = cachedEntry.publishedAt;
6733
+ if (cachedEntry.locale) targetObj.locale = cachedEntry.locale;
6734
+ }
6735
+ targets.push(targetObj);
4830
6736
  }
4831
- targets.push(targetObj);
4832
6737
  }
4833
- }
4834
- });
4835
- if (targets.length === 0) {
4836
- toggleNotification({
4837
- type: "warning",
4838
- message: "Please select at least one collection type or entry to preview"
4839
6738
  });
4840
- return;
6739
+ if (targets.length === 0) {
6740
+ toggleNotification({
6741
+ type: "warning",
6742
+ message: "Please select at least one collection type or entry to preview"
6743
+ });
6744
+ return;
6745
+ }
4841
6746
  }
4842
6747
  setShowPreviewModal(true);
4843
6748
  setPreviewLoading(true);
4844
6749
  try {
4845
6750
  const res = await post("/bulk-updater/preview", {
4846
6751
  attribute: selectedAttribute,
4847
- value: attributeValue,
6752
+ value: gridEditMode ? "" : attributeValue,
6753
+ editMode: gridEditMode ? "grid" : "common",
4848
6754
  selectedEntries: targets,
4849
- isRegex: useRegex,
4850
- regexPattern,
6755
+ isRegex: gridEditMode ? false : useRegex,
6756
+ regexPattern: gridEditMode ? "" : regexPattern,
4851
6757
  publishOnApproval
4852
6758
  });
4853
6759
  if (res.data && res.data.success) {
@@ -4868,28 +6774,33 @@ const BulkUpdater = () => {
4868
6774
  }
4869
6775
  };
4870
6776
  const executeBatchWithMode = async (executionMode, forceImmediate = false) => {
4871
- const targets = [];
4872
- Object.keys(selectedEntries).forEach((key) => {
4873
- if (selectedEntries[key]) {
4874
- const parts = key.split(KEY_SEP);
4875
- if (parts.length === 2) {
4876
- const colUid = parts[0];
4877
- const docId = parts[1];
4878
- const targetObj = { uid: colUid, documentId: docId };
4879
- if (selectedDzBlocks[key] && selectedDzBlocks[key].length > 0) {
4880
- targetObj.dynamicZoneIndexes = selectedDzBlocks[key];
4881
- }
4882
- const colPage = collectionPages[colUid];
4883
- const cachedEntry = colPage?.entries?.find((e) => e.documentId === docId);
4884
- if (cachedEntry) {
4885
- if (cachedEntry.status) targetObj.status = cachedEntry.status;
4886
- if (cachedEntry.publishedAt) targetObj.publishedAt = cachedEntry.publishedAt;
4887
- if (cachedEntry.locale) targetObj.locale = cachedEntry.locale;
6777
+ let targets = [];
6778
+ if (gridEditMode) {
6779
+ targets = gridSerialized.targets;
6780
+ } else {
6781
+ Object.keys(selectedEntries).forEach((key) => {
6782
+ if (selectedEntries[key]) {
6783
+ const parts = key.split(KEY_SEP);
6784
+ if (parts.length === 2) {
6785
+ const colUid = parts[0];
6786
+ const docId = parts[1];
6787
+ const targetObj = { uid: colUid, documentId: docId };
6788
+ if (selectedDzBlocks[key] && selectedDzBlocks[key].length > 0) {
6789
+ targetObj.dynamicZoneIndexes = selectedDzBlocks[key];
6790
+ }
6791
+ const colPage = collectionPages[colUid];
6792
+ const cachedEntry = colPage?.entries?.find((e) => e.documentId === docId);
6793
+ if (cachedEntry) {
6794
+ if (cachedEntry.status) targetObj.status = cachedEntry.status;
6795
+ if (cachedEntry.publishedAt) targetObj.publishedAt = cachedEntry.publishedAt;
6796
+ if (cachedEntry.locale) targetObj.locale = cachedEntry.locale;
6797
+ }
6798
+ targets.push(targetObj);
4888
6799
  }
4889
- targets.push(targetObj);
4890
6800
  }
4891
- }
4892
- });
6801
+ });
6802
+ }
6803
+ const displaySummaryVal = gridEditMode ? `Grid Editing (${gridSerialized.totalEditCount} edits across ${targets.length} records)` : attributeValue;
4893
6804
  try {
4894
6805
  setUpdating(true);
4895
6806
  setShowConfirmModal(false);
@@ -4904,7 +6815,7 @@ const BulkUpdater = () => {
4904
6815
  status: "processing",
4905
6816
  executionMode,
4906
6817
  attribute: selectedAttribute,
4907
- value: attributeValue,
6818
+ value: displaySummaryVal,
4908
6819
  totalTargets: targets.length,
4909
6820
  processedCount: 0,
4910
6821
  updatedCount: 0,
@@ -4919,10 +6830,11 @@ const BulkUpdater = () => {
4919
6830
  });
4920
6831
  const payload = {
4921
6832
  attribute: selectedAttribute,
4922
- value: attributeValue,
6833
+ value: gridEditMode ? "" : attributeValue,
6834
+ editMode: gridEditMode ? "grid" : "common",
4923
6835
  selectedEntries: targets,
4924
- isRegex: useRegex,
4925
- regexPattern,
6836
+ isRegex: gridEditMode ? false : useRegex,
6837
+ regexPattern: gridEditMode ? "" : regexPattern,
4926
6838
  executionMode,
4927
6839
  makerNotes: makerNotesInput,
4928
6840
  forceImmediate,
@@ -4934,11 +6846,12 @@ const BulkUpdater = () => {
4934
6846
  const res = await post("/bulk-updater/batch-update", payload);
4935
6847
  setIsSubmittingBatch(false);
4936
6848
  if (res.data && res.data.success) {
4937
- setSelectedEntries({});
4938
- setSelectedDzBlocks({});
4939
6849
  const finalBatchId = res.data.batchId;
4940
6850
  setDashboardBatchId(finalBatchId);
4941
6851
  if (res.data.pending) {
6852
+ setSelectedEntries({});
6853
+ setSelectedDzBlocks({});
6854
+ if (gridEditMode) setGridEdits({});
4942
6855
  setDashboardJob({
4943
6856
  id: finalBatchId,
4944
6857
  createdAt: (/* @__PURE__ */ new Date()).toISOString(),
@@ -4946,7 +6859,7 @@ const BulkUpdater = () => {
4946
6859
  executionMode,
4947
6860
  scheduledFor: res.data.scheduledFor,
4948
6861
  attribute: selectedAttribute,
4949
- value: attributeValue,
6862
+ value: displaySummaryVal,
4950
6863
  totalTargets: targets.length,
4951
6864
  processedCount: 0,
4952
6865
  updatedCount: 0,
@@ -4964,7 +6877,31 @@ const BulkUpdater = () => {
4964
6877
  });
4965
6878
  await fetchPendingBatches();
4966
6879
  } else {
4967
- setLastResults(res.data.results || []);
6880
+ const resultList = res.data.results || [];
6881
+ if (gridEditMode) {
6882
+ const failedKeys = new Set(
6883
+ resultList.filter((r) => r.status === "error" && r.uid && r.documentId).map((r) => `${r.uid}${KEY_SEP}${r.documentId}`)
6884
+ );
6885
+ setGridEdits((prev) => {
6886
+ const next = {};
6887
+ for (const k of Object.keys(prev)) {
6888
+ if (failedKeys.has(k)) next[k] = prev[k];
6889
+ }
6890
+ return next;
6891
+ });
6892
+ setSelectedEntries((prev) => {
6893
+ const next = {};
6894
+ for (const k of Object.keys(prev)) {
6895
+ if (failedKeys.has(k) && prev[k]) next[k] = true;
6896
+ }
6897
+ return next;
6898
+ });
6899
+ setSelectedDzBlocks({});
6900
+ } else {
6901
+ setSelectedEntries({});
6902
+ setSelectedDzBlocks({});
6903
+ }
6904
+ setLastResults(resultList);
4968
6905
  setUpdateSummary({
4969
6906
  updatedCount: res.data.updatedCount || 0,
4970
6907
  skippedCount: res.data.skippedCount || 0,
@@ -4977,15 +6914,15 @@ const BulkUpdater = () => {
4977
6914
  status: res.data.status || "successful",
4978
6915
  executionMode: "immediate",
4979
6916
  attribute: selectedAttribute,
4980
- value: attributeValue,
6917
+ value: res.data.value || displaySummaryVal,
4981
6918
  totalTargets: res.data.totalTargets || targets.length,
4982
- processedCount: res.data.results?.length || targets.length,
6919
+ processedCount: resultList.length || targets.length,
4983
6920
  updatedCount: res.data.updatedCount || 0,
4984
6921
  skippedCount: res.data.skippedCount || 0,
4985
6922
  failedCount: res.data.failedCount || 0,
4986
6923
  isLive: res.data.isLive !== false && res.data.updatedCount > 0,
4987
6924
  publishOnApproval,
4988
- results: res.data.results || []
6925
+ results: resultList
4989
6926
  });
4990
6927
  toggleNotification({
4991
6928
  type: "success",
@@ -5838,6 +7775,7 @@ const BulkUpdater = () => {
5838
7775
  designSystem.Checkbox,
5839
7776
  {
5840
7777
  checked: useRegex,
7778
+ disabled: gridEditMode,
5841
7779
  onCheckedChange: (checked) => setUseRegex(Boolean(checked)),
5842
7780
  children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "bold", children: "Enable Regex Search & Replace" })
5843
7781
  }
@@ -5845,10 +7783,10 @@ const BulkUpdater = () => {
5845
7783
  /* @__PURE__ */ jsxRuntime.jsx(
5846
7784
  designSystem.Badge,
5847
7785
  {
5848
- backgroundColor: useRegex ? "secondary100" : "neutral200",
5849
- textColor: useRegex ? "secondary700" : "neutral600",
7786
+ backgroundColor: gridEditMode ? "neutral200" : useRegex ? "secondary100" : "neutral200",
7787
+ textColor: gridEditMode ? "neutral600" : useRegex ? "secondary700" : "neutral600",
5850
7788
  size: "S",
5851
- children: useRegex ? "REGEX SEARCH ACTIVE" : "REGEX OFF"
7789
+ children: gridEditMode ? "DISABLED IN GRID EDIT" : useRegex ? "REGEX SEARCH ACTIVE" : "REGEX OFF"
5852
7790
  }
5853
7791
  )
5854
7792
  ] }),
@@ -6273,6 +8211,72 @@ const BulkUpdater = () => {
6273
8211
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral500", children: col.isSingleType ? "1 single entry" : isFilterActive ? `${totalEntries} matching entries in DB` : `${totalEntries} entries` })
6274
8212
  ] })
6275
8213
  ] }),
8214
+ gridEditMode && /* @__PURE__ */ jsxRuntime.jsx(
8215
+ designSystem.Box,
8216
+ {
8217
+ padding: 3,
8218
+ marginBottom: 3,
8219
+ background: "primary100",
8220
+ hasRadius: true,
8221
+ style: { border: "1px solid #d9d8ff" },
8222
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", wrap: "wrap", gap: 2, children: [
8223
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", wrap: "wrap", children: [
8224
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "primary600", textColor: "neutral0", children: "GRID EDITING MODE" }),
8225
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", fontWeight: "bold", textColor: "primary700", children: selectedAttribute ? `Editing "${selectedAttribute}" directly per record & component block` : 'Select an "Attribute to Update" below to enable inline cell editors' }),
8226
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "neutral0", textColor: "primary700", children: [
8227
+ totalDirtyCellsCount,
8228
+ " edit",
8229
+ totalDirtyCellsCount === 1 ? "" : "s",
8230
+ " across ",
8231
+ totalDirtyRecordsCount,
8232
+ " record",
8233
+ totalDirtyRecordsCount === 1 ? "" : "s"
8234
+ ] })
8235
+ ] }),
8236
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", wrap: "wrap", children: [
8237
+ (activeAttrMeta?.rootType === "dynamiczone" || activeAttrMeta?.rootRepeatable) && visibleEntries.length > 0 && /* @__PURE__ */ jsxRuntime.jsx(
8238
+ designSystem.Button,
8239
+ {
8240
+ variant: "secondary",
8241
+ size: "S",
8242
+ onClick: () => {
8243
+ const allVisibleKeys = visibleEntries.map((e) => `${col.uid}${KEY_SEP}${e.documentId}`);
8244
+ const anyCollapsed = allVisibleKeys.some((k) => !expandedDzEntries[k]);
8245
+ setExpandedDzEntries((prev) => {
8246
+ const next = { ...prev };
8247
+ allVisibleKeys.forEach((k) => {
8248
+ next[k] = anyCollapsed;
8249
+ });
8250
+ return next;
8251
+ });
8252
+ },
8253
+ children: visibleEntries.some((e) => !expandedDzEntries[`${col.uid}${KEY_SEP}${e.documentId}`]) ? "Expand All Blocks" : "Collapse All Blocks"
8254
+ }
8255
+ ),
8256
+ /* @__PURE__ */ jsxRuntime.jsx(
8257
+ designSystem.Button,
8258
+ {
8259
+ variant: gridFilterModifiedOnly ? "default" : "tertiary",
8260
+ size: "S",
8261
+ onClick: () => setGridFilterModifiedOnly((v) => !v),
8262
+ disabled: totalDirtyRecordsCount === 0 && !gridFilterModifiedOnly,
8263
+ children: gridFilterModifiedOnly ? "Showing Modified Only" : "Filter: Modified Only"
8264
+ }
8265
+ ),
8266
+ /* @__PURE__ */ jsxRuntime.jsx(
8267
+ designSystem.Button,
8268
+ {
8269
+ variant: "danger-light",
8270
+ size: "S",
8271
+ disabled: totalDirtyCellsCount === 0,
8272
+ onClick: () => setGridEdits({}),
8273
+ children: "Discard All Edits"
8274
+ }
8275
+ )
8276
+ ] })
8277
+ ] })
8278
+ }
8279
+ ),
6276
8280
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { className: "bulk-updater-table-container", style: { width: "100%", maxWidth: "100%", minWidth: 0, overflowX: "auto" }, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Table, { colCount: activeColumns.length, rowCount: visibleEntries.length + 1, style: { width: "100%" }, children: [
6277
8281
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Thead, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tr, { children: activeColumns.map(
6278
8282
  (colDef) => renderHeaderCell(colDef, col, currentSort, selectedAttribute, searchAttribute, handleHeaderSortClick)
@@ -6289,12 +8293,27 @@ const BulkUpdater = () => {
6289
8293
  const dzFields = Object.keys(entry).filter(
6290
8294
  (k) => Array.isArray(entry[k]) && entry[k].length > 0 && entry[k].some((item) => item && item.__component)
6291
8295
  );
8296
+ const selectedRootKey = selectedAttribute ? selectedAttribute.split("[")[0].split(".")[0] : "";
8297
+ const expandableArrayFields = gridEditMode && selectedRootKey && activeAttrMeta?.rootRepeatable && !dzFields.includes(selectedRootKey) && Array.isArray(entry[selectedRootKey]) && entry[selectedRootKey].length > 0 ? [...dzFields, selectedRootKey] : dzFields;
8298
+ const recordEdits = gridEdits[key];
8299
+ const gridCtx = gridEditMode ? {
8300
+ gridEditMode: true,
8301
+ selectedAttrMeta: activeAttrMeta,
8302
+ recordEdits,
8303
+ relationOptions,
8304
+ relationOptionsLoading,
8305
+ relationIsMulti: Boolean(relationsMeta[selectedAttribute]?.isMulti),
8306
+ validationRules,
8307
+ onCommitEdit: handleGridCellCommit,
8308
+ onResetEdit: handleGridCellReset
8309
+ } : void 0;
8310
+ const rowOccs = gridEditMode && isDzExpanded && selectedAttribute ? enumerateClientOccurrences(entry, selectedAttribute, col?.attributes, activeAttrMeta) : [];
6292
8311
  return /* @__PURE__ */ jsxRuntime.jsxs(React__default.default.Fragment, { children: [
6293
8312
  /* @__PURE__ */ jsxRuntime.jsx(
6294
8313
  designSystem.Tr,
6295
8314
  {
6296
8315
  style: {
6297
- backgroundColor: isSelected ? "rgba(73, 69, 255, 0.14)" : isMatch ? "rgba(46, 213, 115, 0.08)" : void 0,
8316
+ backgroundColor: recordEdits ? "rgba(73, 69, 255, 0.10)" : isSelected ? "rgba(73, 69, 255, 0.14)" : isMatch ? "rgba(46, 213, 115, 0.08)" : void 0,
6298
8317
  boxShadow: isSelected ? "inset 3px 0 0 0 #4945ff" : isMatch ? "inset 3px 0 0 0 #2ed573" : void 0
6299
8318
  },
6300
8319
  children: activeColumns.map((colDef) => /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: renderCellContent(
@@ -6310,97 +8329,47 @@ const BulkUpdater = () => {
6310
8329
  pendingBatches,
6311
8330
  isDzExpanded,
6312
8331
  onToggleExpandDz,
6313
- filterQuery
8332
+ filterQuery,
8333
+ gridCtx
6314
8334
  ) }, colDef.key))
6315
8335
  }
6316
8336
  ),
6317
- isDzExpanded && dzFields.map((dzKey) => {
6318
- const blocks = entry[dzKey] || [];
6319
- const targetParsed = parseDynamicZonePath(selectedAttribute);
6320
- const isBlockApplicable = (blockItem) => {
6321
- if (!targetParsed.subPath) return true;
6322
- const scopedPath = `${dzKey}[${blockItem?.__component}].${targetParsed.subPath}`;
6323
- const componentSupports = (col?.attributes || attributes || []).includes(scopedPath);
6324
- return componentSupports || getNestedValue(blockItem, targetParsed.subPath) !== void 0;
6325
- };
6326
- const allApplicableIndexes = blocks.map((_, i) => i).filter((i) => isBlockApplicable(blocks[i]));
6327
- return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tr, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { colSpan: activeColumns.length, style: { padding: "12px 16px", backgroundColor: "rgba(73, 69, 255, 0.02)", borderBottom: "2px solid rgba(73, 69, 255, 0.15)" }, children: /* @__PURE__ */ jsxRuntime.jsxs(
6328
- designSystem.Box,
8337
+ isDzExpanded && expandableArrayFields.map((dzKey) => {
8338
+ const drawerOccurrences = gridEditMode && selectedAttribute ? rowOccs : enumerateClientOccurrences(entry, selectedAttribute, col?.attributes, activeAttrMeta);
8339
+ return /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tr, { children: /* @__PURE__ */ jsxRuntime.jsx(
8340
+ designSystem.Td,
6329
8341
  {
6330
- padding: 3,
6331
- background: "neutral0",
6332
- hasRadius: true,
6333
- style: { border: "1px solid rgba(73, 69, 255, 0.25)", boxShadow: "0 2px 8px rgba(0,0,0,0.05)" },
6334
- children: [
6335
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", marginBottom: 2, children: [
6336
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
6337
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "sigma", textColor: "primary700", children: [
6338
- 'DYNAMIC ZONE: "',
6339
- dzKey,
6340
- '" (',
6341
- blocks.length,
6342
- " blocks)"
6343
- ] }),
6344
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "primary100", textColor: "primary700", children: "Selective Block Targeting" })
6345
- ] }),
6346
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral500", children: "Selectively choose which blocks to update for this entry" })
6347
- ] }),
6348
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Table, { colCount: 5, rowCount: blocks.length + 1, style: { width: "100%", background: "#fff" }, children: [
6349
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Thead, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
6350
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 64 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Update?" }) }),
6351
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 60 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Pos" }) }),
6352
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { style: { width: 220 }, children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Component" }) }),
6353
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "sigma", children: [
6354
- "Target Field Value (",
6355
- selectedAttribute || "selected",
6356
- ")"
6357
- ] }) }),
6358
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Block Summary" }) })
6359
- ] }) }),
6360
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tbody, { children: blocks.map((block, bIdx) => {
6361
- const compUid = block.__component;
6362
- const compLabel = formatComponentName(compUid);
6363
- const scopedPath = `${dzKey}[${compUid}].${targetParsed.subPath}`;
6364
- const componentSupports = (col?.attributes || attributes || []).includes(scopedPath);
6365
- const blockVal = targetParsed.subPath ? getNestedValue(block, targetParsed.subPath) : void 0;
6366
- const hasTargetAttr = componentSupports || blockVal !== void 0;
6367
- const isBlockChecked = hasTargetAttr && isSelected && (selectedDzBlocks[key] !== void 0 ? selectedDzBlocks[key].includes(bIdx) : true);
6368
- return /* @__PURE__ */ jsxRuntime.jsxs(
6369
- designSystem.Tr,
6370
- {
6371
- style: {
6372
- backgroundColor: isBlockChecked ? "rgba(73, 69, 255, 0.08)" : void 0
6373
- },
6374
- children: [
6375
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(
6376
- designSystem.Checkbox,
6377
- {
6378
- checked: isBlockChecked,
6379
- disabled: !hasTargetAttr,
6380
- onCheckedChange: () => {
6381
- toggleDzBlock(col.uid, entry.documentId, bIdx, allApplicableIndexes);
6382
- }
6383
- }
6384
- ) }),
6385
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", fontWeight: "bold", children: [
6386
- "#",
6387
- bIdx
6388
- ] }) }),
6389
- /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Td, { children: [
6390
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "neutral150", textColor: "neutral800", children: compLabel }),
6391
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral500", display: "block", style: { fontSize: "0.68rem", marginTop: 2 }, children: compUid })
6392
- ] }),
6393
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: hasTargetAttr ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", fontWeight: "semiBold", textColor: "primary700", children: formatDisplayValue(blockVal) }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "neutral100", textColor: "neutral500", children: "Does not contain attribute" }) }),
6394
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", style: { maxWidth: 300, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }, children: block.title || block.name || block.heading || block.body || Object.keys(block).filter((k) => !k.startsWith("_") && k !== "id").slice(0, 3).map((k) => `${k}: ${formatDisplayValue(block[k])}`).join(", ") || "-" }) })
6395
- ]
6396
- },
6397
- bIdx
6398
- );
6399
- }) })
6400
- ] })
6401
- ]
8342
+ colSpan: activeColumns.length,
8343
+ style: {
8344
+ padding: "12px 16px",
8345
+ backgroundColor: "rgba(73, 69, 255, 0.02)",
8346
+ borderBottom: "2px solid rgba(73, 69, 255, 0.15)"
8347
+ },
8348
+ children: /* @__PURE__ */ jsxRuntime.jsx(
8349
+ ComponentOccurrencesDrawer,
8350
+ {
8351
+ colUid: col.uid,
8352
+ rootKey: dzKey,
8353
+ entry,
8354
+ selectedAttribute,
8355
+ attrMeta: activeAttrMeta,
8356
+ colAttributes: col?.attributes || attributes || [],
8357
+ gridEditMode,
8358
+ isSelected,
8359
+ selectedDzBlocks: selectedDzBlocks[key],
8360
+ occurrences: drawerOccurrences,
8361
+ recordEdits,
8362
+ relationOptions,
8363
+ relationOptionsLoading,
8364
+ relationIsMulti: Boolean(relationsMeta[selectedAttribute]?.isMulti),
8365
+ validationRules,
8366
+ onToggleDzBlock: toggleDzBlock,
8367
+ onCommitEdit: handleGridCellCommit,
8368
+ onResetEdit: handleGridCellReset
8369
+ }
8370
+ )
6402
8371
  }
6403
- ) }) }, `${key}-dz-${dzKey}`);
8372
+ ) }, `${key}-dz-${dzKey}`);
6404
8373
  })
6405
8374
  ] }, key);
6406
8375
  }) })
@@ -6499,10 +8468,38 @@ const BulkUpdater = () => {
6499
8468
  marginBottom: 6,
6500
8469
  style: { width: "100%", maxWidth: "100%", minWidth: 0, boxSizing: "border-box" },
6501
8470
  children: [
6502
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", marginBottom: 4, wrap: "wrap", gap: 3, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { children: [
6503
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "delta", tag: "h2", fontWeight: "semiBold", children: "2. Configure Attribute Update" }),
6504
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: "Select the target attribute to update and configure the replacement value for your selected entries." })
6505
- ] }) }),
8471
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", marginBottom: 4, wrap: "wrap", gap: 3, children: [
8472
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { children: [
8473
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "delta", tag: "h2", fontWeight: "semiBold", children: "2. Configure Attribute Update" }),
8474
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: "Select the target attribute to update and either apply a common value or enable inline Grid Editing." })
8475
+ ] }),
8476
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { gap: 3, alignItems: "center", wrap: "wrap", children: /* @__PURE__ */ jsxRuntime.jsx(
8477
+ designSystem.Box,
8478
+ {
8479
+ padding: 2,
8480
+ paddingLeft: 3,
8481
+ paddingRight: 3,
8482
+ background: gridEditMode ? "primary100" : "neutral100",
8483
+ hasRadius: true,
8484
+ style: { border: gridEditMode ? "1px solid #4945ff" : "1px solid #eaeaef" },
8485
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", children: [
8486
+ /* @__PURE__ */ jsxRuntime.jsx(
8487
+ designSystem.Checkbox,
8488
+ {
8489
+ checked: gridEditMode,
8490
+ onCheckedChange: (checked) => handleToggleGridEditMode(Boolean(checked)),
8491
+ children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "bold", textColor: gridEditMode ? "primary700" : "neutral800", children: "Edit Values in Grid" })
8492
+ }
8493
+ ),
8494
+ gridEditMode && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "primary600", textColor: "neutral0", size: "S", children: [
8495
+ "ON (",
8496
+ gridSerialized.totalEditCount,
8497
+ " edits)"
8498
+ ] })
8499
+ ] })
8500
+ }
8501
+ ) })
8502
+ ] }),
6506
8503
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 3, alignItems: "flex-end", wrap: "wrap", children: [
6507
8504
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { width: 280, minWidth: 230 }, children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Field.Root, { children: [
6508
8505
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Field.Label, { children: "Attribute to Update" }),
@@ -6529,7 +8526,35 @@ const BulkUpdater = () => {
6529
8526
  `update-attr-${selectedCollectionUid}`
6530
8527
  )
6531
8528
  ] }) }),
6532
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1, minWidth: 340 }, children: relationsMeta[selectedAttribute] ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 1, style: { width: "100%" }, children: [
8529
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Box, { style: { flex: 1, minWidth: 340 }, children: gridEditMode ? /* @__PURE__ */ jsxRuntime.jsx(
8530
+ designSystem.Box,
8531
+ {
8532
+ padding: 3,
8533
+ background: "primary100",
8534
+ hasRadius: true,
8535
+ style: { border: "1px solid #d9d8ff" },
8536
+ children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", wrap: "wrap", gap: 2, children: [
8537
+ /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { children: [
8538
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", fontWeight: "bold", textColor: "primary700", display: "block", children: "Common value input hidden — Grid Editing Mode active" }),
8539
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "neutral700", children: gridSerialized.targets.length > 0 ? `Ready: ${gridSerialized.totalEditCount} edited field/block value(s) across ${gridSerialized.targets.length} selected record(s).` : "Edit cell values directly in the table above (or expand component blocks) to queue heterogeneous updates." }),
8540
+ gridSerialized.hasValidationErrors && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", fontWeight: "bold", display: "block", children: "⚠️ Resolve inline red validation errors before previewing or updating." })
8541
+ ] }),
8542
+ totalDirtyCellsCount > 0 && /* @__PURE__ */ jsxRuntime.jsxs(
8543
+ designSystem.Button,
8544
+ {
8545
+ variant: "danger-light",
8546
+ size: "S",
8547
+ onClick: () => setGridEdits({}),
8548
+ children: [
8549
+ "Discard Edits (",
8550
+ totalDirtyCellsCount,
8551
+ ")"
8552
+ ]
8553
+ }
8554
+ )
8555
+ ] })
8556
+ }
8557
+ ) : relationsMeta[selectedAttribute] ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 1, style: { width: "100%" }, children: [
6533
8558
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, alignItems: "center", wrap: "wrap", children: [
6534
8559
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", fontWeight: "bold", textColor: "neutral700", children: [
6535
8560
  "Target ",
@@ -6614,10 +8639,10 @@ const BulkUpdater = () => {
6614
8639
  size: "L",
6615
8640
  onClick: handleOpenPreviewModal,
6616
8641
  loading: previewLoading,
6617
- disabled: loading || totalSelectedCount === 0 || !selectedAttribute || !selectedAttribute.trim(),
8642
+ disabled: loading || !selectedAttribute || !selectedAttribute.trim() || (gridEditMode ? gridSerialized.targets.length === 0 || gridSerialized.hasValidationErrors : totalSelectedCount === 0),
6618
8643
  children: [
6619
8644
  "Preview Changes (",
6620
- totalSelectedCount,
8645
+ gridEditMode ? gridSerialized.targets.length : totalSelectedCount,
6621
8646
  ")"
6622
8647
  ]
6623
8648
  }
@@ -6630,10 +8655,10 @@ const BulkUpdater = () => {
6630
8655
  size: "L",
6631
8656
  onClick: handleOpenConfirmModal,
6632
8657
  loading: updating,
6633
- disabled: loading || totalSelectedCount === 0 || !selectedAttribute || !selectedAttribute.trim(),
8658
+ disabled: loading || !selectedAttribute || !selectedAttribute.trim() || (gridEditMode ? gridSerialized.targets.length === 0 || gridSerialized.hasValidationErrors : totalSelectedCount === 0),
6634
8659
  children: [
6635
8660
  "Update Selected (",
6636
- totalSelectedCount,
8661
+ gridEditMode ? gridSerialized.targets.length : totalSelectedCount,
6637
8662
  ")"
6638
8663
  ]
6639
8664
  }
@@ -6720,11 +8745,11 @@ const BulkUpdater = () => {
6720
8745
  "Attribute: ",
6721
8746
  selectedAttribute,
6722
8747
  " ",
6723
- attributesMeta[selectedAttribute]?.type ? `(${attributesMeta[selectedAttribute].type})` : ""
8748
+ activeAttrMeta?.type ? `(${activeAttrMeta.type})` : ""
6724
8749
  ] }),
6725
- attributesMeta[selectedAttribute]?.depth ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "neutral200", textColor: "neutral700", children: [
8750
+ activeAttrMeta?.depth ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "neutral200", textColor: "neutral700", children: [
6726
8751
  "Nesting Level: L",
6727
- attributesMeta[selectedAttribute].depth
8752
+ activeAttrMeta.depth
6728
8753
  ] }) : null,
6729
8754
  selectedCol.draftAndPublish ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "success100", textColor: "success700", children: "Draft & Publish Enabled" }) : /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "warning100", textColor: "warning700", children: "Direct Publish Only" })
6730
8755
  ] }) }) })
@@ -7162,7 +9187,15 @@ const BulkUpdater = () => {
7162
9187
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Previous Value" }) }),
7163
9188
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Th, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", children: "Applied Value" }) })
7164
9189
  ] }) }),
7165
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tbody, { children: rec.diffs.map((d, dIdx) => /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
9190
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Tbody, { children: rec.diffs.flatMap(
9191
+ (d) => Array.isArray(d.dynamicZoneDiffs) && d.dynamicZoneDiffs.length > 0 ? d.dynamicZoneDiffs.map((dz) => ({
9192
+ collectionName: d.collectionName,
9193
+ label: `${d.label}${dz.componentName ? ` [${dz.componentName}]` : ""}`,
9194
+ attribute: dz.attribute || d.attribute,
9195
+ oldValue: dz.oldValue,
9196
+ newValue: dz.newValue
9197
+ })) : [d]
9198
+ ).map((d, dIdx) => /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Tr, { children: [
7166
9199
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "semiBold", children: d.collectionName }) }),
7167
9200
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { children: d.label }) }),
7168
9201
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Td, { children: /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "secondary100", textColor: "secondary700", children: d.attribute || "field" }) }),
@@ -7251,7 +9284,13 @@ const BulkUpdater = () => {
7251
9284
  ] }),
7252
9285
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", children: [
7253
9286
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "semiBold", children: "Target Value:" }),
7254
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", style: { wordBreak: "break-all", maxWidth: 360 }, children: relationsMeta[selectedAttribute] ? /* @__PURE__ */ jsxRuntime.jsx("span", { children: selectedRelationDocId === "__clear__" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "danger100", textColor: "danger700", children: "Clear / Unlink Relation" }) : /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "secondary100", textColor: "secondary700", children: [
9287
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "omega", style: { wordBreak: "break-all", maxWidth: 360 }, children: gridEditMode ? /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "secondary100", textColor: "secondary700", children: [
9288
+ "Grid Editing (",
9289
+ gridSerialized.totalEditCount,
9290
+ " heterogeneous edits across ",
9291
+ gridSerialized.targets.length,
9292
+ " records)"
9293
+ ] }) : relationsMeta[selectedAttribute] ? /* @__PURE__ */ jsxRuntime.jsx("span", { children: selectedRelationDocId === "__clear__" ? /* @__PURE__ */ jsxRuntime.jsx(designSystem.Badge, { backgroundColor: "danger100", textColor: "danger700", children: "Clear / Unlink Relation" }) : /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "secondary100", textColor: "secondary700", children: [
7255
9294
  relationsMeta[selectedAttribute].isMulti ? `[${relationMode.toUpperCase()}] ` : "",
7256
9295
  relationOptions.find((o) => o.documentId === selectedRelationDocId)?.label || selectedRelationDocId || "(none selected)"
7257
9296
  ] }) }) : useRegex ? /* @__PURE__ */ jsxRuntime.jsxs("span", { children: [
@@ -7276,7 +9315,7 @@ const BulkUpdater = () => {
7276
9315
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", children: [
7277
9316
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "semiBold", children: "Total Selected Records:" }),
7278
9317
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { fontWeight: "bold", textColor: "primary600", children: [
7279
- totalSelectedCount,
9318
+ gridEditMode ? gridSerialized.targets.length : totalSelectedCount,
7280
9319
  " records"
7281
9320
  ] })
7282
9321
  ] }),
@@ -7312,31 +9351,31 @@ const BulkUpdater = () => {
7312
9351
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { marginBottom: 4, padding: 3, background: "neutral100", hasRadius: true, style: { border: "1px solid rgba(120, 120, 150, 0.15)" }, children: [
7313
9352
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "sigma", textColor: "neutral600", marginBottom: 2, display: "block", children: [
7314
9353
  "LIFECYCLE STATUS BREAKDOWN (",
7315
- totalSelectedCount,
9354
+ gridEditMode ? gridSerialized.targets.length : totalSelectedCount,
7316
9355
  " Selected)"
7317
9356
  ] }),
7318
9357
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, wrap: "wrap", children: [
7319
9358
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "success100", textColor: "success700", children: [
7320
9359
  "✓ Published / Approved: ",
7321
- selectedLifecycleStats.published
9360
+ updateModalLifecycleStats.published
7322
9361
  ] }),
7323
- selectedLifecycleStats.modified > 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "primary100", textColor: "primary700", children: [
9362
+ updateModalLifecycleStats.modified > 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "primary100", textColor: "primary700", children: [
7324
9363
  "📝 Modified (Unreviewed Revisions): ",
7325
- selectedLifecycleStats.modified
9364
+ updateModalLifecycleStats.modified
7326
9365
  ] }),
7327
- selectedLifecycleStats.draft > 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "neutral200", textColor: "neutral800", children: [
9366
+ updateModalLifecycleStats.draft > 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "neutral200", textColor: "neutral800", children: [
7328
9367
  "📄 Draft (Never Published): ",
7329
- selectedLifecycleStats.draft
9368
+ updateModalLifecycleStats.draft
7330
9369
  ] }),
7331
- selectedLifecycleStats.pendingReview > 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "warning100", textColor: "warning700", children: [
9370
+ updateModalLifecycleStats.pendingReview > 0 && /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Badge, { backgroundColor: "warning100", textColor: "warning700", children: [
7332
9371
  "⏳ Pending Review: ",
7333
- selectedLifecycleStats.pendingReview
9372
+ updateModalLifecycleStats.pendingReview
7334
9373
  ] })
7335
9374
  ] })
7336
9375
  ] }),
7337
9376
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Box, { marginBottom: 4, children: [
7338
9377
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "sigma", textColor: "neutral600", marginBottom: 2, display: "block", children: "COLLECTION BREAKDOWN" }),
7339
- /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", gap: 1, children: Object.entries(getSelectedBreakdown()).map(([name, count]) => /* @__PURE__ */ jsxRuntime.jsxs(
9378
+ /* @__PURE__ */ jsxRuntime.jsx(designSystem.Flex, { direction: "column", gap: 1, children: Object.entries(getSelectedBreakdown(gridEditMode ? gridTargetKeys : void 0)).map(([name, count]) => /* @__PURE__ */ jsxRuntime.jsxs(
7340
9379
  designSystem.Flex,
7341
9380
  {
7342
9381
  justifyContent: "space-between",
@@ -7384,7 +9423,7 @@ const BulkUpdater = () => {
7384
9423
  ] })
7385
9424
  }
7386
9425
  ),
7387
- publishOnApproval && selectedLifecycleStats.unreviewedCount > 0 && /* @__PURE__ */ jsxRuntime.jsxs(
9426
+ publishOnApproval && updateModalLifecycleStats.unreviewedCount > 0 && /* @__PURE__ */ jsxRuntime.jsxs(
7388
9427
  designSystem.Box,
7389
9428
  {
7390
9429
  padding: 4,
@@ -7428,11 +9467,11 @@ const BulkUpdater = () => {
7428
9467
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "bold", display: "block", children: "🛡️ Safe Publishing (Recommended)" }),
7429
9468
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: [
7430
9469
  "Only publish records that are already approved & live (",
7431
- selectedLifecycleStats.published,
9470
+ updateModalLifecycleStats.published,
7432
9471
  " record",
7433
- selectedLifecycleStats.published === 1 ? "" : "s",
9472
+ updateModalLifecycleStats.published === 1 ? "" : "s",
7434
9473
  "). The ",
7435
- selectedLifecycleStats.unreviewedCount,
9474
+ updateModalLifecycleStats.unreviewedCount,
7436
9475
  " unreviewed or draft record(s) will receive the bulk update in Draft mode without publishing unreviewed draft revisions to visitors."
7437
9476
  ] })
7438
9477
  ] })
@@ -7466,9 +9505,9 @@ const BulkUpdater = () => {
7466
9505
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "bold", textColor: "danger700", display: "block", children: "⚠️ Publish All Selected Records (Includes Unreviewed Drafts)" }),
7467
9506
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", textColor: "neutral600", children: [
7468
9507
  "Publish all ",
7469
- totalSelectedCount,
9508
+ gridEditMode ? gridSerialized.targets.length : totalSelectedCount,
7470
9509
  " records live to production immediately, pushing all pending unreviewed draft edits in the ",
7471
- selectedLifecycleStats.unreviewedCount,
9510
+ updateModalLifecycleStats.unreviewedCount,
7472
9511
  " draft/modified record(s) live."
7473
9512
  ] })
7474
9513
  ] })
@@ -7495,7 +9534,7 @@ const BulkUpdater = () => {
7495
9534
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { fontWeight: "bold", textColor: "danger700", display: "block", children: "Mandatory Risk Consent Required" }),
7496
9535
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Typography, { variant: "pi", textColor: "danger700", children: [
7497
9536
  "I understand and explicitly consent that ",
7498
- selectedLifecycleStats.unreviewedCount,
9537
+ updateModalLifecycleStats.unreviewedCount,
7499
9538
  " record(s) with unreviewed draft revisions or saved draft states will be published live to production visitors."
7500
9539
  ] })
7501
9540
  ] })
@@ -7533,7 +9572,7 @@ const BulkUpdater = () => {
7533
9572
  boxShadow: "0 -4px 16px rgba(0, 0, 0, 0.08)"
7534
9573
  },
7535
9574
  children: /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { direction: "column", gap: 2, style: { width: "100%" }, children: [
7536
- publishOnApproval && selectedLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", fontWeight: "bold", children: "⚠️ Explicit consent is required before publishing records with unreviewed draft revisions." }),
9575
+ publishOnApproval && updateModalLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent && /* @__PURE__ */ jsxRuntime.jsx(designSystem.Typography, { variant: "pi", textColor: "danger700", fontWeight: "bold", children: "⚠️ Explicit consent is required before publishing records with unreviewed draft revisions." }),
7537
9576
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { justifyContent: "space-between", alignItems: "center", gap: 3, style: { width: "100%" }, children: [
7538
9577
  /* @__PURE__ */ jsxRuntime.jsx(designSystem.Button, { variant: "tertiary", size: "M", onClick: () => setShowConfirmModal(false), children: "Cancel" }),
7539
9578
  /* @__PURE__ */ jsxRuntime.jsxs(designSystem.Flex, { gap: 2, wrap: "wrap", justifyContent: "flex-end", alignItems: "center", children: [
@@ -7544,7 +9583,7 @@ const BulkUpdater = () => {
7544
9583
  size: "M",
7545
9584
  onClick: () => executeBatchWithMode("maker_checker"),
7546
9585
  loading: updating,
7547
- disabled: updating || publishOnApproval && selectedLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent,
9586
+ disabled: updating || publishOnApproval && updateModalLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent,
7548
9587
  children: "Submit for Checker Approval"
7549
9588
  }
7550
9589
  ),
@@ -7556,7 +9595,7 @@ const BulkUpdater = () => {
7556
9595
  size: "M",
7557
9596
  onClick: () => executeBatchWithMode("queue_offpeak"),
7558
9597
  loading: updating,
7559
- disabled: updating || publishOnApproval && selectedLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent,
9598
+ disabled: updating || publishOnApproval && updateModalLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent,
7560
9599
  children: [
7561
9600
  "Queue for Off-Peak (",
7562
9601
  executionWindow?.offPeakStartTime || "18:00",
@@ -7571,7 +9610,7 @@ const BulkUpdater = () => {
7571
9610
  size: "S",
7572
9611
  onClick: () => executeBatchWithMode("immediate", true),
7573
9612
  loading: updating,
7574
- disabled: updating || publishOnApproval && selectedLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent,
9613
+ disabled: updating || publishOnApproval && updateModalLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent,
7575
9614
  children: "Force Run Now"
7576
9615
  }
7577
9616
  )
@@ -7582,7 +9621,7 @@ const BulkUpdater = () => {
7582
9621
  size: "M",
7583
9622
  onClick: () => executeBatchWithMode("immediate"),
7584
9623
  loading: updating,
7585
- disabled: updating || publishOnApproval && selectedLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent,
9624
+ disabled: updating || publishOnApproval && updateModalLifecycleStats.unreviewedCount > 0 && publishStrategy === "all" && !unreviewedConsent,
7586
9625
  children: "Confirm & Execute Now"
7587
9626
  }
7588
9627
  )
@@ -7871,9 +9910,10 @@ const BulkUpdater = () => {
7871
9910
  loading: previewLoading,
7872
9911
  previewData,
7873
9912
  attribute: selectedAttribute,
9913
+ editMode: gridEditMode ? "grid" : "common",
7874
9914
  publishOnApproval,
7875
9915
  lifecycleStats: selectedLifecycleStats,
7876
- targetValueDisplay: relationsMeta[selectedAttribute] ? selectedRelationDocId === "__clear__" ? "Clear / Unlink Relation" : relationOptions.find((o) => o.documentId === selectedRelationDocId)?.label || selectedRelationDocId || "(none)" : useRegex ? `Replace /${regexPattern}/g with "${attributeValue}"` : attributeValue
9916
+ targetValueDisplay: gridEditMode ? `Grid Editing (${gridSerialized.totalEditCount} edits across ${gridSerialized.targets.length} records)` : relationsMeta[selectedAttribute] ? selectedRelationDocId === "__clear__" ? "Clear / Unlink Relation" : relationOptions.find((o) => o.documentId === selectedRelationDocId)?.label || selectedRelationDocId || "(none)" : useRegex ? `Replace /${regexPattern}/g with "${attributeValue}"` : attributeValue
7877
9917
  }
7878
9918
  ),
7879
9919
  /* @__PURE__ */ jsxRuntime.jsx(
@@ -7913,4 +9953,4 @@ exports.getNestedValue = getNestedValue;
7913
9953
  exports.getPropertyValue = getPropertyValue;
7914
9954
  exports.getSortOptionsForCollection = getSortOptionsForCollection;
7915
9955
  exports.parseDynamicZonePath = parseDynamicZonePath;
7916
- //# sourceMappingURL=BulkUpdater-CrmdSFUB.js.map
9956
+ //# sourceMappingURL=BulkUpdater-D12SUhTd.js.map