@jsb188/mday 1.1.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (202) hide show
  1. package/package.json +142 -0
  2. package/src/constants/agentMemory.ts +166 -0
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +10 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +236 -0
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +22 -0
  10. package/src/constants/dataTableFieldTypes.generated.ts +59 -0
  11. package/src/constants/docAccess.ts +33 -0
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +146 -0
  14. package/src/constants/fieldDoc.ts +104 -0
  15. package/src/constants/graphqlReactivity.ts +196 -0
  16. package/src/constants/inboundContact.ts +8 -0
  17. package/src/constants/integration.ts +13 -0
  18. package/src/constants/log.ts +21 -0
  19. package/src/constants/logDisplay/README.md +88 -0
  20. package/src/constants/logDisplay/defaults.ts +39 -0
  21. package/src/constants/logDisplay/index.ts +27 -0
  22. package/src/constants/logDisplay/operations/arable.ts +16 -0
  23. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  24. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  25. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  26. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  27. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  28. package/src/constants/logTaxonomy.generated.ts +2199 -0
  29. package/src/constants/noteDoc.ts +77 -0
  30. package/src/constants/organization.ts +60 -0
  31. package/src/constants/pageRoute.ts +23 -0
  32. package/src/constants/qrCode.ts +30 -0
  33. package/src/constants/sheet.ts +132 -0
  34. package/src/constants/sms.ts +18 -0
  35. package/src/constants/square.ts +16 -0
  36. package/src/constants/storage.ts +85 -0
  37. package/src/constants/usage.ts +82 -0
  38. package/src/constants/workflowSteps.ts +60 -0
  39. package/src/schemas/editLogEntry.ts +879 -0
  40. package/src/schemas/inboundContact.ts +77 -0
  41. package/src/schemas/logsQuery.ts +93 -0
  42. package/src/types/account.d.ts +81 -0
  43. package/src/types/agentMemory.d.ts +100 -0
  44. package/src/types/agentNote.d.ts +441 -0
  45. package/src/types/billing.d.ts +537 -0
  46. package/src/types/campaign.d.ts +1533 -0
  47. package/src/types/contact.d.ts +15 -0
  48. package/src/types/csvExport.d.ts +213 -0
  49. package/src/types/dataAnalysis.d.ts +44 -0
  50. package/src/types/dataTable.d.ts +159 -0
  51. package/src/types/definitionElement.d.ts +35 -0
  52. package/src/types/docAccess.d.ts +96 -0
  53. package/src/types/dt.d.ts +257 -0
  54. package/src/types/email.d.ts +231 -0
  55. package/src/types/emailReplyReport.d.ts +76 -0
  56. package/src/types/fieldDoc.d.ts +702 -0
  57. package/src/types/fieldDocContract.d.ts +90 -0
  58. package/src/types/inboundContact.d.ts +65 -0
  59. package/src/types/integration.d.ts +42 -0
  60. package/src/types/log.d.ts +338 -0
  61. package/src/types/logDisplay.types.ts +85 -0
  62. package/src/types/organization.d.ts +350 -0
  63. package/src/types/pageRoute.d.ts +48 -0
  64. package/src/types/qrCode.d.ts +96 -0
  65. package/src/types/richText.d.ts +81 -0
  66. package/src/types/sheet.d.ts +847 -0
  67. package/src/types/sms.d.ts +38 -0
  68. package/src/types/storage.d.ts +481 -0
  69. package/src/types/usage.d.ts +106 -0
  70. package/src/types/workflow.d.ts +435 -0
  71. package/src/utils/agentMemory.ts +15 -0
  72. package/src/utils/agentNote.ts +850 -0
  73. package/src/utils/aiChat.ts +43 -0
  74. package/src/utils/aiChatWork.ts +64 -0
  75. package/src/utils/billing.ts +37 -0
  76. package/src/utils/campaign.ts +1173 -0
  77. package/src/utils/campaignAI.ts +72 -0
  78. package/src/utils/campaignAccess.ts +239 -0
  79. package/src/utils/campaignEmail.ts +601 -0
  80. package/src/utils/campaignEmailCompiler.ts +372 -0
  81. package/src/utils/campaignEmailImages.ts +60 -0
  82. package/src/utils/campaignEmailStyles.ts +544 -0
  83. package/src/utils/campaignLifecycle.ts +104 -0
  84. package/src/utils/campaignPreview.ts +285 -0
  85. package/src/utils/contact.ts +50 -0
  86. package/src/utils/csvExport.ts +19 -0
  87. package/src/utils/dataTable.ts +311 -0
  88. package/src/utils/dataTableFieldTypeRegistry.ts +106 -0
  89. package/src/utils/dataTableRelativeDate.ts +447 -0
  90. package/src/utils/definitionElement.ts +84 -0
  91. package/src/utils/docAccess.ts +383 -0
  92. package/src/utils/documentName.ts +53 -0
  93. package/src/utils/email.ts +379 -0
  94. package/src/utils/emailReplyReport.test.ts +187 -0
  95. package/src/utils/emailReplyReport.ts +143 -0
  96. package/src/utils/fieldDoc.ts +157 -0
  97. package/src/utils/fieldDocAnswers.ts +128 -0
  98. package/src/utils/fieldDocDefaults.ts +36 -0
  99. package/src/utils/fieldDocProgram.ts +36 -0
  100. package/src/utils/fieldDocSummary.ts +30 -0
  101. package/src/utils/log.ts +357 -0
  102. package/src/utils/logDisplay.helpers.ts +177 -0
  103. package/src/utils/logDisplay.ts +87 -0
  104. package/src/utils/logRegistryValue.ts +90 -0
  105. package/src/utils/logStoreRead.ts +262 -0
  106. package/src/utils/logTaxonomy.helpers.ts +17 -0
  107. package/src/utils/logTaxonomy.ts +76 -0
  108. package/src/utils/logTaxonomyDisplay.ts +395 -0
  109. package/src/utils/noteDoc.ts +609 -0
  110. package/src/utils/organization.ts +669 -0
  111. package/src/utils/pageRoute.ts +71 -0
  112. package/src/utils/qrCode.helpers.ts +189 -0
  113. package/src/utils/qrCode.test.ts +519 -0
  114. package/src/utils/qrCode.ts +273 -0
  115. package/src/utils/richTextHTML.ts +385 -0
  116. package/src/utils/sheet.ts +262 -0
  117. package/src/utils/sheetAxisMove.ts +616 -0
  118. package/src/utils/sheetBootstrap.ts +1402 -0
  119. package/src/utils/sheetCellLiteral.ts +101 -0
  120. package/src/utils/sheetCommand.ts +358 -0
  121. package/src/utils/sheetDesign.ts +705 -0
  122. package/src/utils/sheetExport.ts +186 -0
  123. package/src/utils/sheetFeatureReference.ts +183 -0
  124. package/src/utils/sheetFormulaArgs.ts +168 -0
  125. package/src/utils/sheetFormulaCompile.ts +475 -0
  126. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  127. package/src/utils/sheetFormulaCriteria.ts +656 -0
  128. package/src/utils/sheetFormulaDate.ts +444 -0
  129. package/src/utils/sheetFormulaEvaluation.ts +899 -0
  130. package/src/utils/sheetFormulaEvaluator.ts +997 -0
  131. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  132. package/src/utils/sheetFormulaLogical.ts +116 -0
  133. package/src/utils/sheetFormulaLookup.ts +488 -0
  134. package/src/utils/sheetFormulaMath.ts +48 -0
  135. package/src/utils/sheetFormulaParser.ts +729 -0
  136. package/src/utils/sheetFormulaRange.ts +330 -0
  137. package/src/utils/sheetFormulaReference.ts +703 -0
  138. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  139. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  140. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  141. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  142. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  143. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  144. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  145. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  146. package/src/utils/sheetFormulaText.ts +430 -0
  147. package/src/utils/sheetJournal.ts +200 -0
  148. package/src/utils/sheetNumberFormat.ts +1012 -0
  149. package/src/utils/sheetPreview.ts +68 -0
  150. package/src/utils/sheetSequence.ts +118 -0
  151. package/src/utils/sheetSnapshot.ts +739 -0
  152. package/src/utils/sheetStructureEdit.ts +914 -0
  153. package/src/utils/sheetStructureReferences.ts +389 -0
  154. package/src/utils/square.ts +32 -0
  155. package/src/utils/storage.ts +198 -0
  156. package/src/utils/table-route.ts +262 -0
  157. package/src/utils/time.ts +12 -0
  158. package/src/utils/workflow.ts +506 -0
  159. package/src/utils/workflowLogFingerprint.ts +302 -0
  160. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  161. package/src/utils/workflowProgress.ts +280 -0
  162. package/src/utils/workflowTriggers.ts +61 -0
  163. package/tests/agentNote.test.ts +395 -0
  164. package/tests/campaignAI.test.ts +119 -0
  165. package/tests/campaignAccess.test.ts +239 -0
  166. package/tests/campaignEmail.test.ts +441 -0
  167. package/tests/campaignLifecycle.test.ts +134 -0
  168. package/tests/campaignPublication.test.ts +309 -0
  169. package/tests/dataTableFieldTypeRegistry.test.ts +111 -0
  170. package/tests/dataTableRelativeDate.test.ts +412 -0
  171. package/tests/docAccess.test.ts +525 -0
  172. package/tests/editLogEntry.test.ts +112 -0
  173. package/tests/email.test.ts +39 -0
  174. package/tests/fieldDocProgram.test.ts +114 -0
  175. package/tests/logDisplay.fixtures.ts +67 -0
  176. package/tests/logDisplay.test.ts +227 -0
  177. package/tests/noteDoc.test.ts +514 -0
  178. package/tests/richTextHTML.test.ts +185 -0
  179. package/tests/sheetAxisMove.test.ts +352 -0
  180. package/tests/sheetBootstrap.test.ts +1967 -0
  181. package/tests/sheetFeatureReference.test.ts +22 -0
  182. package/tests/sheetFormulaCriteria.test.ts +269 -0
  183. package/tests/sheetFormulaEvaluator.test.ts +468 -0
  184. package/tests/sheetFormulaFunctions.test.ts +538 -0
  185. package/tests/sheetFormulaLanguage.test.ts +361 -0
  186. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  187. package/tests/sheetFormulaParity.test.ts +188 -0
  188. package/tests/sheetFormulaRange.test.ts +167 -0
  189. package/tests/sheetFormulaReference.test.ts +78 -0
  190. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  191. package/tests/sheetFormulaTextDate.test.ts +512 -0
  192. package/tests/sheetSequence.test.ts +22 -0
  193. package/tests/sheetSnapshot.test.ts +134 -0
  194. package/tests/sheetStructureEdit.test.ts +537 -0
  195. package/tests/sheetStructureReferences.test.ts +589 -0
  196. package/tests/workflowLifecycleStatus.test.ts +60 -0
  197. package/tests/workflowLogFingerprint.test.ts +203 -0
  198. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  199. package/tests/workflowProgress.test.ts +180 -0
  200. package/tests/workflowTriggers.test.ts +29 -0
  201. package/tsconfig.json +12 -0
  202. package/vitest.config.ts +8 -0
