@jsb188/mday 1.1.11 → 1.1.12

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 (210) hide show
  1. package/package.json +58 -23
  2. package/src/constants/agentMemory.ts +14 -45
  3. package/src/constants/agentNote.ts +212 -0
  4. package/src/constants/aiChat.ts +5 -0
  5. package/src/constants/billing.ts +126 -0
  6. package/src/constants/campaign.ts +156 -47
  7. package/src/constants/contact.ts +72 -0
  8. package/src/constants/csvExport.ts +133 -0
  9. package/src/constants/dataTable.ts +12 -38
  10. package/src/constants/dataTableFieldTypes.generated.ts +3 -7
  11. package/src/constants/docAccess.ts +3 -2
  12. package/src/constants/dt.ts +234 -0
  13. package/src/constants/email.ts +114 -12
  14. package/src/constants/fieldDoc.ts +74 -4
  15. package/src/constants/graphqlReactivity.ts +108 -25
  16. package/src/constants/log.ts +9 -0
  17. package/src/constants/logDisplay/README.md +88 -0
  18. package/src/constants/logDisplay/defaults.ts +39 -0
  19. package/src/constants/logDisplay/index.ts +27 -0
  20. package/src/constants/logDisplay/operations/arable.ts +16 -0
  21. package/src/constants/logDisplay/operations/farmersMarket.ts +10 -0
  22. package/src/constants/logDisplay/operations/foodManufacturing.ts +13 -0
  23. package/src/constants/logDisplay/shared/accounting.ts +13 -0
  24. package/src/constants/logDisplay/shared/interactions.ts +13 -0
  25. package/src/constants/logDisplay/shared/rackTemperatures.ts +42 -0
  26. package/src/constants/logTaxonomy.generated.ts +1834 -730
  27. package/src/constants/organization.ts +13 -14
  28. package/src/constants/qrCode.ts +30 -0
  29. package/src/constants/sheet.ts +65 -101
  30. package/src/constants/sms.ts +18 -0
  31. package/src/constants/storage.ts +33 -9
  32. package/src/constants/usage.ts +3 -0
  33. package/src/constants/workflowSteps.ts +60 -0
  34. package/src/schemas/editLogEntry.ts +106 -283
  35. package/src/schemas/inboundContact.ts +5 -5
  36. package/src/types/agentMemory.d.ts +38 -14
  37. package/src/types/agentNote.d.ts +443 -0
  38. package/src/types/billing.d.ts +537 -0
  39. package/src/types/campaign.d.ts +1043 -193
  40. package/src/types/contact.d.ts +15 -0
  41. package/src/types/csvExport.d.ts +213 -0
  42. package/src/types/dataAnalysis.d.ts +44 -0
  43. package/src/types/dataTable.d.ts +102 -309
  44. package/src/types/definitionElement.d.ts +35 -0
  45. package/src/types/dt.d.ts +257 -0
  46. package/src/types/email.d.ts +144 -55
  47. package/src/types/emailReplyReport.d.ts +76 -0
  48. package/src/types/fieldDoc.d.ts +579 -150
  49. package/src/types/fieldDocContract.d.ts +90 -0
  50. package/src/types/inboundContact.d.ts +8 -0
  51. package/src/types/log.d.ts +94 -3
  52. package/src/types/logDisplay.types.ts +85 -0
  53. package/src/types/organization.d.ts +8 -3
  54. package/src/types/qrCode.d.ts +96 -0
  55. package/src/types/richText.d.ts +81 -0
  56. package/src/types/sheet.d.ts +180 -463
  57. package/src/types/sms.d.ts +38 -0
  58. package/src/types/storage.d.ts +266 -27
  59. package/src/types/workflow.d.ts +196 -66
  60. package/src/utils/agentMemory.ts +15 -0
  61. package/src/utils/agentNote.ts +850 -0
  62. package/src/utils/aiChat.ts +31 -14
  63. package/src/utils/aiChatWork.ts +64 -0
  64. package/src/utils/billing.ts +37 -0
  65. package/src/utils/campaign.ts +642 -209
  66. package/src/utils/campaignAI.ts +72 -0
  67. package/src/utils/campaignAccess.ts +239 -0
  68. package/src/utils/campaignEmail.ts +601 -0
  69. package/src/utils/campaignEmailCompiler.ts +372 -0
  70. package/src/utils/campaignEmailImages.ts +60 -0
  71. package/src/utils/campaignEmailStyles.ts +544 -0
  72. package/src/utils/campaignLifecycle.ts +104 -0
  73. package/src/utils/campaignPreview.ts +285 -0
  74. package/src/utils/contact.ts +50 -0
  75. package/src/utils/csvExport.ts +19 -0
  76. package/src/utils/dataTable.ts +18 -556
  77. package/src/utils/dataTableFieldTypeRegistry.ts +1 -0
  78. package/src/utils/dataTableRelativeDate.ts +447 -0
  79. package/src/utils/definitionElement.ts +84 -0
  80. package/src/utils/email.ts +208 -1
  81. package/src/utils/emailReplyReport.test.ts +187 -0
  82. package/src/utils/emailReplyReport.ts +143 -0
  83. package/src/utils/fieldDoc.ts +81 -37
  84. package/src/utils/fieldDocAnswers.ts +128 -0
  85. package/src/utils/fieldDocDefaults.ts +36 -0
  86. package/src/utils/fieldDocProgram.ts +36 -0
  87. package/src/utils/fieldDocSummary.ts +30 -0
  88. package/src/utils/log.ts +232 -141
  89. package/src/utils/logDisplay.helpers.ts +177 -0
  90. package/src/utils/logDisplay.ts +87 -0
  91. package/src/utils/logStoreRead.ts +9 -13
  92. package/src/utils/logTaxonomy.helpers.ts +17 -0
  93. package/src/utils/logTaxonomyDisplay.ts +80 -124
  94. package/src/utils/noteDoc.ts +66 -284
  95. package/src/utils/organization.ts +117 -283
  96. package/src/utils/qrCode.helpers.ts +189 -0
  97. package/src/utils/qrCode.test.ts +519 -0
  98. package/src/utils/qrCode.ts +273 -0
  99. package/src/utils/richTextHTML.ts +385 -0
  100. package/src/utils/sheet.ts +123 -4834
  101. package/src/utils/sheetAxisMove.ts +77 -291
  102. package/src/utils/sheetBootstrap.ts +771 -1138
  103. package/src/utils/sheetCellLiteral.ts +101 -0
  104. package/src/utils/sheetCommand.ts +23 -88
  105. package/src/utils/sheetDesign.ts +705 -0
  106. package/src/utils/sheetExport.ts +17 -69
  107. package/src/utils/sheetFeatureReference.ts +183 -0
  108. package/src/utils/sheetFormulaArgs.ts +168 -0
  109. package/src/utils/sheetFormulaCompile.ts +475 -0
  110. package/src/utils/sheetFormulaConditionalAggregate.ts +254 -0
  111. package/src/utils/sheetFormulaCriteria.ts +656 -0
  112. package/src/utils/sheetFormulaDate.ts +444 -0
  113. package/src/utils/sheetFormulaEvaluation.ts +388 -403
  114. package/src/utils/sheetFormulaEvaluator.ts +589 -444
  115. package/src/utils/sheetFormulaFunctionHandlers.ts +403 -0
  116. package/src/utils/sheetFormulaLogical.ts +116 -0
  117. package/src/utils/sheetFormulaLookup.ts +488 -0
  118. package/src/utils/sheetFormulaMath.ts +48 -0
  119. package/src/utils/sheetFormulaParser.ts +729 -0
  120. package/src/utils/sheetFormulaRange.ts +330 -0
  121. package/src/utils/sheetFormulaReference.ts +703 -0
  122. package/src/utils/sheetFormulaReferenceAggregates.ts +313 -0
  123. package/src/utils/sheetFormulaReferenceDates.ts +237 -0
  124. package/src/utils/sheetFormulaReferenceLogical.ts +330 -0
  125. package/src/utils/sheetFormulaReferenceLookup.ts +341 -0
  126. package/src/utils/sheetFormulaReferenceMath.ts +95 -0
  127. package/src/utils/sheetFormulaReferenceRewrite.ts +220 -0
  128. package/src/utils/sheetFormulaReferenceText.ts +462 -0
  129. package/src/utils/sheetFormulaSyntax.ts +1027 -0
  130. package/src/utils/sheetFormulaText.ts +430 -0
  131. package/src/utils/sheetJournal.ts +140 -18
  132. package/src/utils/sheetNumberFormat.ts +68 -267
  133. package/src/utils/sheetPreview.ts +68 -0
  134. package/src/utils/sheetSequence.ts +13 -43
  135. package/src/utils/sheetSnapshot.ts +176 -429
  136. package/src/utils/sheetStructureEdit.ts +537 -907
  137. package/src/utils/sheetStructureReferences.ts +389 -0
  138. package/src/utils/storage.ts +49 -3
  139. package/src/utils/time.ts +12 -0
  140. package/src/utils/workflow.ts +199 -73
  141. package/src/utils/workflowLogFingerprint.ts +302 -0
  142. package/src/utils/workflowLogRevisionSnapshot.ts +424 -0
  143. package/src/utils/workflowProgress.ts +280 -0
  144. package/src/utils/workflowTriggers.ts +61 -0
  145. package/tests/agentNote.test.ts +395 -0
  146. package/tests/campaignAI.test.ts +119 -0
  147. package/tests/campaignAccess.test.ts +239 -0
  148. package/tests/campaignEmail.test.ts +441 -0
  149. package/tests/campaignLifecycle.test.ts +134 -0
  150. package/tests/campaignPublication.test.ts +309 -0
  151. package/tests/dataTableFieldTypeRegistry.test.ts +2 -1
  152. package/tests/dataTableRelativeDate.test.ts +412 -0
  153. package/tests/email.test.ts +39 -0
  154. package/tests/fieldDocProgram.test.ts +114 -0
  155. package/tests/logDisplay.fixtures.ts +67 -0
  156. package/tests/logDisplay.test.ts +227 -0
  157. package/tests/noteDoc.test.ts +37 -192
  158. package/tests/richTextHTML.test.ts +185 -0
  159. package/tests/sheetAxisMove.test.ts +49 -40
  160. package/tests/sheetBootstrap.test.ts +1967 -0
  161. package/tests/sheetFeatureReference.test.ts +22 -0
  162. package/tests/sheetFormulaCriteria.test.ts +269 -0
  163. package/tests/sheetFormulaEvaluator.test.ts +93 -200
  164. package/tests/sheetFormulaFunctions.test.ts +538 -0
  165. package/tests/sheetFormulaLanguage.test.ts +361 -0
  166. package/tests/sheetFormulaParity.fixtures.ts +872 -0
  167. package/tests/sheetFormulaParity.test.ts +188 -0
  168. package/tests/sheetFormulaRange.test.ts +167 -0
  169. package/tests/sheetFormulaReference.test.ts +78 -0
  170. package/tests/sheetFormulaReferenceRewrite.test.ts +117 -0
  171. package/tests/sheetFormulaTextDate.test.ts +512 -0
  172. package/tests/sheetSequence.test.ts +4 -23
  173. package/tests/sheetSnapshot.test.ts +134 -0
  174. package/tests/sheetStructureEdit.test.ts +492 -37
  175. package/tests/sheetStructureReferences.test.ts +589 -0
  176. package/tests/workflowLifecycleStatus.test.ts +60 -0
  177. package/tests/workflowLogFingerprint.test.ts +203 -0
  178. package/tests/workflowLogRevisionSnapshot.test.ts +96 -0
  179. package/tests/workflowProgress.test.ts +180 -0
  180. package/tests/workflowTriggers.test.ts +29 -0
  181. package/src/constants/agentDoc.ts +0 -12
  182. package/src/constants/logActivityGroupColors.generated.ts +0 -19
  183. package/src/constants/schedule.ts +0 -220
  184. package/src/constants/scheduleRuleTemplateSeed.ts +0 -138
  185. package/src/constants/scheduleRuleTemplates.generated.ts +0 -145
  186. package/src/constants/sheetRegionSources.generated.ts +0 -578
  187. package/src/schemas/fieldDocsQuery.ts +0 -12
  188. package/src/schemas/organization.ts +0 -68
  189. package/src/types/agentDoc.d.ts +0 -64
  190. package/src/types/noteDoc.d.ts +0 -86
  191. package/src/types/schedule.d.ts +0 -391
  192. package/src/utils/agentDoc.ts +0 -109
  193. package/src/utils/campaignFormEditor.ts +0 -871
  194. package/src/utils/dataTableRealtimeAuthority.ts +0 -209
  195. package/src/utils/dataTableRealtimeSelection.ts +0 -134
  196. package/src/utils/dataTableRowDocument.ts +0 -508
  197. package/src/utils/dataTableSource.ts +0 -230
  198. package/src/utils/schedule.ts +0 -799
  199. package/src/utils/scheduleEvaluation.ts +0 -1994
  200. package/src/utils/scheduleICS.ts +0 -246
  201. package/src/utils/scheduleRuleTemplates.ts +0 -188
  202. package/src/utils/sheetRegion.ts +0 -374
  203. package/src/utils/sheetRegionFilter.ts +0 -1259
  204. package/src/utils/sheetRegionSourceRegistry.ts +0 -594
  205. package/tests/schedule.test.ts +0 -693
  206. package/tests/scheduleEvaluation.test.ts +0 -1970
  207. package/tests/scheduleICS.test.ts +0 -208
  208. package/tests/scheduleRuleTemplates.test.ts +0 -176
  209. package/tests/scheduleSweepInvariants.test.ts +0 -428
  210. package/tests/sheetRegionFilter.test.ts +0 -1135
