@quirekit/xlsx 0.0.0-stage → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (336) hide show
  1. package/LICENSE.md +21 -0
  2. package/THIRD_PARTY_NOTICES.md +150 -0
  3. package/dist/index.d.mts +122 -0
  4. package/dist/index.d.mts.map +1 -0
  5. package/dist/index.mjs +19167 -0
  6. package/dist/index.mjs.map +1 -0
  7. package/licenses/saxes.LICENSE +64 -0
  8. package/licenses/xmlchars.LICENSE +18 -0
  9. package/package.json +52 -3
  10. package/src/bundle.ts +17 -0
  11. package/src/comments/legacy/read.ts +68 -0
  12. package/src/comments/legacy/write.ts +64 -0
  13. package/src/comments/package/ranges.ts +78 -0
  14. package/src/comments/package/read.ts +95 -0
  15. package/src/comments/package/roundtrip.test.ts +106 -0
  16. package/src/comments/package/write.ts +130 -0
  17. package/src/comments/thread/read.ts +69 -0
  18. package/src/comments/thread/write.ts +61 -0
  19. package/src/comments/types.ts +43 -0
  20. package/src/comments/xml.ts +50 -0
  21. package/src/create.ts +13 -0
  22. package/src/drawing/cache.ts +48 -0
  23. package/src/drawing/chart.test.ts +96 -0
  24. package/src/drawing/chart.ts +87 -0
  25. package/src/drawing/definition/plots.ts +76 -0
  26. package/src/drawing/definition/read.ts +65 -0
  27. package/src/drawing/definition/shape.ts +40 -0
  28. package/src/drawing/definition/types.ts +24 -0
  29. package/src/drawing/editable-picture.ts +80 -0
  30. package/src/drawing/graph.ts +148 -0
  31. package/src/drawing/identity.ts +22 -0
  32. package/src/drawing/import.ts +133 -0
  33. package/src/drawing/namespaces.ts +11 -0
  34. package/src/drawing/picture.test.ts +98 -0
  35. package/src/drawing/picture.ts +54 -0
  36. package/src/drawing/placement/anchor.ts +71 -0
  37. package/src/drawing/placement/axes.ts +113 -0
  38. package/src/drawing/placement/marker.ts +16 -0
  39. package/src/drawing/placement/transform.ts +132 -0
  40. package/src/drawing/placement/types.ts +20 -0
  41. package/src/drawing/presentation/cartesian/axes.ts +103 -0
  42. package/src/drawing/presentation/cartesian/plot.ts +109 -0
  43. package/src/drawing/presentation/cartesian/types.ts +9 -0
  44. package/src/drawing/presentation/layout.ts +29 -0
  45. package/src/drawing/presentation/paint.ts +56 -0
  46. package/src/drawing/presentation/properties.ts +31 -0
  47. package/src/drawing/read.ts +85 -0
  48. package/src/drawing/shapes/connector.ts +55 -0
  49. package/src/drawing/shapes/paint.ts +108 -0
  50. package/src/drawing/shapes/read.ts +89 -0
  51. package/src/drawing/shapes/text.ts +89 -0
  52. package/src/drawing/shapes/types.ts +13 -0
  53. package/src/drawing/sources.test.ts +27 -0
  54. package/src/drawing/sources.ts +43 -0
  55. package/src/drawing/types.ts +54 -0
  56. package/src/drawing/worksheet-connector.test.ts +135 -0
  57. package/src/drawing/worksheet-shape.test.ts +61 -0
  58. package/src/drawing/write/anchor.ts +17 -0
  59. package/src/drawing/write/axes.ts +23 -0
  60. package/src/drawing/write/chart.ts +56 -0
  61. package/src/drawing/write/drawing.ts +61 -0
  62. package/src/drawing/write/pictures.ts +68 -0
  63. package/src/drawing/write/series.ts +43 -0
  64. package/src/drawing/write/shapes.ts +113 -0
  65. package/src/drawing/write/text.ts +26 -0
  66. package/src/drawing/write/workbook.test.ts +199 -0
  67. package/src/drawing/write/workbook.ts +217 -0
  68. package/src/external-links/formulas.ts +21 -0
  69. package/src/external-links/read.test.ts +93 -0
  70. package/src/external-links/read.ts +104 -0
  71. package/src/external-links/types.ts +9 -0
  72. package/src/external-links/write.ts +120 -0
  73. package/src/image/excel.ts +122 -0
  74. package/src/image/native.ts +21 -0
  75. package/src/image/ownership.ts +77 -0
  76. package/src/image/parts.ts +45 -0
  77. package/src/image/raster.ts +25 -0
  78. package/src/image/read.test.ts +95 -0
  79. package/src/image/read.ts +66 -0
  80. package/src/image/relationships.ts +26 -0
  81. package/src/image/types.ts +48 -0
  82. package/src/image/wps.ts +43 -0
  83. package/src/image/write.test.ts +53 -0
  84. package/src/image/write.ts +118 -0
  85. package/src/index.ts +6 -0
  86. package/src/metadata/dynamic-array.ts +105 -0
  87. package/src/metadata/package.ts +75 -0
  88. package/src/metadata/types.ts +7 -0
  89. package/src/opc/archive.ts +26 -0
  90. package/src/opc/ownership.ts +40 -0
  91. package/src/opc/relationships.ts +98 -0
  92. package/src/opc/revision.ts +28 -0
  93. package/src/opc/shape.ts +23 -0
  94. package/src/opc/types.ts +13 -0
  95. package/src/opc/xml.test.ts +49 -0
  96. package/src/opc/xml.ts +128 -0
  97. package/src/optimization/blanks.ts +53 -0
  98. package/src/optimization/optimize.test.ts +117 -0
  99. package/src/optimization/optimize.ts +41 -0
  100. package/src/optimization/package.ts +65 -0
  101. package/src/optimization/rules.ts +46 -0
  102. package/src/optimization/styles.ts +76 -0
  103. package/src/optimization/types.ts +33 -0
  104. package/src/package/assembly.test.ts +117 -0
  105. package/src/package/calculation-metadata.test.ts +85 -0
  106. package/src/package/calculation-metadata.ts +88 -0
  107. package/src/package/checkboxes.ts +37 -0
  108. package/src/package/cleanup.test.ts +61 -0
  109. package/src/package/dashboard.test.ts +53 -0
  110. package/src/package/dashboard.ts +84 -0
  111. package/src/package/extensions.ts +16 -0
  112. package/src/package/merge-recipes.ts +84 -0
  113. package/src/package/names/conditional.ts +64 -0
  114. package/src/package/names/defined.test.ts +52 -0
  115. package/src/package/names/defined.ts +75 -0
  116. package/src/package/names/filter.ts +68 -0
  117. package/src/package/names/print-layout.ts +62 -0
  118. package/src/package/names/print.ts +62 -0
  119. package/src/package/new.ts +46 -0
  120. package/src/package/open/appearance.ts +46 -0
  121. package/src/package/open/directory.ts +61 -0
  122. package/src/package/open/restrictions.ts +27 -0
  123. package/src/package/open/snapshot.test.ts +48 -0
  124. package/src/package/open/snapshot.ts +34 -0
  125. package/src/package/open/source-write.ts +130 -0
  126. package/src/package/open/types.ts +73 -0
  127. package/src/package/open/worksheets.ts +149 -0
  128. package/src/package/positions.ts +40 -0
  129. package/src/package/read.ts +143 -0
  130. package/src/package/save/types.ts +57 -0
  131. package/src/package/save/worksheets.ts +126 -0
  132. package/src/package/selection-copy.test.ts +70 -0
  133. package/src/package/styles.ts +39 -0
  134. package/src/package/types.ts +52 -0
  135. package/src/package/workbook-views.ts +34 -0
  136. package/src/package/worksheets.test.ts +190 -0
  137. package/src/package/worksheets.ts +162 -0
  138. package/src/package/write.ts +175 -0
  139. package/src/pivot/cache/calculated.ts +34 -0
  140. package/src/pivot/cache/dates.ts +124 -0
  141. package/src/pivot/cache/groups.ts +11 -0
  142. package/src/pivot/cache/members.ts +99 -0
  143. package/src/pivot/cache/numbers.ts +63 -0
  144. package/src/pivot/cache/read.ts +131 -0
  145. package/src/pivot/cache/time.ts +20 -0
  146. package/src/pivot/cache/values.ts +43 -0
  147. package/src/pivot/cache/write.ts +117 -0
  148. package/src/pivot/definition/axes.ts +35 -0
  149. package/src/pivot/definition/dates.ts +87 -0
  150. package/src/pivot/definition/display.ts +86 -0
  151. package/src/pivot/definition/extension.ts +57 -0
  152. package/src/pivot/definition/field-settings/caption.ts +38 -0
  153. package/src/pivot/definition/field-settings/comparison.ts +47 -0
  154. package/src/pivot/definition/field-settings/field.ts +66 -0
  155. package/src/pivot/definition/field-settings/filters.ts +86 -0
  156. package/src/pivot/definition/field-settings/measure.ts +79 -0
  157. package/src/pivot/definition/field-settings/types.ts +19 -0
  158. package/src/pivot/definition/functions.ts +21 -0
  159. package/src/pivot/definition/items.ts +144 -0
  160. package/src/pivot/definition/members.ts +98 -0
  161. package/src/pivot/definition/numbers.ts +19 -0
  162. package/src/pivot/definition/presentation.ts +52 -0
  163. package/src/pivot/definition/read.ts +143 -0
  164. package/src/pivot/definition/report-layout.ts +39 -0
  165. package/src/pivot/definition/write.ts +157 -0
  166. package/src/pivot/package/calculated.test.ts +103 -0
  167. package/src/pivot/package/dates.test.ts +266 -0
  168. package/src/pivot/package/display.test.ts +133 -0
  169. package/src/pivot/package/field-settings.test.ts +59 -0
  170. package/src/pivot/package/layout.test.ts +148 -0
  171. package/src/pivot/package/measure-settings.test.ts +85 -0
  172. package/src/pivot/package/members.test.ts +167 -0
  173. package/src/pivot/package/numbers.test.ts +120 -0
  174. package/src/pivot/package/read.ts +93 -0
  175. package/src/pivot/package/roundtrip.test.ts +244 -0
  176. package/src/pivot/package/write.ts +103 -0
  177. package/src/pivot/types.ts +36 -0
  178. package/src/pivot/xml.ts +50 -0
  179. package/src/presentation.test.ts +186 -0
  180. package/src/roundtrip.test.ts +72 -0
  181. package/src/styles/checkbox/bags.ts +85 -0
  182. package/src/styles/checkbox/style.ts +45 -0
  183. package/src/styles/checkbox/types.ts +7 -0
  184. package/src/styles/color.ts +64 -0
  185. package/src/styles/differential-preview.ts +60 -0
  186. package/src/styles/differential.ts +119 -0
  187. package/src/styles/numbers.ts +9 -0
  188. package/src/styles/parts.ts +107 -0
  189. package/src/styles/read.ts +95 -0
  190. package/src/styles/reference.ts +14 -0
  191. package/src/styles/types.ts +9 -0
  192. package/src/styles/write.test.ts +88 -0
  193. package/src/styles/write.ts +162 -0
  194. package/src/table/conversion.test.ts +73 -0
  195. package/src/table/definition.ts +89 -0
  196. package/src/table/filter.ts +42 -0
  197. package/src/table/ownership.ts +112 -0
  198. package/src/table/read.test.ts +274 -0
  199. package/src/table/read.ts +117 -0
  200. package/src/table/remove.ts +55 -0
  201. package/src/table/sort.test.ts +79 -0
  202. package/src/table/styles/builtin.ts +40 -0
  203. package/src/table/styles/differential.ts +55 -0
  204. package/src/table/styles/preset-data.ts +17 -0
  205. package/src/table/styles/presets/dark.ts +104 -0
  206. package/src/table/styles/presets/light-grid.ts +68 -0
  207. package/src/table/styles/presets/light.ts +145 -0
  208. package/src/table/styles/presets/medium-edges.ts +131 -0
  209. package/src/table/styles/presets/medium.ts +131 -0
  210. package/src/table/styles/read.ts +70 -0
  211. package/src/table/styles/types.ts +27 -0
  212. package/src/table/totals.test.ts +77 -0
  213. package/src/table/totals.ts +79 -0
  214. package/src/table/types.ts +21 -0
  215. package/src/table/write.ts +189 -0
  216. package/src/types.ts +74 -0
  217. package/src/value/date.ts +21 -0
  218. package/src/worksheet/appearance.ts +55 -0
  219. package/src/worksheet/axis.test.ts +185 -0
  220. package/src/worksheet/axis.ts +131 -0
  221. package/src/worksheet/background/read.ts +41 -0
  222. package/src/worksheet/background/roundtrip.test.ts +77 -0
  223. package/src/worksheet/background/write.ts +96 -0
  224. package/src/worksheet/cell-shift.ts +44 -0
  225. package/src/worksheet/cells.ts +75 -0
  226. package/src/worksheet/checkbox/formats.ts +53 -0
  227. package/src/worksheet/checkbox/ranges.ts +112 -0
  228. package/src/worksheet/checkbox/write.test.ts +62 -0
  229. package/src/worksheet/conditional/color-scale.ts +61 -0
  230. package/src/worksheet/conditional/data-bar.ts +76 -0
  231. package/src/worksheet/conditional/extensions.ts +95 -0
  232. package/src/worksheet/conditional/icon-reference.ts +69 -0
  233. package/src/worksheet/conditional/icon-set.test.ts +60 -0
  234. package/src/worksheet/conditional/icon-set.ts +79 -0
  235. package/src/worksheet/conditional/preview.ts +44 -0
  236. package/src/worksheet/conditional/read.ts +185 -0
  237. package/src/worksheet/conditional/text.test.ts +71 -0
  238. package/src/worksheet/conditional/text.ts +122 -0
  239. package/src/worksheet/conditional/threshold.ts +47 -0
  240. package/src/worksheet/conditional/types.ts +20 -0
  241. package/src/worksheet/conditional/write-bar.ts +66 -0
  242. package/src/worksheet/conditional/write.test.ts +218 -0
  243. package/src/worksheet/conditional/write.ts +103 -0
  244. package/src/worksheet/copied-axis.ts +70 -0
  245. package/src/worksheet/data/rows.ts +59 -0
  246. package/src/worksheet/data/source.test.ts +68 -0
  247. package/src/worksheet/data/source.ts +31 -0
  248. package/src/worksheet/data/types.ts +9 -0
  249. package/src/worksheet/data.test.ts +314 -0
  250. package/src/worksheet/dimensions/columns.ts +87 -0
  251. package/src/worksheet/dimensions/write.test.ts +110 -0
  252. package/src/worksheet/dimensions/write.ts +36 -0
  253. package/src/worksheet/filters/advanced.test.ts +57 -0
  254. package/src/worksheet/filters/color.ts +105 -0
  255. package/src/worksheet/filters/icon.test.ts +83 -0
  256. package/src/worksheet/filters/icon.ts +39 -0
  257. package/src/worksheet/filters/read.ts +114 -0
  258. package/src/worksheet/filters/relative-dates.ts +47 -0
  259. package/src/worksheet/filters/restore-icons.ts +33 -0
  260. package/src/worksheet/filters/restore.ts +169 -0
  261. package/src/worksheet/filters/rules.ts +23 -0
  262. package/src/worksheet/filters/types.ts +23 -0
  263. package/src/worksheet/filters/visibility.ts +188 -0
  264. package/src/worksheet/filters/write.ts +121 -0
  265. package/src/worksheet/formula/cache.ts +29 -0
  266. package/src/worksheet/formula/external-results.test.ts +39 -0
  267. package/src/worksheet/formula/functions.ts +29 -0
  268. package/src/worksheet/formula/prefix.ts +27 -0
  269. package/src/worksheet/formula/shared/read.test.ts +121 -0
  270. package/src/worksheet/formula/shared/read.ts +94 -0
  271. package/src/worksheet/formula/shared/references.ts +100 -0
  272. package/src/worksheet/formula/shared/types.ts +21 -0
  273. package/src/worksheet/formula/spill-read.ts +54 -0
  274. package/src/worksheet/formula/spill-write.ts +32 -0
  275. package/src/worksheet/formula/spill.test.ts +101 -0
  276. package/src/worksheet/formula/write.test.ts +26 -0
  277. package/src/worksheet/hyperlinks/location.ts +59 -0
  278. package/src/worksheet/hyperlinks/model.ts +22 -0
  279. package/src/worksheet/hyperlinks/read.ts +70 -0
  280. package/src/worksheet/hyperlinks/types.ts +21 -0
  281. package/src/worksheet/hyperlinks/write.test.ts +203 -0
  282. package/src/worksheet/hyperlinks/write.ts +51 -0
  283. package/src/worksheet/merge.test.ts +58 -0
  284. package/src/worksheet/merge.ts +61 -0
  285. package/src/worksheet/outline/columns.ts +46 -0
  286. package/src/worksheet/outline/metadata.ts +68 -0
  287. package/src/worksheet/outline/native.ts +81 -0
  288. package/src/worksheet/outline/read.ts +50 -0
  289. package/src/worksheet/outline/roundtrip.test.ts +73 -0
  290. package/src/worksheet/outline/types.ts +37 -0
  291. package/src/worksheet/outline/write.ts +110 -0
  292. package/src/worksheet/positions.test.ts +46 -0
  293. package/src/worksheet/positions.ts +48 -0
  294. package/src/worksheet/print/breaks.ts +72 -0
  295. package/src/worksheet/print/elements.ts +16 -0
  296. package/src/worksheet/print/page-text.ts +139 -0
  297. package/src/worksheet/print/setup.test.ts +141 -0
  298. package/src/worksheet/print/setup.ts +116 -0
  299. package/src/worksheet/progress/read.ts +73 -0
  300. package/src/worksheet/progress/solid.ts +26 -0
  301. package/src/worksheet/progress/types.ts +11 -0
  302. package/src/worksheet/progress/write.test.ts +63 -0
  303. package/src/worksheet/progress/write.ts +46 -0
  304. package/src/worksheet/read.ts +197 -0
  305. package/src/worksheet/rich-text.test.ts +41 -0
  306. package/src/worksheet/rich-text.ts +76 -0
  307. package/src/worksheet/sort/read.ts +115 -0
  308. package/src/worksheet/sort/relocate.ts +62 -0
  309. package/src/worksheet/sort/roundtrip.test.ts +116 -0
  310. package/src/worksheet/sort/types.ts +11 -0
  311. package/src/worksheet/sort/write.ts +77 -0
  312. package/src/worksheet/template.ts +9 -0
  313. package/src/worksheet/text.ts +33 -0
  314. package/src/worksheet/validation/extended.ts +36 -0
  315. package/src/worksheet/validation/image.ts +7 -0
  316. package/src/worksheet/validation/list-options/portable.ts +90 -0
  317. package/src/worksheet/validation/list-options/types.ts +14 -0
  318. package/src/worksheet/validation/list-options/wps.ts +51 -0
  319. package/src/worksheet/validation/read.ts +162 -0
  320. package/src/worksheet/validation/text.ts +13 -0
  321. package/src/worksheet/validation/write.test.ts +259 -0
  322. package/src/worksheet/validation/write.ts +99 -0
  323. package/src/worksheet/view/coordinates.ts +39 -0
  324. package/src/worksheet/view/named/read.ts +116 -0
  325. package/src/worksheet/view/named/roundtrip.test.ts +136 -0
  326. package/src/worksheet/view/named/sort.ts +57 -0
  327. package/src/worksheet/view/named/types.ts +15 -0
  328. package/src/worksheet/view/named/write.ts +107 -0
  329. package/src/worksheet/view/named/xml.ts +33 -0
  330. package/src/worksheet/view/panes.ts +75 -0
  331. package/src/worksheet/view/read.ts +61 -0
  332. package/src/worksheet/view/relocate.ts +57 -0
  333. package/src/worksheet/view/write.test.ts +91 -0
  334. package/src/worksheet/view/write.ts +57 -0
  335. package/src/worksheet/write.ts +86 -0
  336. package/README.md +0 -3