@@ -0,0 +1,914 @@
1
+ /**
2
+ * Sheet structure-edit helpers shared by the client and the server.
3
+ * Formerly at packages/@jsb188:sheet/src/libs/sheet-structure-edit.ts
4
+ * (moved verbatim for layering; check that path for older git blame).
5
+ */
6
+
7
+ import { parseJSON, stringifyJSON } from '@jsb188/app/utils/object.ts';
8
+ import { SHEET_MAX_COLUMN_COUNT, SHEET_MAX_ROW_COUNT } from '@jsb188/mday/constants/sheet.ts';
9
+ import type {
10
+ SheetAxisDesignObj,
11
+ SheetDesignObj,
12
+ SheetMergedRangeObj,
13
+ SheetNamedRangeObj,
14
+ SheetStructureOperationEnum,
15
+ } from '@jsb188/mday/types/sheet.d.ts';
16
+ import {
17
+ getSheetMergedRanges,
18
+ normalizeSheetDesign,
19
+ shiftSheetAxisDesignForStructureEdit,
20
+ shiftSheetMergedRangesForStructureEdit,
21
+ } from '@jsb188/mday/utils/sheetDesign.ts';
22
+
23
+ /*
24
+ * Return one design patch field as a parsed object. Patch fields carry
25
+ * serialized JSON, but already-parsed objects pass through unchanged. Local
26
+ * because this module is shared with the server.
27
+ */
28
+ function parseSheetDesignPatchObject<T extends Record<string, any>>(value: unknown, fallback: T): T {
29
+ if (value && typeof value === 'object' && !Array.isArray(value)) {
30
+ return value as T;
31
+ }
32
+
33
+ if (typeof value !== 'string' || !value) {
34
+ return fallback;
35
+ }
36
+
37
+ const parsed = parseJSON(value);
38
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as T) : fallback;
39
+ }
40
+
41
+ export interface SheetStructureBounds {
42
+ endColumnIndex: number;
43
+ endRowIndex: number;
44
+ startColumnIndex: number;
45
+ startRowIndex: number;
46
+ }
47
+
48
+ export interface SheetStructureCellCoord {
49
+ columnIndex: number;
50
+ rowIndex: number;
51
+ }
52
+
53
+ export interface SheetStructureCellLike {
54
+ columnIndex?: number | null;
55
+ rowIndex?: number | null;
56
+ }
57
+
58
+ export interface SheetStructureRangeLike {
59
+ endColumnIndex?: number | null;
60
+ endRowIndex?: number | null;
61
+ startColumnIndex?: number | null;
62
+ startRowIndex?: number | null;
63
+ }
64
+
65
+ /* The stored content properties that make one cell non-blank. */
66
+ export interface SheetStructureCellContentLike {
67
+ booleanValue?: boolean | null;
68
+ dateValue?: string | null;
69
+ datetimeValue?: string | null;
70
+ formulaText?: string | null;
71
+ numberValue?: number | null;
72
+ rawInput?: string | null;
73
+ textValue?: string | null;
74
+ value?: unknown;
75
+ }
76
+
77
+ /* Why an insert at the grid cap cannot run (null = it can). */
78
+ export type SheetStructureInsertAtCapBlocker = 'BEYOND_GRID' | 'CELLS' | 'MERGES';
79
+
80
+ /*
81
+ * One row/column insert or delete: the operation, its one-based index and,
82
+ * only when the operation's own delta must not decide it, the count the edited
83
+ * axis ends at (the inverse of an edit the shared clamp absorbed).
84
+ */
85
+ export interface SheetStructureEdit {
86
+ axisCount?: number;
87
+ index: number;
88
+ operation: SheetStructureOperationEnum;
89
+ }
90
+
91
+ /* One ordinary row or column edit shared by cells and references. */
92
+ export type SheetStructureCellRuleEdit = SheetStructureEdit;
93
+
94
+ /*
95
+ * The new position of one row or column after an edit.
96
+ */
97
+ export type SheetStructureLineAfterEdit = { index: number; kind: 'MOVED' } | { kind: 'DELETED' };
98
+
99
+ /*
100
+ * The change applied to a row or column span.
101
+ */
102
+ export type SheetStructureSpanEditFlag = 'CLAMPED' | 'EDGE' | 'KEPT' | 'SHIFTED' | 'UNCHANGED';
103
+
104
+ /* One span of the edited axis after a structure edit (end null = open). */
105
+ export interface SheetStructureSpanAfterEdit {
106
+ end: number | null;
107
+ flag: SheetStructureSpanEditFlag;
108
+ start: number;
109
+ }
110
+
111
+ /*
112
+ * One named range a structure edit changed in a way the inverse edit's math
113
+ * cannot rebuild (dropped, edge-shrunk, clamped at the cap): the inverse swaps
114
+ * `after` (null = dropped) back for `before`. `position` is the range's index
115
+ * in the list before the edit, where a dropped range comes back.
116
+ */
117
+ export interface SheetNamedRangeStructureRestore {
118
+ after: SheetNamedRangeObj | null;
119
+ before: SheetNamedRangeObj;
120
+ position?: number;
121
+ }
122
+
123
+ /* Named ranges after one structure edit, plus the pairs its inverse needs. */
124
+ export interface SheetNamedRangesAfterStructureEdit {
125
+ namedRanges: SheetNamedRangeObj[];
126
+ restores: SheetNamedRangeStructureRestore[];
127
+ }
128
+
129
+ const FILE_CONSTANTS = {
130
+ inverseOperation: {
131
+ DELETE_COLUMN: 'INSERT_COLUMN_LEFT',
132
+ DELETE_ROW: 'INSERT_ROW_ABOVE',
133
+ INSERT_COLUMN_LEFT: 'DELETE_COLUMN',
134
+ INSERT_ROW_ABOVE: 'DELETE_ROW',
135
+ } satisfies Record<SheetStructureOperationEnum, SheetStructureOperationEnum>,
136
+ };
137
+
138
+ /*
139
+ * Return a normalized positive one-based sheet index.
140
+ */
141
+ function normalizeSheetStructureIndex(value: number | null | undefined) {
142
+ const index = Math.floor(Number(value || 0));
143
+
144
+ return Number.isFinite(index) && index > 0 ? index : null;
145
+ }
146
+
147
+ /*
148
+ * Return a stable coordinate key for one one-based sheet cell.
149
+ */
150
+ export function getSheetStructureCoordKey(rowIndex: number, columnIndex: number) {
151
+ return `${rowIndex}:${columnIndex}`;
152
+ }
153
+
154
+ /*
155
+ * Return whether a coordinate falls inside a rectangle.
156
+ */
157
+ export function sheetStructureBoundsContainCell(bounds: SheetStructureBounds, rowIndex: number, columnIndex: number) {
158
+ return (
159
+ rowIndex >= bounds.startRowIndex &&
160
+ rowIndex <= bounds.endRowIndex &&
161
+ columnIndex >= bounds.startColumnIndex &&
162
+ columnIndex <= bounds.endColumnIndex
163
+ );
164
+ }
165
+
166
+ /*
167
+ * Return whether two rectangular extents overlap.
168
+ */
169
+ export function sheetStructureBoundsOverlapRange(
170
+ bounds: SheetStructureBounds,
171
+ startRowIndex: number,
172
+ endRowIndex: number,
173
+ startColumnIndex: number,
174
+ endColumnIndex: number,
175
+ ) {
176
+ return (
177
+ startRowIndex <= bounds.endRowIndex &&
178
+ endRowIndex >= bounds.startRowIndex &&
179
+ startColumnIndex <= bounds.endColumnIndex &&
180
+ endColumnIndex >= bounds.startColumnIndex
181
+ );
182
+ }
183
+
184
+ /* Return a cell's coordinate after an ordinary row or column edit. */
185
+ export function getSheetStructureCellCoordAfterEdit(
186
+ rowIndex: number,
187
+ columnIndex: number,
188
+ operation: SheetStructureOperationEnum,
189
+ targetIndex: number,
190
+ ): SheetStructureCellCoord | null {
191
+ const isRow = operation === 'INSERT_ROW_ABOVE' || operation === 'DELETE_ROW';
192
+ const coordinate = getSheetStructureUnboundedLineAfterEdit(isRow ? rowIndex : columnIndex, { operation, index: targetIndex });
193
+ return coordinate.kind === 'DELETED'
194
+ ? null
195
+ : { rowIndex: isRow ? coordinate.index : rowIndex, columnIndex: isRow ? columnIndex : coordinate.index };
196
+ }
197
+
198
+ /*
199
+ * Return a range after inserting or deleting one row or column.
200
+ */
201
+ export function getSheetStructureRangeAfterEdit<T extends SheetStructureRangeLike>(
202
+ range: T,
203
+ operation: SheetStructureOperationEnum,
204
+ targetIndex: number,
205
+ ): T | null {
206
+ const startRowIndex = normalizeSheetStructureIndex(range.startRowIndex);
207
+ const endRowIndex = normalizeSheetStructureIndex(range.endRowIndex);
208
+ const startColumnIndex = normalizeSheetStructureIndex(range.startColumnIndex);
209
+ const endColumnIndex = normalizeSheetStructureIndex(range.endColumnIndex);
210
+
211
+ if (!startRowIndex || !endRowIndex || !startColumnIndex || !endColumnIndex) {
212
+ return range;
213
+ }
214
+
215
+ if (operation === 'INSERT_ROW_ABOVE') {
216
+ if (startRowIndex >= targetIndex) {
217
+ return {
218
+ ...range,
219
+ endRowIndex: endRowIndex + 1,
220
+ startRowIndex: startRowIndex + 1,
221
+ };
222
+ }
223
+
224
+ if (startRowIndex < targetIndex && endRowIndex >= targetIndex) {
225
+ return {
226
+ ...range,
227
+ endRowIndex: endRowIndex + 1,
228
+ };
229
+ }
230
+ }
231
+
232
+ if (operation === 'INSERT_COLUMN_LEFT') {
233
+ if (startColumnIndex >= targetIndex) {
234
+ return {
235
+ ...range,
236
+ endColumnIndex: endColumnIndex + 1,
237
+ startColumnIndex: startColumnIndex + 1,
238
+ };
239
+ }
240
+
241
+ if (startColumnIndex < targetIndex && endColumnIndex >= targetIndex) {
242
+ return {
243
+ ...range,
244
+ endColumnIndex: endColumnIndex + 1,
245
+ };
246
+ }
247
+ }
248
+
249
+ if (operation === 'DELETE_ROW') {
250
+ if (startRowIndex === targetIndex && endRowIndex === targetIndex) {
251
+ return null;
252
+ }
253
+
254
+ if (startRowIndex <= targetIndex && endRowIndex >= targetIndex) {
255
+ return {
256
+ ...range,
257
+ endRowIndex: endRowIndex - 1,
258
+ };
259
+ }
260
+
261
+ if (startRowIndex > targetIndex) {
262
+ return {
263
+ ...range,
264
+ endRowIndex: endRowIndex - 1,
265
+ startRowIndex: startRowIndex - 1,
266
+ };
267
+ }
268
+ }
269
+
270
+ if (operation === 'DELETE_COLUMN') {
271
+ if (startColumnIndex === targetIndex && endColumnIndex === targetIndex) {
272
+ return null;
273
+ }
274
+
275
+ if (startColumnIndex <= targetIndex && endColumnIndex >= targetIndex) {
276
+ return {
277
+ ...range,
278
+ endColumnIndex: endColumnIndex - 1,
279
+ };
280
+ }
281
+
282
+ if (startColumnIndex > targetIndex) {
283
+ return {
284
+ ...range,
285
+ endColumnIndex: endColumnIndex - 1,
286
+ startColumnIndex: startColumnIndex - 1,
287
+ };
288
+ }
289
+ }
290
+
291
+ return range;
292
+ }
293
+
294
+ /*
295
+ * Return sparse cells keyed by their post-structure-edit coordinates.
296
+ */
297
+ export function applySheetStructureEditToCellsByCoord<T extends SheetStructureCellLike>(
298
+ cellsByCoord: Map<string, T>,
299
+ operation: SheetStructureOperationEnum,
300
+ targetIndex: number,
301
+ ) {
302
+ let changed = false;
303
+ const nextCellsByCoord = new Map<string, T>();
304
+
305
+ cellsByCoord.forEach((cell, coordKey) => {
306
+ const rowIndex = normalizeSheetStructureIndex(cell.rowIndex);
307
+ const columnIndex = normalizeSheetStructureIndex(cell.columnIndex);
308
+
309
+ if (!rowIndex || !columnIndex) {
310
+ nextCellsByCoord.set(coordKey, cell);
311
+ return;
312
+ }
313
+
314
+ const nextCoord = getSheetStructureCellCoordAfterEdit(rowIndex, columnIndex, operation, targetIndex);
315
+ if (!nextCoord) {
316
+ changed = true;
317
+ return;
318
+ }
319
+
320
+ const nextCoordKey = getSheetStructureCoordKey(nextCoord.rowIndex, nextCoord.columnIndex);
321
+ const nextCell =
322
+ nextCoord.rowIndex === rowIndex && nextCoord.columnIndex === columnIndex
323
+ ? cell
324
+ : ({
325
+ ...cell,
326
+ columnIndex: nextCoord.columnIndex,
327
+ rowIndex: nextCoord.rowIndex,
328
+ } as T);
329
+
330
+ if (nextCoordKey !== coordKey || nextCell !== cell) {
331
+ changed = true;
332
+ }
333
+
334
+ nextCellsByCoord.set(nextCoordKey, nextCell);
335
+ });
336
+
337
+ return changed ? nextCellsByCoord : cellsByCoord;
338
+ }
339
+
340
+ /*
341
+ * Return the operation that undoes one structure operation: an insert and the
342
+ * delete at the same index invert each other.
343
+ */
344
+ export function getSheetStructureInverseOperation(operation: SheetStructureOperationEnum): SheetStructureOperationEnum {
345
+ return FILE_CONSTANTS.inverseOperation[operation];
346
+ }
347
+
348
+ /*
349
+ * Return the signed change one structure operation makes to each grid count.
350
+ */
351
+ function getSheetStructureAxisDeltas(operation: SheetStructureOperationEnum) {
352
+ return {
353
+ columnDelta: operation === 'INSERT_COLUMN_LEFT' ? 1 : operation === 'DELETE_COLUMN' ? -1 : 0,
354
+ rowDelta: operation === 'INSERT_ROW_ABOVE' ? 1 : operation === 'DELETE_ROW' ? -1 : 0,
355
+ };
356
+ }
357
+
358
+ /*
359
+ * Return the count of one axis after a structure edit: the operation's delta
360
+ * clamped to [1, max], or `axisCount` (clamped the same way) when the edit
361
+ * names the count it must end at — the inverse of an edit the clamp absorbed.
362
+ */
363
+ function getSheetStructureAxisCountAfterEdit(count: number, delta: number, max: number, axisCount?: number | null) {
364
+ const target = typeof axisCount === 'number' && Number.isFinite(axisCount) ? Math.floor(axisCount) : count + delta;
365
+
366
+ return Math.min(max, Math.max(1, target));
367
+ }
368
+
369
+ /*
370
+ * Return the edit that exactly undoes one structure edit applied to `design`
371
+ * (the design BEFORE the edit): the opposite operation at the same index,
372
+ * ending at the axis count that design held. Below the cap the opposite
373
+ * operation's own delta restores that count and `axisCount` is omitted. An
374
+ * insert on an axis at its cap kept the count and dropped the trailing line
375
+ * (free by construction: the grid-full guard refuses it otherwise), so its
376
+ * inverse delete names the cap as `axisCount` and re-appends that line —
377
+ * lossless, and the geometry returns exactly. The client paints this inverse;
378
+ * the server replays the same rule from its stored geometry.
379
+ */
380
+ export function getSheetStructureInverseEdit(
381
+ designInput: SheetDesignObj,
382
+ operation: SheetStructureOperationEnum,
383
+ index: number,
384
+ ): SheetStructureEdit {
385
+ const design = normalizeSheetDesign(designInput);
386
+ const isRowOperation = operation === 'INSERT_ROW_ABOVE' || operation === 'DELETE_ROW';
387
+ const { columnDelta, rowDelta } = getSheetStructureAxisDeltas(operation);
388
+ const delta = isRowOperation ? rowDelta : columnDelta;
389
+ const max = isRowOperation ? SHEET_MAX_ROW_COUNT : SHEET_MAX_COLUMN_COUNT;
390
+ const count = isRowOperation ? design.grid.rowCount : design.grid.columnCount;
391
+ const afterCount = getSheetStructureAxisCountAfterEdit(count, delta, max);
392
+ const restoredCount = getSheetStructureAxisCountAfterEdit(afterCount, -delta, max);
393
+
394
+ return {
395
+ index,
396
+ operation: getSheetStructureInverseOperation(operation),
397
+ ...(restoredCount === count ? {} : { axisCount: count }),
398
+ };
399
+ }
400
+
401
+ /*
402
+ * Return the inverse edit with the original axis count for clamped edits.
403
+ */
404
+ export function getSheetStructureInverseEditForAxisCount<T extends SheetStructureEdit>(edit: T, axisCountBefore: number): T {
405
+ return {
406
+ ...edit,
407
+ axisCount: axisCountBefore,
408
+ operation: getSheetStructureInverseOperation(edit.operation),
409
+ };
410
+ }
411
+
412
+ /*
413
+ * Return whether one structure operation inserts or deletes a row.
414
+ */
415
+ function isSheetStructureRowOperation(operation: SheetStructureOperationEnum) {
416
+ return operation === 'INSERT_ROW_ABOVE' || operation === 'DELETE_ROW';
417
+ }
418
+
419
+ /*
420
+ * Return the hard cap of the axis one structure operation edits.
421
+ */
422
+ export function getSheetStructureEditAxisMax(operation: SheetStructureOperationEnum) {
423
+ return isSheetStructureRowOperation(operation) ? SHEET_MAX_ROW_COUNT : SHEET_MAX_COLUMN_COUNT;
424
+ }
425
+
426
+ /*
427
+ * Return whether one delete keeps its axis at the cap and re-appends a blank
428
+ * trailing line (the undo of an insert the cap clamped). A span ending on the
429
+ * last line then keeps ending there, the mirror of the insert's end clamp.
430
+ */
431
+ export function sheetStructureEditReappendsLastLine(edit: SheetStructureEdit) {
432
+ return (
433
+ (edit.operation === 'DELETE_ROW' || edit.operation === 'DELETE_COLUMN') &&
434
+ typeof edit.axisCount === 'number' &&
435
+ edit.axisCount >= getSheetStructureEditAxisMax(edit.operation)
436
+ );
437
+ }
438
+
439
+ /*
440
+ * Return the new position of a row or column before applying grid limits.
441
+ */
442
+ export function getSheetStructureUnboundedLineAfterEdit(line: number, edit: SheetStructureEdit): SheetStructureLineAfterEdit {
443
+ if (edit.operation === 'INSERT_ROW_ABOVE' || edit.operation === 'INSERT_COLUMN_LEFT') {
444
+ return { index: line >= edit.index ? line + 1 : line, kind: 'MOVED' };
445
+ }
446
+
447
+ if (line === edit.index) {
448
+ return { kind: 'DELETED' };
449
+ }
450
+
451
+ return { index: line > edit.index ? line - 1 : line, kind: 'MOVED' };
452
+ }
453
+
454
+ /* Return a cell's coordinate through the shared structure rule. */
455
+ export function getSheetStructureCellAfterEdit(
456
+ rowIndex: number,
457
+ columnIndex: number,
458
+ edit: SheetStructureCellRuleEdit,
459
+ ): SheetStructureCellCoord | null {
460
+ return getSheetStructureCellCoordAfterEdit(rowIndex, columnIndex, edit.operation, edit.index);
461
+ }
462
+
463
+ /* Return the new position of one complete row or column. */
464
+ export function getSheetStructureLineAfterEdit(line: number, edit: SheetStructureCellRuleEdit): SheetStructureLineAfterEdit {
465
+ return getSheetStructureUnboundedLineAfterEdit(line, edit);
466
+ }
467
+
468
+ /*
469
+ * Return a span after an edit, or null when every line is deleted or pushed past the grid cap. A null end preserves an open range.
470
+ */
471
+ export function getSheetStructureSpanAfterEdit(
472
+ start: number,
473
+ end: number | null,
474
+ edit: SheetStructureEdit,
475
+ getLine: (line: number) => SheetStructureLineAfterEdit = (line) => getSheetStructureUnboundedLineAfterEdit(line, edit),
476
+ ): SheetStructureSpanAfterEdit | null {
477
+ const max = getSheetStructureEditAxisMax(edit.operation);
478
+ if (start > max) {
479
+ return { end, flag: 'UNCHANGED', start };
480
+ }
481
+
482
+ const kept: SheetStructureSpanAfterEdit = { end, flag: 'KEPT', start };
483
+ const endMoves = end !== null && end <= max;
484
+ const finish = (nextStart: number, nextEnd: number | null, flag: SheetStructureSpanEditFlag | null): SheetStructureSpanAfterEdit => {
485
+ if (nextEnd !== null && nextStart > nextEnd) {
486
+ return kept;
487
+ }
488
+
489
+ return {
490
+ end: nextEnd,
491
+ flag: flag || (nextStart !== start || nextEnd !== end ? 'SHIFTED' : 'UNCHANGED'),
492
+ start: nextStart,
493
+ };
494
+ };
495
+
496
+ if (edit.operation === 'INSERT_ROW_ABOVE' || edit.operation === 'INSERT_COLUMN_LEFT') {
497
+ const startLine = getLine(start);
498
+ if (startLine.kind !== 'MOVED') {
499
+ return kept;
500
+ }
501
+ if (startLine.index > max) {
502
+ return null;
503
+ }
504
+ if (!endMoves) {
505
+ return finish(startLine.index, end, null);
506
+ }
507
+
508
+ const endLine = getLine(end);
509
+ if (endLine.kind !== 'MOVED') {
510
+ return kept;
511
+ }
512
+
513
+ return endLine.index > max ? finish(startLine.index, max, 'CLAMPED') : finish(startLine.index, endLine.index, null);
514
+ }
515
+
516
+ if (end === start) {
517
+ const line = getLine(start);
518
+ if (line.kind === 'DELETED') {
519
+ return null;
520
+ }
521
+
522
+ return finish(line.index, line.index, null);
523
+ }
524
+
525
+ let edge = false;
526
+ let startLine = getLine(start);
527
+ if (startLine.kind === 'DELETED') {
528
+ // Only an open or past-the-cap end can leave no grid line after the start
529
+ if (start + 1 > max) {
530
+ return null;
531
+ }
532
+ edge = true;
533
+ startLine = getLine(start + 1);
534
+ }
535
+ if (startLine.kind !== 'MOVED') {
536
+ return kept;
537
+ }
538
+ if (!endMoves || (sheetStructureEditReappendsLastLine(edit) && (end as number) >= max)) {
539
+ return finish(startLine.index, end, edge ? 'EDGE' : null);
540
+ }
541
+
542
+ let endLine = getLine(end as number);
543
+ if (endLine.kind === 'DELETED') {
544
+ edge = true;
545
+ endLine = getLine((end as number) - 1);
546
+ }
547
+ if (endLine.kind !== 'MOVED') {
548
+ return kept;
549
+ }
550
+
551
+ return finish(startLine.index, endLine.index, edge ? 'EDGE' : null);
552
+ }
553
+
554
+ /* Return one merged range after a row or column edit. */
555
+ export function getSheetStructureMergedRangeAfterEdit<T extends SheetMergedRangeObj>(
556
+ merge: T,
557
+ edit: SheetStructureCellRuleEdit,
558
+ ): T | null {
559
+ const [shifted] = shiftSheetMergedRangesForStructureEdit([merge], edit.operation, edit.index);
560
+ return shifted ? { ...merge, ...shifted } : null;
561
+ }
562
+
563
+ /* Return the surviving merged ranges after a row or column edit. */
564
+ export function getSheetStructureMergedRangesAfterEdit(
565
+ merges: SheetMergedRangeObj[],
566
+ edit: SheetStructureCellRuleEdit,
567
+ ): SheetMergedRangeObj[] {
568
+ return shiftSheetMergedRangesForStructureEdit(merges, edit.operation, edit.index);
569
+ }
570
+
571
+ /*
572
+ * Return the trimmed name one named range is keyed by.
573
+ */
574
+ function getSheetNamedRangeKey(range: SheetNamedRangeObj | null | undefined) {
575
+ return String(range?.name || '').trim();
576
+ }
577
+
578
+ /*
579
+ * Return whether two named ranges have the same name and coordinates.
580
+ */
581
+ function sheetNamedRangesAreEqual(left: SheetNamedRangeObj | null | undefined, right: SheetNamedRangeObj | null | undefined) {
582
+ if (!left || !right) {
583
+ return left === right;
584
+ }
585
+
586
+ return (
587
+ getSheetNamedRangeKey(left) === getSheetNamedRangeKey(right) &&
588
+ Number(left.startRowIndex) === Number(right.startRowIndex) &&
589
+ Number(left.startColumnIndex) === Number(right.startColumnIndex) &&
590
+ Number(left.endRowIndex) === Number(right.endRowIndex) &&
591
+ Number(left.endColumnIndex) === Number(right.endColumnIndex)
592
+ );
593
+ }
594
+
595
+ /*
596
+ * Move a named range with its cells while preserving grid limits and deleted endpoints.
597
+ */
598
+ export function getSheetNamedRangeAfterStructureEdit(range: SheetNamedRangeObj, edit: SheetStructureEdit): SheetNamedRangeObj | null {
599
+ const isRow = isSheetStructureRowOperation(edit.operation);
600
+ const start = Math.floor(Number(isRow ? range.startRowIndex : range.startColumnIndex));
601
+ const end = Math.floor(Number(isRow ? range.endRowIndex : range.endColumnIndex));
602
+ if (!Number.isFinite(start) || !Number.isFinite(end) || start < 1) {
603
+ return range;
604
+ }
605
+ if (end < start) {
606
+ return range;
607
+ }
608
+
609
+ const next = getSheetStructureSpanAfterEdit(start, end, edit);
610
+ if (!next) {
611
+ return null;
612
+ }
613
+ if (next.start === start && next.end === end) {
614
+ return range;
615
+ }
616
+
617
+ return isRow
618
+ ? { ...range, endRowIndex: next.end as number, startRowIndex: next.start }
619
+ : {
620
+ ...range,
621
+ endColumnIndex: next.end as number,
622
+ startColumnIndex: next.start,
623
+ };
624
+ }
625
+
626
+ /*
627
+ * Return the named ranges after one structure edit, keeping their order.
628
+ * - `restores` (a replay's stored pairs): a range equal to a pair's `after`
629
+ * becomes its `before` instead of following the math, and a dropped range
630
+ * (`after` null) comes back at its old position unless its name is taken.
631
+ * - `inverseEdit` (the edit that would undo this one): every range the
632
+ * inverse math could not rebuild exactly (dropped, edge-shrunk, clamped at
633
+ * the cap) is returned in `restores`, ready to store for that inverse.
634
+ */
635
+ export function getSheetNamedRangesAfterStructureEdit(
636
+ namedRanges: readonly SheetNamedRangeObj[] | null | undefined,
637
+ edit: SheetStructureEdit,
638
+ options?: {
639
+ inverseEdit?: SheetStructureEdit | null;
640
+ restores?: readonly SheetNamedRangeStructureRestore[] | null;
641
+ },
642
+ ): SheetNamedRangesAfterStructureEdit {
643
+ const applied = options?.restores || [];
644
+ const inverseEdit = options?.inverseEdit || null;
645
+ const nextRanges: SheetNamedRangeObj[] = [];
646
+ const restores: SheetNamedRangeStructureRestore[] = [];
647
+
648
+ (Array.isArray(namedRanges) ? namedRanges : []).forEach((range, position) => {
649
+ const restore = applied.find((item) => item.after && sheetNamedRangesAreEqual(item.after, range));
650
+ const next = restore ? restore.before : getSheetNamedRangeAfterStructureEdit(range, edit);
651
+ if (next) {
652
+ nextRanges.push(next);
653
+ }
654
+ if (inverseEdit && (!next || !sheetNamedRangesAreEqual(getSheetNamedRangeAfterStructureEdit(next, inverseEdit), range))) {
655
+ restores.push({ after: next, before: range, position });
656
+ }
657
+ });
658
+
659
+ // A dropped range lay only on the lines this edit's inverse removes again,
660
+ // so bringing it back never needs a restore of its own
661
+ [...applied]
662
+ .filter((restore) => !restore.after && getSheetNamedRangeKey(restore.before))
663
+ .sort((left, right) => (left.position ?? 0) - (right.position ?? 0))
664
+ .forEach((restore) => {
665
+ const name = getSheetNamedRangeKey(restore.before);
666
+ if (nextRanges.some((range) => getSheetNamedRangeKey(range) === name)) {
667
+ return;
668
+ }
669
+ const position = Math.min(Math.max(0, Math.floor(Number(restore.position ?? nextRanges.length))), nextRanges.length);
670
+ nextRanges.splice(position, 0, restore.before);
671
+ });
672
+
673
+ return { namedRanges: nextRanges, restores };
674
+ }
675
+
676
+ /*
677
+ * Shift row and column design, merges, and named ranges through a structure edit.
678
+ */
679
+ export function getSheetStructureDesignAfterEdit(
680
+ designInput: SheetDesignObj,
681
+ operation: SheetStructureOperationEnum,
682
+ targetIndex: number,
683
+ axisCount?: number | null,
684
+ options?: {
685
+ namedRangeRestores?: readonly SheetNamedRangeStructureRestore[] | null;
686
+ },
687
+ ) {
688
+ const design = normalizeSheetDesign(designInput);
689
+
690
+ const { columnDelta, rowDelta } = getSheetStructureAxisDeltas(operation);
691
+
692
+ const merges = getSheetMergedRanges(design.metadata);
693
+ const shiftedMerges = merges.length
694
+ ? getSheetStructureMergedRangesAfterEdit(merges, {
695
+ index: targetIndex,
696
+ operation,
697
+ })
698
+ : merges;
699
+ const namedRangeRestores = options?.namedRangeRestores || [];
700
+ const namedRanges =
701
+ design.namedRanges?.length || namedRangeRestores.length
702
+ ? getSheetNamedRangesAfterStructureEdit(
703
+ design.namedRanges,
704
+ {
705
+ index: targetIndex,
706
+ operation,
707
+ ...(typeof axisCount === 'number' ? { axisCount } : {}),
708
+ },
709
+ { restores: namedRangeRestores },
710
+ ).namedRanges
711
+ : design.namedRanges;
712
+
713
+ return {
714
+ ...design,
715
+ namedRanges,
716
+ grid: {
717
+ ...design.grid,
718
+ columnCount: getSheetStructureAxisCountAfterEdit(
719
+ design.grid.columnCount,
720
+ columnDelta,
721
+ SHEET_MAX_COLUMN_COUNT,
722
+ columnDelta ? axisCount : null,
723
+ ),
724
+ rowCount: getSheetStructureAxisCountAfterEdit(design.grid.rowCount, rowDelta, SHEET_MAX_ROW_COUNT, rowDelta ? axisCount : null),
725
+ },
726
+ columns: columnDelta ? shiftSheetAxisDesignForStructureEdit(design.columns, operation, targetIndex) : design.columns,
727
+ rows: rowDelta ? shiftSheetAxisDesignForStructureEdit(design.rows, operation, targetIndex) : design.rows,
728
+ ...(merges.length
729
+ ? {
730
+ metadata: {
731
+ ...(design.metadata || {}),
732
+ merges: shiftedMerges,
733
+ },
734
+ }
735
+ : {}),
736
+ };
737
+ }
738
+
739
+ /*
740
+ * Return the one-based index of the line an insert pushes off the sheet when
741
+ * the grid is already at its cap (the last row for INSERT_ROW_ABOVE, the last
742
+ * column for INSERT_COLUMN_LEFT), or null when the insert grows the grid. The
743
+ * default grid IS the cap (SHEET_DEFAULT_ROW_COUNT = SHEET_MAX_ROW_COUNT), so
744
+ * getSheetStructureDesignAfterEdit clamps the count there and the trailing
745
+ * line falls off instead: the caller decides whether that line is free.
746
+ */
747
+ export function getSheetStructureInsertDroppedLineIndex(
748
+ designInput: SheetDesignObj,
749
+ operation: SheetStructureOperationEnum,
750
+ ): number | null {
751
+ const design = normalizeSheetDesign(designInput);
752
+ if (operation === 'INSERT_ROW_ABOVE') {
753
+ return design.grid.rowCount >= SHEET_MAX_ROW_COUNT ? design.grid.rowCount : null;
754
+ }
755
+ if (operation === 'INSERT_COLUMN_LEFT') {
756
+ return design.grid.columnCount >= SHEET_MAX_COLUMN_COUNT ? design.grid.columnCount : null;
757
+ }
758
+ return null;
759
+ }
760
+
761
+ /*
762
+ * Return whether one merged range reaches the line an insert would push off
763
+ * the sheet: shifting such a merge would leave part of it outside the grid.
764
+ */
765
+ export function sheetStructureMergesReachLine(designInput: SheetDesignObj, operation: SheetStructureOperationEnum, lineIndex: number) {
766
+ const design = normalizeSheetDesign(designInput);
767
+ return getSheetMergedRanges(design.metadata).some((merge) =>
768
+ operation === 'INSERT_ROW_ABOVE' ? merge.endRowIndex >= lineIndex : merge.endColumnIndex >= lineIndex,
769
+ );
770
+ }
771
+
772
+ /*
773
+ * Return whether one cell holds stored content (a raw input, a value of any
774
+ * type or a formula). Style, format and notes alone do not count: the server
775
+ * SQL predicate in sheetOps-structureRecord.ts mirrors this list exactly.
776
+ */
777
+ export function sheetStructureCellHasContent(cell: SheetStructureCellContentLike | null | undefined) {
778
+ if (!cell) {
779
+ return false;
780
+ }
781
+ const stored = [cell.rawInput, cell.value, cell.textValue, cell.numberValue, cell.booleanValue, cell.dateValue, cell.datetimeValue];
782
+ return stored.some((property) => property !== null && property !== undefined) || String(cell.formulaText ?? '').trim() !== '';
783
+ }
784
+
785
+ /*
786
+ * Return why an insert cannot drop the last grid line: content, a merge, or a target beyond the grid.
787
+ */
788
+ export function getSheetStructureInsertAtCapBlocker(params: {
789
+ cellsByCoord: ReadonlyMap<string, SheetStructureCellContentLike & SheetStructureCellLike>;
790
+ design: SheetDesignObj;
791
+ index: number;
792
+ operation: SheetStructureOperationEnum;
793
+ }): SheetStructureInsertAtCapBlocker | null {
794
+ const lineIndex = getSheetStructureInsertDroppedLineIndex(params.design, params.operation);
795
+ if (lineIndex === null) {
796
+ return null;
797
+ }
798
+ if (params.index > lineIndex) {
799
+ return 'BEYOND_GRID';
800
+ }
801
+ if (sheetStructureMergesReachLine(params.design, params.operation, lineIndex)) {
802
+ return 'MERGES';
803
+ }
804
+
805
+ const isRowOperation = params.operation === 'INSERT_ROW_ABOVE';
806
+ for (const cell of params.cellsByCoord.values()) {
807
+ const rowIndex = normalizeSheetStructureIndex(cell.rowIndex);
808
+ const columnIndex = normalizeSheetStructureIndex(cell.columnIndex);
809
+ if (!rowIndex || !columnIndex) {
810
+ continue;
811
+ }
812
+ if ((isRowOperation ? rowIndex : columnIndex) !== lineIndex) {
813
+ continue;
814
+ }
815
+ if (sheetStructureCellHasContent(cell)) {
816
+ return 'CELLS';
817
+ }
818
+ }
819
+ return null;
820
+ }
821
+
822
+ /*
823
+ * Return one queued design-save patch with its axis maps, merged ranges and
824
+ * named ranges projected through a structure edit. A patch built before a
825
+ * collaborator's insert/delete would otherwise write pre-shift indexes over
826
+ * the design the server already shifted.
827
+ */
828
+ export function applySheetStructureEditToDesignPatch<
829
+ T extends {
830
+ columns?: string | null;
831
+ metadata?: string | null;
832
+ namedRanges?: SheetNamedRangeObj[] | null;
833
+ rows?: string | null;
834
+ },
835
+ >(patch: T, operation: SheetStructureOperationEnum, targetIndex: number): T {
836
+ const rowDelta = operation === 'INSERT_ROW_ABOVE' ? 1 : operation === 'DELETE_ROW' ? -1 : 0;
837
+ const columnDelta = operation === 'INSERT_COLUMN_LEFT' ? 1 : operation === 'DELETE_COLUMN' ? -1 : 0;
838
+ let next = patch;
839
+ const ensureNext = () => {
840
+ if (next === patch) {
841
+ next = { ...patch };
842
+ }
843
+ return next;
844
+ };
845
+
846
+ if (patch.columns && columnDelta) {
847
+ const columns = parseSheetDesignPatchObject<Record<string, SheetAxisDesignObj>>(patch.columns, {});
848
+
849
+ ensureNext().columns = stringifyJSON(shiftSheetAxisDesignForStructureEdit(columns, operation, targetIndex));
850
+ }
851
+
852
+ if (patch.rows && rowDelta) {
853
+ const rows = parseSheetDesignPatchObject<Record<string, SheetAxisDesignObj>>(patch.rows, {});
854
+
855
+ ensureNext().rows = stringifyJSON(shiftSheetAxisDesignForStructureEdit(rows, operation, targetIndex));
856
+ }
857
+
858
+ if (patch.metadata) {
859
+ const metadata = parseSheetDesignPatchObject<Record<string, any>>(patch.metadata, {});
860
+ const merges = getSheetMergedRanges(metadata);
861
+
862
+ if (merges.length) {
863
+ ensureNext().metadata = stringifyJSON({
864
+ ...metadata,
865
+ merges: getSheetStructureMergedRangesAfterEdit(merges, {
866
+ index: targetIndex,
867
+ operation,
868
+ }),
869
+ });
870
+ }
871
+ }
872
+
873
+ if (Array.isArray(patch.namedRanges) && patch.namedRanges.length) {
874
+ ensureNext().namedRanges = getSheetNamedRangesAfterStructureEdit(patch.namedRanges, { index: targetIndex, operation }).namedRanges;
875
+ }
876
+
877
+ return next;
878
+ }
879
+
880
+ /*
881
+ * Return one loaded row count after an optimistic row structure edit.
882
+ */
883
+ export function getSheetLoadedRowCountAfterStructureEdit(
884
+ loadedRowCount: number,
885
+ operation: SheetStructureOperationEnum,
886
+ nextDesign: SheetDesignObj,
887
+ ) {
888
+ const rowDelta = operation === 'INSERT_ROW_ABOVE' ? 1 : operation === 'DELETE_ROW' ? -1 : 0;
889
+
890
+ return Math.max(1, Math.min(nextDesign.grid.rowCount, loadedRowCount + rowDelta));
891
+ }
892
+
893
+ /*
894
+ * Return one last-content row index after an optimistic row structure edit.
895
+ */
896
+ export function getSheetLastContentRowIndexAfterStructureEdit(
897
+ lastContentRowIndex: number | null | undefined,
898
+ operation: SheetStructureOperationEnum,
899
+ targetIndex: number,
900
+ ) {
901
+ if (!lastContentRowIndex || operation === 'INSERT_COLUMN_LEFT' || operation === 'DELETE_COLUMN') {
902
+ return lastContentRowIndex || null;
903
+ }
904
+
905
+ if (operation === 'INSERT_ROW_ABOVE' && targetIndex <= lastContentRowIndex) {
906
+ return lastContentRowIndex + 1;
907
+ }
908
+
909
+ if (operation === 'DELETE_ROW' && targetIndex <= lastContentRowIndex) {
910
+ return Math.max(1, lastContentRowIndex - 1);
911
+ }
912
+
913
+ return lastContentRowIndex;
914
+ }