@rowsncolumns/toolkit 24.4.2 → 24.4.4

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 (166) hide show
  1. package/dist/cjs/excel-parser/cfb-decryptor.d.ts +6 -0
  2. package/dist/cjs/excel-parser/cfb-decryptor.d.ts.map +1 -1
  3. package/dist/cjs/excel-parser/cfb-decryptor.js +6 -0
  4. package/dist/cjs/excel-parser/helpers.d.ts +9 -1
  5. package/dist/cjs/excel-parser/helpers.d.ts.map +1 -1
  6. package/dist/cjs/excel-parser/helpers.js +37 -0
  7. package/dist/cjs/excel-parser/interface.d.ts +15 -2
  8. package/dist/cjs/excel-parser/interface.d.ts.map +1 -1
  9. package/dist/cjs/excel-parser/plugins/base/index.d.ts +2 -0
  10. package/dist/cjs/excel-parser/plugins/base/index.d.ts.map +1 -1
  11. package/dist/cjs/excel-parser/plugins/base/index.js +3 -0
  12. package/dist/cjs/excel-parser/plugins/ods/index.d.ts +19 -0
  13. package/dist/cjs/excel-parser/plugins/ods/index.d.ts.map +1 -1
  14. package/dist/cjs/excel-parser/plugins/ods/index.js +676 -304
  15. package/dist/cjs/excel-parser/plugins/ods/styles.d.ts +43 -1
  16. package/dist/cjs/excel-parser/plugins/ods/styles.d.ts.map +1 -1
  17. package/dist/cjs/excel-parser/plugins/ods/styles.js +343 -45
  18. package/dist/cjs/excel-parser/plugins/xls/index.d.ts +55 -1
  19. package/dist/cjs/excel-parser/plugins/xls/index.d.ts.map +1 -1
  20. package/dist/cjs/excel-parser/plugins/xls/index.js +518 -6
  21. package/dist/cjs/excel-parser/plugins/xlsb/index.d.ts +4 -0
  22. package/dist/cjs/excel-parser/plugins/xlsb/index.d.ts.map +1 -1
  23. package/dist/cjs/excel-parser/plugins/xlsb/index.js +33 -14
  24. package/dist/cjs/excel-parser/plugins/xlsx/chartex.d.ts +37 -0
  25. package/dist/cjs/excel-parser/plugins/xlsx/chartex.d.ts.map +1 -0
  26. package/dist/cjs/excel-parser/plugins/xlsx/chartex.js +244 -0
  27. package/dist/cjs/excel-parser/plugins/xlsx/charts.d.ts +10 -0
  28. package/dist/cjs/excel-parser/plugins/xlsx/charts.d.ts.map +1 -1
  29. package/dist/cjs/excel-parser/plugins/xlsx/charts.js +68 -9
  30. package/dist/cjs/excel-parser/plugins/xlsx/drawing.d.ts +28 -1
  31. package/dist/cjs/excel-parser/plugins/xlsx/drawing.d.ts.map +1 -1
  32. package/dist/cjs/excel-parser/plugins/xlsx/drawing.js +155 -20
  33. package/dist/cjs/excel-parser/plugins/xlsx/form-controls.d.ts +70 -0
  34. package/dist/cjs/excel-parser/plugins/xlsx/form-controls.d.ts.map +1 -0
  35. package/dist/cjs/excel-parser/plugins/xlsx/form-controls.js +295 -0
  36. package/dist/cjs/excel-parser/plugins/xlsx/index.d.ts +35 -2
  37. package/dist/cjs/excel-parser/plugins/xlsx/index.d.ts.map +1 -1
  38. package/dist/cjs/excel-parser/plugins/xlsx/index.js +737 -257
  39. package/dist/cjs/excel-parser/plugins/xlsx/pivots.d.ts.map +1 -1
  40. package/dist/cjs/excel-parser/plugins/xlsx/pivots.js +125 -37
  41. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.d.ts +3 -0
  42. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.d.ts.map +1 -1
  43. package/dist/cjs/excel-parser/plugins/xlsx/sheet-views.js +4 -1
  44. package/dist/cjs/excel-parser/plugins/xlsx/styles.d.ts +15 -1
  45. package/dist/cjs/excel-parser/plugins/xlsx/styles.d.ts.map +1 -1
  46. package/dist/cjs/excel-parser/plugins/xlsx/styles.js +102 -6
  47. package/dist/cjs/excel-parser/registry.d.ts +7 -0
  48. package/dist/cjs/excel-parser/registry.d.ts.map +1 -1
  49. package/dist/cjs/excel-parser/registry.js +29 -0
  50. package/dist/cjs/excel-parser/types.d.ts +17 -2
  51. package/dist/cjs/excel-parser/types.d.ts.map +1 -1
  52. package/dist/cjs/excel-parser/workbook.d.ts +3 -0
  53. package/dist/cjs/excel-parser/workbook.d.ts.map +1 -1
  54. package/dist/cjs/excel-parser/workbook.js +24 -14
  55. package/dist/cjs/excel-parser/worker.js +131 -131
  56. package/dist/cjs/exporter/ods/ods-export.d.ts.map +1 -1
  57. package/dist/cjs/exporter/ods/ods-export.js +432 -175
  58. package/dist/cjs/exporter/xlsx/chart-builder.d.ts.map +1 -1
  59. package/dist/cjs/exporter/xlsx/chart-builder.js +215 -39
  60. package/dist/cjs/exporter/xlsx/chartex-builder.d.ts +36 -0
  61. package/dist/cjs/exporter/xlsx/chartex-builder.d.ts.map +1 -0
  62. package/dist/cjs/exporter/xlsx/chartex-builder.js +109 -0
  63. package/dist/cjs/exporter/xlsx/form-controls-builder.d.ts +61 -0
  64. package/dist/cjs/exporter/xlsx/form-controls-builder.d.ts.map +1 -0
  65. package/dist/cjs/exporter/xlsx/form-controls-builder.js +197 -0
  66. package/dist/cjs/exporter/xlsx/pivot-builder.d.ts +8 -0
  67. package/dist/cjs/exporter/xlsx/pivot-builder.d.ts.map +1 -1
  68. package/dist/cjs/exporter/xlsx/pivot-builder.js +141 -42
  69. package/dist/cjs/exporter/xlsx/style-builder.js +9 -3
  70. package/dist/cjs/exporter/xlsx/threaded-comments-builder.d.ts +7 -1
  71. package/dist/cjs/exporter/xlsx/threaded-comments-builder.d.ts.map +1 -1
  72. package/dist/cjs/exporter/xlsx/threaded-comments-builder.js +15 -3
  73. package/dist/cjs/exporter/xlsx/xlsx-export.d.ts +11 -2
  74. package/dist/cjs/exporter/xlsx/xlsx-export.d.ts.map +1 -1
  75. package/dist/cjs/exporter/xlsx/xlsx-export.js +991 -297
  76. package/dist/cjs/helpers/implicit-intersection.d.ts +16 -0
  77. package/dist/cjs/helpers/implicit-intersection.d.ts.map +1 -0
  78. package/dist/cjs/helpers/implicit-intersection.js +197 -0
  79. package/dist/cjs/print-settings.d.ts +105 -0
  80. package/dist/cjs/print-settings.d.ts.map +1 -0
  81. package/dist/cjs/print-settings.js +494 -0
  82. package/dist/cjs/tsconfig.cjs.tsbuildinfo +1 -1
  83. package/dist/esm/excel-parser/cfb-decryptor.d.ts +6 -0
  84. package/dist/esm/excel-parser/cfb-decryptor.d.ts.map +1 -1
  85. package/dist/esm/excel-parser/cfb-decryptor.js +6 -0
  86. package/dist/esm/excel-parser/helpers.d.ts +9 -1
  87. package/dist/esm/excel-parser/helpers.d.ts.map +1 -1
  88. package/dist/esm/excel-parser/helpers.js +34 -0
  89. package/dist/esm/excel-parser/interface.d.ts +15 -2
  90. package/dist/esm/excel-parser/interface.d.ts.map +1 -1
  91. package/dist/esm/excel-parser/plugins/base/index.d.ts +2 -0
  92. package/dist/esm/excel-parser/plugins/base/index.d.ts.map +1 -1
  93. package/dist/esm/excel-parser/plugins/base/index.js +3 -0
  94. package/dist/esm/excel-parser/plugins/ods/index.d.ts +19 -0
  95. package/dist/esm/excel-parser/plugins/ods/index.d.ts.map +1 -1
  96. package/dist/esm/excel-parser/plugins/ods/index.js +347 -33
  97. package/dist/esm/excel-parser/plugins/ods/styles.d.ts +43 -1
  98. package/dist/esm/excel-parser/plugins/ods/styles.d.ts.map +1 -1
  99. package/dist/esm/excel-parser/plugins/ods/styles.js +276 -2
  100. package/dist/esm/excel-parser/plugins/xls/index.d.ts +55 -1
  101. package/dist/esm/excel-parser/plugins/xls/index.d.ts.map +1 -1
  102. package/dist/esm/excel-parser/plugins/xls/index.js +441 -3
  103. package/dist/esm/excel-parser/plugins/xlsb/index.d.ts +4 -0
  104. package/dist/esm/excel-parser/plugins/xlsb/index.d.ts.map +1 -1
  105. package/dist/esm/excel-parser/plugins/xlsb/index.js +30 -9
  106. package/dist/esm/excel-parser/plugins/xlsx/chartex.d.ts +37 -0
  107. package/dist/esm/excel-parser/plugins/xlsx/chartex.d.ts.map +1 -0
  108. package/dist/esm/excel-parser/plugins/xlsx/chartex.js +199 -0
  109. package/dist/esm/excel-parser/plugins/xlsx/charts.d.ts +10 -0
  110. package/dist/esm/excel-parser/plugins/xlsx/charts.d.ts.map +1 -1
  111. package/dist/esm/excel-parser/plugins/xlsx/charts.js +69 -6
  112. package/dist/esm/excel-parser/plugins/xlsx/drawing.d.ts +28 -1
  113. package/dist/esm/excel-parser/plugins/xlsx/drawing.d.ts.map +1 -1
  114. package/dist/esm/excel-parser/plugins/xlsx/drawing.js +99 -0
  115. package/dist/esm/excel-parser/plugins/xlsx/form-controls.d.ts +70 -0
  116. package/dist/esm/excel-parser/plugins/xlsx/form-controls.d.ts.map +1 -0
  117. package/dist/esm/excel-parser/plugins/xlsx/form-controls.js +246 -0
  118. package/dist/esm/excel-parser/plugins/xlsx/index.d.ts +35 -2
  119. package/dist/esm/excel-parser/plugins/xlsx/index.d.ts.map +1 -1
  120. package/dist/esm/excel-parser/plugins/xlsx/index.js +454 -32
  121. package/dist/esm/excel-parser/plugins/xlsx/pivots.d.ts.map +1 -1
  122. package/dist/esm/excel-parser/plugins/xlsx/pivots.js +86 -6
  123. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.d.ts +3 -0
  124. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.d.ts.map +1 -1
  125. package/dist/esm/excel-parser/plugins/xlsx/sheet-views.js +2 -0
  126. package/dist/esm/excel-parser/plugins/xlsx/styles.d.ts +15 -1
  127. package/dist/esm/excel-parser/plugins/xlsx/styles.d.ts.map +1 -1
  128. package/dist/esm/excel-parser/plugins/xlsx/styles.js +92 -2
  129. package/dist/esm/excel-parser/registry.d.ts +7 -0
  130. package/dist/esm/excel-parser/registry.d.ts.map +1 -1
  131. package/dist/esm/excel-parser/registry.js +19 -0
  132. package/dist/esm/excel-parser/types.d.ts +17 -2
  133. package/dist/esm/excel-parser/types.d.ts.map +1 -1
  134. package/dist/esm/excel-parser/workbook.d.ts +3 -0
  135. package/dist/esm/excel-parser/workbook.d.ts.map +1 -1
  136. package/dist/esm/excel-parser/workbook.js +19 -10
  137. package/dist/esm/excel-parser/worker.js +12 -18
  138. package/dist/esm/exporter/ods/ods-export.d.ts.map +1 -1
  139. package/dist/esm/exporter/ods/ods-export.js +306 -35
  140. package/dist/esm/exporter/xlsx/chart-builder.d.ts.map +1 -1
  141. package/dist/esm/exporter/xlsx/chart-builder.js +161 -28
  142. package/dist/esm/exporter/xlsx/chartex-builder.d.ts +36 -0
  143. package/dist/esm/exporter/xlsx/chartex-builder.d.ts.map +1 -0
  144. package/dist/esm/exporter/xlsx/chartex-builder.js +97 -0
  145. package/dist/esm/exporter/xlsx/form-controls-builder.d.ts +61 -0
  146. package/dist/esm/exporter/xlsx/form-controls-builder.d.ts.map +1 -0
  147. package/dist/esm/exporter/xlsx/form-controls-builder.js +173 -0
  148. package/dist/esm/exporter/xlsx/pivot-builder.d.ts +8 -0
  149. package/dist/esm/exporter/xlsx/pivot-builder.d.ts.map +1 -1
  150. package/dist/esm/exporter/xlsx/pivot-builder.js +104 -19
  151. package/dist/esm/exporter/xlsx/style-builder.js +9 -3
  152. package/dist/esm/exporter/xlsx/threaded-comments-builder.d.ts +7 -1
  153. package/dist/esm/exporter/xlsx/threaded-comments-builder.d.ts.map +1 -1
  154. package/dist/esm/exporter/xlsx/threaded-comments-builder.js +15 -3
  155. package/dist/esm/exporter/xlsx/xlsx-export.d.ts +11 -2
  156. package/dist/esm/exporter/xlsx/xlsx-export.d.ts.map +1 -1
  157. package/dist/esm/exporter/xlsx/xlsx-export.js +675 -64
  158. package/dist/esm/helpers/implicit-intersection.d.ts +16 -0
  159. package/dist/esm/helpers/implicit-intersection.d.ts.map +1 -0
  160. package/dist/esm/helpers/implicit-intersection.js +184 -0
  161. package/dist/esm/print-settings.d.ts +105 -0
  162. package/dist/esm/print-settings.d.ts.map +1 -0
  163. package/dist/esm/print-settings.js +422 -0
  164. package/dist/esm/tsconfig.esm.tsbuildinfo +1 -1
  165. package/package.json +3 -3
  166. package/xlsx.d.ts +14 -0