@@ -5,38 +5,27 @@
5
5
  */
6
6
 
7
7
  import { parseJSON, stringifyJSON } from '@jsb188/app/utils/object.ts';
8
- import {
9
- SHEET_DATA_TABLE_REGION_DEFAULT_LIMIT,
10
- SHEET_DATA_TABLE_REGION_MAX_ROWS,
11
- SHEET_MAX_COLUMN_COUNT,
12
- SHEET_MAX_ROW_COUNT,
13
- } from '@jsb188/mday/constants/sheet.ts';
8
+ import { SHEET_MAX_COLUMN_COUNT, SHEET_MAX_ROW_COUNT } from '@jsb188/mday/constants/sheet.ts';
14
9
  import type {
15
10
  SheetAxisDesignObj,
16
11
  SheetDesignObj,
17
- SheetRangeData,
18
- SheetRangeGQL,
19
- SheetRegionColumnObj,
20
- SheetRegionOptionsObj,
12
+ SheetMergedRangeObj,
13
+ SheetNamedRangeObj,
21
14
  SheetStructureOperationEnum,
22
15
  } from '@jsb188/mday/types/sheet.d.ts';
23
16
  import {
24
17
  getSheetMergedRanges,
25
18
  normalizeSheetDesign,
26
- type SheetProtectedAxisSpan,
27
19
  shiftSheetAxisDesignForStructureEdit,
28
20
  shiftSheetMergedRangesForStructureEdit,
29
- } from '@jsb188/mday/utils/sheet.ts';
21
+ } from '@jsb188/mday/utils/sheetDesign.ts';
30
22
 
31
23
  /*
32
24
  * Return one design patch field as a parsed object. Patch fields carry
33
25
  * serialized JSON, but already-parsed objects pass through unchanged. Local
34
26
  * because this module is shared with the server.
35
27
  */