@@ -0,0 +1,117 @@
1
+ import { openWorkbook, parseWorkbookRange, type WorkbookSnapshot } from "@quirekit/workbook";
2
+ import { unzipSync } from "fflate";
3
+ import { expect, it } from "vitest";
4
+ import { createXlsx, createXlsxBundle, openXlsx } from "../index";
5
+
6
+ const seed: WorkbookSnapshot = { id: "assembly-file", version: 1, name: "Ledger", revision: 0, dateSystem: "1904", sheets: [
7
+ { id: "ledger", name: "Ledger <A>", cells: [
8
+ { row: 1, column: 1, input: { kind: "value", value: "Period" } },
9
+ { row: 2, column: 1, input: { kind: "value", value: "0007" } },
10
+ { row: 2, column: 2, input: { kind: "value", value: 5 } },
11
+ { row: 3, column: 1, input: { kind: "value", value: "=A1" } }
12
+ ], merges: [parseWorkbookRange("ledger", "B2:C2")],
13
+ formats: [{ row: 2, column: 2, format: { numberFormat: "yyyy-mm-dd", bold: true } }] },
14
+ { id: "archive", name: "Ledger >A<", cells: [{ row: 0, column: 0, input: { kind: "value", value: true } }], formats: [
15
+ { row: 3, column: 3, format: { numberFormat: "0.00%", background: "#DEADBA" } }
16
+ ] },
17
+ { id: "other", name: "Unaffected", cells: [{ row: 8, column: 4, input: { kind: "value", value: 6 } }] }
18
+ ] };
19
+
20
+ it("creates standalone XLSX entries with stable safe names, typed values, dates, formats and complete merges", async () => {
21
+ const workbook = await openWorkbook(seed, { isEditable: () => false });
22
+ const target = parseWorkbookRange("ledger", "B2:C4");
23
+ try {
24
+ expect(() => workbook.tableAssemblyCopies(target, { kind: "copyWorksheetTables", options: {
25
+ sources: [{ sheetId: "ledger", range: "B2:B4" }]
26
+ } })).toThrow(/whole merged area/u);
27
+ const copies = workbook.tableAssemblyCopies(target, { kind: "copyWorksheetTables", options: {
28
+ sources: [{ sheetId: "ledger", range: "B2:C4" }, { sheetId: "archive", range: "A1" }]
29
+ } });
30
+ const files = unzipSync(createXlsxBundle(copies));
31
+ expect(Object.keys(files)).toEqual(["Ledger A.xlsx", "Ledger A (2).xlsx"]);
32
+ const file = openXlsx("Split", files["Ledger A.xlsx"]!);
33
+ const first = file.snapshot.sheets[0]!;
34
+ expect(file.snapshot.dateSystem).toBe("1904");
35
+ expect(first.merges).toMatchObject([parseWorkbookRange(first.id, "A1:B1")]);
36
+ expect(first.cells).toContainEqual({ row: 1, column: 0, input: { kind: "value", value: "0007" } });
37
+ expect(first.cells).toContainEqual({ row: 1, column: 1, input: { kind: "value", value: 5 } });
38
+ expect(first.cells).toContainEqual({ row: 2, column: 0, input: { kind: "value", value: "=A1" } });
39
+ const styleId = file.appearance.sheets.get(first.id)?.cellStyles[1]?.[1] ?? -1;
40
+ expect(file.appearance.styles[styleId]).toMatchObject({ numberFormat: "yyyy-mm-dd", bold: true });
41
+ expect(openXlsx("Copy", files["Ledger A (2).xlsx"]!).snapshot.sheets[0]?.cells[0]?.input).toEqual({ kind: "value", value: true });
42
+ expect(workbook.revision).toBe(0);
43
+ } finally { await workbook.close(); }
44
+ });
45
+
46
+ it("round-trips overwritten imported formatting while leaving unrelated worksheet parts intact", async () => {
47
+ const bytes = createXlsx(seed);
48
+ const file = openXlsx("Ledger", bytes);
49
+ const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
50
+ const [ledger, archive, other] = workbook.worksheets().map(sheet => sheet.id);
51
+ const target = parseWorkbookRange(ledger!, "B3");
52
+ try {
53
+ const edit = workbook.prepare({ operationId: "merge-import", baseRevision: 0, commands: [{ name: "mergeTables", target, params: {
54
+ headers: 0, sources: [{ sheetId: ledger, range: "B3" }, { sheetId: archive, range: "A1" }],
55
+ destination: { kind: "range", sheetId: archive, start: "D4" }
56
+ } }] });
57
+ await workbook.commit(edit.id);
58
+ const saved = file.write(workbook.snapshot());
59
+ expect(unzipSync(saved)["xl/worksheets/sheet3.xml"]).toEqual(unzipSync(bytes)["xl/worksheets/sheet3.xml"]);
60
+ const reopened = openXlsx("Ledger", saved);
61
+ const readable = await openWorkbook(reopened.snapshot, { appearance: reopened.appearance });
62
+ try {
63
+ const address = { sheetId: archive!, row: 3, column: 3 };
64
+ expect(readable.readCell(address).input).toEqual({ kind: "value", value: "0007" });
65
+ expect(readable.readCell({ ...address, row: 4 }).input).toEqual({ kind: "value", value: true });
66
+ expect(["General", undefined]).toContain(readable.readFormat(address).numberFormat);
67
+ expect(readable.readFormat(address).background).toBeUndefined();
68
+ expect(readable.sheetName(other!)).toBe("Unaffected");
69
+ expect(reopened.snapshot.dateSystem).toBe("1904");
70
+ } finally { await readable.close(); }
71
+ await workbook.undo("undo-xlsx-combine");
72
+ expect(file.write(workbook.snapshot())).toEqual(bytes);
73
+ } finally { await workbook.close(); }
74
+ });
75
+
76
+ it("reopens saved merge settings on the serialized worksheet IDs and writes a refreshed result in place", async () => {
77
+ const file = openXlsx("Ledger", createXlsx(seed));
78
+ const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
79
+ const [ledger, archive] = workbook.worksheets().map(({ id }) => id);
80
+ let saved: Uint8Array;
81
+ try {
82
+ const candidate = workbook.prepare({ operationId: "save-merge", baseRevision: 0, commands: [{
83
+ name: "mergeTables", target: parseWorkbookRange(ledger!, "B3"), params: {
84
+ headers: 0, followSourceRows: true, sourceColumn: "原始 <表>", sources: [{ sheetId: ledger, range: "B3" }, { sheetId: archive, range: "A1" }],
85
+ destination: { kind: "sheet", name: "合并结果" }
86
+ }
87
+ }] });
88
+ await workbook.commit(candidate.id);
89
+ saved = file.write(workbook.snapshot());
90
+ } finally { await workbook.close(); }
91
+
92
+ const reopened = openXlsx("Ledger", saved);
93
+ const combined = reopened.snapshot.sheets.find(sheet => sheet.name === "合并结果")!;
94
+ expect(reopened.snapshot.tableMergeRecipes).toEqual([{
95
+ output: parseWorkbookRange(combined.id, "A1:B2"),
96
+ options: { headers: 0, followSourceRows: true, sourceColumn: "原始 <表>",
97
+ sources: [{ sheetId: ledger, range: "B3" }, { sheetId: archive, range: "A1" }] }
98
+ }]);
99
+ expect(reopened.write(reopened.snapshot)).toEqual(saved);
100
+
101
+ const session = await openWorkbook(reopened.snapshot, { appearance: reopened.appearance });
102
+ try {
103
+ const target = parseWorkbookRange(combined.id, "A1");
104
+ const candidate = session.prepare({ operationId: "refresh-reopened", baseRevision: 0, commands: [
105
+ { name: "setCells", target: parseWorkbookRange(archive!, "A2"), params: { value: 125 } },
106
+ { name: "remergeTables", target, params: { overwrite: true } }
107
+ ] });
108
+ await session.commit(candidate.id);
109
+ const result = openXlsx("Ledger", reopened.write(session.snapshot())).snapshot;
110
+ expect(result.sheets.find(({ id }) => id === combined.id)?.cells).toEqual(expect.arrayContaining([
111
+ { row: 0, column: 0, input: { kind: "value", value: "0007" } },
112
+ { row: 2, column: 0, input: { kind: "value", value: true } },
113
+ { row: 3, column: 0, input: { kind: "value", value: 125 } }
114
+ ]));
115
+ expect(result.tableMergeRecipes?.[0]?.output).toEqual(parseWorkbookRange(combined.id, "A1:B4"));
116
+ } finally { await session.close(); }
117
+ });
@@ -0,0 +1,85 @@
1
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
2
+ import { type WorkbookSnapshot } from "@quirekit/workbook";
3
+ import { expect, it } from "vitest";
4
+ import { createXlsx, openXlsx } from "../index";
5
+
6
+ const seed: WorkbookSnapshot = { version: 1, revision: 0, id: "iterations", name: "Costs", sheets: [
7
+ { id: "cost", name: "Cost", cells: [{ row: 0, column: 0, input: { kind: "formula", formula: "=(A1+4)/2" } }] }
8
+ ] };
9
+ const workbook = "xl/workbook.xml";
10
+ const worksheet = "xl/worksheets/sheet1.xml";
11
+
12
+ it("imports native iteration attributes and keeps unrelated calculation attributes and the new cache", () => {
13
+ const parts = unzipSync(createXlsx(seed));
14
+ parts[workbook] = strToU8(strFromU8(parts[workbook]!).replace("<calcPr ", '<calcPr calcId="191029" refMode="A1" iterate="true" iterateCount="25" iterateDelta="1e-5" '));
15
+ const bytes = zipSync(parts);
16
+ const source = openXlsx("Costs", bytes);
17
+ expect(source.restrictions).toEqual([]);
18
+ expect(source.snapshot.calculationSettings).toEqual({ iterativeCalculation: true, maxIterations: 25, maxChange: 0.00001 });
19
+ expect(source.write(source.snapshot)).toEqual(bytes);
20
+
21
+ const settings = { iterativeCalculation: false, maxIterations: 10, maxChange: 0.002 };
22
+ const output = source.write({ ...source.snapshot, calculationSettings: settings }, { result: () => ({ status: "value", value: 0 }) });
23
+ const saved = unzipSync(output);
24
+ expect(strFromU8(saved[workbook]!)).toContain('calcId="191029" refMode="A1" iterate="0" iterateCount="10" iterateDelta="0.002"');
25
+ expect(strFromU8(saved[worksheet]!)).toContain("<f>(A1+4)/2</f><v>0</v>");
26
+ expect(openXlsx("Costs", output).snapshot.calculationSettings).toEqual(settings);
27
+ });
28
+
29
+ it.each(['iterate="1" iterateDelta="0"', 'iterate="1" iterateCount="32768"', 'iterate="true" iterateDelta="INF"'])(
30
+ "retains the full source when iteration options are outside the calculation engine scope: %s", attributes => {
31
+ const parts = unzipSync(createXlsx(seed));
32
+ parts[workbook] = strToU8(strFromU8(parts[workbook]!).replace("<calcPr ", `<calcPr ${attributes} `));
33
+ const bytes = zipSync(parts);
34
+ const source = openXlsx("Costs", bytes);
35
+ expect(source.restrictions).toContain("迭代计算参数含暂未支持的值");
36
+ expect(source.original()).toEqual(bytes);
37
+ });
38
+
39
+ it("writes a formula-result-only revision with native caches and honors its completed calculation on reopen", () => {
40
+ const file = createXlsx(seed, { result: () => ({ status: "value", value: 0 }) });
41
+ const source = openXlsx("Costs", file);
42
+ expect(source.snapshot.formulaResults).toBeUndefined();
43
+ const address = { sheetId: source.snapshot.sheets[0]!.id, row: 0, column: 0 };
44
+ const output = source.write({ ...source.snapshot, revision: 1, formulaResults: [
45
+ { ...address, result: { status: "value", value: 3.9990234375 } }
46
+ ] });
47
+ const parts = unzipSync(output);
48
+ expect(strFromU8(parts[workbook]!)).toMatch(/<calcPr [^>]*fullCalcOnLoad="0"[^>]*calcCompleted="1"/u);
49
+ expect(strFromU8(parts[worksheet]!)).toContain("<f>(A1+4)/2</f><v>3.9990234375</v>");
50
+ const loaded = openXlsx("Costs", output);
51
+ expect(loaded.snapshot.formulaResults).toMatchObject([{ row: 0, column: 0, result: { status: "value", value: 3.9990234375 } }]);
52
+ expect(loaded.write(loaded.snapshot)).toEqual(output);
53
+
54
+ parts[workbook] = strToU8(strFromU8(parts[workbook]!).replace('calcCompleted="1"', 'calcCompleted="1" forceFullCalc="1"'));
55
+ expect(openXlsx("Costs", zipSync(parts)).snapshot.formulaResults).toBeUndefined();
56
+ });
57
+
58
+ it("reads native manual mode and preserves stale values, unavailable results and the original calculation flags", () => {
59
+ const parts = unzipSync(createXlsx(seed, { result: () => ({ status: "value", value: 0 }) }));
60
+ parts[workbook] = strToU8(strFromU8(parts[workbook]!).replace(
61
+ '<calcPr fullCalcOnLoad="1"', '<calcPr calcMode="manual" calcOnSave="1" calcCompleted="0" fullCalcOnLoad="0"'));
62
+ const bytes = zipSync(parts);
63
+ const incoming = openXlsx("Costs", bytes);
64
+ expect(incoming.restrictions).toEqual([]);
65
+ expect(incoming.snapshot).toMatchObject({ calculationSettings: { mode: "manual" }, formulaPendingRevision: 0,
66
+ formulaResults: [{ row: 0, column: 0, result: { status: "value", value: 0 } }] });
67
+ expect(incoming.write(incoming.snapshot)).toEqual(bytes);
68
+
69
+ const sheet = incoming.snapshot.sheets[0]!;
70
+ const pending = incoming.write({ ...incoming.snapshot, revision: 1, formulaPendingRevision: 1,
71
+ sheets: [{ ...sheet, cells: [...sheet.cells, { row: 1, column: 0, input: { kind: "formula", formula: "=A1+1" } }] }],
72
+ formulaResults: [...incoming.snapshot.formulaResults!, { sheetId: sheet.id, row: 1, column: 0, result: { status: "unavailable" } }] });
73
+ const saved = unzipSync(pending);
74
+ expect(strFromU8(saved[workbook]!)).toContain('calcMode="manual" calcOnSave="0" calcCompleted="0" fullCalcOnLoad="0"');
75
+ expect(strFromU8(saved[worksheet]!)).toContain("<f>A1+1</f>");
76
+ const reopened = openXlsx("Costs", pending);
77
+ expect(reopened.snapshot.formulaPendingRevision).toBe(0);
78
+ expect(reopened.snapshot.formulaResults?.map(entry => entry.result)).toEqual([{ status: "value", value: 0 }, { status: "unavailable" }]);
79
+
80
+ const automatic = incoming.write({ ...incoming.snapshot, revision: 1, formulaPendingRevision: undefined, calculationSettings: undefined });
81
+ const metadata = strFromU8(unzipSync(automatic)[workbook]!);
82
+ expect(metadata).toContain('calcMode="auto"');
83
+ expect(metadata).not.toContain("calcOnSave=");
84
+ expect(openXlsx("Costs", automatic).snapshot.calculationSettings).toBeUndefined();
85
+ });
@@ -0,0 +1,88 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { copyWorkbookCalculationSettings, defaultWorkbookCalculationSettings, sameWorkbookCalculationSettings,
3
+ type WorkbookCalculationSettings } from "@quirekit/workbook";
4
+ import { hasKnownAttributes, hasKnownChildren } from "../opc/shape";
5
+ import { child, children, spreadNs } from "../opc/xml";
6
+
7
+ const calculationFeaturesUri = "{B58B0392-4F1F-4190-BB64-5DF3571DCE5F}";
8
+ const calculationFeaturesNs = "http://schemas.microsoft.com/office/spreadsheetml/2018/calcfeatures";
9
+
10
+ /** @param settings - Native calculation properties. @param name - Boolean attribute. @returns Its explicit true value. */
11
+ function enabled(settings: Element, name: string): boolean {
12
+ return /^(?:1|true)$/u.test(settings.getAttribute(name)?.trim() ?? "");
13
+ }
14
+
15
+ /** @param workbook - The workbook root. @returns Whether the producer explicitly saved a completed calculation without a full calculation on load. */
16
+ export function hasRetainedXlsxCalculation(workbook: Element): boolean {
17
+ const settings = child(workbook, "calcPr");
18
+ return !!settings && enabled(settings, "calcCompleted")
19
+ && /^(?:0|false)$/u.test(settings.getAttribute("fullCalcOnLoad")?.trim() ?? "")
20
+ && !enabled(settings, "forceFullCalc");
21
+ }
22
+
23
+ /** @param workbook - Workbook containing manual calculation settings. @returns Whether the source declares a calculation still needed. */
24
+ export function xlsxCalculationIsPending(workbook: Element): boolean {
25
+ const settings = child(workbook, "calcPr");
26
+ return !!settings && (/^(?:0|false)$/u.test(settings.getAttribute("calcCompleted")?.trim() ?? "")
27
+ || enabled(settings, "fullCalcOnLoad") || enabled(settings, "forceFullCalc"));
28
+ }
29
+
30
+ /** @param workbook - The workbook root. @param restrictions - Import diagnostics for settings the evaluator cannot use.
31
+ * @returns Supported native calculation options. */
32
+ export function readXlsxCalculationSettings(workbook: Element, restrictions: Set<string>): WorkbookCalculationSettings | undefined {
33
+ const node = child(workbook, "calcPr");
34
+ if (!node) return undefined;
35
+ const attribute = (name: string) => node.hasAttribute(name) ? (node.getAttribute(name) ?? "").trim() : undefined;
36
+ const mode = attribute("calcMode");
37
+ if (mode !== undefined && !["auto", "manual", "autoNoTable"].includes(mode)) restrictions.add("工作簿计算模式含未知值");
38
+ const iterate = attribute("iterate") ?? "0";
39
+ const count = attribute("iterateCount") ?? String(defaultWorkbookCalculationSettings.maxIterations);
40
+ const delta = attribute("iterateDelta") ?? String(defaultWorkbookCalculationSettings.maxChange);
41
+ try {
42
+ const settings = copyWorkbookCalculationSettings({
43
+ iterativeCalculation: iterate === "1" || iterate === "true",
44
+ maxIterations: /^\+?\d+$/u.test(count) ? Number(count) : NaN,
45
+ maxChange: /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$/u.test(delta) ? Number(delta) : NaN,
46
+ ...(mode === "manual" && { mode })
47
+ });
48
+ if (["0", "1", "false", "true"].includes(iterate)) {
49
+ return settings === defaultWorkbookCalculationSettings ? undefined : settings;
50
+ }
51
+ } catch {
52
+ // Keep unsupported calculation attributes in the downloadable source package.
53
+ }
54
+ restrictions.add("迭代计算参数含暂未支持的值");
55
+ return mode === "manual" ? copyWorkbookCalculationSettings({ ...defaultWorkbookCalculationSettings, mode }) : undefined;
56
+ }
57
+
58
+ /** @param element - Native calculation properties. @param settings - Current calculation options.
59
+ * @param baseline - Options read from the source package. */
60
+ export function writeXlsxCalculationSettings(element: Element, settings = defaultWorkbookCalculationSettings,
61
+ baseline = defaultWorkbookCalculationSettings): void {
62
+ const current = copyWorkbookCalculationSettings(settings);
63
+ if (current.mode === "manual") {
64
+ element.setAttribute("calcMode", "manual");
65
+ element.setAttribute("calcOnSave", "0");
66
+ } else if (baseline.mode === "manual") {
67
+ element.setAttribute("calcMode", "auto");
68
+ element.removeAttribute("calcOnSave");
69
+ }
70
+ if (sameWorkbookCalculationSettings({ ...current, mode: undefined }, { ...baseline, mode: undefined })) return;
71
+ element.setAttribute("iterate", current.iterativeCalculation ? "1" : "0");
72
+ element.setAttribute("iterateCount", String(current.maxIterations));
73
+ element.setAttribute("iterateDelta", String(current.maxChange));
74
+ }
75
+
76
+ /** @param extension - Native workbook extension. @returns Whether it is a known calculation engine signature. */
77
+ export function isXlsxCalculationMetadata(extension: Element): boolean {
78
+ const features = child(extension, "calcFeatures");
79
+ if (!features || extension.namespaceURI !== spreadNs || extension.localName !== "ext"
80
+ || extension.getAttribute("uri")?.toUpperCase() !== calculationFeaturesUri
81
+ || !hasKnownAttributes(extension, ["uri"]) || !hasKnownChildren(extension, ["calcFeatures"], calculationFeaturesNs)
82
+ || !hasKnownAttributes(features, [])) return false;
83
+ const entries = children(features);
84
+ // This version signature owns no formulas, cell metadata or related parts. The writer
85
+ // keeps it verbatim and separately requests full recalculation on the next open.
86
+ return entries.length > 0 && entries.every(feature => feature.namespaceURI === calculationFeaturesNs && feature.localName === "feature"
87
+ && Boolean(feature.getAttribute("name")) && hasKnownAttributes(feature, ["name"]) && hasKnownChildren(feature, []));
88
+ }
@@ -0,0 +1,37 @@
1
+ import { strToU8 } from "fflate";
2
+ import { relationshipsPath } from "../opc/relationships";
3
+ import { children, contentTypeNs, packageRelationshipNs, parsePart, rootOf, writePart } from "../opc/xml";
4
+ import { checkboxFeatureXml, featurePropertyContentType, featurePropertyRelationship } from "../styles/checkbox/bags";
5
+ import type { XlsxPackage } from "./types";
6
+
7
+ /** @param source - Package and recognized source graph. @param parts - Output archive.
8
+ * @returns Usable native checkbox XF complement mapper index. */
9
+ export function registerXlsxCheckboxes(source: XlsxPackage, parts: Record<string, Uint8Array>): number {
10
+ if (source.checkboxStyles) return source.checkboxStyles.complement;
11
+ const directory = source.workbookPath.slice(0, source.workbookPath.lastIndexOf("/") + 1);
12
+ let target = "featurePropertyBag/featurePropertyBag.xml";
13
+ for (let suffix = 2; parts[directory + target]; suffix++) target = `featurePropertyBag/featurePropertyBag${suffix}.xml`;
14
+ const path = directory + target;
15
+ const relPath = relationshipsPath(source.workbookPath);
16
+ const rels = parsePart(parts[relPath], relPath);
17
+ const root = rootOf(rels, packageRelationshipNs, "Relationships");
18
+ const used = new Set(children(root).map(relation => relation.getAttribute("Id")));
19
+ let serial = 1;
20
+ while (used.has(`rId${serial}`)) serial++;
21
+ const relationship = rels.createElementNS(packageRelationshipNs, "Relationship");
22
+ relationship.setAttribute("Id", `rId${serial}`);
23
+ relationship.setAttribute("Type", featurePropertyRelationship);
24
+ relationship.setAttribute("Target", target);
25
+ root.appendChild(relationship);
26
+ parts[relPath] = writePart(rels);
27
+
28
+ const types = parsePart(parts["[Content_Types].xml"], "[Content_Types].xml");
29
+ const content = rootOf(types, contentTypeNs, "Types");
30
+ const override = types.createElementNS(contentTypeNs, "Override");
31
+ override.setAttribute("PartName", "/" + path);
32
+ override.setAttribute("ContentType", featurePropertyContentType);
33
+ content.appendChild(override);
34
+ parts["[Content_Types].xml"] = writePart(types);
35
+ parts[path] = strToU8(checkboxFeatureXml);
36
+ return 0;
37
+ }
@@ -0,0 +1,61 @@
1
+ import { unzipSync } from "fflate";
2
+ import { openWorkbook, parseWorkbookRange, type WorkbookSnapshot } from "@quirekit/workbook";
3
+ import { expect, it } from "vitest";
4
+ import { createXlsx, openXlsx } from "../index";
5
+
6
+ const original: WorkbookSnapshot = {
7
+ id: "raw", name: "Orders", version: 1, revision: 0, dateSystem: "1904",
8
+ sheets: [
9
+ { id: "orders", name: "Orders", cells: [
10
+ { row: 0, column: 0, input: { kind: "value", value: "Order" } },
11
+ { row: 1, column: 0, input: { kind: "value", value: "Invoice" } },
12
+ { row: 2, column: 0, input: { kind: "value", value: "Invoice" } },
13
+ { row: 3, column: 0, input: { kind: "value", value: "Service" } },
14
+ { row: 3, column: 1, input: { kind: "value", value: 0.35 } },
15
+ { row: 2, column: 2, input: { kind: "value", value: "outside" } },
16
+ { row: 1, column: 3, input: { kind: "value", value: "0007|1904-01-02|=A1" } },
17
+ { row: 2, column: 3, input: { kind: "value", value: "0088|1904-01-03|=A2" } },
18
+ { row: 3, column: 4, input: { kind: "value", value: "9 100,25" } }
19
+ ], formats: [{ row: 3, column: 1, format: { bold: true, numberFormat: "0.0%" } }] },
20
+ { id: "output", name: "Output", cells: [] },
21
+ { id: "other", name: "Untouched", cells: [{ row: 0, column: 0, input: { kind: "value", value: 7 } }] }
22
+ ]
23
+ };
24
+
25
+ it("round-trips compacted native styles, converted numbers and newly formatted dates through XLSX", async () => {
26
+ const bytes = createXlsx(original);
27
+ const file = openXlsx("Orders", bytes);
28
+ const book = await openWorkbook(file.snapshot, { appearance: file.appearance, sortRestrictions: file.sortRestrictions });
29
+ try {
30
+ const orders = book.worksheets()[0]!.id, output = book.worksheets()[1]!.id;
31
+ const edit = book.prepare({ operationId: "clean-imported-sheet", baseRevision: 0, commands: [
32
+ { name: "deduplicateRows", target: parseWorkbookRange(orders, "A1:B4"), params: { columns: ["A"], header: true } },
33
+ { name: "splitTextToColumns", target: parseWorkbookRange(orders, "D2:D3"), params: {
34
+ mode: { type: "delimited", delimiters: ["|"] }, columns: [{ column: 1, type: "dateYmd" }],
35
+ destination: { sheetId: output, cell: "A2" }
36
+ } },
37
+ { name: "convertTextToNumbers", target: parseWorkbookRange(orders, "E4"), params: { decimal: "comma", grouping: "space" } }
38
+ ] });
39
+ expect(edit.cleanupEffects?.map(effect => effect.kind)).toEqual(["deduplicateRows", "splitTextToColumns", "convertTextToNumbers"]);
40
+ const receipt = await book.commit(edit.id);
41
+ expect(receipt.sortedRanges).toBeUndefined();
42
+ const saved = file.write(book.snapshot());
43
+ expect(unzipSync(saved)["xl/worksheets/sheet3.xml"]).toEqual(unzipSync(bytes)["xl/worksheets/sheet3.xml"]);
44
+
45
+ const reopened = openXlsx("Orders", saved);
46
+ expect(reopened.restrictions).toEqual([]);
47
+ const readable = await openWorkbook(reopened.snapshot, { appearance: reopened.appearance });
48
+ try {
49
+ expect(readable.readCell({ sheetId: orders, row: 2, column: 1 }).input).toEqual({ kind: "value", value: 0.35 });
50
+ expect(readable.readFormat({ sheetId: orders, row: 2, column: 1 })).toMatchObject({ bold: true, numberFormat: "0.0%" });
51
+ expect(readable.readCell({ sheetId: orders, row: 2, column: 2 }).input).toEqual({ kind: "value", value: "outside" });
52
+ expect(readable.readCell({ sheetId: orders, row: 3, column: 4 }).input).toEqual({ kind: "value", value: 9100.25 });
53
+ expect(readable.readCell({ sheetId: output, row: 1, column: 0 }).input).toEqual({ kind: "value", value: "0007" });
54
+ expect(readable.readCell({ sheetId: output, row: 1, column: 1 }).input).toEqual({ kind: "value", value: 1 });
55
+ expect(readable.readFormat({ sheetId: output, row: 1, column: 1 }).numberFormat).toBe("yyyy-mm-dd");
56
+ expect(readable.readCell({ sheetId: output, row: 1, column: 2 }).input).toEqual({ kind: "value", value: "=A1" });
57
+ } finally { await readable.close(); }
58
+ await book.undo("undo-cleanup");
59
+ expect(file.write(book.snapshot())).toEqual(bytes);
60
+ } finally { await book.close(); }
61
+ });
@@ -0,0 +1,53 @@
1
+ import { expect, it } from "vitest";
2
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
3
+ import { openWorkbook, parseWorkbookRange, readWorkbookDashboard, type WorkbookSnapshot } from "@quirekit/workbook";
4
+ import { createXlsx, openXlsx } from "../index";
5
+
6
+ const snapshot: WorkbookSnapshot = {
7
+ version: 1, revision: 0, id: "dashboard-native-sample", name: "合成金额",
8
+ sheets: [
9
+ { id: "orders", name: "金额", cells: [
10
+ { row: 0, column: 0, input: { kind: "value", value: "应收" } }, { row: 1, column: 0, input: { kind: "value", value: 17 } }
11
+ ] },
12
+ { id: "board", name: "报表", cells: [], dashboard: {
13
+ components: [{ id: "00000000-0000-4000-8000-000000001244", kind: "metric", title: "应收账款", source: { sheetId: "orders", range: "A1:A2" },
14
+ measure: { kind: "field", field: 0, aggregate: "sum" }, width: "half" }]
15
+ } }
16
+ ]
17
+ };
18
+
19
+ it("keeps live dashboard data bindings and writes board-only settings into the native workbook part", async () => {
20
+ const original = createXlsx(snapshot);
21
+ const file = openXlsx("仪表盘", original);
22
+ expect(file.restrictions).toEqual([]);
23
+ const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
24
+ try {
25
+ const [source, target] = workbook.worksheets();
26
+ expect(target?.dashboard?.components[0]).toMatchObject({ source: { sheetId: source!.id, range: "A1:A2" }, width: "half" });
27
+ await workbook.commit(workbook.prepare({ operationId: "edit-dashboard-settings", baseRevision: workbook.revision, commands: [{
28
+ name: "updateDashboard", target: parseWorkbookRange(target!.id, "A1"), params: { title: "应收总览", theme: "jade" }
29
+ }] }).id);
30
+ const saved = openXlsx("仪表盘", file.write(workbook.snapshot()));
31
+ expect(saved.restrictions).toEqual([]);
32
+ expect(saved.snapshot.sheets[1]?.dashboard).toMatchObject({ title: "应收总览", theme: "jade" });
33
+ const reopened = await openWorkbook(saved.snapshot, { appearance: saved.appearance });
34
+ try {
35
+ const dashboard = reopened.worksheets()[1]!.dashboard!;
36
+ expect(readWorkbookDashboard(dashboard, { read: reopened.readCell })[0]?.data).toEqual({ kind: "metric", value: 17 });
37
+ } finally { await reopened.close(); }
38
+ } finally { await workbook.close(); }
39
+ });
40
+
41
+ it("preserves the original bytes when a newer or malformed dashboard definition cannot be edited", () => {
42
+ const parts = unzipSync(createXlsx(snapshot));
43
+ const path = "xl/workbook.xml";
44
+ const xml = strFromU8(parts[path]!);
45
+ const malformed = xml.replace(/(<qkd:dashboards\b[^>]*>)[\s\S]+?(<\/qkd:dashboards>)/u, "$1{}$2");
46
+ expect(malformed).not.toBe(xml);
47
+ parts[path] = strToU8(malformed);
48
+ const original = zipSync(parts);
49
+ const file = openXlsx("未知仪表盘", original);
50
+ expect(file.restrictions).toContain("仪表盘的配置无法读取");
51
+ expect(file.snapshot.sheets.every(sheet => !sheet.dashboard)).toBe(true);
52
+ expect(file.write(file.snapshot)).toEqual(original);
53
+ });
@@ -0,0 +1,84 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { copyWorkbookDashboard, sameWorkbookDashboard, type WorkbookDashboard, type WorkbookWorksheetIdentity } from "@quirekit/workbook";
3
+ import { hasKnownAttributes, hasKnownChildren } from "../opc/shape";
4
+ import { child, children, relationshipNs, spreadNs } from "../opc/xml";
5
+
6
+ const namespace = "urn:quirekit:spreadsheet:dashboard:1";
7
+
8
+ /** @param entry - Workbook extension. @returns Whether it belongs to the versioned dashboard codec. */
9
+ export function isXlsxDashboardExtension(entry: Element): boolean {
10
+ const body = child(entry, "dashboards");
11
+ return entry.namespaceURI === spreadNs && entry.localName === "ext" && entry.getAttribute("uri") === namespace
12
+ && hasKnownAttributes(entry, ["uri"]) && hasKnownChildren(entry, ["dashboards"], namespace)
13
+ && Boolean(body && hasKnownAttributes(body, []) && !children(body).length);
14
+ }
15
+
16
+ /** @param workbook - Native workbook properties. @param directory - Resolved native sheet IDs.
17
+ * @returns Validated boards or null if the original metadata must be retained untouched. */
18
+ export function readXlsxDashboards(workbook: Element, directory: readonly WorkbookWorksheetIdentity[]): ReadonlyMap<string, WorkbookDashboard> | null {
19
+ const extensions = child(workbook, "extLst");
20
+ const entries = extensions ? children(extensions).filter(isXlsxDashboardExtension) : [];
21
+ const result = new Map<string, WorkbookDashboard>();
22
+ if (!entries.length) return result;
23
+ try {
24
+ if (entries.length !== 1) return null;
25
+ const records: { sheetId: string; dashboard: WorkbookDashboard }[] = JSON.parse(child(entries[0]!, "dashboards")?.textContent ?? "");
26
+ if (!Array.isArray(records) || records.length > directory.length || records.some(entry => !entry || typeof entry.sheetId !== "string")) return null;
27
+ const owners = new Set(records.map(record => record.sheetId));
28
+ if (owners.size !== records.length) return null;
29
+ const ordinarySheets = directory.filter(sheet => !owners.has(sheet.id));
30
+ const sheetIds = new Set(directory.map(sheet => sheet.id));
31
+ for (const { sheetId, dashboard } of records) {
32
+ if (!sheetIds.has(sheetId)) continue;
33
+ const components = dashboard.components.map(component => component.kind !== "text" && component.source
34
+ && !sheetIds.has(component.source.sheetId) ? { ...component, source: null } : component);
35
+ result.set(sheetId, copyWorkbookDashboard({ ...dashboard, components }, ordinarySheets, sheetId));
36
+ }
37
+ return result;
38
+ } catch { return null; }
39
+ }
40
+
41
+ /** @param before - File checkpoint. @param after - Proposed snapshot. @returns Whether the same boards can be preserved verbatim. */
42
+ export function sameXlsxDashboards(before: readonly WorkbookWorksheetIdentity[] = [], after: readonly WorkbookWorksheetIdentity[]): boolean {
43
+ const previous = new Map(before.filter(sheet => sheet.dashboard).map(sheet => [sheet.id, sheet.dashboard!]));
44
+ const next = after.filter(sheet => sheet.dashboard);
45
+ return previous.size === next.length && next.every(sheet => sameWorkbookDashboard(previous.get(sheet.id), sheet.dashboard));
46
+ }
47
+
48
+ /** @param workbook - Staged native workbook directory. @param worksheets - Worksheet identities in file order. */
49
+ export function writeXlsxDashboards(workbook: Element, worksheets: readonly WorkbookWorksheetIdentity[]): void {
50
+ let list = child(workbook, "extLst");
51
+ if (list) for (const entry of children(list).filter(isXlsxDashboardExtension)) list.removeChild(entry);
52
+ const owners = worksheets.filter(sheet => sheet.dashboard);
53
+ if (!owners.length) {
54
+ if (list && !children(list).length) workbook.removeChild(list);
55
+ return;
56
+ }
57
+ // Preserve links across renames and native directory allocation by storing file IDs,
58
+ // which QuireKit resolves back to its source identities when opening a saved file.
59
+ const sheets = children(child(workbook, "sheets")!, "sheet");
60
+ const native = new Map(worksheets.map(({ id }, index) => {
61
+ const sheet = sheets[index]!;
62
+ return [id, sheet.getAttribute("sheetId") || sheet.getAttributeNS(relationshipNs, "id")!];
63
+ }));
64
+ const data = owners.map(sheet => ({
65
+ sheetId: native.get(sheet.id),
66
+ dashboard: { ...sheet.dashboard!, components: sheet.dashboard!.components.map(component => {
67
+ if (component.kind === "text" || !component.source) return component;
68
+ const sheetId = native.get(component.source.sheetId);
69
+ if (!sheetId) throw new Error("仪表盘的数据源不在当前工作簿中。");
70
+ return { ...component, source: { ...component.source, sheetId } };
71
+ }) }
72
+ }));
73
+ const document = workbook.ownerDocument!;
74
+ if (!list) {
75
+ list = document.createElementNS(spreadNs, "extLst");
76
+ workbook.appendChild(list);
77
+ }
78
+ const entry = document.createElementNS(spreadNs, "ext");
79
+ entry.setAttribute("uri", namespace);
80
+ const body = document.createElementNS(namespace, "qkd:dashboards");
81
+ body.appendChild(document.createTextNode(JSON.stringify(data)));
82
+ entry.appendChild(body);
83
+ list.appendChild(entry);
84
+ }
@@ -0,0 +1,16 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { hasKnownAttributes } from "../opc/shape";
3
+ import { child, children, spreadNs } from "../opc/xml";
4
+ import { isXlsxCalculationMetadata } from "./calculation-metadata";
5
+ import { isXlsxDashboardExtension } from "./dashboard";
6
+ import { isXlsxMergeRecipeExtension } from "./merge-recipes";
7
+
8
+ /** @param workbook - Native workbook metadata. @returns Whether each extension has a known, nonoverlapping owner. */
9
+ export function hasKnownWorkbookExtensions(workbook: Element): boolean {
10
+ const list = child(workbook, "extLst");
11
+ if (!list) return true;
12
+ const entries = children(list);
13
+ if (list.namespaceURI !== spreadNs || !hasKnownAttributes(list, []) || !entries.length) return false;
14
+ const kinds = entries.map(entry => isXlsxCalculationMetadata(entry) ? "calculation" : isXlsxMergeRecipeExtension(entry) ? "merge" : isXlsxDashboardExtension(entry) ? "dashboard" : null);
15
+ return !kinds.includes(null) && new Set(kinds).size === kinds.length;
16
+ }
@@ -0,0 +1,84 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { copyWorkbookMergeRecipe, sameWorkbookMergeRecipe, type WorkbookMergeRecipe, type WorkbookWorksheetIdentity } from "@quirekit/workbook";
3
+ import { hasKnownAttributes, hasKnownChildren } from "../opc/shape";
4
+ import { child, children, relationshipNs, spreadNs } from "../opc/xml";
5
+
6
+ const namespace = "urn:quirekit:spreadsheet:merge-recipes:1";
7
+
8
+ /** @param node - Member of the workbook extension list. @returns Whether this codec owns it. */
9
+ export function isXlsxMergeRecipeExtension(node: Element): boolean {
10
+ const body = child(node, "recipes");
11
+ return node.namespaceURI === spreadNs && node.localName === "ext" && node.getAttribute("uri") === namespace
12
+ && hasKnownAttributes(node, ["uri"]) && hasKnownChildren(node, ["recipes"], namespace)
13
+ && Boolean(body && hasKnownAttributes(body, []) && !children(body).length);
14
+ }
15
+
16
+ /** @param workbook - Original sheet directory and extension list. @param directory - Resolved XLSX worksheet identities.
17
+ * @returns Safe associations for existing result sheets. Malformed or stale settings leave the native data accessible. */
18
+ export function readXlsxMergeRecipes(workbook: Element, directory: readonly WorkbookWorksheetIdentity[]): readonly WorkbookMergeRecipe[] {
19
+ const group = child(workbook, "extLst");
20
+ const records = group ? children(group).filter(isXlsxMergeRecipeExtension) : [];
21
+ if (records.length !== 1) return [];
22
+ const body = child(records[0]!, "recipes")!;
23
+ const sheets = new Set(directory.map(({ id }) => id));
24
+ const entries: WorkbookMergeRecipe[] = [], seen = new Set<string>();
25
+ try {
26
+ const decoded: unknown = JSON.parse(body.textContent ?? "");
27
+ if (!Array.isArray(decoded) || decoded.length > sheets.size) return [];
28
+ for (const value of decoded) {
29
+ try {
30
+ const recipe = copyWorkbookMergeRecipe(value, sheets);
31
+ if (seen.has(recipe.output.sheetId)) return [];
32
+ seen.add(recipe.output.sheetId);
33
+ entries.push(recipe);
34
+ } catch { /* A prior producer may have removed a worksheet that this recipe used. */ }
35
+ }
36
+ } catch { return []; }
37
+ return entries;
38
+ }
39
+
40
+ /** @param before - Imported workbook settings. @param after - Current settings in session coordinates.
41
+ * @returns Whether the workbook extension can be kept byte-for-byte. */
42
+ export function sameXlsxMergeRecipes(before: readonly WorkbookMergeRecipe[] = [], after: readonly WorkbookMergeRecipe[] = []): boolean {
43
+ return before.length === after.length && before.every((entry, index) => sameWorkbookMergeRecipe(entry, after[index]));
44
+ }
45
+
46
+ /** @param workbook - Staged native workbook. @param directory - Session IDs in file order.
47
+ * @param recipes - Current settings in session coordinates. */
48
+ export function writeXlsxMergeRecipes(workbook: Element, directory: readonly WorkbookWorksheetIdentity[],
49
+ recipes: readonly WorkbookMergeRecipe[]): void {
50
+ let group = child(workbook, "extLst");
51
+ if (group) for (const earlier of children(group).filter(isXlsxMergeRecipeExtension)) group.removeChild(earlier);
52
+ if (!recipes.length) {
53
+ if (group && !children(group).length) workbook.removeChild(group);
54
+ return;
55
+ }
56
+
57
+ // Bind configuration to the IDs in the written XLSX directory, including newly allocated numeric sheet IDs.
58
+ const worksheets = children(child(workbook, "sheets")!, "sheet");
59
+ const ids = new Map(directory.map(({ id }, index) => {
60
+ const sheet = worksheets[index]!;
61
+ return [id, sheet.getAttribute("sheetId") || sheet.getAttributeNS(relationshipNs, "id")!];
62
+ }));
63
+ /** @param id - Sheet identity in the current session. @returns Its native XLSX ID. */
64
+ function nativeId(id: string): string {
65
+ const value = ids.get(id);
66
+ if (!value) throw new Error("保存合并配置时无法定位工作表。");
67
+ return value;
68
+ }
69
+ const data = recipes.map(({ output, options }) => ({
70
+ output: { ...output, sheetId: nativeId(output.sheetId) },
71
+ options: { ...options, sources: options.sources.map(source => ({ ...source, sheetId: nativeId(source.sheetId) })) }
72
+ }));
73
+ const document = workbook.ownerDocument!;
74
+ if (!group) {
75
+ group = document.createElementNS(spreadNs, "extLst");
76
+ workbook.appendChild(group);
77
+ }
78
+ const entry = document.createElementNS(spreadNs, "ext");
79
+ entry.setAttribute("uri", namespace);
80
+ const body = document.createElementNS(namespace, "qkm:recipes");
81
+ body.appendChild(document.createTextNode(JSON.stringify(data)));
82
+ entry.appendChild(body);
83
+ group.appendChild(entry);
84
+ }