@@ -3,17 +3,21 @@ import { cellRangeToAddress, cellToAddress, escapeCharacters, getCellEffectiveFo
3
3
  import { zipSync } from "fflate";
4
4
  import { omitInvalidDataValidationError } from "../invalid-data-validation";
5
5
  import { buildAutoFilterConditionXml } from "../../autofilter-condition";
6
+ import { buildControlElementXml, buildControlsXml, buildCtrlPropXml, buildFormControlVmlShape, buildVmlDrawingXml, CTRL_PROP_CONTENT_TYPE, CTRL_PROP_REL_TYPE, FORM_CONTROL_VML_SHAPETYPE, } from "./form-controls-builder";
7
+ import { buildChartExGraphicFrameXml, buildChartExXml, CHART_EX_CONTENT_TYPE, CHART_EX_REL_TYPE, isChartExType, } from "./chartex-builder";
6
8
  import { applyPowerQueryParts } from "./power-query-builder";
9
+ import { encodeImplicitIntersection } from "../../helpers/implicit-intersection";
7
10
  import { qualifyFutureFunctions } from "./future-functions";
8
11
  import { PERSON_CONTENT_TYPE, PERSON_REL_TYPE, PersonRegistry, THREADED_COMMENT_REL_TYPE, THREADED_COMMENTS_CONTENT_TYPE, ThreadedCommentsCollector, } from "./threaded-comments-builder";
9
12
  import { CFBEncryptor } from "../../excel-parser/cfb-encryptor";
10
13
  import { columnPixelToChars, imageUrlToBase64 } from "../../helpers";
14
+ import { buildPrintAreaFormula, buildPrintTitlesFormula, isBuiltinPrintName, isHeaderFooterEmpty, PRINT_AREA_NAME, PRINT_TITLES_NAME, } from "../../print-settings";
11
15
  import { generateThemeXml } from "../../helpers/theme-xml-generator";
12
16
  import theme1Xml from "../../theme1";
13
17
  import { tokenize as defaultTokenizer } from "@rowsncolumns/calculator";
14
18
  import { CellXfsRegistry, deriveEffectiveNumberFormatFromFormula, } from "@rowsncolumns/spreadsheet-state";
15
19
  import { buildChartXml } from "./chart-builder";
16
- import { buildPivotCacheDefinitionXml, buildPivotTableRelsXml, buildPivotTableXml, } from "./pivot-builder";
20
+ import { buildPivotCacheDefinitionXml, buildPivotTableRelsXml, buildPivotTableXml, calculatedFieldReferences, } from "./pivot-builder";
17
21
  import { buildSlicerCacheXml, buildSlicerXml } from "./slicer-builder";
18
22
  import { buildSparklineGroupsXml } from "./sparkline-builder";
19
23
  import { StyleBuilder } from "./style-builder";
@@ -27,12 +31,12 @@ var pixelToPoints = function (px) {
27
31
  return Math.max(1, Number(((px * 72) / 96).toFixed(2)));
28
32
  };
29
33
  export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
30
- var sortedSheets, sharedStrings, personRegistry, styleBuilder, exportableTables, tableIdMap, preparedTables, embedsBySheet, textBoxesBySheet, shapesBySheet, chartsBySheet, remappedSlicers, slicersBySheet, workbookSheetNames, sheetNameById, dataValidationsById, globalSlicerIndex, slicerCacheEntries, slicerEntries, globalPivotIndex, pivotCacheEntries, pivotCacheRelsEntries, pivotTableEntries, pivotTableRelsEntries, pivotsByTargetSheet, pivotTables_1, pivotTables_1_1, p, sid, list, workbookPivotCacheRefs, worksheetEntries, _d, workbookRelationshipsXml, sheetRelationshipIds, slicerCacheRelationshipIds, pivotCacheRelationshipIds, externalLinkRelationshipIds, workbookXml, sharedStringsXml, rootRelationshipsXml, appXml, coreXml, stylesXml, themeXml, files, worksheetEntries_1, worksheetEntries_1_1, entry, personsXml, preparedTables_1, preparedTables_1_1, table, rows, tableXml, globalImageIndex, globalChartIndex, drawingSheets, imageExtensions, chartEntries, worksheetEntries_2, worksheetEntries_2_1, entry, placements, textBoxesForSheet, shapesForSheet, chartsForSheet, slicersForSheet, drawingParts, _e, _f, media, _g, _h, chartEntry, e_1_1, chartEntries_1, chartEntries_1_1, chartEntry, slicerCacheEntries_1, slicerCacheEntries_1_1, slicerCacheEntry, slicerEntries_1, slicerEntries_1_1, slicerEntry, pivotCacheEntries_1, pivotCacheEntries_1_1, cacheEntry, pivotCacheRelsEntries_1, pivotCacheRelsEntries_1_1, cacheRels, pivotTableEntries_1, pivotTableEntries_1_1, tableEntry, pivotTableRelsEntries_1, pivotTableRelsEntries_1_1, tableRels, i, link, linkPath, relsPath, commentsSheets, threadedCommentsSheets, contentTypesXml, zipBytes;
31
- var e_2, _j, e_3, _k, e_4, _l, e_1, _m, e_5, _o, e_6, _p, e_7, _q, e_8, _s, e_9, _t, e_10, _u, e_11, _v, e_12, _w, e_13, _x;
32
- var _y, _z, _0, _1, _2, _3;
33
- var _conditionalFormats = _b.conditionalFormats, _dataValidations = _b.dataValidations, sheets = _b.sheets, sheetData = _b.sheetData, sourceSharedStrings = _b.sharedStrings, _4 = _b.tables, _tables = _4 === void 0 ? [] : _4, cellXfs = _b.cellXfs, theme = _b.theme, defaultFont = _b.defaultFont, _5 = _b.embeds, embeds = _5 === void 0 ? [] : _5, _6 = _b.charts, charts = _6 === void 0 ? [] : _6, _7 = _b.slicers, slicers = _7 === void 0 ? [] : _7, _8 = _b.pivotTables, pivotTables = _8 === void 0 ? [] : _8, _9 = _b.externalLinks, externalLinks = _9 === void 0 ? [] : _9, _10 = _b.namedRanges, namedRanges = _10 === void 0 ? [] : _10, namedCellStyles = _b.namedCellStyles, customTableStyles = _b.customTableStyles, iterativeCalculationOptions = _b.iterativeCalculationOptions, ignoreFormulaPatterns = _b.ignoreFormulaPatterns, citations = _b.citations, comments = _b.comments, password = _b.password, locale = _b.locale, _11 = _b.use1904, use1904 = _11 === void 0 ? false : _11, properties = _b.properties, powerQuery = _b.powerQuery;
34
- return __generator(this, function (_12) {
35
- switch (_12.label) {
34
+ var sortedSheets, sharedStrings, personRegistry, styleBuilder, exportableTables, tableIdMap, preparedTables, embedsBySheet, textBoxesBySheet, shapesBySheet, formControlsBySheet, ctrlProps, chartsBySheet, remappedSlicers, slicersBySheet, workbookSheetNames, sheetNameById, dataValidationsById, globalSlicerIndex, slicerCacheEntries, slicerEntries, globalPivotIndex, pivotCacheEntries, pivotCacheRelsEntries, pivotTableEntries, pivotTableRelsEntries, pivotsByTargetSheet, pivotTables_1, pivotTables_1_1, p, sid, list, workbookPivotCacheRefs, worksheetEntries, _d, workbookRelationshipsXml, sheetRelationshipIds, slicerCacheRelationshipIds, pivotCacheRelationshipIds, externalLinkRelationshipIds, workbookXml, sharedStringsXml, rootRelationshipsXml, appXml, coreXml, stylesXml, themeXml, files, worksheetEntries_1, worksheetEntries_1_1, entry, personsXml, preparedTables_1, preparedTables_1_1, table, rows, tableXml, globalImageIndex, globalChartIndex, drawingSheets, imageExtensions, chartEntries, chartExEntries, globalChartExIndex, worksheetEntries_2, worksheetEntries_2_1, entry, placements, textBoxesForSheet, shapesForSheet, chartsForSheet, slicersForSheet, drawingParts, _e, _f, media, _g, _h, chartEntry, _j, _k, chartExEntry, e_1_1, chartEntries_1, chartEntries_1_1, chartEntry, chartExEntries_1, chartExEntries_1_1, chartExEntry, slicerCacheEntries_1, slicerCacheEntries_1_1, slicerCacheEntry, slicerEntries_1, slicerEntries_1_1, slicerEntry, pivotCacheEntries_1, pivotCacheEntries_1_1, cacheEntry, pivotCacheRelsEntries_1, pivotCacheRelsEntries_1_1, cacheRels, pivotTableEntries_1, pivotTableEntries_1_1, tableEntry, pivotTableRelsEntries_1, pivotTableRelsEntries_1_1, tableRels, i, link, linkPath, relsPath, commentsSheets, hasVmlDrawings, _l, _m, part, threadedCommentsSheets, contentTypesXml, zipBytes;
35
+ var e_2, _o, e_3, _p, e_4, _q, e_1, _s, e_5, _t, e_6, _u, e_7, _v, e_8, _w, e_9, _x, e_10, _y, e_11, _z, e_12, _0, e_13, _1, e_14, _2, e_15, _3, e_16, _4;
36
+ var _5, _6, _7, _8, _9, _10;
37
+ var _conditionalFormats = _b.conditionalFormats, _dataValidations = _b.dataValidations, sheets = _b.sheets, sheetData = _b.sheetData, sourceSharedStrings = _b.sharedStrings, _11 = _b.tables, _tables = _11 === void 0 ? [] : _11, cellXfs = _b.cellXfs, theme = _b.theme, defaultFont = _b.defaultFont, _12 = _b.embeds, embeds = _12 === void 0 ? [] : _12, _13 = _b.charts, charts = _13 === void 0 ? [] : _13, _14 = _b.slicers, slicers = _14 === void 0 ? [] : _14, _15 = _b.pivotTables, pivotTables = _15 === void 0 ? [] : _15, _16 = _b.externalLinks, externalLinks = _16 === void 0 ? [] : _16, _17 = _b.namedRanges, namedRanges = _17 === void 0 ? [] : _17, _18 = _b.protectedRanges, protectedRanges = _18 === void 0 ? [] : _18, namedCellStyles = _b.namedCellStyles, customTableStyles = _b.customTableStyles, iterativeCalculationOptions = _b.iterativeCalculationOptions, ignoreFormulaPatterns = _b.ignoreFormulaPatterns, citations = _b.citations, comments = _b.comments, password = _b.password, locale = _b.locale, _19 = _b.use1904, use1904 = _19 === void 0 ? false : _19, properties = _b.properties, powerQuery = _b.powerQuery;
38
+ return __generator(this, function (_20) {
39
+ switch (_20.label) {
36
40
  case 0:
37
41
  sortedSheets = sortSheetsByIndex(sheets, true);
38
42
  sharedStrings = new SharedStrings();
@@ -57,6 +61,8 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
57
61
  embedsBySheet = groupEmbedsBySheet(embeds !== null && embeds !== void 0 ? embeds : []);
58
62
  textBoxesBySheet = groupTextBoxesBySheet(embeds !== null && embeds !== void 0 ? embeds : []);
59
63
  shapesBySheet = groupShapesBySheet(embeds !== null && embeds !== void 0 ? embeds : []);
64
+ formControlsBySheet = groupFormControlsBySheet(embeds !== null && embeds !== void 0 ? embeds : []);
65
+ ctrlProps = { parts: [] };
60
66
  chartsBySheet = groupChartsBySheet(charts !== null && charts !== void 0 ? charts : []);
61
67
  remappedSlicers = slicers.map(function (slicer) {
62
68
  if (slicer.spec.type !== "table")
@@ -74,10 +80,10 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
74
80
  var _a;
75
81
  sheetNameById.set((_a = sheet.sheetId) !== null && _a !== void 0 ? _a : index + 1, workbookSheetNames[index]);
76
82
  });
77
- dataValidationsById = (_y = _dataValidations === null || _dataValidations === void 0 ? void 0 : _dataValidations.reduce(function (acc, rule) {
83
+ dataValidationsById = (_5 = _dataValidations === null || _dataValidations === void 0 ? void 0 : _dataValidations.reduce(function (acc, rule) {
78
84
  acc[rule.id] = rule;
79
85
  return acc;
80
- }, {})) !== null && _y !== void 0 ? _y : undefined;
86
+ }, {})) !== null && _5 !== void 0 ? _5 : undefined;
81
87
  globalSlicerIndex = 1;
82
88
  slicerCacheEntries = [];
83
89
  slicerEntries = [];
@@ -90,7 +96,7 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
90
96
  try {
91
97
  for (pivotTables_1 = __values(pivotTables), pivotTables_1_1 = pivotTables_1.next(); !pivotTables_1_1.done; pivotTables_1_1 = pivotTables_1.next()) {
92
98
  p = pivotTables_1_1.value;
93
- sid = (_z = p.targetPosition) === null || _z === void 0 ? void 0 : _z.sheetId;
99
+ sid = (_6 = p.targetPosition) === null || _6 === void 0 ? void 0 : _6.sheetId;
94
100
  if (sid == null)
95
101
  continue;
96
102
  list = pivotsByTargetSheet.get(sid);
@@ -103,22 +109,23 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
103
109
  catch (e_2_1) { e_2 = { error: e_2_1 }; }
104
110
  finally {
105
111
  try {
106
- if (pivotTables_1_1 && !pivotTables_1_1.done && (_j = pivotTables_1.return)) _j.call(pivotTables_1);
112
+ if (pivotTables_1_1 && !pivotTables_1_1.done && (_o = pivotTables_1.return)) _o.call(pivotTables_1);
107
113
  }
108
114
  finally { if (e_2) throw e_2.error; }
109
115
  }
110
116
  workbookPivotCacheRefs = [];
111
117
  worksheetEntries = sortedSheets.map(function (sheet, index) {
112
- var e_14, _a, e_15, _b;
113
- var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
118
+ var e_17, _a, e_18, _b;
119
+ var _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q, _s, _t, _u;
114
120
  var rows = getRowsForSheet(sheetData, sheet.sheetId);
115
121
  var sheetRelationships = new RelationshipsBuilder();
116
122
  var sheetTables = preparedTables.filter(function (table) { return table.sheetId === sheet.sheetId; });
117
123
  var embedImages = (_d = embedsBySheet.get(sheet.sheetId)) !== null && _d !== void 0 ? _d : [];
118
124
  var textBoxes = (_e = textBoxesBySheet.get(sheet.sheetId)) !== null && _e !== void 0 ? _e : [];
119
125
  var sheetShapes = (_f = shapesBySheet.get(sheet.sheetId)) !== null && _f !== void 0 ? _f : [];
120
- var sheetCharts = (_g = chartsBySheet.get(sheet.sheetId)) !== null && _g !== void 0 ? _g : [];
121
- var sheetSlicers = (_h = slicersBySheet.get(sheet.sheetId)) !== null && _h !== void 0 ? _h : [];
126
+ var sheetFormControls = (_g = formControlsBySheet.get(sheet.sheetId)) !== null && _g !== void 0 ? _g : [];
127
+ var sheetCharts = (_h = chartsBySheet.get(sheet.sheetId)) !== null && _h !== void 0 ? _h : [];
128
+ var sheetSlicers = (_j = slicersBySheet.get(sheet.sheetId)) !== null && _j !== void 0 ? _j : [];
122
129
  var worksheetSlicerRelIds = [];
123
130
  var drawingSlicers = [];
124
131
  var sheetConditionalFormats = (_conditionalFormats !== null && _conditionalFormats !== void 0 ? _conditionalFormats : []).filter(function (rule) { var _a; return (_a = rule.ranges) === null || _a === void 0 ? void 0 : _a.some(function (range) { return range.sheetId === sheet.sheetId; }); });
@@ -166,24 +173,24 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
166
173
  }
167
174
  }
168
175
  }
169
- catch (e_14_1) { e_14 = { error: e_14_1 }; }
176
+ catch (e_17_1) { e_17 = { error: e_17_1 }; }
170
177
  finally {
171
178
  try {
172
179
  if (sheetSlicers_1_1 && !sheetSlicers_1_1.done && (_a = sheetSlicers_1.return)) _a.call(sheetSlicers_1);
173
180
  }
174
- finally { if (e_14) throw e_14.error; }
181
+ finally { if (e_17) throw e_17.error; }
175
182
  }
176
183
  // Phase D2 — emit pivot table XMLs + relationships for this
177
184
  // sheet. PivotTable lives on the rendering sheet; its cache
178
185
  // definition is workbook-scoped (added to <pivotCaches> after
179
186
  // this loop).
180
- var sheetPivots = (_j = pivotsByTargetSheet.get(sheet.sheetId)) !== null && _j !== void 0 ? _j : [];
187
+ var sheetPivots = (_k = pivotsByTargetSheet.get(sheet.sheetId)) !== null && _k !== void 0 ? _k : [];
181
188
  var _loop_1 = function (pivot) {
182
- var e_16, _q, e_17, _s, e_18, _t;
189
+ var e_19, _v, e_20, _w, e_21, _x, e_22, _y, e_23, _z, e_24, _0;
183
190
  var cacheIndex = globalPivotIndex;
184
191
  var tableIndex = globalPivotIndex;
185
192
  var sourceSheet = sortedSheets.find(function (s) { var _a; return s.sheetId === ((_a = pivot.source) === null || _a === void 0 ? void 0 : _a.sheetId); });
186
- var sourceSheetName = (_l = (_k = sourceSheet === null || sourceSheet === void 0 ? void 0 : sourceSheet.title) !== null && _k !== void 0 ? _k : sheet.title) !== null && _l !== void 0 ? _l : "Sheet".concat(sheet.sheetId);
193
+ var sourceSheetName = (_m = (_l = sourceSheet === null || sourceSheet === void 0 ? void 0 : sourceSheet.title) !== null && _l !== void 0 ? _l : sheet.title) !== null && _m !== void 0 ? _m : "Sheet".concat(sheet.sheetId);
187
194
  // Field universe: union of every field referenced by the
188
195
  // pivot. PivotCacheDefinition requires one <cacheField>
189
196
  // entry per field, and pivotTable.fld indices reference them.
@@ -195,44 +202,88 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
195
202
  fieldIndex.set(name, fieldNameList.length);
196
203
  fieldNameList.push(name);
197
204
  };
205
+ var calculatedNames = new Set(((_o = pivot.calculatedFields) !== null && _o !== void 0 ? _o : []).map(function (c) { return c.name; }));
198
206
  try {
199
- for (var _u = (e_16 = void 0, __values((_m = pivot.rows) !== null && _m !== void 0 ? _m : [])), _v = _u.next(); !_v.done; _v = _u.next()) {
200
- var r = _v.value;
207
+ for (var _1 = (e_19 = void 0, __values((_p = pivot.rows) !== null && _p !== void 0 ? _p : [])), _2 = _1.next(); !_2.done; _2 = _1.next()) {
208
+ var r = _2.value;
201
209
  registerField(r.field);
202
210
  }
203
211
  }
204
- catch (e_16_1) { e_16 = { error: e_16_1 }; }
212
+ catch (e_19_1) { e_19 = { error: e_19_1 }; }
205
213
  finally {
206
214
  try {
207
- if (_v && !_v.done && (_q = _u.return)) _q.call(_u);
215
+ if (_2 && !_2.done && (_v = _1.return)) _v.call(_1);
208
216
  }
209
- finally { if (e_16) throw e_16.error; }
217
+ finally { if (e_19) throw e_19.error; }
210
218
  }
211
219
  try {
212
- for (var _w = (e_17 = void 0, __values((_o = pivot.columns) !== null && _o !== void 0 ? _o : [])), _x = _w.next(); !_x.done; _x = _w.next()) {
213
- var c = _x.value;
220
+ for (var _3 = (e_20 = void 0, __values((_q = pivot.columns) !== null && _q !== void 0 ? _q : [])), _4 = _3.next(); !_4.done; _4 = _3.next()) {
221
+ var c = _4.value;
214
222
  registerField(c.field);
215
223
  }
216
224
  }
217
- catch (e_17_1) { e_17 = { error: e_17_1 }; }
225
+ catch (e_20_1) { e_20 = { error: e_20_1 }; }
218
226
  finally {
219
227
  try {
220
- if (_x && !_x.done && (_s = _w.return)) _s.call(_w);
228
+ if (_4 && !_4.done && (_w = _3.return)) _w.call(_3);
221
229
  }
222
- finally { if (e_17) throw e_17.error; }
230
+ finally { if (e_20) throw e_20.error; }
223
231
  }
224
232
  try {
225
- for (var _y = (e_18 = void 0, __values((_p = pivot.values) !== null && _p !== void 0 ? _p : [])), _z = _y.next(); !_z.done; _z = _y.next()) {
226
- var v = _z.value;
227
- registerField(v.field);
233
+ for (var _5 = (e_21 = void 0, __values((_s = pivot.values) !== null && _s !== void 0 ? _s : [])), _6 = _5.next(); !_6.done; _6 = _5.next()) {
234
+ var v = _6.value;
235
+ if (!calculatedNames.has(v.field))
236
+ registerField(v.field);
228
237
  }
229
238
  }
230
- catch (e_18_1) { e_18 = { error: e_18_1 }; }
239
+ catch (e_21_1) { e_21 = { error: e_21_1 }; }
231
240
  finally {
232
241
  try {
233
- if (_z && !_z.done && (_t = _y.return)) _t.call(_y);
242
+ if (_6 && !_6.done && (_x = _5.return)) _x.call(_5);
234
243
  }
235
- finally { if (e_18) throw e_18.error; }
244
+ finally { if (e_21) throw e_21.error; }
245
+ }
246
+ try {
247
+ // Source fields a calculated field reads must exist in the cache
248
+ // for Excel to evaluate the formula; the calculated fields
249
+ // themselves come last, as Excel orders them.
250
+ for (var _7 = (e_22 = void 0, __values((_t = pivot.calculatedFields) !== null && _t !== void 0 ? _t : [])), _8 = _7.next(); !_8.done; _8 = _7.next()) {
251
+ var c = _8.value;
252
+ try {
253
+ for (var _9 = (e_23 = void 0, __values(calculatedFieldReferences(c.formula))), _10 = _9.next(); !_10.done; _10 = _9.next()) {
254
+ var ref = _10.value;
255
+ if (!calculatedNames.has(ref))
256
+ registerField(ref);
257
+ }
258
+ }
259
+ catch (e_23_1) { e_23 = { error: e_23_1 }; }
260
+ finally {
261
+ try {
262
+ if (_10 && !_10.done && (_z = _9.return)) _z.call(_9);
263
+ }
264
+ finally { if (e_23) throw e_23.error; }
265
+ }
266
+ }
267
+ }
268
+ catch (e_22_1) { e_22 = { error: e_22_1 }; }
269
+ finally {
270
+ try {
271
+ if (_8 && !_8.done && (_y = _7.return)) _y.call(_7);
272
+ }
273
+ finally { if (e_22) throw e_22.error; }
274
+ }
275
+ try {
276
+ for (var _11 = (e_24 = void 0, __values((_u = pivot.calculatedFields) !== null && _u !== void 0 ? _u : [])), _12 = _11.next(); !_12.done; _12 = _11.next()) {
277
+ var c = _12.value;
278
+ registerField(c.name);
279
+ }
280
+ }
281
+ catch (e_24_1) { e_24 = { error: e_24_1 }; }
282
+ finally {
283
+ try {
284
+ if (_12 && !_12.done && (_0 = _11.return)) _0.call(_11);
285
+ }
286
+ finally { if (e_24) throw e_24.error; }
236
287
  }
237
288
  var cacheXml = buildPivotCacheDefinitionXml(pivot, sourceSheetName, fieldNameList);
238
289
  var tableXml = buildPivotTableXml(pivot, cacheIndex, fieldIndex);
@@ -263,12 +314,12 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
263
314
  _loop_1(pivot);
264
315
  }
265
316
  }
266
- catch (e_15_1) { e_15 = { error: e_15_1 }; }
317
+ catch (e_18_1) { e_18 = { error: e_18_1 }; }
267
318
  finally {
268
319
  try {
269
320
  if (sheetPivots_1_1 && !sheetPivots_1_1.done && (_b = sheetPivots_1.return)) _b.call(sheetPivots_1);
270
321
  }
271
- finally { if (e_15) throw e_15.error; }
322
+ finally { if (e_18) throw e_18.error; }
272
323
  }
273
324
  var result = buildWorksheetXml({
274
325
  sheet: sheet,
@@ -291,6 +342,9 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
291
342
  sheetData: sheetData,
292
343
  sheets: sortedSheets,
293
344
  locale: locale,
345
+ protectedRanges: protectedRanges,
346
+ formControls: sheetFormControls,
347
+ ctrlProps: ctrlProps,
294
348
  });
295
349
  return {
296
350
  index: index,
@@ -352,7 +406,7 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
352
406
  catch (e_3_1) { e_3 = { error: e_3_1 }; }
353
407
  finally {
354
408
  try {
355
- if (worksheetEntries_1_1 && !worksheetEntries_1_1.done && (_k = worksheetEntries_1.return)) _k.call(worksheetEntries_1);
409
+ if (worksheetEntries_1_1 && !worksheetEntries_1_1.done && (_p = worksheetEntries_1.return)) _p.call(worksheetEntries_1);
356
410
  }
357
411
  finally { if (e_3) throw e_3.error; }
358
412
  }
@@ -373,7 +427,7 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
373
427
  catch (e_4_1) { e_4 = { error: e_4_1 }; }
374
428
  finally {
375
429
  try {
376
- if (preparedTables_1_1 && !preparedTables_1_1.done && (_l = preparedTables_1.return)) _l.call(preparedTables_1);
430
+ if (preparedTables_1_1 && !preparedTables_1_1.done && (_q = preparedTables_1.return)) _q.call(preparedTables_1);
377
431
  }
378
432
  finally { if (e_4) throw e_4.error; }
379
433
  }
@@ -382,19 +436,21 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
382
436
  drawingSheets = [];
383
437
  imageExtensions = new Set();
384
438
  chartEntries = [];
385
- _12.label = 1;
439
+ chartExEntries = [];
440
+ globalChartExIndex = 1;
441
+ _20.label = 1;
386
442
  case 1:
387
- _12.trys.push([1, 6, 7, 8]);
443
+ _20.trys.push([1, 6, 7, 8]);
388
444
  worksheetEntries_2 = __values(worksheetEntries), worksheetEntries_2_1 = worksheetEntries_2.next();
389
- _12.label = 2;
445
+ _20.label = 2;
390
446
  case 2:
391
447
  if (!!worksheetEntries_2_1.done) return [3 /*break*/, 5];
392
448
  entry = worksheetEntries_2_1.value;
393
449
  placements = __spreadArray(__spreadArray([], __read(entry.cellImages), false), __read(entry.embedImages), false);
394
- textBoxesForSheet = (_0 = entry.textBoxes) !== null && _0 !== void 0 ? _0 : [];
395
- shapesForSheet = (_1 = entry.shapes) !== null && _1 !== void 0 ? _1 : [];
396
- chartsForSheet = (_2 = entry.charts) !== null && _2 !== void 0 ? _2 : [];
397
- slicersForSheet = (_3 = entry.slicers) !== null && _3 !== void 0 ? _3 : [];
450
+ textBoxesForSheet = (_7 = entry.textBoxes) !== null && _7 !== void 0 ? _7 : [];
451
+ shapesForSheet = (_8 = entry.shapes) !== null && _8 !== void 0 ? _8 : [];
452
+ chartsForSheet = (_9 = entry.charts) !== null && _9 !== void 0 ? _9 : [];
453
+ slicersForSheet = (_10 = entry.slicers) !== null && _10 !== void 0 ? _10 : [];
398
454
  if (!placements.length &&
399
455
  !textBoxesForSheet.length &&
400
456
  !shapesForSheet.length &&
@@ -408,12 +464,13 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
408
464
  shapes: shapesForSheet,
409
465
  startImageIndex: globalImageIndex,
410
466
  startChartIndex: globalChartIndex,
467
+ startChartExIndex: globalChartExIndex,
411
468
  charts: chartsForSheet,
412
469
  slicers: slicersForSheet,
413
470
  sheetNameById: sheetNameById,
414
471
  })];
415
472
  case 3:
416
- drawingParts = _12.sent();
473
+ drawingParts = _20.sent();
417
474
  if (!drawingParts)
418
475
  return [3 /*break*/, 4];
419
476
  files[entry.drawingPath] = encodeXml(drawingParts.xml);
@@ -430,7 +487,7 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
430
487
  catch (e_5_1) { e_5 = { error: e_5_1 }; }
431
488
  finally {
432
489
  try {
433
- if (_f && !_f.done && (_o = _e.return)) _o.call(_e);
490
+ if (_f && !_f.done && (_t = _e.return)) _t.call(_e);
434
491
  }
435
492
  finally { if (e_5) throw e_5.error; }
436
493
  }
@@ -443,25 +500,39 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
443
500
  catch (e_6_1) { e_6 = { error: e_6_1 }; }
444
501
  finally {
445
502
  try {
446
- if (_h && !_h.done && (_p = _g.return)) _p.call(_g);
503
+ if (_h && !_h.done && (_u = _g.return)) _u.call(_g);
447
504
  }
448
505
  finally { if (e_6) throw e_6.error; }
449
506
  }
507
+ try {
508
+ for (_j = (e_7 = void 0, __values(drawingParts.chartExs)), _k = _j.next(); !_k.done; _k = _j.next()) {
509
+ chartExEntry = _k.value;
510
+ chartExEntries.push(chartExEntry);
511
+ }
512
+ }
513
+ catch (e_7_1) { e_7 = { error: e_7_1 }; }
514
+ finally {
515
+ try {
516
+ if (_k && !_k.done && (_v = _j.return)) _v.call(_j);
517
+ }
518
+ finally { if (e_7) throw e_7.error; }
519
+ }
450
520
  globalImageIndex = drawingParts.nextImageIndex;
451
521
  globalChartIndex = drawingParts.nextChartIndex;
522
+ globalChartExIndex = drawingParts.nextChartExIndex;
452
523
  drawingSheets.push(entry.index + 1);
453
- _12.label = 4;
524
+ _20.label = 4;
454
525
  case 4:
455
526
  worksheetEntries_2_1 = worksheetEntries_2.next();
456
527
  return [3 /*break*/, 2];
457
528
  case 5: return [3 /*break*/, 8];
458
529
  case 6:
459
- e_1_1 = _12.sent();
530
+ e_1_1 = _20.sent();
460
531
  e_1 = { error: e_1_1 };
461
532
  return [3 /*break*/, 8];
462
533
  case 7:
463
534
  try {
464
- if (worksheetEntries_2_1 && !worksheetEntries_2_1.done && (_m = worksheetEntries_2.return)) _m.call(worksheetEntries_2);
535
+ if (worksheetEntries_2_1 && !worksheetEntries_2_1.done && (_s = worksheetEntries_2.return)) _s.call(worksheetEntries_2);
465
536
  }
466
537
  finally { if (e_1) throw e_1.error; }
467
538
  return [7 /*endfinally*/];
@@ -472,12 +543,25 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
472
543
  files[chartEntry.path] = encodeXml(chartEntry.xml);
473
544
  }
474
545
  }
475
- catch (e_7_1) { e_7 = { error: e_7_1 }; }
546
+ catch (e_8_1) { e_8 = { error: e_8_1 }; }
476
547
  finally {
477
548
  try {
478
- if (chartEntries_1_1 && !chartEntries_1_1.done && (_q = chartEntries_1.return)) _q.call(chartEntries_1);
549
+ if (chartEntries_1_1 && !chartEntries_1_1.done && (_w = chartEntries_1.return)) _w.call(chartEntries_1);
479
550
  }
480
- finally { if (e_7) throw e_7.error; }
551
+ finally { if (e_8) throw e_8.error; }
552
+ }
553
+ try {
554
+ for (chartExEntries_1 = __values(chartExEntries), chartExEntries_1_1 = chartExEntries_1.next(); !chartExEntries_1_1.done; chartExEntries_1_1 = chartExEntries_1.next()) {
555
+ chartExEntry = chartExEntries_1_1.value;
556
+ files[chartExEntry.path] = encodeXml(chartExEntry.xml);
557
+ }
558
+ }
559
+ catch (e_9_1) { e_9 = { error: e_9_1 }; }
560
+ finally {
561
+ try {
562
+ if (chartExEntries_1_1 && !chartExEntries_1_1.done && (_x = chartExEntries_1.return)) _x.call(chartExEntries_1);
563
+ }
564
+ finally { if (e_9) throw e_9.error; }
481
565
  }
482
566
  try {
483
567
  for (slicerCacheEntries_1 = __values(slicerCacheEntries), slicerCacheEntries_1_1 = slicerCacheEntries_1.next(); !slicerCacheEntries_1_1.done; slicerCacheEntries_1_1 = slicerCacheEntries_1.next()) {
@@ -485,12 +569,12 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
485
569
  files[slicerCacheEntry.path] = encodeXml(slicerCacheEntry.xml);
486
570
  }
487
571
  }
488
- catch (e_8_1) { e_8 = { error: e_8_1 }; }
572
+ catch (e_10_1) { e_10 = { error: e_10_1 }; }
489
573
  finally {
490
574
  try {
491
- if (slicerCacheEntries_1_1 && !slicerCacheEntries_1_1.done && (_s = slicerCacheEntries_1.return)) _s.call(slicerCacheEntries_1);
575
+ if (slicerCacheEntries_1_1 && !slicerCacheEntries_1_1.done && (_y = slicerCacheEntries_1.return)) _y.call(slicerCacheEntries_1);
492
576
  }
493
- finally { if (e_8) throw e_8.error; }
577
+ finally { if (e_10) throw e_10.error; }
494
578
  }
495
579
  try {
496
580
  for (slicerEntries_1 = __values(slicerEntries), slicerEntries_1_1 = slicerEntries_1.next(); !slicerEntries_1_1.done; slicerEntries_1_1 = slicerEntries_1.next()) {
@@ -498,12 +582,12 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
498
582
  files[slicerEntry.path] = encodeXml(slicerEntry.xml);
499
583
  }
500
584
  }
501
- catch (e_9_1) { e_9 = { error: e_9_1 }; }
585
+ catch (e_11_1) { e_11 = { error: e_11_1 }; }
502
586
  finally {
503
587
  try {
504
- if (slicerEntries_1_1 && !slicerEntries_1_1.done && (_t = slicerEntries_1.return)) _t.call(slicerEntries_1);
588
+ if (slicerEntries_1_1 && !slicerEntries_1_1.done && (_z = slicerEntries_1.return)) _z.call(slicerEntries_1);
505
589
  }
506
- finally { if (e_9) throw e_9.error; }
590
+ finally { if (e_11) throw e_11.error; }
507
591
  }
508
592
  try {
509
593
  // Phase D2 — emit pivot files.
@@ -512,12 +596,12 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
512
596
  files[cacheEntry.path] = encodeXml(cacheEntry.xml);
513
597
  }
514
598
  }
515
- catch (e_10_1) { e_10 = { error: e_10_1 }; }
599
+ catch (e_12_1) { e_12 = { error: e_12_1 }; }
516
600
  finally {
517
601
  try {
518
- if (pivotCacheEntries_1_1 && !pivotCacheEntries_1_1.done && (_u = pivotCacheEntries_1.return)) _u.call(pivotCacheEntries_1);
602
+ if (pivotCacheEntries_1_1 && !pivotCacheEntries_1_1.done && (_0 = pivotCacheEntries_1.return)) _0.call(pivotCacheEntries_1);
519
603
  }
520
- finally { if (e_10) throw e_10.error; }
604
+ finally { if (e_12) throw e_12.error; }
521
605
  }
522
606
  try {
523
607
  for (pivotCacheRelsEntries_1 = __values(pivotCacheRelsEntries), pivotCacheRelsEntries_1_1 = pivotCacheRelsEntries_1.next(); !pivotCacheRelsEntries_1_1.done; pivotCacheRelsEntries_1_1 = pivotCacheRelsEntries_1.next()) {
@@ -525,12 +609,12 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
525
609
  files[cacheRels.path] = encodeXml(cacheRels.xml);
526
610
  }
527
611
  }
528
- catch (e_11_1) { e_11 = { error: e_11_1 }; }
612
+ catch (e_13_1) { e_13 = { error: e_13_1 }; }
529
613
  finally {
530
614
  try {
531
- if (pivotCacheRelsEntries_1_1 && !pivotCacheRelsEntries_1_1.done && (_v = pivotCacheRelsEntries_1.return)) _v.call(pivotCacheRelsEntries_1);
615
+ if (pivotCacheRelsEntries_1_1 && !pivotCacheRelsEntries_1_1.done && (_1 = pivotCacheRelsEntries_1.return)) _1.call(pivotCacheRelsEntries_1);
532
616
  }
533
- finally { if (e_11) throw e_11.error; }
617
+ finally { if (e_13) throw e_13.error; }
534
618
  }
535
619
  try {
536
620
  for (pivotTableEntries_1 = __values(pivotTableEntries), pivotTableEntries_1_1 = pivotTableEntries_1.next(); !pivotTableEntries_1_1.done; pivotTableEntries_1_1 = pivotTableEntries_1.next()) {
@@ -538,12 +622,12 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
538
622
  files[tableEntry.path] = encodeXml(tableEntry.xml);
539
623
  }
540
624
  }
541
- catch (e_12_1) { e_12 = { error: e_12_1 }; }
625
+ catch (e_14_1) { e_14 = { error: e_14_1 }; }
542
626
  finally {
543
627
  try {
544
- if (pivotTableEntries_1_1 && !pivotTableEntries_1_1.done && (_w = pivotTableEntries_1.return)) _w.call(pivotTableEntries_1);
628
+ if (pivotTableEntries_1_1 && !pivotTableEntries_1_1.done && (_2 = pivotTableEntries_1.return)) _2.call(pivotTableEntries_1);
545
629
  }
546
- finally { if (e_12) throw e_12.error; }
630
+ finally { if (e_14) throw e_14.error; }
547
631
  }
548
632
  try {
549
633
  for (pivotTableRelsEntries_1 = __values(pivotTableRelsEntries), pivotTableRelsEntries_1_1 = pivotTableRelsEntries_1.next(); !pivotTableRelsEntries_1_1.done; pivotTableRelsEntries_1_1 = pivotTableRelsEntries_1.next()) {
@@ -551,12 +635,12 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
551
635
  files[tableRels.path] = encodeXml(tableRels.xml);
552
636
  }
553
637
  }
554
- catch (e_13_1) { e_13 = { error: e_13_1 }; }
638
+ catch (e_15_1) { e_15 = { error: e_15_1 }; }
555
639
  finally {
556
640
  try {
557
- if (pivotTableRelsEntries_1_1 && !pivotTableRelsEntries_1_1.done && (_x = pivotTableRelsEntries_1.return)) _x.call(pivotTableRelsEntries_1);
641
+ if (pivotTableRelsEntries_1_1 && !pivotTableRelsEntries_1_1.done && (_3 = pivotTableRelsEntries_1.return)) _3.call(pivotTableRelsEntries_1);
558
642
  }
559
- finally { if (e_13) throw e_13.error; }
643
+ finally { if (e_15) throw e_15.error; }
560
644
  }
561
645
  // Add external link files (for formulas referencing other workbooks)
562
646
  for (i = 0; i < externalLinks.length; i++) {
@@ -572,6 +656,20 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
572
656
  commentsSheets = worksheetEntries
573
657
  .filter(function (entry) { return entry.commentsXml; })
574
658
  .map(function (entry) { var _a; return (_a = entry.sheet.sheetId) !== null && _a !== void 0 ? _a : entry.index + 1; });
659
+ hasVmlDrawings = worksheetEntries.some(function (entry) { return entry.vmlDrawingXml; });
660
+ try {
661
+ for (_l = __values(ctrlProps.parts), _m = _l.next(); !_m.done; _m = _l.next()) {
662
+ part = _m.value;
663
+ files[part.path] = encodeXml(part.xml);
664
+ }
665
+ }
666
+ catch (e_16_1) { e_16 = { error: e_16_1 }; }
667
+ finally {
668
+ try {
669
+ if (_m && !_m.done && (_4 = _l.return)) _4.call(_l);
670
+ }
671
+ finally { if (e_16) throw e_16.error; }
672
+ }
575
673
  threadedCommentsSheets = worksheetEntries
576
674
  .filter(function (entry) { return entry.threadedCommentsXml; })
577
675
  .map(function (entry) { var _a; return (_a = entry.sheet.sheetId) !== null && _a !== void 0 ? _a : entry.index + 1; });
@@ -581,6 +679,7 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
581
679
  drawingSheets: drawingSheets,
582
680
  mediaExtensions: Array.from(imageExtensions),
583
681
  chartCount: chartEntries.length,
682
+ chartExCount: chartExEntries.length,
584
683
  slicerCount: slicerEntries.length,
585
684
  slicerCacheCount: slicerCacheEntries.length,
586
685
  pivotTableCount: pivotTableEntries.length,
@@ -589,6 +688,8 @@ export var createExcelFile = function (_a) { return __awaiter(void 0, [_a], void
589
688
  threadedCommentsSheets: threadedCommentsSheets,
590
689
  hasPersons: !personRegistry.isEmpty(),
591
690
  externalLinkCount: externalLinks.length,
691
+ hasVmlDrawings: hasVmlDrawings,
692
+ ctrlPropCount: ctrlProps.parts.length,
592
693
  });
593
694
  files["[Content_Types].xml"] = encodeXml(contentTypesXml);
594
695
  // Preserved Power Query machinery (DataMashup customXml, connections.xml, queryTable parts) is
@@ -756,6 +857,8 @@ var DataValidationCollector = /** @class */ (function () {
756
857
  };
757
858
  return DataValidationCollector;
758
859
  }());
860
+ /** First VML shape id the note shapes take (`_x0000_s1026`, `_x0000_s1027`, …). */
861
+ var NOTE_VML_SHAPE_ID_BASE = 1026;
759
862
  var CommentsCollector = /** @class */ (function () {
760
863
  function CommentsCollector() {
761
864
  this.entries = [];
@@ -783,13 +886,18 @@ var CommentsCollector = /** @class */ (function () {
783
886
  .join("");
784
887
  return "".concat(XML_DECLARATION, "<comments xmlns=\"").concat(WORKSHEET_NS, "\"><authors>").concat(authorsXml, "</authors><commentList>").concat(commentsXml, "</commentList></comments>");
785
888
  };
786
- CommentsCollector.prototype.toVmlXml = function () {
787
- if (!this.entries.length) {
788
- return undefined;
789
- }
790
- var shapes = this.entries
791
- .map(function (entry, index) {
792
- var shapeId = "_x0000_s".concat(1026 + index);
889
+ /**
890
+ * VML shape ids the note shapes occupy. Excel allocates notes and form
891
+ * controls from one per-sheet counter, so the form-control allocator must
892
+ * never hand these out again.
893
+ */
894
+ CommentsCollector.prototype.vmlShapeIds = function () {
895
+ return this.entries.map(function (_, index) { return NOTE_VML_SHAPE_ID_BASE + index; });
896
+ };
897
+ /** One `<v:shape>` per note (Excel's hidden `Note` object). */
898
+ CommentsCollector.prototype.toVmlShapes = function () {
899
+ return this.entries.map(function (entry, index) {
900
+ var shapeId = "_x0000_s".concat(NOTE_VML_SHAPE_ID_BASE + index);
793
901
  // Parse cell address to get row and column
794
902
  var match = entry.address.match(/^([A-Z]+)(\d+)$/);
795
903
  if (!match)
@@ -800,12 +908,12 @@ var CommentsCollector = /** @class */ (function () {
800
908
  .split("")
801
909
  .reduce(function (acc, char) { return acc * 26 + (char.charCodeAt(0) - 64); }, 0) - 1;
802
910
  return "<v:shape id=\"".concat(shapeId, "\" type=\"#_x0000_t202\" style='position:absolute;margin-left:59.25pt;margin-top:1.5pt;width:108pt;height:59.25pt;z-index:").concat(index + 1, ";visibility:hidden' fillcolor=\"#ffffe1\" o:insetmode=\"auto\"><v:fill color2=\"#ffffe1\"/><v:shadow on=\"t\" color=\"black\" obscured=\"t\"/><v:path o:connecttype=\"none\"/><v:textbox style='mso-direction-alt:auto'><div style='text-align:left'></div></v:textbox><x:ClientData ObjectType=\"Note\"><x:MoveWithCells/><x:SizeWithCells/><x:Anchor>1, 15, 0, 2, 3, 15, 3, 16</x:Anchor><x:AutoFill>False</x:AutoFill><x:Row>").concat(row - 1, "</x:Row><x:Column>").concat(colIndex, "</x:Column></x:ClientData></v:shape>");
803
- })
804
- .join("");
805
- return "<xml xmlns:v=\"urn:schemas-microsoft-com:vml\" xmlns:o=\"urn:schemas-microsoft-com:office:office\" xmlns:x=\"urn:schemas-microsoft-com:office:excel\"><o:shapelayout v:ext=\"edit\"><o:idmap v:ext=\"edit\" data=\"1\"/></o:shapelayout><v:shapetype id=\"_x0000_t202\" coordsize=\"21600,21600\" o:spt=\"202\" path=\"m,l,21600r21600,l21600,xe\"><v:stroke joinstyle=\"miter\"/><v:path gradientshapeok=\"t\" o:connecttype=\"rect\"/></v:shapetype>".concat(shapes, "</xml>");
911
+ }).filter(Boolean);
806
912
  };
807
913
  return CommentsCollector;
808
914
  }());
915
+ /** VML `<v:shapetype>` for legacy notes (`#_x0000_t202`). */
916
+ var NOTE_VML_SHAPETYPE = "<v:shapetype id=\"_x0000_t202\" coordsize=\"21600,21600\" o:spt=\"202\" path=\"m,l,21600r21600,l21600,xe\"><v:stroke joinstyle=\"miter\"/><v:path gradientshapeok=\"t\" o:connecttype=\"rect\"/></v:shapetype>";
809
917
  var INVALID_XML_CHAR_REGEX = /[\u0000-\u0008\u000B\u000C\u000E-\u001F]/g;
810
918
  var sanitizeXmlText = function (value) {
811
919
  if (!value)
@@ -863,9 +971,9 @@ var getRowsForSheet = function (sheetData, sheetId) {
863
971
  return ((_d = (_b = (_a = sheetData[sheetId]) !== null && _a !== void 0 ? _a : sheetData[String(sheetId)]) !== null && _b !== void 0 ? _b : sheetData[Number(sheetId)]) !== null && _d !== void 0 ? _d : []);
864
972
  };
865
973
  var buildWorksheetXml = function (_a) {
866
- var e_19, _b, e_20, _d, e_21, _e, e_22, _f, e_23, _g, e_24, _h;
974
+ var e_25, _b, e_26, _d, e_27, _e, e_28, _f, e_29, _g, e_30, _h;
867
975
  var _j, _k;
868
- var sheet = _a.sheet, rows = _a.rows, sharedStrings = _a.sharedStrings, sourceSharedStrings = _a.sourceSharedStrings, cellXfs = _a.cellXfs, styleBuilder = _a.styleBuilder, tables = _a.tables, relationships = _a.relationships, drawingContext = _a.drawingContext, conditionalFormats = _a.conditionalFormats, dataValidationsById = _a.dataValidationsById, dataValidations = _a.dataValidations, ignoreFormulaPatterns = _a.ignoreFormulaPatterns, citations = _a.citations, comments = _a.comments, personRegistry = _a.personRegistry, slicerRelIds = _a.slicerRelIds, sheetData = _a.sheetData, sheets = _a.sheets, locale = _a.locale;
976
+ var sheet = _a.sheet, rows = _a.rows, sharedStrings = _a.sharedStrings, sourceSharedStrings = _a.sourceSharedStrings, cellXfs = _a.cellXfs, styleBuilder = _a.styleBuilder, tables = _a.tables, relationships = _a.relationships, drawingContext = _a.drawingContext, conditionalFormats = _a.conditionalFormats, dataValidationsById = _a.dataValidationsById, dataValidations = _a.dataValidations, ignoreFormulaPatterns = _a.ignoreFormulaPatterns, citations = _a.citations, comments = _a.comments, personRegistry = _a.personRegistry, slicerRelIds = _a.slicerRelIds, sheetData = _a.sheetData, sheets = _a.sheets, locale = _a.locale, protectedRanges = _a.protectedRanges, _l = _a.formControls, formControls = _l === void 0 ? [] : _l, _m = _a.ctrlProps, ctrlProps = _m === void 0 ? { parts: [] } : _m;
869
977
  var tableNameMap = buildTableNameMap(tables);
870
978
  var bounds = {
871
979
  minRow: Number.POSITIVE_INFINITY,
@@ -900,12 +1008,12 @@ var buildWorksheetXml = function (_a) {
900
1008
  }
901
1009
  }
902
1010
  }
903
- catch (e_19_1) { e_19 = { error: e_19_1 }; }
1011
+ catch (e_25_1) { e_25 = { error: e_25_1 }; }
904
1012
  finally {
905
1013
  try {
906
1014
  if (citations_1_1 && !citations_1_1.done && (_b = citations_1.return)) _b.call(citations_1);
907
1015
  }
908
- finally { if (e_19) throw e_19.error; }
1016
+ finally { if (e_25) throw e_25.error; }
909
1017
  }
910
1018
  }
911
1019
  if (dataValidations) {
@@ -915,8 +1023,8 @@ var buildWorksheetXml = function (_a) {
915
1023
  if (!rule.ranges)
916
1024
  continue;
917
1025
  try {
918
- for (var _l = (e_21 = void 0, __values(rule.ranges)), _m = _l.next(); !_m.done; _m = _l.next()) {
919
- var range = _m.value;
1026
+ for (var _o = (e_27 = void 0, __values(rule.ranges)), _p = _o.next(); !_p.done; _p = _o.next()) {
1027
+ var range = _p.value;
920
1028
  if (range.sheetId !== sheet.sheetId)
921
1029
  continue;
922
1030
  // Ranges from the DV import are already 1-indexed (addressToSelection
@@ -929,21 +1037,21 @@ var buildWorksheetXml = function (_a) {
929
1037
  }
930
1038
  }
931
1039
  }
932
- catch (e_21_1) { e_21 = { error: e_21_1 }; }
1040
+ catch (e_27_1) { e_27 = { error: e_27_1 }; }
933
1041
  finally {
934
1042
  try {
935
- if (_m && !_m.done && (_e = _l.return)) _e.call(_l);
1043
+ if (_p && !_p.done && (_e = _o.return)) _e.call(_o);
936
1044
  }
937
- finally { if (e_21) throw e_21.error; }
1045
+ finally { if (e_27) throw e_27.error; }
938
1046
  }
939
1047
  }
940
1048
  }
941
- catch (e_20_1) { e_20 = { error: e_20_1 }; }
1049
+ catch (e_26_1) { e_26 = { error: e_26_1 }; }
942
1050
  finally {
943
1051
  try {
944
1052
  if (dataValidations_1_1 && !dataValidations_1_1.done && (_d = dataValidations_1.return)) _d.call(dataValidations_1);
945
1053
  }
946
- finally { if (e_20) throw e_20.error; }
1054
+ finally { if (e_26) throw e_26.error; }
947
1055
  }
948
1056
  }
949
1057
  // Pre-scan for valid shared-formula leaders in this sheet. The cell-emit
@@ -963,7 +1071,7 @@ var buildWorksheetXml = function (_a) {
963
1071
  if (!Array.isArray(rowValues))
964
1072
  continue;
965
1073
  try {
966
- for (var rowValues_1 = (e_22 = void 0, __values(rowValues)), rowValues_1_1 = rowValues_1.next(); !rowValues_1_1.done; rowValues_1_1 = rowValues_1.next()) {
1074
+ for (var rowValues_1 = (e_28 = void 0, __values(rowValues)), rowValues_1_1 = rowValues_1.next(); !rowValues_1_1.done; rowValues_1_1 = rowValues_1.next()) {
967
1075
  var cell = rowValues_1_1.value;
968
1076
  var sf = cell === null || cell === void 0 ? void 0 : cell.sf;
969
1077
  if (sf && sf.ref && Number.isFinite(sf.si)) {
@@ -971,12 +1079,12 @@ var buildWorksheetXml = function (_a) {
971
1079
  }
972
1080
  }
973
1081
  }
974
- catch (e_22_1) { e_22 = { error: e_22_1 }; }
1082
+ catch (e_28_1) { e_28 = { error: e_28_1 }; }
975
1083
  finally {
976
1084
  try {
977
1085
  if (rowValues_1_1 && !rowValues_1_1.done && (_f = rowValues_1.return)) _f.call(rowValues_1);
978
1086
  }
979
- finally { if (e_22) throw e_22.error; }
1087
+ finally { if (e_28) throw e_28.error; }
980
1088
  }
981
1089
  }
982
1090
  for (var rowIndex = 1; rowIndex < maxRows; rowIndex++) {
@@ -1062,30 +1170,49 @@ var buildWorksheetXml = function (_a) {
1062
1170
  var threadedCommentsXml = threadedCommentsCollector.toXml();
1063
1171
  if (threadedCommentsXml) {
1064
1172
  try {
1065
- for (var _o = __values(threadedCommentsCollector.legacyEntries()), _p = _o.next(); !_p.done; _p = _o.next()) {
1066
- var entry = _p.value;
1173
+ for (var _q = __values(threadedCommentsCollector.legacyEntries()), _s = _q.next(); !_s.done; _s = _q.next()) {
1174
+ var entry = _s.value;
1067
1175
  commentsCollector.add(entry.address, entry.text, entry.author);
1068
1176
  }
1069
1177
  }
1070
- catch (e_23_1) { e_23 = { error: e_23_1 }; }
1178
+ catch (e_29_1) { e_29 = { error: e_29_1 }; }
1071
1179
  finally {
1072
1180
  try {
1073
- if (_p && !_p.done && (_g = _o.return)) _g.call(_o);
1181
+ if (_s && !_s.done && (_g = _q.return)) _g.call(_q);
1074
1182
  }
1075
- finally { if (e_23) throw e_23.error; }
1183
+ finally { if (e_29) throw e_29.error; }
1076
1184
  }
1077
1185
  relationships.add(THREADED_COMMENT_REL_TYPE, "../threadedComments/threadedComment".concat(sheet.sheetId, ".xml"));
1078
1186
  }
1079
1187
  // Generate comments XML (notes) and add relationships if there are comments
1080
1188
  var commentsXml = commentsCollector.toXml();
1081
- var legacyDrawingXml = "";
1082
1189
  if (commentsXml) {
1083
1190
  relationships.add(COMMENTS_REL_TYPE, "../comments".concat(sheet.sheetId, ".xml"));
1191
+ }
1192
+ // Notes and form controls share the sheet's one legacy VML part
1193
+ // (`<legacyDrawing>`); a control without its VML shape is dropped by Excel.
1194
+ var noteVmlShapes = commentsCollector.toVmlShapes();
1195
+ var formControlBuild = buildSheetFormControls({
1196
+ sheet: sheet,
1197
+ controls: formControls,
1198
+ relationships: relationships,
1199
+ ctrlProps: ctrlProps,
1200
+ zIndexStart: noteVmlShapes.length,
1201
+ reservedShapeIds: commentsCollector.vmlShapeIds(),
1202
+ });
1203
+ var vmlDrawingXml = buildVmlDrawingXml({
1204
+ shapeTypes: __spreadArray(__spreadArray([], __read((noteVmlShapes.length ? [NOTE_VML_SHAPETYPE] : [])), false), __read((formControlBuild.vmlShapes.length ? [FORM_CONTROL_VML_SHAPETYPE] : [])), false),
1205
+ shapes: __spreadArray(__spreadArray([], __read(noteVmlShapes), false), __read(formControlBuild.vmlShapes), false),
1206
+ });
1207
+ var legacyDrawingXml = "";
1208
+ if (vmlDrawingXml) {
1084
1209
  var legacyDrawingRelId = relationships.add("http://schemas.openxmlformats.org/officeDocument/2006/relationships/vmlDrawing", "../drawings/vmlDrawing".concat(sheet.sheetId, ".vml"));
1085
1210
  legacyDrawingXml = "<legacyDrawing r:id=\"".concat(legacyDrawingRelId, "\"/>");
1086
1211
  }
1212
+ var controlsXml = formControlBuild.controlsXml;
1087
1213
  var sheetDataXml = "<sheetData>".concat(rowXmlChunks.join(""), "</sheetData>");
1088
- var pageMargins = DEFAULT_PAGE_MARGINS;
1214
+ var protectionXml = buildSheetProtectionXml(sheet, protectedRanges);
1215
+ var printSettingsXml = buildPrintSettingsXml(sheet.printSettings);
1089
1216
  // Build row data map for sparkline detection
1090
1217
  var rowDataMap = {};
1091
1218
  for (var rowIndex = 1; rowIndex < maxRows; rowIndex++) {
@@ -1093,19 +1220,19 @@ var buildWorksheetXml = function (_a) {
1093
1220
  if (row === null || row === void 0 ? void 0 : row.values) {
1094
1221
  var rowValues = {};
1095
1222
  try {
1096
- for (var _q = (e_24 = void 0, __values(Object.entries(row.values))), _s = _q.next(); !_s.done; _s = _q.next()) {
1097
- var _t = __read(_s.value, 2), colIndex = _t[0], cell = _t[1];
1223
+ for (var _t = (e_30 = void 0, __values(Object.entries(row.values))), _u = _t.next(); !_u.done; _u = _t.next()) {
1224
+ var _v = __read(_u.value, 2), colIndex = _v[0], cell = _v[1];
1098
1225
  if (cell) {
1099
1226
  rowValues[parseInt(colIndex, 10)] = cell;
1100
1227
  }
1101
1228
  }
1102
1229
  }
1103
- catch (e_24_1) { e_24 = { error: e_24_1 }; }
1230
+ catch (e_30_1) { e_30 = { error: e_30_1 }; }
1104
1231
  finally {
1105
1232
  try {
1106
- if (_s && !_s.done && (_h = _q.return)) _h.call(_q);
1233
+ if (_u && !_u.done && (_h = _t.return)) _h.call(_t);
1107
1234
  }
1108
- finally { if (e_24) throw e_24.error; }
1235
+ finally { if (e_30) throw e_30.error; }
1109
1236
  }
1110
1237
  if (Object.keys(rowValues).length > 0) {
1111
1238
  rowDataMap[rowIndex] = rowValues;
@@ -1128,13 +1255,13 @@ var buildWorksheetXml = function (_a) {
1128
1255
  explicitDefaultColumnWidthPx > 0) {
1129
1256
  sheetFormatPrAttrs.push("defaultColWidth=\"".concat(columnPixelToChars(explicitDefaultColumnWidthPx).toFixed(2), "\""));
1130
1257
  }
1131
- var worksheetXml = "".concat(XML_DECLARATION, "<worksheet xmlns=\"").concat(WORKSHEET_NS, "\" xmlns:r=\"").concat(REL_NS, "\">").concat(sheetPrXml, "<dimension ref=\"").concat(dimension, "\"/>").concat(sheetViews, "<sheetFormatPr ").concat(sheetFormatPrAttrs.join(" "), "/>").concat(columnXml).concat(sheetDataXml).concat(basicFilterXml).concat(mergeXml).concat(conditionalFormattingXml).concat(dataValidationsXml).concat(hyperlinksXml).concat(pageMargins).concat(drawingXml).concat(legacyDrawingXml).concat(tablePartsXml).concat(extLstXml, "</worksheet>");
1258
+ var worksheetXml = "".concat(XML_DECLARATION, "<worksheet xmlns=\"").concat(WORKSHEET_NS, "\" xmlns:r=\"").concat(REL_NS, "\">").concat(sheetPrXml, "<dimension ref=\"").concat(dimension, "\"/>").concat(sheetViews, "<sheetFormatPr ").concat(sheetFormatPrAttrs.join(" "), "/>").concat(columnXml).concat(sheetDataXml).concat(protectionXml).concat(basicFilterXml).concat(mergeXml).concat(conditionalFormattingXml).concat(dataValidationsXml).concat(hyperlinksXml).concat(printSettingsXml).concat(drawingXml).concat(legacyDrawingXml).concat(controlsXml).concat(tablePartsXml).concat(extLstXml, "</worksheet>");
1132
1259
  return {
1133
1260
  xml: worksheetXml,
1134
1261
  relationshipsXml: relationships.toXml(),
1135
1262
  images: collectedImages,
1136
1263
  commentsXml: commentsXml,
1137
- vmlDrawingXml: commentsCollector.toVmlXml(),
1264
+ vmlDrawingXml: vmlDrawingXml,
1138
1265
  threadedCommentsXml: threadedCommentsXml,
1139
1266
  };
1140
1267
  };
@@ -1189,7 +1316,7 @@ var sanitizeIndex = function (value) {
1189
1316
  return Math.max(1, Math.floor(value));
1190
1317
  };
1191
1318
  var normalizeMergeRanges = function (ranges) {
1192
- var e_25, _a;
1319
+ var e_31, _a;
1193
1320
  if (!(ranges === null || ranges === void 0 ? void 0 : ranges.length))
1194
1321
  return [];
1195
1322
  var sanitized = ranges
@@ -1231,12 +1358,12 @@ var normalizeMergeRanges = function (ranges) {
1231
1358
  _loop_3(merge);
1232
1359
  }
1233
1360
  }
1234
- catch (e_25_1) { e_25 = { error: e_25_1 }; }
1361
+ catch (e_31_1) { e_31 = { error: e_31_1 }; }
1235
1362
  finally {
1236
1363
  try {
1237
1364
  if (sorted_1_1 && !sorted_1_1.done && (_a = sorted_1.return)) _a.call(sorted_1);
1238
1365
  }
1239
- finally { if (e_25) throw e_25.error; }
1366
+ finally { if (e_31) throw e_31.error; }
1240
1367
  }
1241
1368
  return valid;
1242
1369
  };
@@ -1603,7 +1730,7 @@ var buildWorksheetRow = function (_a) {
1603
1730
  };
1604
1731
  };
1605
1732
  var buildCellXml = function (_a) {
1606
- var e_26, _b;
1733
+ var e_32, _b;
1607
1734
  var _d, _e, _f, _g, _h, _j, _k, _l;
1608
1735
  var rowNumber = _a.rowNumber, columnIndex = _a.columnIndex, cell = _a.cell, sharedStrings = _a.sharedStrings, sourceSharedStrings = _a.sourceSharedStrings, cellXfs = _a.cellXfs, styleBuilder = _a.styleBuilder, onImage = _a.onImage, onHyperlink = _a.onHyperlink, dataValidationsById = _a.dataValidationsById, onDataValidation = _a.onDataValidation, tableNameMap = _a.tableNameMap, tables = _a.tables, ignoreFormulaPatterns = _a.ignoreFormulaPatterns, commentsCollector = _a.commentsCollector, onCommentThread = _a.onCommentThread, sheetId = _a.sheetId, sheetData = _a.sheetData, sheets = _a.sheets, locale = _a.locale, validSharedFormulaLeaders = _a.validSharedFormulaLeaders;
1609
1736
  var normalizedCell = cell;
@@ -1700,12 +1827,12 @@ var buildCellXml = function (_a) {
1700
1827
  sheetIdByName_1.set(s.title, s.sheetId);
1701
1828
  }
1702
1829
  }
1703
- catch (e_26_1) { e_26 = { error: e_26_1 }; }
1830
+ catch (e_32_1) { e_32 = { error: e_32_1 }; }
1704
1831
  finally {
1705
1832
  try {
1706
1833
  if (sheets_1_1 && !sheets_1_1.done && (_b = sheets_1.return)) _b.call(sheets_1);
1707
1834
  }
1708
- finally { if (e_26) throw e_26.error; }
1835
+ finally { if (e_32) throw e_32.error; }
1709
1836
  }
1710
1837
  // A real CellXfsRegistry so `SheetCell.assign` inside the derive
1711
1838
  // helper can resolve precedent cells whose `uf` is a `{ sid }` style
@@ -1942,7 +2069,7 @@ function isValidExcelDateSerial(value) {
1942
2069
  return value >= MIN_EXCEL_DATE_SERIAL && value <= MAX_EXCEL_DATE_SERIAL;
1943
2070
  }
1944
2071
  function rewriteTableNamesInFormula(formula, tableNameMap) {
1945
- var e_27, _a;
2072
+ var e_33, _a;
1946
2073
  if (!(tableNameMap === null || tableNameMap === void 0 ? void 0 : tableNameMap.size))
1947
2074
  return formula;
1948
2075
  var normalized = formula;
@@ -1957,12 +2084,12 @@ function rewriteTableNamesInFormula(formula, tableNameMap) {
1957
2084
  normalized = normalized.replace(new RegExp("".concat(escaped, "(?=\\[)"), "g"), exportedName);
1958
2085
  }
1959
2086
  }
1960
- catch (e_27_1) { e_27 = { error: e_27_1 }; }
2087
+ catch (e_33_1) { e_33 = { error: e_33_1 }; }
1961
2088
  finally {
1962
2089
  try {
1963
2090
  if (tableNameMap_1_1 && !tableNameMap_1_1.done && (_a = tableNameMap_1.return)) _a.call(tableNameMap_1);
1964
2091
  }
1965
- finally { if (e_27) throw e_27.error; }
2092
+ finally { if (e_33) throw e_33.error; }
1966
2093
  }
1967
2094
  return normalized;
1968
2095
  }
@@ -2060,7 +2187,9 @@ function rewriteStructuredReferenceFormula(formula, tableNameMap, tables, rowNum
2060
2187
  }
2061
2188
  function sanitizeFormulaText(formula) {
2062
2189
  var normalized = sanitizeXmlText(formula);
2063
- return qualifyFutureFunctions(normalized.replace(/\r\n|\r|\n/g, " "));
2190
+ // `@x` is persisted as `_xlfn.SINGLE(x)`; encoding first lets the
2191
+ // future-function pass add the prefix.
2192
+ return qualifyFutureFunctions(encodeImplicitIntersection(normalized.replace(/\r\n|\r|\n/g, " ")));
2064
2193
  }
2065
2194
  function escapeXmlBase(value) {
2066
2195
  return sanitizeXmlText(value)
@@ -2224,6 +2353,11 @@ var buildSheetViewsXml = function (sheet) {
2224
2353
  zoomScale !== 100) {
2225
2354
  attrs.push("zoomScale=\"".concat(zoomScale, "\""));
2226
2355
  }
2356
+ // `rightToLeft` — only an explicit true is written (Excel's default is
2357
+ // LTR and the attribute is omitted), mirroring the Rust exporter.
2358
+ if (sheet.rightToLeft) {
2359
+ attrs.push("rightToLeft=\"1\"");
2360
+ }
2227
2361
  var panes = [];
2228
2362
  var frozenRows = (_e = sheet.frozenRowCount) !== null && _e !== void 0 ? _e : 0;
2229
2363
  var frozenColumns = (_f = sheet.frozenColumnCount) !== null && _f !== void 0 ? _f : 0;
@@ -2355,7 +2489,7 @@ var buildRichRunProperties = function (format) {
2355
2489
  * style flag, but that's a cell-style concern, not a sharedString one.
2356
2490
  */
2357
2491
  var buildRichTextRuns = function (text, runs) {
2358
- var e_28, _a;
2492
+ var e_34, _a;
2359
2493
  var sorted = __spreadArray([], __read(runs), false).sort(function (a, b) { return a.startIndex - b.startIndex; });
2360
2494
  var out = [];
2361
2495
  var cursor = 0;
@@ -2388,12 +2522,12 @@ var buildRichTextRuns = function (text, runs) {
2388
2522
  cursor = end;
2389
2523
  }
2390
2524
  }
2391
- catch (e_28_1) { e_28 = { error: e_28_1 }; }
2525
+ catch (e_34_1) { e_34 = { error: e_34_1 }; }
2392
2526
  finally {
2393
2527
  try {
2394
2528
  if (sorted_2_1 && !sorted_2_1.done && (_a = sorted_2.return)) _a.call(sorted_2);
2395
2529
  }
2396
- finally { if (e_28) throw e_28.error; }
2530
+ finally { if (e_34) throw e_34.error; }
2397
2531
  }
2398
2532
  if (cursor < text.length) {
2399
2533
  emit(text.slice(cursor), "");
@@ -2414,7 +2548,7 @@ var buildSharedStringsXml = function (sharedStrings) {
2414
2548
  return "".concat(XML_DECLARATION, "<sst xmlns=\"").concat(WORKSHEET_NS, "\" count=\"").concat(sharedStrings.totalCount, "\" uniqueCount=\"").concat(sharedStrings.entries.length, "\">").concat(entries, "</sst>");
2415
2549
  };
2416
2550
  var buildTableNameMap = function (tables) {
2417
- var e_29, _a;
2551
+ var e_35, _a;
2418
2552
  var _b;
2419
2553
  var map = new Map();
2420
2554
  try {
@@ -2426,12 +2560,12 @@ var buildTableNameMap = function (tables) {
2426
2560
  map.set(tableTitle, table.name);
2427
2561
  }
2428
2562
  }
2429
- catch (e_29_1) { e_29 = { error: e_29_1 }; }
2563
+ catch (e_35_1) { e_35 = { error: e_35_1 }; }
2430
2564
  finally {
2431
2565
  try {
2432
2566
  if (tables_1_1 && !tables_1_1.done && (_a = tables_1.return)) _a.call(tables_1);
2433
2567
  }
2434
- finally { if (e_29) throw e_29.error; }
2568
+ finally { if (e_35) throw e_35.error; }
2435
2569
  }
2436
2570
  return map;
2437
2571
  };
@@ -2439,7 +2573,7 @@ var buildTableNameMap = function (tables) {
2439
2573
  // whose box intersects another table on the same sheet. Drop both before
2440
2574
  // emitting so the workbook opens without "We found a problem" recovery prompts.
2441
2575
  var filterExportableTables = function (tables) {
2442
- var e_30, _a;
2576
+ var e_36, _a;
2443
2577
  var _b;
2444
2578
  var isValidBox = function (range) {
2445
2579
  if (!range)
@@ -2482,12 +2616,12 @@ var filterExportableTables = function (tables) {
2482
2616
  _loop_4(table);
2483
2617
  }
2484
2618
  }
2485
- catch (e_30_1) { e_30 = { error: e_30_1 }; }
2619
+ catch (e_36_1) { e_36 = { error: e_36_1 }; }
2486
2620
  finally {
2487
2621
  try {
2488
2622
  if (tables_2_1 && !tables_2_1.done && (_a = tables_2.return)) _a.call(tables_2);
2489
2623
  }
2490
- finally { if (e_30) throw e_30.error; }
2624
+ finally { if (e_36) throw e_36.error; }
2491
2625
  }
2492
2626
  return result;
2493
2627
  };
@@ -2511,6 +2645,58 @@ var sanitizeTableName = function (name) {
2511
2645
  }
2512
2646
  return cleaned;
2513
2647
  };
2648
+ /**
2649
+ * `SUBTOTAL()` function numbers (the 101+ "ignore hidden rows" family Excel
2650
+ * writes into totals-row cells) → `totalsRowFunction`.
2651
+ */
2652
+ var SUBTOTAL_TOTALS_ROW_FUNCTIONS = {
2653
+ "101": "average",
2654
+ "102": "countNums",
2655
+ "103": "count",
2656
+ "104": "max",
2657
+ "105": "min",
2658
+ "107": "stdDev",
2659
+ "109": "sum",
2660
+ "110": "var",
2661
+ };
2662
+ /**
2663
+ * Totals-row metadata for one `<tableColumn>`. Explicit column metadata
2664
+ * (imported from Excel, or set by the host) wins — an explicit `none` means
2665
+ * "no totals function" and is not second-guessed from the cell (the Rust
2666
+ * exporter's `totals_for_column` agrees). Otherwise it is derived from the
2667
+ * totals-row cell so tables whose totals row was added in-app (a "Total"
2668
+ * label + `=SUBTOTAL(109,[Col])` per numeric column) open in Excel with the
2669
+ * matching function selected in the totals dropdown. A formula that is not
2670
+ * a plain `SUBTOTAL(n, ref)` is left to the cell.
2671
+ */
2672
+ var resolveTableColumnTotals = function (column, totalsCell) {
2673
+ var _a;
2674
+ if (column === null || column === void 0 ? void 0 : column.totalsRowLabel) {
2675
+ return { totalsRowLabel: column.totalsRowLabel };
2676
+ }
2677
+ if (column === null || column === void 0 ? void 0 : column.totalsRowFunction) {
2678
+ if (column.totalsRowFunction === "none") {
2679
+ return undefined;
2680
+ }
2681
+ if (column.totalsRowFunction === "custom" && !column.totalsRowFormula) {
2682
+ return undefined;
2683
+ }
2684
+ return {
2685
+ totalsRowFunction: column.totalsRowFunction,
2686
+ totalsRowFormula: (_a = column.totalsRowFormula) !== null && _a !== void 0 ? _a : undefined,
2687
+ };
2688
+ }
2689
+ if (!totalsCell)
2690
+ return undefined;
2691
+ var formula = getExtendedValueFormula(getCellUserEnteredValue(totalsCell));
2692
+ if (formula) {
2693
+ var match = /^=?\s*SUBTOTAL\(\s*(\d{3})\s*,[^,]*\)\s*$/i.exec(formula);
2694
+ var fn = match ? SUBTOTAL_TOTALS_ROW_FUNCTIONS[match[1]] : undefined;
2695
+ return fn ? { totalsRowFunction: fn } : undefined;
2696
+ }
2697
+ var label = getExtendedValueString(getCellUserEnteredValue(totalsCell));
2698
+ return label && label.trim() !== "" ? { totalsRowLabel: label } : undefined;
2699
+ };
2514
2700
  var buildTableXml = function (table, rows, sourceSharedStrings, styleBuilder) {
2515
2701
  var _a, _b, _d;
2516
2702
  var rangeRef = table.ref;
@@ -2558,9 +2744,10 @@ var buildTableXml = function (table, rows, sourceSharedStrings, styleBuilder) {
2558
2744
  // Fallback to table.columns name or generic name
2559
2745
  return (_f = (_e = (_d = table.columns) === null || _d === void 0 ? void 0 : _d[index]) === null || _e === void 0 ? void 0 : _e.name) !== null && _f !== void 0 ? _f : "Column".concat(index + 1);
2560
2746
  });
2747
+ var totalsRowIndex = table.range.endRowIndex;
2561
2748
  var tableColumns = "<tableColumns count=\"".concat(columnCount, "\">").concat(columnNames
2562
2749
  .map(function (name, idx) {
2563
- var _a, _b;
2750
+ var _a, _b, _d, _e, _f;
2564
2751
  var columnFormula = (_b = (_a = table.columns) === null || _a === void 0 ? void 0 : _a[idx]) === null || _b === void 0 ? void 0 : _b.formula;
2565
2752
  var normalizedFormula = columnFormula
2566
2753
  ? normalizeCalculatedColumnFormula(columnFormula, table)
@@ -2568,7 +2755,22 @@ var buildTableXml = function (table, rows, sourceSharedStrings, styleBuilder) {
2568
2755
  var formulaXml = normalizedFormula
2569
2756
  ? "<calculatedColumnFormula>".concat(escapeXmlText(stripFormula(normalizedFormula)), "</calculatedColumnFormula>")
2570
2757
  : "";
2571
- return "<tableColumn id=\"".concat(idx + 1, "\" name=\"").concat(escapeXmlAttr(name), "\">").concat(formulaXml, "</tableColumn>");
2758
+ // Explicit per-column totals metadata exports whether or not the totals
2759
+ // row is shown: Excel keeps it on a table whose totals row is toggled
2760
+ // off so re-enabling restores each column's choice. Deriving it from
2761
+ // the last row only applies when that row IS the totals row.
2762
+ var totals = resolveTableColumnTotals((_d = table.columns) === null || _d === void 0 ? void 0 : _d[idx], totalsRowCount > 0
2763
+ ? (_f = (_e = rows[totalsRowIndex]) === null || _e === void 0 ? void 0 : _e.values) === null || _f === void 0 ? void 0 : _f[table.range.startColumnIndex + idx]
2764
+ : undefined);
2765
+ var totalsAttrs = (totals === null || totals === void 0 ? void 0 : totals.totalsRowLabel)
2766
+ ? " totalsRowLabel=\"".concat(escapeXmlAttr(totals.totalsRowLabel), "\"")
2767
+ : (totals === null || totals === void 0 ? void 0 : totals.totalsRowFunction)
2768
+ ? " totalsRowFunction=\"".concat(totals.totalsRowFunction, "\"")
2769
+ : "";
2770
+ var totalsFormulaXml = (totals === null || totals === void 0 ? void 0 : totals.totalsRowFunction) === "custom" && totals.totalsRowFormula
2771
+ ? "<totalsRowFormula>".concat(escapeXmlText(stripFormula(normalizeCalculatedColumnFormula(totals.totalsRowFormula, table))), "</totalsRowFormula>")
2772
+ : "";
2773
+ return "<tableColumn id=\"".concat(idx + 1, "\" name=\"").concat(escapeXmlAttr(name), "\"").concat(totalsAttrs, ">").concat(formulaXml).concat(totalsFormulaXml, "</tableColumn>");
2572
2774
  })
2573
2775
  .join(""), "</tableColumns>");
2574
2776
  var isBuiltInStyle = table.theme && /^TableStyle(Light|Medium|Dark)\d+$/.test(table.theme);
@@ -2618,8 +2820,130 @@ var buildWorksheetAutoFilterXml = function (sheet, rows, styleBuilder) {
2618
2820
  }
2619
2821
  return "<autoFilter ref=\"".concat(ref, "\"/>");
2620
2822
  };
2823
+ /** `CT_SheetProtection` boolean attributes in Excel's attribute order. */
2824
+ var SHEET_PROTECTION_FLAG_ATTRS = [
2825
+ "sheet",
2826
+ "objects",
2827
+ "scenarios",
2828
+ "formatCells",
2829
+ "formatColumns",
2830
+ "formatRows",
2831
+ "insertColumns",
2832
+ "insertRows",
2833
+ "insertHyperlinks",
2834
+ "deleteColumns",
2835
+ "deleteRows",
2836
+ "selectLockedCells",
2837
+ "sort",
2838
+ "autoFilter",
2839
+ "pivotTables",
2840
+ "selectUnlockedCells",
2841
+ ];
2842
+ /**
2843
+ * `<sheetProtection …/>` from `Sheet.sheetProtection`: the password hash first
2844
+ * (legacy `password` or the agile quartet, verbatim), then only the action
2845
+ * flags the model carries (`true` → `"1"`, `false` → `"0"`, absent → omitted so
2846
+ * Excel's schema default applies). Mirrors `rnc-export`'s `sheet_protection_xml`.
2847
+ */
2848
+ var buildSheetProtectionElementXml = function (protection) {
2849
+ var e_37, _a;
2850
+ var attrs = [];
2851
+ if (protection.algorithmName) {
2852
+ attrs.push("algorithmName=\"".concat(escapeXmlAttr(protection.algorithmName), "\""));
2853
+ }
2854
+ if (protection.hashValue) {
2855
+ attrs.push("hashValue=\"".concat(escapeXmlAttr(protection.hashValue), "\""));
2856
+ }
2857
+ if (protection.saltValue) {
2858
+ attrs.push("saltValue=\"".concat(escapeXmlAttr(protection.saltValue), "\""));
2859
+ }
2860
+ if (protection.spinCount != null) {
2861
+ attrs.push("spinCount=\"".concat(protection.spinCount, "\""));
2862
+ }
2863
+ if (protection.password) {
2864
+ attrs.push("password=\"".concat(escapeXmlAttr(protection.password), "\""));
2865
+ }
2866
+ try {
2867
+ for (var SHEET_PROTECTION_FLAG_ATTRS_1 = __values(SHEET_PROTECTION_FLAG_ATTRS), SHEET_PROTECTION_FLAG_ATTRS_1_1 = SHEET_PROTECTION_FLAG_ATTRS_1.next(); !SHEET_PROTECTION_FLAG_ATTRS_1_1.done; SHEET_PROTECTION_FLAG_ATTRS_1_1 = SHEET_PROTECTION_FLAG_ATTRS_1.next()) {
2868
+ var flag = SHEET_PROTECTION_FLAG_ATTRS_1_1.value;
2869
+ var value = protection[flag];
2870
+ if (typeof value === "boolean") {
2871
+ attrs.push("".concat(flag, "=\"").concat(value ? 1 : 0, "\""));
2872
+ }
2873
+ }
2874
+ }
2875
+ catch (e_37_1) { e_37 = { error: e_37_1 }; }
2876
+ finally {
2877
+ try {
2878
+ if (SHEET_PROTECTION_FLAG_ATTRS_1_1 && !SHEET_PROTECTION_FLAG_ATTRS_1_1.done && (_a = SHEET_PROTECTION_FLAG_ATTRS_1.return)) _a.call(SHEET_PROTECTION_FLAG_ATTRS_1);
2879
+ }
2880
+ finally { if (e_37) throw e_37.error; }
2881
+ }
2882
+ return attrs.length ? "<sheetProtection ".concat(attrs.join(" "), "/>") : "";
2883
+ };
2884
+ /**
2885
+ * The sheet's protection block — `<sheetProtection>` followed by
2886
+ * `<protectedRanges>` — or `""` when the sheet is unprotected and has no
2887
+ * allow-edit ranges. Ranges missing a bound (a sheet-wide `protect-sheet`
2888
+ * entry only carries `sheetId`) have no `sqref` and are skipped; the `name`
2889
+ * is the range's id, synthesized as `Range{n}` when absent (schema requires it).
2890
+ */
2891
+ var buildSheetProtectionXml = function (sheet, protectedRanges) {
2892
+ var e_38, _a;
2893
+ var protectionXml = sheet.sheetProtection
2894
+ ? buildSheetProtectionElementXml(sheet.sheetProtection)
2895
+ : "";
2896
+ var rangeItems = [];
2897
+ try {
2898
+ for (var _b = __values(protectedRanges !== null && protectedRanges !== void 0 ? protectedRanges : []), _d = _b.next(); !_d.done; _d = _b.next()) {
2899
+ var protectedRange = _d.value;
2900
+ var range = protectedRange.range;
2901
+ if (range.sheetId !== sheet.sheetId)
2902
+ continue;
2903
+ if (range.startRowIndex == null ||
2904
+ range.endRowIndex == null ||
2905
+ range.startColumnIndex == null ||
2906
+ range.endColumnIndex == null) {
2907
+ continue;
2908
+ }
2909
+ // Excel writes a single cell as `D10`, a block as `A2:C5`.
2910
+ var isSingleCell = range.startRowIndex === range.endRowIndex &&
2911
+ range.startColumnIndex === range.endColumnIndex;
2912
+ var sqref = isSingleCell
2913
+ ? cellToAddress({
2914
+ rowIndex: range.startRowIndex,
2915
+ columnIndex: range.startColumnIndex,
2916
+ })
2917
+ : cellRangeToAddress(undefined, {
2918
+ startRowIndex: range.startRowIndex,
2919
+ endRowIndex: range.endRowIndex,
2920
+ startColumnIndex: range.startColumnIndex,
2921
+ endColumnIndex: range.endColumnIndex,
2922
+ });
2923
+ if (!sqref)
2924
+ continue;
2925
+ var id = protectedRange.protectedRangeId;
2926
+ var name_1 = id != null && String(id) !== "" ? String(id) : "Range".concat(rangeItems.length + 1);
2927
+ var securityDescriptor = protectedRange.securityDescriptor
2928
+ ? " securityDescriptor=\"".concat(escapeXmlAttr(protectedRange.securityDescriptor), "\"")
2929
+ : "";
2930
+ rangeItems.push("<protectedRange sqref=\"".concat(escapeXmlAttr(sqref), "\" name=\"").concat(escapeXmlAttr(name_1), "\"").concat(securityDescriptor, "/>"));
2931
+ }
2932
+ }
2933
+ catch (e_38_1) { e_38 = { error: e_38_1 }; }
2934
+ finally {
2935
+ try {
2936
+ if (_d && !_d.done && (_a = _b.return)) _a.call(_b);
2937
+ }
2938
+ finally { if (e_38) throw e_38.error; }
2939
+ }
2940
+ var rangesXml = rangeItems.length
2941
+ ? "<protectedRanges>".concat(rangeItems.join(""), "</protectedRanges>")
2942
+ : "";
2943
+ return "".concat(protectionXml).concat(rangesXml);
2944
+ };
2621
2945
  var buildSheetPropertiesXml = function (sheet) {
2622
- var _a;
2946
+ var _a, _b, _d;
2623
2947
  var tabColor = serializeColorXml((_a = sheet.tabColor) !== null && _a !== void 0 ? _a : undefined);
2624
2948
  // <outlinePr> mirrors the sheet's `outlinePr` setting; both attrs
2625
2949
  // default to true in Excel, so only emit when explicitly false. If
@@ -2635,11 +2959,110 @@ var buildSheetPropertiesXml = function (sheet) {
2635
2959
  var outlineXml = outlineAttrs.length
2636
2960
  ? "<outlinePr ".concat(outlineAttrs.join(" "), "/>")
2637
2961
  : "";
2638
- if (!tabColor && !outlineXml)
2962
+ // `<pageSetUpPr fitToPage="1">` is what makes Excel honour
2963
+ // `<pageSetup fitToWidth/fitToHeight>` instead of `scale`.
2964
+ var pageSetUpPrXml = ((_d = (_b = sheet.printSettings) === null || _b === void 0 ? void 0 : _b.pageSetup) === null || _d === void 0 ? void 0 : _d.fitToPage)
2965
+ ? "<pageSetUpPr fitToPage=\"1\"/>"
2966
+ : "";
2967
+ if (!tabColor && !outlineXml && !pageSetUpPrXml)
2639
2968
  return "";
2640
- var inner = "".concat(tabColor ? "<tabColor ".concat(tabColor, "/>") : "").concat(outlineXml);
2969
+ var inner = "".concat(tabColor ? "<tabColor ".concat(tabColor, "/>") : "").concat(outlineXml).concat(pageSetUpPrXml);
2641
2970
  return "<sheetPr>".concat(inner, "</sheetPr>");
2642
2971
  };
2972
+ var xmlBoolAttr = function (name, value) {
2973
+ return value == null ? "" : " ".concat(name, "=\"").concat(value ? "1" : "0", "\"");
2974
+ };
2975
+ var xmlNumAttr = function (name, value) {
2976
+ return typeof value === "number" && Number.isFinite(value)
2977
+ ? " ".concat(name, "=\"").concat(value, "\"")
2978
+ : "";
2979
+ };
2980
+ /**
2981
+ * The `CT_Worksheet` print tail — `<printOptions>`, `<pageMargins>`,
2982
+ * `<pageSetup>`, `<headerFooter>`, `<rowBreaks>`, `<colBreaks>` — in schema
2983
+ * order (after `<hyperlinks>`, before `<drawing>`). `<pageMargins>` is
2984
+ * mandatory in practice (Excel always writes it), so the default margins go
2985
+ * out when the sheet has none of its own.
2986
+ */
2987
+ var buildPrintSettingsXml = function (print) {
2988
+ var _a, _b, _d, _e, _f, _g;
2989
+ var parts = [];
2990
+ var options = print === null || print === void 0 ? void 0 : print.printOptions;
2991
+ var optionAttrs = xmlBoolAttr("horizontalCentered", options === null || options === void 0 ? void 0 : options.horizontalCentered) +
2992
+ xmlBoolAttr("verticalCentered", options === null || options === void 0 ? void 0 : options.verticalCentered) +
2993
+ xmlBoolAttr("headings", options === null || options === void 0 ? void 0 : options.headings) +
2994
+ xmlBoolAttr("gridLines", options === null || options === void 0 ? void 0 : options.gridLines);
2995
+ if (optionAttrs)
2996
+ parts.push("<printOptions".concat(optionAttrs, "/>"));
2997
+ var margins = print === null || print === void 0 ? void 0 : print.pageMargins;
2998
+ parts.push(margins &&
2999
+ Object.values(margins).some(function (v) { return typeof v === "number"; })
3000
+ ? "<pageMargins left=\"".concat((_a = margins.left) !== null && _a !== void 0 ? _a : 0.7, "\" right=\"").concat((_b = margins.right) !== null && _b !== void 0 ? _b : 0.7, "\" top=\"").concat((_d = margins.top) !== null && _d !== void 0 ? _d : 0.75, "\" bottom=\"").concat((_e = margins.bottom) !== null && _e !== void 0 ? _e : 0.75, "\" header=\"").concat((_f = margins.header) !== null && _f !== void 0 ? _f : 0.3, "\" footer=\"").concat((_g = margins.footer) !== null && _g !== void 0 ? _g : 0.3, "\"/>")
3001
+ : DEFAULT_PAGE_MARGINS);
3002
+ var setup = print === null || print === void 0 ? void 0 : print.pageSetup;
3003
+ if (setup) {
3004
+ // Excel keeps `firstPageNumber` as a dormant value until the user picks
3005
+ // a first page number (`useFirstPageNumber="1"`); a bare number means
3006
+ // "Auto", so the flag is written only when the model has it on.
3007
+ var useFirst = setup.useFirstPageNumber === true ? true : undefined;
3008
+ var setupAttrs = xmlNumAttr("paperSize", setup.paperSize) +
3009
+ xmlNumAttr("scale", setup.scale) +
3010
+ xmlNumAttr("firstPageNumber", setup.firstPageNumber) +
3011
+ xmlNumAttr("fitToWidth", setup.fitToWidth) +
3012
+ xmlNumAttr("fitToHeight", setup.fitToHeight) +
3013
+ (setup.pageOrder ? " pageOrder=\"".concat(setup.pageOrder, "\"") : "") +
3014
+ (setup.orientation ? " orientation=\"".concat(setup.orientation, "\"") : "") +
3015
+ xmlBoolAttr("blackAndWhite", setup.blackAndWhite) +
3016
+ xmlBoolAttr("draft", setup.draft) +
3017
+ xmlBoolAttr("useFirstPageNumber", useFirst);
3018
+ if (setupAttrs)
3019
+ parts.push("<pageSetup".concat(setupAttrs, "/>"));
3020
+ }
3021
+ var hf = print === null || print === void 0 ? void 0 : print.headerFooter;
3022
+ if (hf && !isHeaderFooterEmpty(hf)) {
3023
+ var hfAttrs = xmlBoolAttr("differentOddEven", hf.differentOddEven) +
3024
+ xmlBoolAttr("differentFirst", hf.differentFirst) +
3025
+ xmlBoolAttr("scaleWithDoc", hf.scaleWithDoc) +
3026
+ xmlBoolAttr("alignWithMargins", hf.alignWithMargins);
3027
+ var children = [
3028
+ "oddHeader",
3029
+ "oddFooter",
3030
+ "evenHeader",
3031
+ "evenFooter",
3032
+ "firstHeader",
3033
+ "firstFooter",
3034
+ ]
3035
+ .map(function (key) {
3036
+ var text = hf[key];
3037
+ return typeof text === "string" && text
3038
+ ? "<".concat(key, ">").concat(escapeXmlText(text), "</").concat(key, ">")
3039
+ : "";
3040
+ })
3041
+ .join("");
3042
+ parts.push(children
3043
+ ? "<headerFooter".concat(hfAttrs, ">").concat(children, "</headerFooter>")
3044
+ : "<headerFooter".concat(hfAttrs, "/>"));
3045
+ }
3046
+ var breaks = function (ids, max) {
3047
+ var valid = Array.from(new Set((ids !== null && ids !== void 0 ? ids : []).filter(function (id) { return Number.isInteger(id) && id > 0; }))).sort(function (a, b) { return a - b; });
3048
+ if (!valid.length)
3049
+ return "";
3050
+ return valid
3051
+ .map(function (id) { return "<brk id=\"".concat(id, "\" max=\"").concat(max, "\" man=\"1\"/>"); })
3052
+ .join("");
3053
+ };
3054
+ var rowBrks = breaks(print === null || print === void 0 ? void 0 : print.rowBreaks, 16383);
3055
+ if (rowBrks) {
3056
+ var count = rowBrks.split("<brk ").length - 1;
3057
+ parts.push("<rowBreaks count=\"".concat(count, "\" manualBreakCount=\"").concat(count, "\">").concat(rowBrks, "</rowBreaks>"));
3058
+ }
3059
+ var colBrks = breaks(print === null || print === void 0 ? void 0 : print.columnBreaks, 1048575);
3060
+ if (colBrks) {
3061
+ var count = colBrks.split("<brk ").length - 1;
3062
+ parts.push("<colBreaks count=\"".concat(count, "\" manualBreakCount=\"").concat(count, "\">").concat(colBrks, "</colBreaks>"));
3063
+ }
3064
+ return parts.join("");
3065
+ };
2643
3066
  var buildFilterColumnsXml = function (filterSpecs, range, rows, headerRow, totalRow, styleBuilder) {
2644
3067
  if (headerRow === void 0) { headerRow = true; }
2645
3068
  if (totalRow === void 0) { totalRow = false; }
@@ -2712,113 +3135,220 @@ var gridRangeToRef = function (range) {
2712
3135
  }
2713
3136
  };
2714
3137
  var groupEmbedsBySheet = function (embeds) {
2715
- var e_31, _a;
2716
- var _b, _d, _e, _f, _g, _h, _j;
2717
3138
  var result = new Map();
2718
- try {
2719
- for (var _k = __values(embeds !== null && embeds !== void 0 ? embeds : []), _l = _k.next(); !_l.done; _l = _k.next()) {
2720
- var embed = _l.value;
2721
- if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2722
- continue;
2723
- if (((_d = embed.spec) === null || _d === void 0 ? void 0 : _d.type) !== "image")
2724
- continue;
2725
- var overlay = embed.position.overlayPosition;
2726
- var placement = {
2727
- kind: "embed",
2728
- imageUrl: embed.spec.imageUrl,
2729
- rowIndex: overlay.anchorCell.rowIndex,
2730
- columnIndex: overlay.anchorCell.columnIndex,
2731
- offsetX: (_e = overlay.offsetXPixels) !== null && _e !== void 0 ? _e : 0,
2732
- offsetY: (_f = overlay.offsetYPixels) !== null && _f !== void 0 ? _f : 0,
2733
- width: (_g = overlay.widthPixels) !== null && _g !== void 0 ? _g : 120,
2734
- height: (_h = overlay.heightPixels) !== null && _h !== void 0 ? _h : 120,
2735
- };
2736
- var list = (_j = result.get(embed.position.sheetId)) !== null && _j !== void 0 ? _j : [];
2737
- list.push(placement);
2738
- result.set(embed.position.sheetId, list);
2739
- }
2740
- }
2741
- catch (e_31_1) { e_31 = { error: e_31_1 }; }
2742
- finally {
2743
- try {
2744
- if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
2745
- }
2746
- finally { if (e_31) throw e_31.error; }
2747
- }
3139
+ (embeds !== null && embeds !== void 0 ? embeds : []).forEach(function (embed, order) {
3140
+ var _a, _b, _d, _e, _f, _g, _h, _j, _k, _l, _m;
3141
+ if (!((_a = embed.position) === null || _a === void 0 ? void 0 : _a.overlayPosition))
3142
+ return;
3143
+ if (((_b = embed.spec) === null || _b === void 0 ? void 0 : _b.type) !== "image")
3144
+ return;
3145
+ var overlay = embed.position.overlayPosition;
3146
+ var imageSpec = embed.spec;
3147
+ var adjustments = {
3148
+ crop: (_d = imageSpec.crop) !== null && _d !== void 0 ? _d : undefined,
3149
+ brightness: (_e = imageSpec.brightness) !== null && _e !== void 0 ? _e : undefined,
3150
+ contrast: (_f = imageSpec.contrast) !== null && _f !== void 0 ? _f : undefined,
3151
+ transparency: (_g = imageSpec.transparency) !== null && _g !== void 0 ? _g : undefined,
3152
+ };
3153
+ var placement = {
3154
+ kind: "embed",
3155
+ imageUrl: imageSpec.imageUrl,
3156
+ adjustments: Object.values(adjustments).some(function (v) { return v !== undefined; })
3157
+ ? adjustments
3158
+ : undefined,
3159
+ order: order,
3160
+ rowIndex: overlay.anchorCell.rowIndex,
3161
+ columnIndex: overlay.anchorCell.columnIndex,
3162
+ offsetX: (_h = overlay.offsetXPixels) !== null && _h !== void 0 ? _h : 0,
3163
+ offsetY: (_j = overlay.offsetYPixels) !== null && _j !== void 0 ? _j : 0,
3164
+ width: (_k = overlay.widthPixels) !== null && _k !== void 0 ? _k : 120,
3165
+ height: (_l = overlay.heightPixels) !== null && _l !== void 0 ? _l : 120,
3166
+ };
3167
+ var list = (_m = result.get(embed.position.sheetId)) !== null && _m !== void 0 ? _m : [];
3168
+ list.push(placement);
3169
+ result.set(embed.position.sheetId, list);
3170
+ });
2748
3171
  return result;
2749
3172
  };
2750
3173
  var groupTextBoxesBySheet = function (embeds) {
2751
- var e_32, _a;
2752
- var _b, _d, _e, _f, _g, _h, _j;
2753
3174
  var result = new Map();
2754
- try {
2755
- for (var _k = __values(embeds !== null && embeds !== void 0 ? embeds : []), _l = _k.next(); !_l.done; _l = _k.next()) {
2756
- var embed = _l.value;
2757
- if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2758
- continue;
2759
- if (((_d = embed.spec) === null || _d === void 0 ? void 0 : _d.type) !== "textbox")
2760
- continue;
2761
- var overlay = embed.position.overlayPosition;
2762
- var placement = {
2763
- textBox: embed,
2764
- rowIndex: overlay.anchorCell.rowIndex,
2765
- columnIndex: overlay.anchorCell.columnIndex,
2766
- offsetX: (_e = overlay.offsetXPixels) !== null && _e !== void 0 ? _e : 0,
2767
- offsetY: (_f = overlay.offsetYPixels) !== null && _f !== void 0 ? _f : 0,
2768
- width: (_g = overlay.widthPixels) !== null && _g !== void 0 ? _g : 120,
2769
- height: (_h = overlay.heightPixels) !== null && _h !== void 0 ? _h : 60,
2770
- };
2771
- var list = (_j = result.get(embed.position.sheetId)) !== null && _j !== void 0 ? _j : [];
2772
- list.push(placement);
2773
- result.set(embed.position.sheetId, list);
2774
- }
2775
- }
2776
- catch (e_32_1) { e_32 = { error: e_32_1 }; }
2777
- finally {
2778
- try {
2779
- if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
2780
- }
2781
- finally { if (e_32) throw e_32.error; }
2782
- }
3175
+ (embeds !== null && embeds !== void 0 ? embeds : []).forEach(function (embed, order) {
3176
+ var _a, _b, _d, _e, _f, _g, _h;
3177
+ if (!((_a = embed.position) === null || _a === void 0 ? void 0 : _a.overlayPosition))
3178
+ return;
3179
+ if (((_b = embed.spec) === null || _b === void 0 ? void 0 : _b.type) !== "textbox")
3180
+ return;
3181
+ var overlay = embed.position.overlayPosition;
3182
+ var placement = {
3183
+ textBox: embed,
3184
+ order: order,
3185
+ rowIndex: overlay.anchorCell.rowIndex,
3186
+ columnIndex: overlay.anchorCell.columnIndex,
3187
+ offsetX: (_d = overlay.offsetXPixels) !== null && _d !== void 0 ? _d : 0,
3188
+ offsetY: (_e = overlay.offsetYPixels) !== null && _e !== void 0 ? _e : 0,
3189
+ width: (_f = overlay.widthPixels) !== null && _f !== void 0 ? _f : 120,
3190
+ height: (_g = overlay.heightPixels) !== null && _g !== void 0 ? _g : 60,
3191
+ };
3192
+ var list = (_h = result.get(embed.position.sheetId)) !== null && _h !== void 0 ? _h : [];
3193
+ list.push(placement);
3194
+ result.set(embed.position.sheetId, list);
3195
+ });
2783
3196
  return result;
2784
3197
  };
2785
- var groupShapesBySheet = function (embeds) {
2786
- var e_33, _a;
2787
- var _b, _d, _e, _f, _g, _h, _j;
3198
+ /** Form-control embeds (`spec.type === "formControl"`) by sheet, in host order. */
3199
+ var groupFormControlsBySheet = function (embeds) {
2788
3200
  var result = new Map();
2789
- try {
2790
- for (var _k = __values(embeds !== null && embeds !== void 0 ? embeds : []), _l = _k.next(); !_l.done; _l = _k.next()) {
2791
- var embed = _l.value;
2792
- if (!((_b = embed.position) === null || _b === void 0 ? void 0 : _b.overlayPosition))
2793
- continue;
2794
- if (((_d = embed.spec) === null || _d === void 0 ? void 0 : _d.type) !== "shape")
2795
- continue;
2796
- var overlay = embed.position.overlayPosition;
2797
- var placement = {
2798
- shape: embed,
2799
- rowIndex: overlay.anchorCell.rowIndex,
2800
- columnIndex: overlay.anchorCell.columnIndex,
2801
- offsetX: (_e = overlay.offsetXPixels) !== null && _e !== void 0 ? _e : 0,
2802
- offsetY: (_f = overlay.offsetYPixels) !== null && _f !== void 0 ? _f : 0,
2803
- width: (_g = overlay.widthPixels) !== null && _g !== void 0 ? _g : 120,
2804
- height: (_h = overlay.heightPixels) !== null && _h !== void 0 ? _h : 60,
2805
- };
2806
- var list = (_j = result.get(embed.position.sheetId)) !== null && _j !== void 0 ? _j : [];
2807
- list.push(placement);
2808
- result.set(embed.position.sheetId, list);
2809
- }
2810
- }
2811
- catch (e_33_1) { e_33 = { error: e_33_1 }; }
2812
- finally {
2813
- try {
2814
- if (_l && !_l.done && (_a = _k.return)) _a.call(_k);
3201
+ (embeds !== null && embeds !== void 0 ? embeds : []).forEach(function (embed, order) {
3202
+ var _a, _b, _d, _e, _f, _g, _h;
3203
+ if (!((_a = embed.position) === null || _a === void 0 ? void 0 : _a.overlayPosition))
3204
+ return;
3205
+ if (((_b = embed.spec) === null || _b === void 0 ? void 0 : _b.type) !== "formControl")
3206
+ return;
3207
+ var overlay = embed.position.overlayPosition;
3208
+ var placement = {
3209
+ shape: embed,
3210
+ order: order,
3211
+ rowIndex: overlay.anchorCell.rowIndex,
3212
+ columnIndex: overlay.anchorCell.columnIndex,
3213
+ offsetX: (_d = overlay.offsetXPixels) !== null && _d !== void 0 ? _d : 0,
3214
+ offsetY: (_e = overlay.offsetYPixels) !== null && _e !== void 0 ? _e : 0,
3215
+ width: (_f = overlay.widthPixels) !== null && _f !== void 0 ? _f : 120,
3216
+ height: (_g = overlay.heightPixels) !== null && _g !== void 0 ? _g : 20,
3217
+ };
3218
+ var list = (_h = result.get(embed.position.sheetId)) !== null && _h !== void 0 ? _h : [];
3219
+ list.push(placement);
3220
+ result.set(embed.position.sheetId, list);
3221
+ });
3222
+ return result;
3223
+ };
3224
+ /**
3225
+ * Write a sheet's form controls: one ctrlProp part + sheet relationship per
3226
+ * control, the `<controls>` worksheet element, and the VML shapes Excel
3227
+ * draws them with (merged into the sheet's `vmlDrawing` alongside notes).
3228
+ */
3229
+ var buildSheetFormControls = function (_a) {
3230
+ var sheet = _a.sheet, controls = _a.controls, relationships = _a.relationships, ctrlProps = _a.ctrlProps, zIndexStart = _a.zIndexStart, reservedShapeIds = _a.reservedShapeIds;
3231
+ if (!controls.length)
3232
+ return { controlsXml: "", vmlShapes: [] };
3233
+ var controlElements = [];
3234
+ var vmlShapes = [];
3235
+ // Excel numbers notes and form-control shapes from one per-sheet counter
3236
+ // (1025 upward); a control that arrived with its own id keeps it unless it
3237
+ // collides with a note shape or another control.
3238
+ var usedShapeIds = new Set(reservedShapeIds);
3239
+ var nextShapeId = 1025;
3240
+ var allocateShapeId = function (wanted) {
3241
+ if (wanted && Number.isInteger(wanted) && !usedShapeIds.has(wanted)) {
3242
+ usedShapeIds.add(wanted);
3243
+ return wanted;
2815
3244
  }
2816
- finally { if (e_33) throw e_33.error; }
2817
- }
3245
+ while (usedShapeIds.has(nextShapeId))
3246
+ nextShapeId += 1;
3247
+ usedShapeIds.add(nextShapeId);
3248
+ return nextShapeId++;
3249
+ };
3250
+ var sumSizes = function (count, getSize) {
3251
+ var total = 0;
3252
+ for (var index = 0; index < count; index++)
3253
+ total += getSize(index);
3254
+ return total;
3255
+ };
3256
+ controls.forEach(function (placement, position) {
3257
+ var _a, _b, _d, _e;
3258
+ var spec = placement.shape.spec;
3259
+ var fromRow = Math.max(0, placement.rowIndex - 1);
3260
+ var fromColumn = Math.max(0, placement.columnIndex - 1);
3261
+ var offsetX = Math.max(0, (_a = placement.offsetX) !== null && _a !== void 0 ? _a : 0);
3262
+ var offsetY = Math.max(0, (_b = placement.offsetY) !== null && _b !== void 0 ? _b : 0);
3263
+ var widthPx = Math.max(5, (_d = placement.width) !== null && _d !== void 0 ? _d : 120);
3264
+ var heightPx = Math.max(5, (_e = placement.height) !== null && _e !== void 0 ? _e : 20);
3265
+ var columnSize = function (index) { return getColumnWidthPx(sheet, index, true); };
3266
+ var rowSize = function (index) { return getRowHeightPx(sheet, index, true); };
3267
+ var toColumn = resolveAnchorEndpoint({
3268
+ startIndex: fromColumn,
3269
+ startOffset: offsetX,
3270
+ span: widthPx,
3271
+ getSize: columnSize,
3272
+ });
3273
+ var toRow = resolveAnchorEndpoint({
3274
+ startIndex: fromRow,
3275
+ startOffset: offsetY,
3276
+ span: heightPx,
3277
+ getSize: rowSize,
3278
+ });
3279
+ var partIndex = ctrlProps.parts.length + 1;
3280
+ var path = "xl/ctrlProps/ctrlProp".concat(partIndex, ".xml");
3281
+ ctrlProps.parts.push({ path: path, xml: buildCtrlPropXml(spec) });
3282
+ var relId = relationships.add(CTRL_PROP_REL_TYPE, "../ctrlProps/ctrlProp".concat(partIndex, ".xml"));
3283
+ var shapeId = allocateShapeId(spec.shapeId);
3284
+ controlElements.push(buildControlElementXml({
3285
+ spec: spec,
3286
+ relId: relId,
3287
+ shapeId: shapeId,
3288
+ from: {
3289
+ col: fromColumn,
3290
+ colOff: offsetX * EMUS_PER_PIXEL,
3291
+ row: fromRow,
3292
+ rowOff: offsetY * EMUS_PER_PIXEL,
3293
+ },
3294
+ to: {
3295
+ col: toColumn.index,
3296
+ colOff: toColumn.offset * EMUS_PER_PIXEL,
3297
+ row: toRow.index,
3298
+ rowOff: toRow.offset * EMUS_PER_PIXEL,
3299
+ },
3300
+ }));
3301
+ vmlShapes.push(buildFormControlVmlShape({
3302
+ spec: spec,
3303
+ shapeId: shapeId,
3304
+ zIndex: zIndexStart + position + 1,
3305
+ geometry: {
3306
+ leftPx: sumSizes(fromColumn, columnSize) + offsetX,
3307
+ topPx: sumSizes(fromRow, rowSize) + offsetY,
3308
+ widthPx: widthPx,
3309
+ heightPx: heightPx,
3310
+ anchor: [
3311
+ fromColumn,
3312
+ Math.round(offsetX),
3313
+ fromRow,
3314
+ Math.round(offsetY),
3315
+ toColumn.index,
3316
+ Math.round(toColumn.offset),
3317
+ toRow.index,
3318
+ Math.round(toRow.offset),
3319
+ ],
3320
+ },
3321
+ }));
3322
+ });
3323
+ return { controlsXml: buildControlsXml(controlElements), vmlShapes: vmlShapes };
3324
+ };
3325
+ var groupShapesBySheet = function (embeds) {
3326
+ var result = new Map();
3327
+ (embeds !== null && embeds !== void 0 ? embeds : []).forEach(function (embed, order) {
3328
+ var _a, _b, _d, _e, _f, _g, _h;
3329
+ if (!((_a = embed.position) === null || _a === void 0 ? void 0 : _a.overlayPosition))
3330
+ return;
3331
+ if (((_b = embed.spec) === null || _b === void 0 ? void 0 : _b.type) !== "shape")
3332
+ return;
3333
+ var overlay = embed.position.overlayPosition;
3334
+ var placement = {
3335
+ shape: embed,
3336
+ order: order,
3337
+ rowIndex: overlay.anchorCell.rowIndex,
3338
+ columnIndex: overlay.anchorCell.columnIndex,
3339
+ offsetX: (_d = overlay.offsetXPixels) !== null && _d !== void 0 ? _d : 0,
3340
+ offsetY: (_e = overlay.offsetYPixels) !== null && _e !== void 0 ? _e : 0,
3341
+ width: (_f = overlay.widthPixels) !== null && _f !== void 0 ? _f : 120,
3342
+ height: (_g = overlay.heightPixels) !== null && _g !== void 0 ? _g : 60,
3343
+ };
3344
+ var list = (_h = result.get(embed.position.sheetId)) !== null && _h !== void 0 ? _h : [];
3345
+ list.push(placement);
3346
+ result.set(embed.position.sheetId, list);
3347
+ });
2818
3348
  return result;
2819
3349
  };
2820
3350
  var groupChartsBySheet = function (charts) {
2821
- var e_34, _a;
3351
+ var e_39, _a;
2822
3352
  var _b, _d, _e, _f, _g, _h;
2823
3353
  var result = new Map();
2824
3354
  try {
@@ -2841,17 +3371,17 @@ var groupChartsBySheet = function (charts) {
2841
3371
  result.set(chart.position.sheetId, list);
2842
3372
  }
2843
3373
  }
2844
- catch (e_34_1) { e_34 = { error: e_34_1 }; }
3374
+ catch (e_39_1) { e_39 = { error: e_39_1 }; }
2845
3375
  finally {
2846
3376
  try {
2847
3377
  if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
2848
3378
  }
2849
- finally { if (e_34) throw e_34.error; }
3379
+ finally { if (e_39) throw e_39.error; }
2850
3380
  }
2851
3381
  return result;
2852
3382
  };
2853
3383
  var groupSlicersBySheet = function (slicers) {
2854
- var e_35, _a;
3384
+ var e_40, _a;
2855
3385
  var _b, _d, _e, _f, _g, _h;
2856
3386
  var result = new Map();
2857
3387
  try {
@@ -2874,17 +3404,17 @@ var groupSlicersBySheet = function (slicers) {
2874
3404
  result.set(slicer.position.sheetId, list);
2875
3405
  }
2876
3406
  }
2877
- catch (e_35_1) { e_35 = { error: e_35_1 }; }
3407
+ catch (e_40_1) { e_40 = { error: e_40_1 }; }
2878
3408
  finally {
2879
3409
  try {
2880
3410
  if (_k && !_k.done && (_a = _j.return)) _a.call(_j);
2881
3411
  }
2882
- finally { if (e_35) throw e_35.error; }
3412
+ finally { if (e_40) throw e_40.error; }
2883
3413
  }
2884
3414
  return result;
2885
3415
  };
2886
3416
  var buildConditionalFormattingXml = function (_a) {
2887
- var e_36, _b;
3417
+ var e_41, _b;
2888
3418
  var _d, _e, _f;
2889
3419
  var conditionalFormats = _a.conditionalFormats, sheetId = _a.sheetId, styleBuilder = _a.styleBuilder;
2890
3420
  if (!(conditionalFormats === null || conditionalFormats === void 0 ? void 0 : conditionalFormats.length)) {
@@ -2948,12 +3478,12 @@ var buildConditionalFormattingXml = function (_a) {
2948
3478
  parts.push("<conditionalFormatting sqref=\"".concat(sqrefParts.join(" "), "\">").concat(ruleXmlEntries.join(""), "</conditionalFormatting>"));
2949
3479
  }
2950
3480
  }
2951
- catch (e_36_1) { e_36 = { error: e_36_1 }; }
3481
+ catch (e_41_1) { e_41 = { error: e_41_1 }; }
2952
3482
  finally {
2953
3483
  try {
2954
3484
  if (orderedRules_1_1 && !orderedRules_1_1.done && (_b = orderedRules_1.return)) _b.call(orderedRules_1);
2955
3485
  }
2956
- finally { if (e_36) throw e_36.error; }
3486
+ finally { if (e_41) throw e_41.error; }
2957
3487
  }
2958
3488
  return parts.join("");
2959
3489
  };
@@ -3449,11 +3979,11 @@ var buildConditionalFormattingRuleXml = function (_a) {
3449
3979
  return rules.length ? rules : undefined;
3450
3980
  };
3451
3981
  var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, function (_b) {
3452
- var anchors, relationships, media, imageIndex, chartIndex, pictureId, frameId, chartEntries, charts_1, charts_1_1, placement, chartXml, relId, slicers_1, slicers_1_1, placement, textBoxes_1, textBoxes_1_1, placement, shapes_1, shapes_1_1, placement, placements_1, placements_1_1, placement, dataUrl, buffer, mediaPath, relId, e_37_1, drawingXml;
3453
- var e_38, _d, e_39, _e, e_40, _f, e_41, _g, e_37, _h;
3454
- var placements = _b.placements, textBoxes = _b.textBoxes, _j = _b.shapes, shapes = _j === void 0 ? [] : _j, startImageIndex = _b.startImageIndex, startChartIndex = _b.startChartIndex, charts = _b.charts, slicers = _b.slicers, sheet = _b.sheet, sheetNameById = _b.sheetNameById;
3455
- return __generator(this, function (_k) {
3456
- switch (_k.label) {
3982
+ var anchors, relationships, media, imageIndex, chartIndex, chartExIndex, pictureId, frameId, chartEntries, chartExEntries, charts_1, charts_1_1, placement, chartExXml, relId_1, chartXml, relId, slicers_1, slicers_1_1, placement, embedAnchors, orderOf, textBoxes_1, textBoxes_1_1, placement, shapes_1, shapes_1_1, placement, placements_1, placements_1_1, placement, dataUrl, buffer, mediaPath, relId, e_42_1, embedAnchors_1, embedAnchors_1_1, entry, drawingXml;
3983
+ var e_43, _d, e_44, _e, e_45, _f, e_46, _g, e_42, _h, e_47, _j;
3984
+ var placements = _b.placements, textBoxes = _b.textBoxes, _k = _b.shapes, shapes = _k === void 0 ? [] : _k, startImageIndex = _b.startImageIndex, startChartIndex = _b.startChartIndex, _l = _b.startChartExIndex, startChartExIndex = _l === void 0 ? 1 : _l, charts = _b.charts, slicers = _b.slicers, sheet = _b.sheet, sheetNameById = _b.sheetNameById;
3985
+ return __generator(this, function (_m) {
3986
+ switch (_m.label) {
3457
3987
  case 0:
3458
3988
  if (!placements.length &&
3459
3989
  !textBoxes.length &&
@@ -3466,12 +3996,28 @@ var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, f
3466
3996
  media = [];
3467
3997
  imageIndex = startImageIndex;
3468
3998
  chartIndex = startChartIndex;
3999
+ chartExIndex = startChartExIndex;
3469
4000
  pictureId = 1;
3470
4001
  frameId = 1;
3471
4002
  chartEntries = [];
4003
+ chartExEntries = [];
3472
4004
  try {
3473
4005
  for (charts_1 = __values(charts), charts_1_1 = charts_1.next(); !charts_1_1.done; charts_1_1 = charts_1.next()) {
3474
4006
  placement = charts_1_1.value;
4007
+ if (isChartExType(placement.chart.spec.chartType)) {
4008
+ chartExXml = buildChartExXml(placement.chart, sheetNameById);
4009
+ if (!chartExXml)
4010
+ continue;
4011
+ relId_1 = relationships.add(CHART_EX_REL_TYPE, "../charts/chartEx".concat(chartExIndex, ".xml"));
4012
+ anchors.push(createChartAnchor({ sheet: sheet, placement: placement, relId: relId_1, frameId: frameId, chartEx: true }));
4013
+ chartExEntries.push({
4014
+ path: "xl/charts/chartEx".concat(chartExIndex, ".xml"),
4015
+ xml: chartExXml,
4016
+ });
4017
+ chartExIndex += 1;
4018
+ frameId += 1;
4019
+ continue;
4020
+ }
3475
4021
  chartXml = buildChartXml(placement.chart, sheetNameById);
3476
4022
  if (!chartXml)
3477
4023
  continue;
@@ -3490,12 +4036,12 @@ var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, f
3490
4036
  frameId += 1;
3491
4037
  }
3492
4038
  }
3493
- catch (e_38_1) { e_38 = { error: e_38_1 }; }
4039
+ catch (e_43_1) { e_43 = { error: e_43_1 }; }
3494
4040
  finally {
3495
4041
  try {
3496
4042
  if (charts_1_1 && !charts_1_1.done && (_d = charts_1.return)) _d.call(charts_1);
3497
4043
  }
3498
- finally { if (e_38) throw e_38.error; }
4044
+ finally { if (e_43) throw e_43.error; }
3499
4045
  }
3500
4046
  try {
3501
4047
  for (slicers_1 = __values(slicers), slicers_1_1 = slicers_1.next(); !slicers_1_1.done; slicers_1_1 = slicers_1.next()) {
@@ -3508,60 +4054,70 @@ var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, f
3508
4054
  frameId += 1;
3509
4055
  }
3510
4056
  }
3511
- catch (e_39_1) { e_39 = { error: e_39_1 }; }
4057
+ catch (e_44_1) { e_44 = { error: e_44_1 }; }
3512
4058
  finally {
3513
4059
  try {
3514
4060
  if (slicers_1_1 && !slicers_1_1.done && (_e = slicers_1.return)) _e.call(slicers_1);
3515
4061
  }
3516
- finally { if (e_39) throw e_39.error; }
4062
+ finally { if (e_44) throw e_44.error; }
3517
4063
  }
4064
+ embedAnchors = [];
4065
+ orderOf = function (order) {
4066
+ return order !== null && order !== void 0 ? order : Number.MAX_SAFE_INTEGER;
4067
+ };
3518
4068
  try {
3519
4069
  for (textBoxes_1 = __values(textBoxes), textBoxes_1_1 = textBoxes_1.next(); !textBoxes_1_1.done; textBoxes_1_1 = textBoxes_1.next()) {
3520
4070
  placement = textBoxes_1_1.value;
3521
- anchors.push(createTextBoxAnchor({
3522
- sheet: sheet,
3523
- placement: placement,
3524
- frameId: frameId,
3525
- }));
4071
+ embedAnchors.push({
4072
+ order: orderOf(placement.order),
4073
+ xml: createTextBoxAnchor({
4074
+ sheet: sheet,
4075
+ placement: placement,
4076
+ frameId: frameId,
4077
+ }),
4078
+ });
3526
4079
  frameId += 1;
3527
4080
  }
3528
4081
  }
3529
- catch (e_40_1) { e_40 = { error: e_40_1 }; }
4082
+ catch (e_45_1) { e_45 = { error: e_45_1 }; }
3530
4083
  finally {
3531
4084
  try {
3532
4085
  if (textBoxes_1_1 && !textBoxes_1_1.done && (_f = textBoxes_1.return)) _f.call(textBoxes_1);
3533
4086
  }
3534
- finally { if (e_40) throw e_40.error; }
4087
+ finally { if (e_45) throw e_45.error; }
3535
4088
  }
3536
4089
  try {
3537
4090
  for (shapes_1 = __values(shapes), shapes_1_1 = shapes_1.next(); !shapes_1_1.done; shapes_1_1 = shapes_1.next()) {
3538
4091
  placement = shapes_1_1.value;
3539
- anchors.push(createShapeAnchor({
3540
- sheet: sheet,
3541
- placement: placement,
3542
- frameId: frameId,
3543
- }));
4092
+ embedAnchors.push({
4093
+ order: orderOf(placement.order),
4094
+ xml: createShapeAnchor({
4095
+ sheet: sheet,
4096
+ placement: placement,
4097
+ frameId: frameId,
4098
+ }),
4099
+ });
3544
4100
  frameId += 1;
3545
4101
  }
3546
4102
  }
3547
- catch (e_41_1) { e_41 = { error: e_41_1 }; }
4103
+ catch (e_46_1) { e_46 = { error: e_46_1 }; }
3548
4104
  finally {
3549
4105
  try {
3550
4106
  if (shapes_1_1 && !shapes_1_1.done && (_g = shapes_1.return)) _g.call(shapes_1);
3551
4107
  }
3552
- finally { if (e_41) throw e_41.error; }
4108
+ finally { if (e_46) throw e_46.error; }
3553
4109
  }
3554
- _k.label = 1;
4110
+ _m.label = 1;
3555
4111
  case 1:
3556
- _k.trys.push([1, 6, 7, 8]);
4112
+ _m.trys.push([1, 6, 7, 8]);
3557
4113
  placements_1 = __values(placements), placements_1_1 = placements_1.next();
3558
- _k.label = 2;
4114
+ _m.label = 2;
3559
4115
  case 2:
3560
4116
  if (!!placements_1_1.done) return [3 /*break*/, 5];
3561
4117
  placement = placements_1_1.value;
3562
4118
  return [4 /*yield*/, resolveImageDataUrl(placement.imageUrl)];
3563
4119
  case 3:
3564
- dataUrl = _k.sent();
4120
+ dataUrl = _m.sent();
3565
4121
  if (!dataUrl)
3566
4122
  return [3 /*break*/, 4];
3567
4123
  buffer = dataUriToBuffer(dataUrl, placement.imageUrl);
@@ -3574,38 +4130,57 @@ var buildDrawingParts = function (_a) { return __awaiter(void 0, [_a], void 0, f
3574
4130
  extension: buffer.extension,
3575
4131
  });
3576
4132
  relId = relationships.add(IMAGE_REL_TYPE, "../media/image".concat(imageIndex, ".").concat(buffer.extension));
3577
- anchors.push(createTwoCellAnchor({
3578
- sheet: sheet,
3579
- placement: placement,
3580
- relId: relId,
3581
- pictureId: pictureId,
3582
- }));
4133
+ embedAnchors.push({
4134
+ order: orderOf(placement.order),
4135
+ xml: createTwoCellAnchor({
4136
+ sheet: sheet,
4137
+ placement: placement,
4138
+ relId: relId,
4139
+ pictureId: pictureId,
4140
+ }),
4141
+ });
3583
4142
  imageIndex += 1;
3584
4143
  pictureId += 1;
3585
- _k.label = 4;
4144
+ _m.label = 4;
3586
4145
  case 4:
3587
4146
  placements_1_1 = placements_1.next();
3588
4147
  return [3 /*break*/, 2];
3589
4148
  case 5: return [3 /*break*/, 8];
3590
4149
  case 6:
3591
- e_37_1 = _k.sent();
3592
- e_37 = { error: e_37_1 };
4150
+ e_42_1 = _m.sent();
4151
+ e_42 = { error: e_42_1 };
3593
4152
  return [3 /*break*/, 8];
3594
4153
  case 7:
3595
4154
  try {
3596
4155
  if (placements_1_1 && !placements_1_1.done && (_h = placements_1.return)) _h.call(placements_1);
3597
4156
  }
3598
- finally { if (e_37) throw e_37.error; }
4157
+ finally { if (e_42) throw e_42.error; }
3599
4158
  return [7 /*endfinally*/];
3600
4159
  case 8:
4160
+ embedAnchors.sort(function (a, b) { return a.order - b.order; });
4161
+ try {
4162
+ for (embedAnchors_1 = __values(embedAnchors), embedAnchors_1_1 = embedAnchors_1.next(); !embedAnchors_1_1.done; embedAnchors_1_1 = embedAnchors_1.next()) {
4163
+ entry = embedAnchors_1_1.value;
4164
+ anchors.push(entry.xml);
4165
+ }
4166
+ }
4167
+ catch (e_47_1) { e_47 = { error: e_47_1 }; }
4168
+ finally {
4169
+ try {
4170
+ if (embedAnchors_1_1 && !embedAnchors_1_1.done && (_j = embedAnchors_1.return)) _j.call(embedAnchors_1);
4171
+ }
4172
+ finally { if (e_47) throw e_47.error; }
4173
+ }
3601
4174
  drawingXml = "".concat(XML_DECLARATION, "<xdr:wsDr xmlns:xdr=\"http://schemas.openxmlformats.org/drawingml/2006/spreadsheetDrawing\" xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\" xmlns:r=\"").concat(REL_NS, "\">").concat(anchors.join(""), "</xdr:wsDr>");
3602
4175
  return [2 /*return*/, {
3603
4176
  xml: drawingXml,
3604
4177
  relsXml: relationships.toXml(),
3605
4178
  media: media,
3606
4179
  charts: chartEntries,
4180
+ chartExs: chartExEntries,
3607
4181
  nextImageIndex: imageIndex,
3608
4182
  nextChartIndex: chartIndex,
4183
+ nextChartExIndex: chartExIndex,
3609
4184
  }];
3610
4185
  }
3611
4186
  });
@@ -3635,11 +4210,59 @@ var createTwoCellAnchor = function (_a) {
3635
4210
  });
3636
4211
  var fromXml = "<xdr:from><xdr:col>".concat(fromColumn, "</xdr:col><xdr:colOff>").concat(Math.round(offsetX * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(fromRow, "</xdr:row><xdr:rowOff>").concat(Math.round(offsetY * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:from>");
3637
4212
  var toXml = "<xdr:to><xdr:col>".concat(toColumn.index, "</xdr:col><xdr:colOff>").concat(Math.round(toColumn.offset * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(toRow.index, "</xdr:row><xdr:rowOff>").concat(Math.round(toRow.offset * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:to>");
3638
- return "<xdr:twoCellAnchor editAs=\"oneCell\">".concat(fromXml).concat(toXml, "<xdr:pic><xdr:nvPicPr><xdr:cNvPr id=\"").concat(pictureId, "\" name=\"Picture ").concat(pictureId, "\"/><xdr:cNvPicPr/></xdr:nvPicPr><xdr:blipFill><a:blip r:embed=\"").concat(relId, "\"/><a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"").concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic><xdr:clientData/></xdr:twoCellAnchor>");
4213
+ var _g = buildPictureAdjustmentsXml(placement.adjustments), blipChildren = _g.blipChildren, srcRectXml = _g.srcRectXml;
4214
+ var blipXml = blipChildren
4215
+ ? "<a:blip r:embed=\"".concat(relId, "\">").concat(blipChildren, "</a:blip>")
4216
+ : "<a:blip r:embed=\"".concat(relId, "\"/>");
4217
+ return "<xdr:twoCellAnchor editAs=\"oneCell\">".concat(fromXml).concat(toXml, "<xdr:pic><xdr:nvPicPr><xdr:cNvPr id=\"").concat(pictureId, "\" name=\"Picture ").concat(pictureId, "\"/><xdr:cNvPicPr/></xdr:nvPicPr><xdr:blipFill>").concat(blipXml).concat(srcRectXml, "<a:stretch><a:fillRect/></a:stretch></xdr:blipFill><xdr:spPr><a:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"").concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></a:xfrm><a:prstGeom prst=\"rect\"><a:avLst/></a:prstGeom></xdr:spPr></xdr:pic><xdr:clientData/></xdr:twoCellAnchor>");
4218
+ };
4219
+ /** Fraction (0…1) → DrawingML per-mille percent (100000 = 100%). */
4220
+ var fractionToPct = function (value) {
4221
+ return Math.round(Math.max(-1, Math.min(1, value)) * 100000);
4222
+ };
4223
+ /**
4224
+ * `<a:blip>` children (`<a:alphaModFix>`, `<a:lum>`) and the `<a:srcRect>`
4225
+ * sibling for an image's picture-format adjustments; both empty when the
4226
+ * spec carries none.
4227
+ */
4228
+ var buildPictureAdjustmentsXml = function (adjustments) {
4229
+ if (!adjustments)
4230
+ return { blipChildren: "", srcRectXml: "" };
4231
+ var blipChildren = "";
4232
+ var transparency = adjustments.transparency, brightness = adjustments.brightness, contrast = adjustments.contrast, crop = adjustments.crop;
4233
+ if (typeof transparency === "number" && transparency > 0) {
4234
+ blipChildren += "<a:alphaModFix amt=\"".concat(fractionToPct(1 - Math.min(1, transparency)), "\"/>");
4235
+ }
4236
+ var hasBrightness = typeof brightness === "number" && brightness !== 0;
4237
+ var hasContrast = typeof contrast === "number" && contrast !== 0;
4238
+ if (hasBrightness || hasContrast) {
4239
+ blipChildren += "<a:lum".concat(hasBrightness ? " bright=\"".concat(fractionToPct(brightness), "\"") : "").concat(hasContrast ? " contrast=\"".concat(fractionToPct(contrast), "\"") : "", "/>");
4240
+ }
4241
+ var srcRectXml = "";
4242
+ if (crop) {
4243
+ var edges = ["l", "t", "r", "b"]
4244
+ .map(function (edge) {
4245
+ var value = {
4246
+ l: crop.left,
4247
+ t: crop.top,
4248
+ r: crop.right,
4249
+ b: crop.bottom,
4250
+ }[edge];
4251
+ // Negative edges are Excel's "out-crop" (padding around the
4252
+ // bitmap) and round-trip like positive ones.
4253
+ return typeof value === "number" && Number.isFinite(value) && value !== 0
4254
+ ? " ".concat(edge, "=\"").concat(fractionToPct(value), "\"")
4255
+ : "";
4256
+ })
4257
+ .join("");
4258
+ if (edges)
4259
+ srcRectXml = "<a:srcRect".concat(edges, "/>");
4260
+ }
4261
+ return { blipChildren: blipChildren, srcRectXml: srcRectXml };
3639
4262
  };
3640
4263
  var createChartAnchor = function (_a) {
3641
4264
  var _b, _d, _e, _f;
3642
- var placement = _a.placement, relId = _a.relId, frameId = _a.frameId, sheet = _a.sheet;
4265
+ var placement = _a.placement, relId = _a.relId, frameId = _a.frameId, sheet = _a.sheet, _g = _a.chartEx, chartEx = _g === void 0 ? false : _g;
3643
4266
  var fromRow = Math.max(0, placement.rowIndex - 1);
3644
4267
  var fromColumn = Math.max(0, placement.columnIndex - 1);
3645
4268
  var offsetX = Math.max(0, (_b = placement.offsetX) !== null && _b !== void 0 ? _b : 0);
@@ -3660,6 +4283,14 @@ var createChartAnchor = function (_a) {
3660
4283
  });
3661
4284
  var fromXml = "<xdr:from><xdr:col>".concat(fromColumn, "</xdr:col><xdr:colOff>").concat(Math.round(offsetX * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(fromRow, "</xdr:row><xdr:rowOff>").concat(Math.round(offsetY * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:from>");
3662
4285
  var toXml = "<xdr:to><xdr:col>".concat(toColumn.index, "</xdr:col><xdr:colOff>").concat(Math.round(toColumn.offset * EMUS_PER_PIXEL), "</xdr:colOff><xdr:row>").concat(toRow.index, "</xdr:row><xdr:rowOff>").concat(Math.round(toRow.offset * EMUS_PER_PIXEL), "</xdr:rowOff></xdr:to>");
4286
+ if (chartEx) {
4287
+ return "<xdr:twoCellAnchor>".concat(fromXml).concat(toXml).concat(buildChartExGraphicFrameXml({
4288
+ relId: relId,
4289
+ frameId: frameId,
4290
+ widthEmu: Math.round(widthPx * EMUS_PER_PIXEL),
4291
+ heightEmu: Math.round(heightPx * EMUS_PER_PIXEL),
4292
+ }), "<xdr:clientData/></xdr:twoCellAnchor>");
4293
+ }
3663
4294
  return "<xdr:twoCellAnchor>".concat(fromXml).concat(toXml, "<xdr:graphicFrame><xdr:nvGraphicFramePr><xdr:cNvPr id=\"").concat(frameId, "\" name=\"Chart ").concat(frameId, "\"/><xdr:cNvGraphicFramePr/></xdr:nvGraphicFramePr><xdr:xfrm><a:off x=\"0\" y=\"0\"/><a:ext cx=\"").concat(Math.round(widthPx * EMUS_PER_PIXEL), "\" cy=\"").concat(Math.round(heightPx * EMUS_PER_PIXEL), "\"/></xdr:xfrm><a:graphic><a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/chart\"><c:chart xmlns:c=\"http://schemas.openxmlformats.org/drawingml/2006/chart\" xmlns:r=\"").concat(REL_NS, "\" r:id=\"").concat(relId, "\"/></a:graphicData></a:graphic></xdr:graphicFrame><xdr:clientData/></xdr:twoCellAnchor>");
3664
4295
  };
3665
4296
  var createSlicerAnchor = function (_a) {
@@ -3900,7 +4531,7 @@ var buildTextWithTabs = function (text, rPrXml) {
3900
4531
  .join("");
3901
4532
  };
3902
4533
  var buildTextBodyXml = function (spec) {
3903
- var e_42, _a;
4534
+ var e_48, _a;
3904
4535
  var richText = spec.richText || [];
3905
4536
  var plainText = spec.text || "";
3906
4537
  // Build vertical alignment and wrap attributes
@@ -3941,12 +4572,12 @@ var buildTextBodyXml = function (spec) {
3941
4572
  }
3942
4573
  }
3943
4574
  }
3944
- catch (e_42_1) { e_42 = { error: e_42_1 }; }
4575
+ catch (e_48_1) { e_48 = { error: e_48_1 }; }
3945
4576
  finally {
3946
4577
  try {
3947
4578
  if (richText_1_1 && !richText_1_1.done && (_a = richText_1.return)) _a.call(richText_1);
3948
4579
  }
3949
- finally { if (e_42) throw e_42.error; }
4580
+ finally { if (e_48) throw e_48.error; }
3950
4581
  }
3951
4582
  paragraphsXml = paragraphs
3952
4583
  .filter(function (runs) { return runs.length > 0; })
@@ -4352,7 +4983,13 @@ var buildWorkbookXml = function (sheets, sheetRelIds, sheetNames, namedRanges, i
4352
4983
  var _a;
4353
4984
  sheetNameById.set((_a = sheet.sheetId) !== null && _a !== void 0 ? _a : index + 1, sheetNames[index]);
4354
4985
  });
4355
- var definedNamesXml = buildDefinedNamesXml(namedRanges, sheetNameById);
4986
+ var definedNamesXml = buildDefinedNamesXml(namedRanges, sheetNameById, sheets.map(function (sheet, index) {
4987
+ var _a;
4988
+ return ({
4989
+ sheetName: (_a = sheetNames[index]) !== null && _a !== void 0 ? _a : "Sheet".concat(index + 1),
4990
+ printSettings: sheet.printSettings,
4991
+ });
4992
+ }));
4356
4993
  var calcPrXml = buildCalcPrXml(iterativeCalculationOptions);
4357
4994
  var slicerCachesXml = buildWorkbookSlicerCachesXml(slicerCacheRelIds);
4358
4995
  // Phase D2 — <pivotCaches> element. Each <pivotCache> pairs a
@@ -4383,19 +5020,70 @@ var buildWorkbookXml = function (sheets, sheetRelIds, sheetNames, namedRanges, i
4383
5020
  : "<workbookPr/>";
4384
5021
  return "".concat(XML_DECLARATION, "<workbook xmlns=\"").concat(WORKSHEET_NS, "\" xmlns:r=\"").concat(REL_NS, "\">").concat(workbookPrXml).concat(calcPrXml, "<bookViews><workbookView activeTab=\"0\" firstSheet=\"0\"/></bookViews><sheets>").concat(sheetEntries, "</sheets>").concat(definedNamesXml).concat(externalReferencesXml).concat(pivotCachesXml).concat(slicerCachesXml, "</workbook>");
4385
5022
  };
4386
- var buildDefinedNamesXml = function (namedRanges, sheetNameById) {
4387
- var e_43, _a;
4388
- var _b;
4389
- if (!(namedRanges === null || namedRanges === void 0 ? void 0 : namedRanges.length))
4390
- return "";
5023
+ var buildDefinedNamesXml = function (namedRanges, sheetNameById, printScopes) {
5024
+ var e_49, _a, e_50, _b;
5025
+ var _d, _e, _f;
5026
+ if (printScopes === void 0) { printScopes = []; }
4391
5027
  var entries = [];
5028
+ // The builtin print names are sheet-scoped (`localSheetId` = position in
5029
+ // `<sheets>`); they come from `sheet.printSettings`, never from
5030
+ // `namedRanges` (a global `_xlnm.Print_Area` makes Excel repair the file).
5031
+ // Documents imported before `printSettings` existed still carry the print
5032
+ // area as a `_xlnm.Print_Area` named range on the sheet; it is converted
5033
+ // to the sheet-scoped name here unless the sheet already has a print area.
5034
+ var sheetIndexByName = new Map(printScopes.map(function (_a, index) {
5035
+ var sheetName = _a.sheetName;
5036
+ return [sheetName, index];
5037
+ }));
5038
+ var legacyPrintAreas = new Map();
4392
5039
  try {
4393
- for (var namedRanges_1 = __values(namedRanges), namedRanges_1_1 = namedRanges_1.next(); !namedRanges_1_1.done; namedRanges_1_1 = namedRanges_1.next()) {
4394
- var namedRange = namedRanges_1_1.value;
4395
- if (!(namedRange === null || namedRange === void 0 ? void 0 : namedRange.name))
5040
+ for (var _g = __values(namedRanges !== null && namedRanges !== void 0 ? namedRanges : []), _h = _g.next(); !_h.done; _h = _g.next()) {
5041
+ var namedRange = _h.value;
5042
+ if ((namedRange === null || namedRange === void 0 ? void 0 : namedRange.name) !== PRINT_AREA_NAME || !((_d = namedRange.range) === null || _d === void 0 ? void 0 : _d.sheetId)) {
5043
+ continue;
5044
+ }
5045
+ var sheetName = sheetNameById.get(namedRange.range.sheetId);
5046
+ var index = sheetName ? sheetIndexByName.get(sheetName) : undefined;
5047
+ if (index == null)
5048
+ continue;
5049
+ legacyPrintAreas.set(index, __spreadArray(__spreadArray([], __read(((_e = legacyPrintAreas.get(index)) !== null && _e !== void 0 ? _e : [])), false), [
5050
+ namedRange.range,
5051
+ ], false));
5052
+ }
5053
+ }
5054
+ catch (e_49_1) { e_49 = { error: e_49_1 }; }
5055
+ finally {
5056
+ try {
5057
+ if (_h && !_h.done && (_a = _g.return)) _a.call(_g);
5058
+ }
5059
+ finally { if (e_49) throw e_49.error; }
5060
+ }
5061
+ printScopes.forEach(function (_a, index) {
5062
+ var _b;
5063
+ var sheetName = _a.sheetName, printSettings = _a.printSettings;
5064
+ var printArea = ((_b = printSettings === null || printSettings === void 0 ? void 0 : printSettings.printArea) === null || _b === void 0 ? void 0 : _b.length)
5065
+ ? printSettings.printArea
5066
+ : legacyPrintAreas.get(index);
5067
+ var area = (printArea === null || printArea === void 0 ? void 0 : printArea.length)
5068
+ ? buildPrintAreaFormula(sheetName, printArea)
5069
+ : undefined;
5070
+ if (area) {
5071
+ entries.push("<definedName name=\"".concat(PRINT_AREA_NAME, "\" localSheetId=\"").concat(index, "\">").concat(escapeXmlText(area), "</definedName>"));
5072
+ }
5073
+ var titles = (printSettings === null || printSettings === void 0 ? void 0 : printSettings.printTitles)
5074
+ ? buildPrintTitlesFormula(sheetName, printSettings.printTitles)
5075
+ : undefined;
5076
+ if (titles) {
5077
+ entries.push("<definedName name=\"".concat(PRINT_TITLES_NAME, "\" localSheetId=\"").concat(index, "\">").concat(escapeXmlText(titles), "</definedName>"));
5078
+ }
5079
+ });
5080
+ try {
5081
+ for (var _j = __values(namedRanges !== null && namedRanges !== void 0 ? namedRanges : []), _k = _j.next(); !_k.done; _k = _j.next()) {
5082
+ var namedRange = _k.value;
5083
+ if (!(namedRange === null || namedRange === void 0 ? void 0 : namedRange.name) || isBuiltinPrintName(namedRange.name))
4396
5084
  continue;
4397
5085
  var hiddenAttr = namedRange.hidden ? " hidden=\"1\"" : "";
4398
- if ((_b = namedRange.range) === null || _b === void 0 ? void 0 : _b.sheetId) {
5086
+ if ((_f = namedRange.range) === null || _f === void 0 ? void 0 : _f.sheetId) {
4399
5087
  var sheetName = sheetNameById.get(namedRange.range.sheetId);
4400
5088
  if (!sheetName)
4401
5089
  continue;
@@ -4416,12 +5104,12 @@ var buildDefinedNamesXml = function (namedRanges, sheetNameById) {
4416
5104
  entries.push("<definedName name=\"".concat(escapeXmlAttr(namedRange.name), "\"").concat(hiddenAttr, ">").concat(escapeXmlText(expression), "</definedName>"));
4417
5105
  }
4418
5106
  }
4419
- catch (e_43_1) { e_43 = { error: e_43_1 }; }
5107
+ catch (e_50_1) { e_50 = { error: e_50_1 }; }
4420
5108
  finally {
4421
5109
  try {
4422
- if (namedRanges_1_1 && !namedRanges_1_1.done && (_a = namedRanges_1.return)) _a.call(namedRanges_1);
5110
+ if (_k && !_k.done && (_b = _j.return)) _b.call(_j);
4423
5111
  }
4424
- finally { if (e_43) throw e_43.error; }
5112
+ finally { if (e_50) throw e_50.error; }
4425
5113
  }
4426
5114
  if (!entries.length)
4427
5115
  return "";
@@ -4511,7 +5199,7 @@ var buildWorkbookRelationships = function (sheetCount, slicerCacheCount, externa
4511
5199
  };
4512
5200
  };
4513
5201
  var buildContentTypesXml = function (_a) {
4514
- var sheetCount = _a.sheetCount, tableCount = _a.tableCount, drawingSheets = _a.drawingSheets, mediaExtensions = _a.mediaExtensions, chartCount = _a.chartCount, _b = _a.slicerCount, slicerCount = _b === void 0 ? 0 : _b, _d = _a.slicerCacheCount, slicerCacheCount = _d === void 0 ? 0 : _d, _e = _a.pivotTableCount, pivotTableCount = _e === void 0 ? 0 : _e, _f = _a.pivotCacheCount, pivotCacheCount = _f === void 0 ? 0 : _f, _g = _a.commentsSheets, commentsSheets = _g === void 0 ? [] : _g, _h = _a.threadedCommentsSheets, threadedCommentsSheets = _h === void 0 ? [] : _h, _j = _a.hasPersons, hasPersons = _j === void 0 ? false : _j, _k = _a.externalLinkCount, externalLinkCount = _k === void 0 ? 0 : _k;
5202
+ var sheetCount = _a.sheetCount, tableCount = _a.tableCount, drawingSheets = _a.drawingSheets, mediaExtensions = _a.mediaExtensions, chartCount = _a.chartCount, _b = _a.chartExCount, chartExCount = _b === void 0 ? 0 : _b, _d = _a.slicerCount, slicerCount = _d === void 0 ? 0 : _d, _e = _a.slicerCacheCount, slicerCacheCount = _e === void 0 ? 0 : _e, _f = _a.pivotTableCount, pivotTableCount = _f === void 0 ? 0 : _f, _g = _a.pivotCacheCount, pivotCacheCount = _g === void 0 ? 0 : _g, _h = _a.commentsSheets, commentsSheets = _h === void 0 ? [] : _h, _j = _a.threadedCommentsSheets, threadedCommentsSheets = _j === void 0 ? [] : _j, _k = _a.hasPersons, hasPersons = _k === void 0 ? false : _k, _l = _a.externalLinkCount, externalLinkCount = _l === void 0 ? 0 : _l, _m = _a.hasVmlDrawings, hasVmlDrawings = _m === void 0 ? false : _m, _o = _a.ctrlPropCount, ctrlPropCount = _o === void 0 ? 0 : _o;
4515
5203
  var sheetOverrides = Array.from({ length: sheetCount }, function (_, index) {
4516
5204
  return "<Override PartName=\"/xl/worksheets/sheet".concat(index + 1, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.worksheet+xml\"/>");
4517
5205
  }).join("");
@@ -4526,6 +5214,9 @@ var buildContentTypesXml = function (_a) {
4526
5214
  var chartOverrides = Array.from({ length: chartCount }, function (_, index) {
4527
5215
  return "<Override PartName=\"/xl/charts/chart".concat(index + 1, ".xml\" ContentType=\"application/vnd.openxmlformats-officedocument.drawingml.chart+xml\"/>");
4528
5216
  }).join("");
5217
+ var chartExOverrides = Array.from({ length: chartExCount }, function (_, index) {
5218
+ return "<Override PartName=\"/xl/charts/chartEx".concat(index + 1, ".xml\" ContentType=\"").concat(CHART_EX_CONTENT_TYPE, "\"/>");
5219
+ }).join("");
4529
5220
  var slicerOverrides = Array.from({ length: slicerCount }, function (_, index) {
4530
5221
  return "<Override PartName=\"/xl/slicers/slicer".concat(index + 1, ".xml\" ContentType=\"application/vnd.ms-excel.slicer+xml\"/>");
4531
5222
  }).join("");
@@ -4560,10 +5251,13 @@ var buildContentTypesXml = function (_a) {
4560
5251
  return "<Default Extension=\"".concat(extension, "\" ContentType=\"image/").concat(extension, "\"/>");
4561
5252
  })
4562
5253
  .join("");
4563
- var vmlDefault = commentsSheets.length
5254
+ var vmlDefault = hasVmlDrawings || commentsSheets.length
4564
5255
  ? "<Default Extension=\"vml\" ContentType=\"application/vnd.openxmlformats-officedocument.vmlDrawing\"/>"
4565
5256
  : "";
4566
- return "".concat(XML_DECLARATION, "<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\"><Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/><Default Extension=\"xml\" ContentType=\"application/xml\"/>").concat(vmlDefault).concat(mediaDefaults, "<Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"/>").concat(sheetOverrides).concat(tableOverrides).concat(drawingOverrides).concat(chartOverrides).concat(slicerOverrides).concat(slicerCacheOverrides).concat(pivotTableOverrides).concat(pivotCacheOverrides).concat(externalLinkOverrides).concat(commentsOverrides).concat(threadedCommentsOverrides).concat(personOverride, "<Override PartName=\"/xl/theme/theme1.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.theme+xml\"/><Override PartName=\"/xl/styles.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\"/><Override PartName=\"/xl/sharedStrings.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml\"/><Override PartName=\"/docProps/core.xml\" ContentType=\"application/vnd.openxmlformats-package.core-properties+xml\"/><Override PartName=\"/docProps/app.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.extended-properties+xml\"/></Types>");
5257
+ var ctrlPropOverrides = Array.from({ length: ctrlPropCount }, function (_, index) {
5258
+ return "<Override PartName=\"/xl/ctrlProps/ctrlProp".concat(index + 1, ".xml\" ContentType=\"").concat(CTRL_PROP_CONTENT_TYPE, "\"/>");
5259
+ }).join("");
5260
+ return "".concat(XML_DECLARATION, "<Types xmlns=\"http://schemas.openxmlformats.org/package/2006/content-types\"><Default Extension=\"rels\" ContentType=\"application/vnd.openxmlformats-package.relationships+xml\"/><Default Extension=\"xml\" ContentType=\"application/xml\"/>").concat(vmlDefault).concat(mediaDefaults, "<Override PartName=\"/xl/workbook.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet.main+xml\"/>").concat(sheetOverrides).concat(tableOverrides).concat(drawingOverrides).concat(chartOverrides).concat(chartExOverrides).concat(slicerOverrides).concat(slicerCacheOverrides).concat(pivotTableOverrides).concat(pivotCacheOverrides).concat(externalLinkOverrides).concat(ctrlPropOverrides).concat(commentsOverrides).concat(threadedCommentsOverrides).concat(personOverride, "<Override PartName=\"/xl/theme/theme1.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.theme+xml\"/><Override PartName=\"/xl/styles.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.styles+xml\"/><Override PartName=\"/xl/sharedStrings.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.spreadsheetml.sharedStrings+xml\"/><Override PartName=\"/docProps/core.xml\" ContentType=\"application/vnd.openxmlformats-package.core-properties+xml\"/><Override PartName=\"/docProps/app.xml\" ContentType=\"application/vnd.openxmlformats-officedocument.extended-properties+xml\"/></Types>");
4567
5261
  };
4568
5262
  var buildRootRelationshipsXml = function () {
4569
5263
  return "".concat(XML_DECLARATION, "<Relationships xmlns=\"").concat(PACKAGE_REL_NS, "\"><Relationship Id=\"rId1\" Type=\"").concat(REL_NS, "/officeDocument\" Target=\"xl/workbook.xml\"/><Relationship Id=\"rId2\" Type=\"").concat(REL_NS, "/extended-properties\" Target=\"docProps/app.xml\"/><Relationship Id=\"rId3\" Type=\"").concat(REL_NS, "/core-properties\" Target=\"docProps/core.xml\"/></Relationships>");