36
- function parseSheetDesignPatchObject<T extends Record<string, any>>(
37
- value: unknown,
38
- fallback: T,
39
- ): T {
28
+ function parseSheetDesignPatchObject<T extends Record<string, any>>(value: unknown, fallback: T): T {
40
29
  if (value && typeof value === 'object' && !Array.isArray(value)) {
41
30
  return value as T;
42
31
  }
@@ -46,9 +35,7 @@ function parseSheetDesignPatchObject<T extends Record<string, any>>(
46
35
  }
47
36
 
48
37
  const parsed = parseJSON(value);
49
- return parsed && typeof parsed === 'object' && !Array.isArray(parsed)
50
- ? (parsed as T)
51
- : fallback;
38
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? (parsed as T) : fallback;
52
39
  }
53
40
 
54
41
  export interface SheetStructureBounds {
@@ -58,19 +45,6 @@ export interface SheetStructureBounds {
58
45
  startRowIndex: number;
59
46
  }
60
47
 
61
- export interface SheetStructureRegionFootprint {
62
- columns?: SheetRegionColumnObj[] | null;
63
- options?: SheetRegionOptionsObj | null;
64
- source?: {
65
- dataTableId?: number | bigint | string | null;
66
- type?: string | null;
67
- } | null;
68
- sourceDataTableId?: number | bigint | string | null;
69
- startColumnIndex?: number | null;
70
- startRowIndex?: number | null;
71
- type?: string | null;
72
- }
73
-
74
48
  export interface SheetStructureCellCoord {
75
49
  columnIndex: number;
76
50
  rowIndex: number;
@@ -81,211 +55,106 @@ export interface SheetStructureCellLike {
81
55
  rowIndex?: number | null;
82
56
  }
83
57
 
84
- export type SheetStructureRangeLike = Pick<
85
- SheetRangeData | SheetRangeGQL,
86
- 'endColumnIndex' | 'endRowIndex' | 'startColumnIndex' | 'startRowIndex'
87
- >;
88
-
89
- export interface SheetStructureBoundsPredicate {
90
- args: Array<number | bigint>;
91
- text: string;
58
+ export interface SheetStructureRangeLike {
59
+ endColumnIndex?: number | null;
60
+ endRowIndex?: number | null;
61
+ startColumnIndex?: number | null;
62
+ startRowIndex?: number | null;
92
63
  }
93
64
 
94
- /*
95
- * Return a normalized positive one-based sheet index.
96
- */
97
- function normalizeSheetStructureIndex(value: number | null | undefined) {
98
- const index = Math.floor(Number(value || 0));
99
-
100
- return Number.isFinite(index) && index > 0 ? index : null;
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;
101
75
  }
102
76
 
103
- /*
104
- * Return a stable coordinate key for one one-based sheet cell.
105
- */
106
- export function getSheetStructureCoordKey(
107
- rowIndex: number,
108
- columnIndex: number,
109
- ) {
110
- return `${rowIndex}:${columnIndex}`;
111
- }
77
+ /* Why an insert at the grid cap cannot run (null = it can). */
78
+ export type SheetStructureInsertAtCapBlocker = 'BEYOND_GRID' | 'CELLS' | 'MERGES';
112
79
 
113
80
  /*
114
- * Return the default finite end row for one data table region.
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).
115
84
  */
116
- function getSheetStructureDataTableRegionDefaultEndRowIndex(
117
- region: Pick<SheetStructureRegionFootprint, 'options' | 'startRowIndex'>,
118
- ) {
119
- return (
120
- getSheetStructureRegionDataStartRowIndex(region) +
121
- SHEET_DATA_TABLE_REGION_DEFAULT_LIMIT -
122
- 1
123
- );
85
+ export interface SheetStructureEdit {
86
+ axisCount?: number;
87
+ index: number;
88
+ operation: SheetStructureOperationEnum;
124
89
  }
125
90
 
91
+ /* One ordinary row or column edit shared by cells and references. */
92
+ export type SheetStructureCellRuleEdit = SheetStructureEdit;
93
+
126
94
  /*
127
- * Return the configured finite end row for one region, defaulting unset limits.
95
+ * The new position of one row or column after an edit.
128
96
  */
129
- export function getSheetStructureRegionConfiguredEndRowIndex(
130
- region: Pick<SheetStructureRegionFootprint, 'options' | 'startRowIndex'>,
131
- ) {
132
- const endRowIndex = Math.floor(Number(region.options?.endRowIndex || 0));
133
- const dataStartRowIndex = getSheetStructureRegionDataStartRowIndex(region);
134
-
135
- return Number.isFinite(endRowIndex) && endRowIndex >= dataStartRowIndex
136
- ? Math.min(
137
- endRowIndex,
138
- getSheetStructureDataTableRegionMaxEndRowIndex(region),
139
- )
140
- : getSheetStructureDataTableRegionDefaultEndRowIndex(region);
141
- }
97
+ export type SheetStructureLineAfterEdit = { index: number; kind: 'MOVED' } | { kind: 'DELETED' };
142
98
 
143
99
  /*
144
- * Return the first row that should contain data table source rows for one region.
100
+ * The change applied to a row or column span.
145
101
  */
146
- export function getSheetStructureRegionDataStartRowIndex(
147
- region: Pick<SheetStructureRegionFootprint, 'options' | 'startRowIndex'>,
148
- ) {
149
- const startRowIndex = normalizeSheetStructureIndex(region.startRowIndex) || 1;
102
+ export type SheetStructureSpanEditFlag = 'CLAMPED' | 'EDGE' | 'KEPT' | 'SHIFTED' | 'UNCHANGED';
150
103
 
151
- return startRowIndex + (region.options?.includeHeaderRow ? 1 : 0);
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;
152
109
  }
153
110
 
154
111
  /*
155
- * Return the last row index one data table region may generate under the hard row cap.
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.
156
116
  */
157
- export function getSheetStructureDataTableRegionMaxEndRowIndex(
158
- region: Pick<SheetStructureRegionFootprint, 'options' | 'startRowIndex'>,
159
- ) {
160
- return (
161
- getSheetStructureRegionDataStartRowIndex(region) +
162
- SHEET_DATA_TABLE_REGION_MAX_ROWS -
163
- 1
164
- );
117
+ export interface SheetNamedRangeStructureRestore {
118
+ after: SheetNamedRangeObj | null;
119
+ before: SheetNamedRangeObj;
120
+ position?: number;
165
121
  }
166
122
 
167
- /*
168
- * Return the rectangular generated output footprint for one data table region.
169
- */
170
- export function getSheetStructureRegionContentBounds(
171
- region: SheetStructureRegionFootprint,
172
- sourceRowCount: number,
173
- ): SheetStructureBounds | null {
174
- const startRowIndex = normalizeSheetStructureIndex(region.startRowIndex);
175
- const startColumnIndex = normalizeSheetStructureIndex(
176
- region.startColumnIndex,
177
- );
178
- const columnCount = Array.isArray(region.columns) ? region.columns.length : 0;
179
-
180
- if (!startRowIndex || !startColumnIndex || !columnCount) {
181
- return null;
182
- }
183
-
184
- const normalizedRegion = {
185
- ...region,
186
- startRowIndex,
187
- startColumnIndex,
188
- };
189
- const configuredEndRowIndex =
190
- getSheetStructureRegionConfiguredEndRowIndex(normalizedRegion);
191
- const allowedEndRowIndex = Math.min(
192
- configuredEndRowIndex ||
193
- getSheetStructureDataTableRegionMaxEndRowIndex(normalizedRegion),
194
- getSheetStructureDataTableRegionMaxEndRowIndex(normalizedRegion),
195
- );
196
- const headerLastRowIndex = normalizedRegion.options?.includeHeaderRow
197
- ? startRowIndex
198
- : 0;
199
- const dataStartRowIndex =
200
- getSheetStructureRegionDataStartRowIndex(normalizedRegion);
201
- const sourceRowsToRender = Math.min(
202
- Math.max(0, Math.floor(Number(sourceRowCount) || 0)),
203
- SHEET_DATA_TABLE_REGION_MAX_ROWS,
204
- );
205
- const sourceLastRowIndex = sourceRowsToRender
206
- ? dataStartRowIndex + sourceRowsToRender - 1
207
- : 0;
208
- const endRowIndex = Math.min(
209
- allowedEndRowIndex,
210
- Math.max(headerLastRowIndex, sourceLastRowIndex),
211
- );
212
-
213
- if (endRowIndex < startRowIndex) {
214
- return null;
215
- }
216
-
217
- return {
218
- endColumnIndex: startColumnIndex + columnCount - 1,
219
- endRowIndex,
220
- startColumnIndex,
221
- startRowIndex,
222
- };
123
+ /* Named ranges after one structure edit, plus the pairs its inverse needs. */
124
+ export interface SheetNamedRangesAfterStructureEdit {
125
+ namedRanges: SheetNamedRangeObj[];
126
+ restores: SheetNamedRangeStructureRestore[];
223
127
  }
224
128
 
225
- /*
226
- * Return the configured footprint reserved by one data table-backed region.
227
- */
228
- export function getSheetStructureRegionConfiguredBounds(
229
- region: SheetStructureRegionFootprint,
230
- ) {
231
- return getSheetStructureRegionContentBounds(
232
- region,
233
- SHEET_DATA_TABLE_REGION_MAX_ROWS,
234
- );
235
- }
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
+ };
236
137
 
237
138
  /*
238
- * Return whether one region should be protected during row or column structure edits.
139
+ * Return a normalized positive one-based sheet index.
239
140
  */
240
- export function isSheetStructureProtectedRegion(
241
- region: SheetStructureRegionFootprint,
242
- ) {
243
- return (
244
- region.type === 'DATA_TABLE' &&
245
- Boolean(region.sourceDataTableId || region.source?.dataTableId)
246
- );
247
- }
141
+ function normalizeSheetStructureIndex(value: number | null | undefined) {
142
+ const index = Math.floor(Number(value || 0));
248
143
 
249
- /*
250
- * Return the active region footprints that should be protected during a structure edit.
251
- */
252
- export function getSheetStructureProtectedBounds(
253
- regions?: SheetStructureRegionFootprint[] | null,
254
- ) {
255
- return (regions || [])
256
- .filter(isSheetStructureProtectedRegion)
257
- .map((region) => getSheetStructureRegionConfiguredBounds(region))
258
- .filter((bounds): bounds is SheetStructureBounds => Boolean(bounds));
144
+ return Number.isFinite(index) && index > 0 ? index : null;
259
145
  }
260
146
 
261
147
  /*
262
- * Return axis spans from protected region bounds for row or column design shifting.
148
+ * Return a stable coordinate key for one one-based sheet cell.
263
149
  */
264
- export function getSheetStructureProtectedAxisSpans(
265
- bounds: SheetStructureBounds[],
266
- axis: 'ROW' | 'COLUMN',
267
- ): SheetProtectedAxisSpan[] {
268
- return bounds.map((item) =>
269
- axis === 'ROW'
270
- ? {
271
- endIndex: item.endRowIndex,
272
- startIndex: item.startRowIndex,
273
- }
274
- : {
275
- endIndex: item.endColumnIndex,
276
- startIndex: item.startColumnIndex,
277
- },
278
- );
150
+ export function getSheetStructureCoordKey(rowIndex: number, columnIndex: number) {
151
+ return `${rowIndex}:${columnIndex}`;
279
152
  }
280
153
 
281
154
  /*
282
- * Return whether one Sheet coordinate falls inside a rectangular protected footprint.
155
+ * Return whether a coordinate falls inside a rectangle.
283
156
  */
284
- export function sheetStructureBoundsContainCell(
285
- bounds: SheetStructureBounds,
286
- rowIndex: number,
287
- columnIndex: number,
288
- ) {
157
+ export function sheetStructureBoundsContainCell(bounds: SheetStructureBounds, rowIndex: number, columnIndex: number) {
289
158
  return (
290
159
  rowIndex >= bounds.startRowIndex &&
291
160
  rowIndex <= bounds.endRowIndex &&
@@ -295,20 +164,7 @@ export function sheetStructureBoundsContainCell(
295
164
  }
296
165
 
297
166
  /*
298
- * Return whether one cell coordinate is outside every protected footprint.
299
- */
300
- export function isSheetStructureCellOutsideProtectedBounds(
301
- bounds: SheetStructureBounds[],
302
- rowIndex: number,
303
- columnIndex: number,
304
- ) {
305
- return !bounds.some((bound) =>
306
- sheetStructureBoundsContainCell(bound, rowIndex, columnIndex),
307
- );
308
- }
309
-
310
- /*
311
- * Return whether one rectangular range overlaps a protected footprint.
167
+ * Return whether two rectangular extents overlap.
312
168
  */
313
169
  export function sheetStructureBoundsOverlapRange(
314
170
  bounds: SheetStructureBounds,
@@ -325,237 +181,27 @@ export function sheetStructureBoundsOverlapRange(
325
181
  );
326
182
  }
327
183
 
328
- /*
329
- * Return whether one range is outside every protected footprint.
330
- */
331
- export function isSheetStructureRangeOutsideProtectedBounds(
332
- bounds: SheetStructureBounds[],
333
- startRowIndex: number,
334
- endRowIndex: number,
335
- startColumnIndex: number,
336
- endColumnIndex: number,
337
- ) {
338
- return !bounds.some((bound) =>
339
- sheetStructureBoundsOverlapRange(
340
- bound,
341
- startRowIndex,
342
- endRowIndex,
343
- startColumnIndex,
344
- endColumnIndex,
345
- ),
346
- );
347
- }
348
-
349
- /*
350
- * Return whether a protected region prevents one row-delete upward shift.
351
- */
352
- export function isSheetStructureRowDeleteShiftBlocked(
353
- bounds: SheetStructureBounds[],
354
- rowIndex: number,
355
- columnIndex: number,
356
- targetIndex: number,
357
- ) {
358
- return bounds.some(
359
- (bound) =>
360
- columnIndex >= bound.startColumnIndex &&
361
- columnIndex <= bound.endColumnIndex &&
362
- bound.startRowIndex <= rowIndex - 1 &&
363
- bound.endRowIndex >= targetIndex,
364
- );
365
- }
366
-
367
- /*
368
- * Return whether a protected region prevents one column-delete left shift.
369
- */
370
- export function isSheetStructureColumnDeleteShiftBlocked(
371
- bounds: SheetStructureBounds[],
372
- rowIndex: number,
373
- columnIndex: number,
374
- targetIndex: number,
375
- ) {
376
- return bounds.some(
377
- (bound) =>
378
- rowIndex >= bound.startRowIndex &&
379
- rowIndex <= bound.endRowIndex &&
380
- bound.startColumnIndex <= columnIndex - 1 &&
381
- bound.endColumnIndex >= targetIndex,
382
- );
383
- }
384
-
385
- /*
386
- * Return whether a protected region prevents one row-range delete upward shift.
387
- */
388
- export function isSheetStructureRangeRowDeleteShiftBlocked(
389
- bounds: SheetStructureBounds[],
390
- startRowIndex: number,
391
- startColumnIndex: number,
392
- endColumnIndex: number,
393
- targetIndex: number,
394
- ) {
395
- return bounds.some(
396
- (bound) =>
397
- startColumnIndex <= bound.endColumnIndex &&
398
- endColumnIndex >= bound.startColumnIndex &&
399
- bound.startRowIndex <= startRowIndex - 1 &&
400
- bound.endRowIndex >= targetIndex,
401
- );
402
- }
403
-
404
- /*
405
- * Return whether a protected region prevents one column-range delete left shift.
406
- */
407
- export function isSheetStructureRangeColumnDeleteShiftBlocked(
408
- bounds: SheetStructureBounds[],
409
- startColumnIndex: number,
410
- startRowIndex: number,
411
- endRowIndex: number,
412
- targetIndex: number,
413
- ) {
414
- return bounds.some(
415
- (bound) =>
416
- startRowIndex <= bound.endRowIndex &&
417
- endRowIndex >= bound.startRowIndex &&
418
- bound.startColumnIndex <= startColumnIndex - 1 &&
419
- bound.endColumnIndex >= targetIndex,
420
- );
421
- }
422
-
423
- /*
424
- * Return the row and column coordinate for one cell after a structure edit.
425
- */
184
+ /* Return a cell's coordinate after an ordinary row or column edit. */
426
185
  export function getSheetStructureCellCoordAfterEdit(
427
186
  rowIndex: number,
428
187
  columnIndex: number,
429
188
  operation: SheetStructureOperationEnum,
430
189
  targetIndex: number,
431
- bounds: SheetStructureBounds[] = [],
432
190
  ): SheetStructureCellCoord | null {
433
- if (operation === 'INSERT_ROW_ABOVE' && rowIndex >= targetIndex) {
434
- return isSheetStructureCellOutsideProtectedBounds(
435
- bounds,
436
- rowIndex,
437
- columnIndex,
438
- ) &&
439
- isSheetStructureCellOutsideProtectedBounds(
440
- bounds,
441
- rowIndex + 1,
442
- columnIndex,
443
- )
444
- ? {
445
- columnIndex,
446
- rowIndex: rowIndex + 1,
447
- }
448
- : {
449
- columnIndex,
450
- rowIndex,
451
- };
452
- }
453
-
454
- if (operation === 'INSERT_COLUMN_LEFT' && columnIndex >= targetIndex) {
455
- return isSheetStructureCellOutsideProtectedBounds(
456
- bounds,
457
- rowIndex,
458
- columnIndex,
459
- ) &&
460
- isSheetStructureCellOutsideProtectedBounds(
461
- bounds,
462
- rowIndex,
463
- columnIndex + 1,
464
- )
465
- ? {
466
- columnIndex: columnIndex + 1,
467
- rowIndex,
468
- }
469
- : {
470
- columnIndex,
471
- rowIndex,
472
- };
473
- }
474
-
475
- if (operation === 'DELETE_ROW') {
476
- if (
477
- rowIndex === targetIndex &&
478
- isSheetStructureCellOutsideProtectedBounds(bounds, rowIndex, columnIndex)
479
- ) {
480
- return null;
481
- }
482
-
483
- if (
484
- rowIndex > targetIndex &&
485
- isSheetStructureCellOutsideProtectedBounds(
486
- bounds,
487
- rowIndex,
488
- columnIndex,
489
- ) &&
490
- isSheetStructureCellOutsideProtectedBounds(
491
- bounds,
492
- rowIndex - 1,
493
- columnIndex,
494
- ) &&
495
- !isSheetStructureRowDeleteShiftBlocked(
496
- bounds,
497
- rowIndex,
498
- columnIndex,
499
- targetIndex,
500
- )
501
- ) {
502
- return {
503
- columnIndex,
504
- rowIndex: rowIndex - 1,
505
- };
506
- }
507
- }
508
-
509
- if (operation === 'DELETE_COLUMN') {
510
- if (
511
- columnIndex === targetIndex &&
512
- isSheetStructureCellOutsideProtectedBounds(bounds, rowIndex, columnIndex)
513
- ) {
514
- return null;
515
- }
516
-
517
- if (
518
- columnIndex > targetIndex &&
519
- isSheetStructureCellOutsideProtectedBounds(
520
- bounds,
521
- rowIndex,
522
- columnIndex,
523
- ) &&
524
- isSheetStructureCellOutsideProtectedBounds(
525
- bounds,
526
- rowIndex,
527
- columnIndex - 1,
528
- ) &&
529
- !isSheetStructureColumnDeleteShiftBlocked(
530
- bounds,
531
- rowIndex,
532
- columnIndex,
533
- targetIndex,
534
- )
535
- ) {
536
- return {
537
- columnIndex: columnIndex - 1,
538
- rowIndex,
539
- };
540
- }
541
- }
542
-
543
- return {
544
- columnIndex,
545
- rowIndex,
546
- };
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 };
547
196
  }
548
197
 
549
198
  /*
550
- * Return the range coordinate fields after a structure edit.
199
+ * Return a range after inserting or deleting one row or column.
551
200
  */
552
- export function getSheetStructureRangeAfterEdit<
553
- T extends SheetStructureRangeLike,
554
- >(
201
+ export function getSheetStructureRangeAfterEdit<T extends SheetStructureRangeLike>(
555
202
  range: T,
556
203
  operation: SheetStructureOperationEnum,
557
204
  targetIndex: number,
558
- bounds: SheetStructureBounds[] = [],
559
205
  ): T | null {
560
206
  const startRowIndex = normalizeSheetStructureIndex(range.startRowIndex);
561
207
  const endRowIndex = normalizeSheetStructureIndex(range.endRowIndex);
@@ -566,18 +212,6 @@ export function getSheetStructureRangeAfterEdit<
566
212
  return range;
567
213
  }
568
214
 
569
- const outside = isSheetStructureRangeOutsideProtectedBounds(
570
- bounds,
571
- startRowIndex,
572
- endRowIndex,
573
- startColumnIndex,
574
- endColumnIndex,
575
- );
576
-
577
- if (!outside) {
578
- return range;
579
- }
580
-
581
215
  if (operation === 'INSERT_ROW_ABOVE') {
582
216
  if (startRowIndex >= targetIndex) {
583
217
  return {
@@ -624,16 +258,7 @@ export function getSheetStructureRangeAfterEdit<
624
258
  };
625
259
  }
626
260
 
627
- if (
628
- startRowIndex > targetIndex &&
629
- !isSheetStructureRangeRowDeleteShiftBlocked(
630
- bounds,
631
- startRowIndex,
632
- startColumnIndex,
633
- endColumnIndex,
634
- targetIndex,
635
- )
636
- ) {
261
+ if (startRowIndex > targetIndex) {
637
262
  return {
638
263
  ...range,
639
264
  endRowIndex: endRowIndex - 1,
@@ -654,16 +279,7 @@ export function getSheetStructureRangeAfterEdit<
654
279
  };
655
280
  }
656
281
 
657
- if (
658
- startColumnIndex > targetIndex &&
659
- !isSheetStructureRangeColumnDeleteShiftBlocked(
660
- bounds,
661
- startColumnIndex,
662
- startRowIndex,
663
- endRowIndex,
664
- targetIndex,
665
- )
666
- ) {
282
+ if (startColumnIndex > targetIndex) {
667
283
  return {
668
284
  ...range,
669
285
  endColumnIndex: endColumnIndex - 1,
@@ -678,13 +294,10 @@ export function getSheetStructureRangeAfterEdit<
678
294
  /*
679
295
  * Return sparse cells keyed by their post-structure-edit coordinates.
680
296
  */
681
- export function applySheetStructureEditToCellsByCoord<
682
- T extends SheetStructureCellLike,
683
- >(
297
+ export function applySheetStructureEditToCellsByCoord<T extends SheetStructureCellLike>(
684
298
  cellsByCoord: Map<string, T>,
685
299
  operation: SheetStructureOperationEnum,
686
300
  targetIndex: number,
687
- bounds: SheetStructureBounds[] = [],
688
301
  ) {
689
302
  let changed = false;
690
303
  const nextCellsByCoord = new Map<string, T>();
@@ -698,22 +311,13 @@ export function applySheetStructureEditToCellsByCoord<
698
311
  return;
699
312
  }
700
313
 
701
- const nextCoord = getSheetStructureCellCoordAfterEdit(
702
- rowIndex,
703
- columnIndex,
704
- operation,
705
- targetIndex,
706
- bounds,
707
- );
314
+ const nextCoord = getSheetStructureCellCoordAfterEdit(rowIndex, columnIndex, operation, targetIndex);
708
315
  if (!nextCoord) {
709
316
  changed = true;
710
317
  return;
711
318
  }
712
319
 
713
- const nextCoordKey = getSheetStructureCoordKey(
714
- nextCoord.rowIndex,
715
- nextCoord.columnIndex,
716
- );
320
+ const nextCoordKey = getSheetStructureCoordKey(nextCoord.rowIndex, nextCoord.columnIndex);
717
321
  const nextCell =
718
322
  nextCoord.rowIndex === rowIndex && nextCoord.columnIndex === columnIndex
719
323
  ? cell
@@ -734,174 +338,393 @@ export function applySheetStructureEditToCellsByCoord<
734
338
  }
735
339
 
736
340
  /*
737
- * Apply one structure edit to a pending-edit map: shift the coordinate keys
738
- * plus each entry's preview cell and edit-input coordinates. Entries whose
739
- * coordinate is removed by the edit are dropped.
341
+ * Return the operation that undoes one structure operation: an insert and the
342
+ * delete at the same index invert each other.
740
343
  */
741
- export function applySheetStructureEditToPendingEdits<
742
- T extends {
743
- input: { cell: { rowIndex: number; columnIndex: number } };
744
- previewCell: { rowIndex?: number | null; columnIndex?: number | null };
745
- },
746
- >(
747
- pendingEditsByCoord: Map<string, T>,
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,
748
382
  operation: SheetStructureOperationEnum,
749
- targetIndex: number,
750
- bounds: SheetStructureBounds[] = [],
751
- ) {
752
- let changed = false;
753
- const nextPendingEditsByCoord = new Map<string, T>();
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);
754
393
 
755
- pendingEditsByCoord.forEach((pendingEdit, coordKey) => {
756
- const rowIndex = normalizeSheetStructureIndex(
757
- pendingEdit.input.cell.rowIndex,
758
- );
759
- const columnIndex = normalizeSheetStructureIndex(
760
- pendingEdit.input.cell.columnIndex,
761
- );
394
+ return {
395
+ index,
396
+ operation: getSheetStructureInverseOperation(operation),
397
+ ...(restoredCount === count ? {} : { axisCount: count }),
398
+ };
399
+ }
762
400
 
763
- if (!rowIndex || !columnIndex) {
764
- nextPendingEditsByCoord.set(coordKey, pendingEdit);
765
- return;
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;
766
487
  }
767
488
 
768
- const nextCoord = getSheetStructureCellCoordAfterEdit(
769
- rowIndex,
770
- columnIndex,
771
- operation,
772
- targetIndex,
773
- bounds,
774
- );
775
- if (!nextCoord) {
776
- changed = true;
777
- return;
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);
778
506
  }
779
507
 
780
- if (
781
- nextCoord.rowIndex === rowIndex &&
782
- nextCoord.columnIndex === columnIndex
783
- ) {
784
- nextPendingEditsByCoord.set(coordKey, pendingEdit);
785
- return;
508
+ const endLine = getLine(end);
509
+ if (endLine.kind !== 'MOVED') {
510
+ return kept;
786
511
  }
787
512
 
788
- changed = true;
789
- nextPendingEditsByCoord.set(
790
- getSheetStructureCoordKey(nextCoord.rowIndex, nextCoord.columnIndex),
791
- {
792
- ...pendingEdit,
793
- input: {
794
- ...pendingEdit.input,
795
- cell: {
796
- ...pendingEdit.input.cell,
797
- columnIndex: nextCoord.columnIndex,
798
- rowIndex: nextCoord.rowIndex,
799
- },
800
- },
801
- previewCell: {
802
- ...pendingEdit.previewCell,
803
- columnIndex: nextCoord.columnIndex,
804
- rowIndex: nextCoord.rowIndex,
805
- },
806
- },
807
- );
808
- });
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
+ }
809
541
 
810
- return changed ? nextPendingEditsByCoord : pendingEditsByCoord;
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);
811
569
  }
812
570
 
813
571
  /*
814
- * Return saved ranges with their coordinates projected through one structure edit.
572
+ * Return the trimmed name one named range is keyed by.
815
573
  */
816
- export function applySheetStructureEditToRanges<
817
- T extends SheetStructureRangeLike,
818
- >(
819
- ranges: T[] | null | undefined,
820
- operation: SheetStructureOperationEnum,
821
- targetIndex: number,
822
- bounds: SheetStructureBounds[] = [],
823
- ) {
824
- let changed = false;
825
- const nextRanges: T[] = [];
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
+ }
826
585
 
827
- (ranges || []).forEach((range) => {
828
- const nextRange = getSheetStructureRangeAfterEdit(
829
- range,
830
- operation,
831
- targetIndex,
832
- bounds,
833
- );
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
+ }
834
594
 
835
- if (!nextRange) {
836
- changed = true;
837
- return;
838
- }
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
+ }
839
608
 
840
- if (nextRange !== range) {
841
- changed = true;
842
- }
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
+ }
843
625
 
844
- nextRanges.push(nextRange);
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
+ }
845
657
  });
846
658
 
847
- return changed ? nextRanges : ranges || [];
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 };
848
674
  }
849
675
 
850
676
  /*
851
- * Return the row or column design after one structure edit.
677
+ * Shift row and column design, merges, and named ranges through a structure edit.
852
678
  */
853
679
  export function getSheetStructureDesignAfterEdit(
854
680
  designInput: SheetDesignObj,
855
681
  operation: SheetStructureOperationEnum,
856
682
  targetIndex: number,
857
- bounds: SheetStructureBounds[] = [],
683
+ axisCount?: number | null,
684
+ options?: {
685
+ namedRangeRestores?: readonly SheetNamedRangeStructureRestore[] | null;
686
+ },
858
687
  ) {
859
688
  const design = normalizeSheetDesign(designInput);
860
- const rowSpans = getSheetStructureProtectedAxisSpans(bounds, 'ROW');
861
- const columnSpans = getSheetStructureProtectedAxisSpans(bounds, 'COLUMN');
862
- const rowDelta =
863
- operation === 'INSERT_ROW_ABOVE' ? 1 : operation === 'DELETE_ROW' ? -1 : 0;
864
- const columnDelta =
865
- operation === 'INSERT_COLUMN_LEFT'
866
- ? 1
867
- : operation === 'DELETE_COLUMN'
868
- ? -1
869
- : 0;
689
+
690
+ const { columnDelta, rowDelta } = getSheetStructureAxisDeltas(operation);
870
691
 
871
692
  const merges = getSheetMergedRanges(design.metadata);
872
693
  const shiftedMerges = merges.length
873
- ? shiftSheetMergedRangesForStructureEdit(merges, operation, targetIndex)
694
+ ? getSheetStructureMergedRangesAfterEdit(merges, {
695
+ index: targetIndex,
696
+ operation,
697
+ })
874
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;
875
712
 
876
713
  return {
877
714
  ...design,
715
+ namedRanges,
878
716
  grid: {
879
717
  ...design.grid,
880
- columnCount: Math.min(
718
+ columnCount: getSheetStructureAxisCountAfterEdit(
719
+ design.grid.columnCount,
720
+ columnDelta,
881
721
  SHEET_MAX_COLUMN_COUNT,
882
- Math.max(1, design.grid.columnCount + columnDelta),
883
- ),
884
- rowCount: Math.min(
885
- SHEET_MAX_ROW_COUNT,
886
- Math.max(1, design.grid.rowCount + rowDelta),
722
+ columnDelta ? axisCount : null,
887
723
  ),
724
+ rowCount: getSheetStructureAxisCountAfterEdit(design.grid.rowCount, rowDelta, SHEET_MAX_ROW_COUNT, rowDelta ? axisCount : null),
888
725
  },
889
- columns: columnDelta
890
- ? shiftSheetAxisDesignForStructureEdit(
891
- design.columns,
892
- operation,
893
- targetIndex,
894
- columnSpans,
895
- )
896
- : design.columns,
897
- rows: rowDelta
898
- ? shiftSheetAxisDesignForStructureEdit(
899
- design.rows,
900
- operation,
901
- targetIndex,
902
- rowSpans,
903
- )
904
- : design.rows,
726
+ columns: columnDelta ? shiftSheetAxisDesignForStructureEdit(design.columns, operation, targetIndex) : design.columns,
727
+ rows: rowDelta ? shiftSheetAxisDesignForStructureEdit(design.rows, operation, targetIndex) : design.rows,
905
728
  ...(merges.length
906
729
  ? {
907
730
  metadata: {
@@ -914,31 +737,104 @@ export function getSheetStructureDesignAfterEdit(
914
737
  }
915
738
 
916
739
  /*
917
- * Return one queued design-save patch with its axis maps and merged ranges
918
- * projected through a structure edit. A patch built before a collaborator's
919
- * insert/delete would otherwise write pre-shift indexes over the design the
920
- * server already shifted.
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.
921
827
  */
922
828
  export function applySheetStructureEditToDesignPatch<
923
829
  T extends {
924
830
  columns?: string | null;
925
831
  metadata?: string | null;
832
+ namedRanges?: SheetNamedRangeObj[] | null;
926
833
  rows?: string | null;
927
834
  },
928
- >(
929
- patch: T,
930
- operation: SheetStructureOperationEnum,
931
- targetIndex: number,
932
- bounds: SheetStructureBounds[] = [],
933
- ): T {
934
- const rowDelta =
935
- operation === 'INSERT_ROW_ABOVE' ? 1 : operation === 'DELETE_ROW' ? -1 : 0;
936
- const columnDelta =
937
- operation === 'INSERT_COLUMN_LEFT'
938
- ? 1
939
- : operation === 'DELETE_COLUMN'
940
- ? -1
941
- : 0;
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;
942
838
  let next = patch;
943
839
  const ensureNext = () => {
944
840
  if (next === patch) {
@@ -948,56 +844,36 @@ export function applySheetStructureEditToDesignPatch<
948
844
  };
949
845
 
950
846
  if (patch.columns && columnDelta) {
951
- const columnSpans = getSheetStructureProtectedAxisSpans(bounds, 'COLUMN');
952
- const columns = parseSheetDesignPatchObject<
953
- Record<string, SheetAxisDesignObj>
954
- >(patch.columns, {});
955
-
956
- ensureNext().columns = stringifyJSON(
957
- shiftSheetAxisDesignForStructureEdit(
958
- columns,
959
- operation,
960
- targetIndex,
961
- columnSpans,
962
- ),
963
- );
847
+ const columns = parseSheetDesignPatchObject<Record<string, SheetAxisDesignObj>>(patch.columns, {});
848
+
849
+ ensureNext().columns = stringifyJSON(shiftSheetAxisDesignForStructureEdit(columns, operation, targetIndex));
964
850
  }
965
851
 
966
852
  if (patch.rows && rowDelta) {
967
- const rowSpans = getSheetStructureProtectedAxisSpans(bounds, 'ROW');
968
- const rows = parseSheetDesignPatchObject<
969
- Record<string, SheetAxisDesignObj>
970
- >(patch.rows, {});
971
-
972
- ensureNext().rows = stringifyJSON(
973
- shiftSheetAxisDesignForStructureEdit(
974
- rows,
975
- operation,
976
- targetIndex,
977
- rowSpans,
978
- ),
979
- );
853
+ const rows = parseSheetDesignPatchObject<Record<string, SheetAxisDesignObj>>(patch.rows, {});
854
+
855
+ ensureNext().rows = stringifyJSON(shiftSheetAxisDesignForStructureEdit(rows, operation, targetIndex));
980
856
  }
981
857
 
982
858
  if (patch.metadata) {
983
- const metadata = parseSheetDesignPatchObject<Record<string, any>>(
984
- patch.metadata,
985
- {},
986
- );
859
+ const metadata = parseSheetDesignPatchObject<Record<string, any>>(patch.metadata, {});
987
860
  const merges = getSheetMergedRanges(metadata);
988
861
 
989
862
  if (merges.length) {
990
863
  ensureNext().metadata = stringifyJSON({
991
864
  ...metadata,
992
- merges: shiftSheetMergedRangesForStructureEdit(
993
- merges,
865
+ merges: getSheetStructureMergedRangesAfterEdit(merges, {
866
+ index: targetIndex,
994
867
  operation,
995
- targetIndex,
996
- ),
868
+ }),
997
869
  });
998
870
  }
999
871
  }
1000
872
 
873
+ if (Array.isArray(patch.namedRanges) && patch.namedRanges.length) {
874
+ ensureNext().namedRanges = getSheetNamedRangesAfterStructureEdit(patch.namedRanges, { index: targetIndex, operation }).namedRanges;
875
+ }
876
+
1001
877
  return next;
1002
878
  }
1003
879
 
@@ -1009,13 +885,9 @@ export function getSheetLoadedRowCountAfterStructureEdit(
1009
885
  operation: SheetStructureOperationEnum,
1010
886
  nextDesign: SheetDesignObj,
1011
887
  ) {
1012
- const rowDelta =
1013
- operation === 'INSERT_ROW_ABOVE' ? 1 : operation === 'DELETE_ROW' ? -1 : 0;
888
+ const rowDelta = operation === 'INSERT_ROW_ABOVE' ? 1 : operation === 'DELETE_ROW' ? -1 : 0;
1014
889
 
1015
- return Math.max(
1016
- 1,
1017
- Math.min(nextDesign.grid.rowCount, loadedRowCount + rowDelta),
1018
- );
890
+ return Math.max(1, Math.min(nextDesign.grid.rowCount, loadedRowCount + rowDelta));
1019
891
  }
1020
892
 
1021
893
  /*
@@ -1026,11 +898,7 @@ export function getSheetLastContentRowIndexAfterStructureEdit(
1026
898
  operation: SheetStructureOperationEnum,
1027
899
  targetIndex: number,
1028
900
  ) {
1029
- if (
1030
- !lastContentRowIndex ||
1031
- operation === 'INSERT_COLUMN_LEFT' ||
1032
- operation === 'DELETE_COLUMN'
1033
- ) {
901
+ if (!lastContentRowIndex || operation === 'INSERT_COLUMN_LEFT' || operation === 'DELETE_COLUMN') {
1034
902
  return lastContentRowIndex || null;
1035
903
  }
1036
904
 
@@ -1044,241 +912,3 @@ export function getSheetLastContentRowIndexAfterStructureEdit(
1044
912
 
1045
913
  return lastContentRowIndex;
1046
914
  }
1047
-
1048
- /*
1049
- * Return a SQL predicate that excludes coordinates inside protected region bounds.
1050
- */
1051
- export function getSheetOutsideProtectedCellBoundsPredicate(
1052
- bounds: SheetStructureBounds[],
1053
- rowExpression: string,
1054
- columnExpression: string,
1055
- startParameterIndex: number,
1056
- ): SheetStructureBoundsPredicate {
1057
- if (!bounds.length) {
1058
- return {
1059
- args: [],
1060
- text: 'TRUE',
1061
- };
1062
- }
1063
-
1064
- const args: number[] = [];
1065
- const clauses = bounds.map((bound, index) => {
1066
- const parameterIndex = startParameterIndex + index * 4;
1067
-
1068
- args.push(
1069
- bound.startRowIndex,
1070
- bound.endRowIndex,
1071
- bound.startColumnIndex,
1072
- bound.endColumnIndex,
1073
- );
1074
-
1075
- return `(${rowExpression} BETWEEN $${parameterIndex} AND $${parameterIndex + 1}
1076
- AND ${columnExpression} BETWEEN $${parameterIndex + 2} AND $${parameterIndex + 3})`;
1077
- });
1078
-
1079
- return {
1080
- args,
1081
- text: `NOT (${clauses.join(' OR ')})`,
1082
- };
1083
- }
1084
-
1085
- /*
1086
- * Return a SQL predicate that excludes ranges overlapping protected region bounds.
1087
- */
1088
- export function getSheetOutsideProtectedRangeBoundsPredicate(
1089
- bounds: SheetStructureBounds[],
1090
- startRowExpression: string,
1091
- endRowExpression: string,
1092
- startColumnExpression: string,
1093
- endColumnExpression: string,
1094
- startParameterIndex: number,
1095
- ): SheetStructureBoundsPredicate {
1096
- if (!bounds.length) {
1097
- return {
1098
- args: [],
1099
- text: 'TRUE',
1100
- };
1101
- }
1102
-
1103
- const args: number[] = [];
1104
- const clauses = bounds.map((bound, index) => {
1105
- const parameterIndex = startParameterIndex + index * 4;
1106
-
1107
- args.push(
1108
- bound.endRowIndex,
1109
- bound.startRowIndex,
1110
- bound.endColumnIndex,
1111
- bound.startColumnIndex,
1112
- );
1113
-
1114
- return `(${startRowExpression} <= $${parameterIndex}
1115
- AND ${endRowExpression} >= $${parameterIndex + 1}
1116
- AND ${startColumnExpression} <= $${parameterIndex + 2}
1117
- AND ${endColumnExpression} >= $${parameterIndex + 3})`;
1118
- });
1119
-
1120
- return {
1121
- args,
1122
- text: `NOT (${clauses.join(' OR ')})`,
1123
- };
1124
- }
1125
-
1126
- /*
1127
- * Return a SQL predicate that prevents row-delete shifts from crossing protected row spans.
1128
- */
1129
- export function getSheetRowDeleteBarrierPredicate(
1130
- bounds: SheetStructureBounds[],
1131
- rowExpression: string,
1132
- columnExpression: string,
1133
- targetIndexExpression: string,
1134
- startParameterIndex: number,
1135
- ): SheetStructureBoundsPredicate {
1136
- if (!bounds.length) {
1137
- return {
1138
- args: [],
1139
- text: 'TRUE',
1140
- };
1141
- }
1142
-
1143
- const args: number[] = [];
1144
- const clauses = bounds.map((bound, index) => {
1145
- const parameterIndex = startParameterIndex + index * 4;
1146
-
1147
- args.push(
1148
- bound.startColumnIndex,
1149
- bound.endColumnIndex,
1150
- bound.startRowIndex,
1151
- bound.endRowIndex,
1152
- );
1153
-
1154
- return `(${columnExpression} BETWEEN $${parameterIndex} AND $${parameterIndex + 1}
1155
- AND $${parameterIndex + 2} <= ${rowExpression} - 1
1156
- AND $${parameterIndex + 3} >= ${targetIndexExpression})`;
1157
- });
1158
-
1159
- return {
1160
- args,
1161
- text: `NOT (${clauses.join(' OR ')})`,
1162
- };
1163
- }
1164
-
1165
- /*
1166
- * Return a SQL predicate that prevents column-delete shifts from crossing protected column spans.
1167
- */
1168
- export function getSheetColumnDeleteBarrierPredicate(
1169
- bounds: SheetStructureBounds[],
1170
- rowExpression: string,
1171
- columnExpression: string,
1172
- targetIndexExpression: string,
1173
- startParameterIndex: number,
1174
- ): SheetStructureBoundsPredicate {
1175
- if (!bounds.length) {
1176
- return {
1177
- args: [],
1178
- text: 'TRUE',
1179
- };
1180
- }
1181
-
1182
- const args: number[] = [];
1183
- const clauses = bounds.map((bound, index) => {
1184
- const parameterIndex = startParameterIndex + index * 4;
1185
-
1186
- args.push(
1187
- bound.startRowIndex,
1188
- bound.endRowIndex,
1189
- bound.startColumnIndex,
1190
- bound.endColumnIndex,
1191
- );
1192
-
1193
- return `(${rowExpression} BETWEEN $${parameterIndex} AND $${parameterIndex + 1}
1194
- AND $${parameterIndex + 2} <= ${columnExpression} - 1
1195
- AND $${parameterIndex + 3} >= ${targetIndexExpression})`;
1196
- });
1197
-
1198
- return {
1199
- args,
1200
- text: `NOT (${clauses.join(' OR ')})`,
1201
- };
1202
- }
1203
-
1204
- /*
1205
- * Return a SQL predicate that prevents row-range shifts from crossing protected bounds.
1206
- */
1207
- export function getSheetRangeRowDeleteBarrierPredicate(
1208
- bounds: SheetStructureBounds[],
1209
- startRowExpression: string,
1210
- startColumnExpression: string,
1211
- endColumnExpression: string,
1212
- targetIndexExpression: string,
1213
- startParameterIndex: number,
1214
- ): SheetStructureBoundsPredicate {
1215
- if (!bounds.length) {
1216
- return {
1217
- args: [],
1218
- text: 'TRUE',
1219
- };
1220
- }
1221
-
1222
- const args: number[] = [];
1223
- const clauses = bounds.map((bound, index) => {
1224
- const parameterIndex = startParameterIndex + index * 4;
1225
-
1226
- args.push(
1227
- bound.startColumnIndex,
1228
- bound.endColumnIndex,
1229
- bound.startRowIndex,
1230
- bound.endRowIndex,
1231
- );
1232
-
1233
- return `(${startColumnExpression} <= $${parameterIndex + 1}
1234
- AND ${endColumnExpression} >= $${parameterIndex}
1235
- AND $${parameterIndex + 2} <= ${startRowExpression} - 1
1236
- AND $${parameterIndex + 3} >= ${targetIndexExpression})`;
1237
- });
1238
-
1239
- return {
1240
- args,
1241
- text: `NOT (${clauses.join(' OR ')})`,
1242
- };
1243
- }
1244
-
1245
- /*
1246
- * Return a SQL predicate that prevents column-range shifts from crossing protected bounds.
1247
- */
1248
- export function getSheetRangeColumnDeleteBarrierPredicate(
1249
- bounds: SheetStructureBounds[],
1250
- startColumnExpression: string,
1251
- startRowExpression: string,
1252
- endRowExpression: string,
1253
- targetIndexExpression: string,
1254
- startParameterIndex: number,
1255
- ): SheetStructureBoundsPredicate {
1256
- if (!bounds.length) {
1257
- return {
1258
- args: [],
1259
- text: 'TRUE',
1260
- };
1261
- }
1262
-
1263
- const args: number[] = [];
1264
- const clauses = bounds.map((bound, index) => {
1265
- const parameterIndex = startParameterIndex + index * 4;
1266
-
1267
- args.push(
1268
- bound.startRowIndex,
1269
- bound.endRowIndex,
1270
- bound.startColumnIndex,
1271
- bound.endColumnIndex,
1272
- );
1273
-
1274
- return `(${startRowExpression} <= $${parameterIndex + 1}
1275
- AND ${endRowExpression} >= $${parameterIndex}
1276
- AND $${parameterIndex + 2} <= ${startColumnExpression} - 1
1277
- AND $${parameterIndex + 3} >= ${targetIndexExpression})`;
1278
- });
1279
-
1280
- return {
1281
- args,
1282
- text: `NOT (${clauses.join(' OR ')})`,
1283
- };
1284
- }