@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,68 @@
1
+ import {
2
+ copyWorkbookFloatingPicture, maximumWorkbookPictures, sameWorkbookFloatingPicture, workbookImagePresentation,
3
+ type WorkbookFloatingPicture, type WorkbookRasterMimeType, type WorkbookSnapshot
4
+ } from "@quirekit/workbook";
5
+ import { retainedXlsxRelationshipTargets } from "../../image/relationships";
6
+ import type { XlsxPackage } from "../../package/types";
7
+
8
+ /** @param left - Original checkpoint. @param right - Candidate save. @returns Whether all authored floating pictures are unchanged. */
9
+ export function sameXlsxPictures(left: WorkbookSnapshot, right: WorkbookSnapshot): boolean {
10
+ const before = left.pictures ?? [], after = right.pictures ?? [];
11
+ const prior = new Map(before.map(item => [item.id, item]));
12
+ return before.length === after.length && after.every(item => sameWorkbookFloatingPicture(prior.get(item.id) ?? null, item));
13
+ }
14
+
15
+ /**
16
+ * @param source - Original validated drawing owners.
17
+ * @param parts - Package entries being written.
18
+ * @param paths - Final worksheet paths.
19
+ * @param snapshot - Committed drawing and resource definitions.
20
+ * @returns Per-sheet placements plus one reusable native part per raster.
21
+ */
22
+ export function planXlsxPictures(source: XlsxPackage, parts: Record<string, Uint8Array>, paths: ReadonlyMap<string, string>,
23
+ snapshot: WorkbookSnapshot) {
24
+ const bySheet = new Map<string, WorkbookFloatingPicture[]>();
25
+ const assets = new Map(snapshot.imageAssets?.map(asset => [asset.id, asset]));
26
+ const initialAssets = new Map(source.baseline?.imageAssets?.map(asset => [asset.id, asset]));
27
+ const ids = new Set(snapshot.charts?.map(chart => chart.id));
28
+ if ((snapshot.pictures?.length ?? 0) > maximumWorkbookPictures) throw new Error("工作簿包含过多浮动图片。");
29
+ for (const input of snapshot.pictures ?? []) {
30
+ const picture = copyWorkbookFloatingPicture(input);
31
+ const { id, assetId, anchor: { sheetId } } = picture;
32
+ if (ids.has(id) || !paths.has(sheetId) || !assets.has(assetId)) {
33
+ throw new Error("浮动图片标识重复,或对应的工作表或媒体不存在。");
34
+ }
35
+ const list = bySheet.get(sheetId) ?? [];
36
+ list.push(picture);
37
+ bySheet.set(sheetId, list);
38
+ ids.add(id);
39
+ }
40
+ const media = new Map<string, string>();
41
+ const originalMedia = new Set<string>();
42
+ for (const graph of source.drawingGraphs?.values() ?? []) {
43
+ for (const { picture: { assetId }, path } of graph.pictures) {
44
+ originalMedia.add(path);
45
+ const original = initialAssets.get(assetId), next = assets.get(assetId);
46
+ if (parts[path] && original && next?.mimeType === original.mimeType && next.data === original.data) media.set(assetId, path);
47
+ }
48
+ }
49
+ return {
50
+ bySheet,
51
+ /** @param assetId - Resource from a validated picture. @param allocate - Reserves a MIME-declared media part. @returns Its package path. */
52
+ path(assetId: string, allocate: (mime: WorkbookRasterMimeType) => string): string {
53
+ const cached = media.get(assetId);
54
+ if (cached) return cached;
55
+ const asset = assets.get(assetId)!;
56
+ const path = allocate(asset.mimeType);
57
+ parts[path] = workbookImagePresentation(asset).bytes();
58
+ media.set(assetId, path);
59
+ return path;
60
+ },
61
+ /** @param remove - Removes a part and its explicit content-type override. */
62
+ collectUnused(remove: (path: string) => void): void {
63
+ if (!originalMedia.size) return;
64
+ const targets = retainedXlsxRelationshipTargets(parts);
65
+ if (targets) for (const path of originalMedia) if (!targets.has(path)) remove(path);
66
+ }
67
+ };
68
+ }
@@ -0,0 +1,43 @@
1
+ import { workbookChartPalette, type WorkbookChart, type WorkbookChartData, type WorkbookChartType } from "@quirekit/workbook";
2
+ import { emuPerCssPixel } from "../namespaces";
3
+ import { chartFormula, chartValue, chartXmlText } from "./text";
4
+
5
+ /** @param values - Indexed points including blanks. @returns Cache records retaining gap indexes. */
6
+ function points(values: readonly (string | number | null)[]): string {
7
+ return chartValue("ptCount", values.length) + values.map((value, index) =>
8
+ value === null ? "" : `<c:pt idx="${index}"><c:v>${chartXmlText(String(value))}</c:v></c:pt>`).join("");
9
+ }
10
+
11
+ /** @param formula - Absolute local reference. @param values - Known values in that vector. @returns Native string reference. */
12
+ function stringReference(formula: string, values: readonly string[]): string {
13
+ return `<c:strRef><c:f>${chartXmlText(formula)}</c:f><c:strCache>${points(values)}</c:strCache></c:strRef>`;
14
+ }
15
+
16
+ /** @param type - Assigned plot shape. @param index - Global series index. @returns Native default paint independent of the theme. */
17
+ function combinationSeriesPaint(type: WorkbookChartType, index: number): string {
18
+ const color = workbookChartPalette[index % workbookChartPalette.length]!.slice(1);
19
+ const fill = `<a:solidFill><a:srgbClr val="${color}"/></a:solidFill>`;
20
+ return `<c:spPr>${type === "line" ? `<a:ln w="${2 * emuPerCssPixel}">${fill}</a:ln>` : fill}</c:spPr>`;
21
+ }
22
+
23
+ /** @param chart - Native chart and bindings. @param data - Values at the saved revision. @param names - Sheet names by ID.
24
+ * @param type - Shape assigned to this plot. @param indices - Ordered indices of the series in this plot.
25
+ * @returns Ordered ChartML series with aligned category and numeric caches. */
26
+ export function chartSeriesXml(chart: WorkbookChart, data: WorkbookChartData, names: ReadonlyMap<string, string>,
27
+ type: WorkbookChartType, indices: readonly number[] = chart.binding.series.map((_, index) => index)): string {
28
+ const categories = chart.binding.categories
29
+ ? `<c:cat>${stringReference(chartFormula(chart.binding.categories, names), data.categories)}</c:cat>` : "";
30
+ return indices.map(index => {
31
+ const { name, nameCell, values } = chart.binding.series[index]!;
32
+ const current = data.series[index]!;
33
+ const title = nameCell ? stringReference(chartFormula({
34
+ sheetId: nameCell.sheetId, startRow: nameCell.row, endRow: nameCell.row,
35
+ startColumn: nameCell.column, endColumn: nameCell.column
36
+ }, names), [current.name]) : `<c:v>${chartXmlText(name ?? current.name)}</c:v>`;
37
+ const value = `<c:val><c:numRef><c:f>${chartXmlText(chartFormula(values, names))}</c:f><c:numCache><c:formatCode>General</c:formatCode>${points(current.values)}</c:numCache></c:numRef></c:val>`;
38
+ const marker = type === "line" ? `<c:marker>${chartValue("symbol", "none")}</c:marker>` : "";
39
+ const paint = chart.type === "combination" ? combinationSeriesPaint(type, index) : "";
40
+ const smooth = chart.type === "combination" && type === "line" ? chartValue("smooth", false) : "";
41
+ return `<c:ser>${chartValue("idx", index)}${chartValue("order", index)}<c:tx>${title}</c:tx>${paint}${marker}${categories}${value}${smooth}</c:ser>`;
42
+ }).join("");
43
+ }
@@ -0,0 +1,113 @@
1
+ import { assertWorkbookShapeConnectionGraph, copyWorkbookFloatingShape, maximumWorkbookShapes, projectWorkbookConnectorFrame, workbookShapeConnectionSites,
2
+ type WorkbookFloatingShape, type WorkbookShapeConnection, type WorkbookShapeConnector, type WorkbookShapeStyle, type WorkbookSnapshot } from "@quirekit/workbook";
3
+ import { emuPerCssPixel } from "../namespaces";
4
+ import { drawingTransformXml, writeXlsxDrawingPlacement } from "../placement/transform";
5
+ import type { XlsxDrawingAxes } from "../placement/types";
6
+ import type { XlsxShapePart } from "../types";
7
+ import { drawingAnchorXml, drawingCreationIdXml } from "./anchor";
8
+ import { chartXmlText } from "./text";
9
+
10
+ /** @param left - Source shape. @param right - Committed shape. @returns Whether native placement and appearance can be reused. */
11
+ export function sameXlsxShape(left: WorkbookFloatingShape | undefined, right: WorkbookFloatingShape): boolean {
12
+ return left === right || JSON.stringify(left) === JSON.stringify(right);
13
+ }
14
+
15
+ /** @param left - XLSX input. @param right - Proposed save. @returns Whether native objects are unchanged. */
16
+ export function sameXlsxShapes(left: WorkbookSnapshot, right: WorkbookSnapshot): boolean {
17
+ const before = left.shapes ?? [], after = right.shapes ?? [];
18
+ const prior = new Map(before.map(item => [item.id, item]));
19
+ return before.length === after.length && after.every(item => sameXlsxShape(prior.get(item.id), item));
20
+ }
21
+
22
+ /** @param snapshot - Edited workbook. @param paths - Final sheet part names. @returns Validated shape placements by worksheet. */
23
+ export function planXlsxShapes(snapshot: WorkbookSnapshot, paths: ReadonlyMap<string, string>) {
24
+ const bySheet = new Map<string, WorkbookFloatingShape[]>();
25
+ const occupied = new Set([...(snapshot.charts ?? []), ...(snapshot.pictures ?? [])].map(({ id }) => id));
26
+ if ((snapshot.shapes?.length ?? 0) > maximumWorkbookShapes) throw new Error("工作簿包含过多形状。");
27
+ for (const item of snapshot.shapes ?? []) {
28
+ const shape = copyWorkbookFloatingShape(item), sheetId = shape.anchor.sheetId;
29
+ if (occupied.has(shape.id) || !paths.has(sheetId)) throw new Error("形状标识重复或工作表不存在。");
30
+ const list = bySheet.get(sheetId) ?? [];
31
+ list.push(shape);
32
+ bySheet.set(sheetId, list);
33
+ occupied.add(shape.id);
34
+ }
35
+ for (const shapes of bySheet.values()) assertWorkbookShapeConnectionGraph(new Map(shapes.map(shape => [shape.id, shape])));
36
+ return bySheet;
37
+ }
38
+
39
+ /** @param value - Opaque CSS RGB or no fill. @returns An explicit DrawingML paint. */
40
+ function solid(value: string | null): string {
41
+ return value ? `<a:solidFill><a:srgbClr val="${value.slice(1)}"/></a:solidFill>` : "<a:noFill/>";
42
+ }
43
+
44
+ /** @param text - Multiline plain text. @param style - Uniform authoring style. @returns Native DrawingML text body. */
45
+ function shapeText(text: string, style: WorkbookShapeStyle): string {
46
+ const anchor = { top: "t", center: "ctr", bottom: "b" }[style.vertical];
47
+ const align = { left: "l", center: "ctr", right: "r" }[style.horizontal];
48
+ const attributes = `sz="${Math.round(style.size * 100)}"${style.bold ? ' b="1"' : ""}${style.italic ? ' i="1"' : ""}`;
49
+ const face = style.font ? `<a:latin typeface="${chartXmlText(style.font)}"/><a:ea typeface="${chartXmlText(style.font)}"/><a:cs typeface="${chartXmlText(style.font)}"/>` : "";
50
+ const paint = solid(style.color) + face;
51
+ const paragraphs = text.split("\n").map(line => `<a:p><a:pPr algn="${align}"/>${line
52
+ ? `<a:r><a:rPr ${attributes}>${paint}</a:rPr><a:t xml:space="preserve">${chartXmlText(line)}</a:t></a:r>`
53
+ : `<a:endParaRPr ${attributes}>${paint}</a:endParaRPr>`}</a:p>`);
54
+ return `<xdr:txBody><a:bodyPr wrap="square" vertOverflow="clip" horzOverflow="clip" anchor="${anchor}"><a:noAutofit/></a:bodyPr><a:lstStyle/>${paragraphs.join("")}</xdr:txBody>`;
55
+ }
56
+
57
+ /** @param tag - End of the directed open path. @param marker - Native marker geometry and size.
58
+ * @returns An explicit DrawingML end marker, or empty XML for a bare end. */
59
+ function lineEnd(tag: "headEnd" | "tailEnd", marker: WorkbookShapeConnector["headEnd"]): string {
60
+ return marker ? `<a:${tag} type="${marker.type}" w="${marker.width}" len="${marker.length}"/>` : "";
61
+ }
62
+
63
+ /** @param tag - Native endpoint tag. @param binding - Canonical endpoint attachment.
64
+ * @param targets - Shape frames with allocated IDs. @returns Native reference, if attached. */
65
+ function connection(tag: "stCxn" | "endCxn", binding: WorkbookShapeConnection | undefined, targets: ReadonlyMap<string, XlsxShapePart>): string {
66
+ if (!binding) return "";
67
+ const frameId = targets.get(binding.shapeId)?.frameId;
68
+ if (frameId === undefined) throw new Error("无法保存缺少目标形状的连接符。");
69
+ return `<a:${tag} id="${frameId}" idx="${binding.site}"/>`;
70
+ }
71
+
72
+ /** @param shape - Ordered path and saved fallback. @param targets - Native shape frames. @param axes - Effective dimensions.
73
+ * @returns A native anchor, optional explicit transform and path direction. */
74
+ function shapePlacement(shape: WorkbookFloatingShape, targets: ReadonlyMap<string, XlsxShapePart>, axes?: XlsxDrawingAxes) {
75
+ const { anchor, rotation, connector } = shape;
76
+ if (!connector?.startConnection && !connector?.endConnection) {
77
+ return { ...writeXlsxDrawingPlacement(anchor, rotation, axes, connector !== undefined),
78
+ flipHorizontal: connector?.flipHorizontal, flipVertical: connector?.flipVertical };
79
+ }
80
+ if (!axes) throw new Error("保存连接符需要工作表的尺寸。");
81
+ // Work in the finalized native layout, including relative row heights, hidden dimensions and the rotated target's center.
82
+ const pose = projectWorkbookConnectorFrame(connector, { rect: axes.bounds(anchor), rotation: 0 }, ({ shapeId, site }) => {
83
+ const target = targets.get(shapeId)?.shape;
84
+ return target && workbookShapeConnectionSites(target, { rect: axes.bounds(target.anchor), rotation: target.rotation ?? 0 })[site];
85
+ });
86
+ const rect = pose.frame.rect;
87
+ const x = Math.max(0, Math.round(rect.x)), y = Math.max(0, Math.round(rect.y));
88
+ const frame = { x, y, width: Math.max(0, Math.round(rect.x + rect.width) - x), height: Math.max(0, Math.round(rect.y + rect.height) - y) };
89
+ return { anchor: axes.anchor(anchor.sheetId, frame), frame, flipHorizontal: pose.flipHorizontal, flipVertical: pose.flipVertical };
90
+ }
91
+
92
+ /** @param part - Planned anchored shape. @param targets - Shape frames with allocated IDs. @param axes - Current worksheet geometry.
93
+ * @returns One native edit-ready worksheet shape, including text boxes. */
94
+ export function shapeFrame({ shape, frameId }: XlsxShapePart, targets: ReadonlyMap<string, XlsxShapePart>, axes?: XlsxDrawingAxes): string {
95
+ const { id, preset, name, alt, text, style, adjustments, rotation, connector } = shape;
96
+ const textbox = preset === "textBox";
97
+ const description = alt ? ` descr="${chartXmlText(alt)}"` : "";
98
+ const identity = `<xdr:cNvPr id="${frameId}" name="${chartXmlText(name)}"${description}>${drawingCreationIdXml(id)}</xdr:cNvPr>`;
99
+ const guides = Object.entries(adjustments ?? {}).map(([key, value]) => `<a:gd name="${chartXmlText(key)}" fmla="val ${value}"/>`).join("");
100
+ const geometry = `<a:prstGeom prst="${textbox ? "rect" : preset}"><a:avLst>${guides}</a:avLst></a:prstGeom>`;
101
+ const markers = connector ? lineEnd("headEnd", connector.headEnd) + lineEnd("tailEnd", connector.tailEnd) : "";
102
+ const paint = `${solid(style.fill)}<a:ln w="${Math.round(style.strokeWidth * emuPerCssPixel)}">${solid(style.stroke)}${markers}</a:ln>`;
103
+ const placement = shapePlacement(shape, targets, axes);
104
+ const transform = drawingTransformXml(rotation, placement.frame, placement.flipHorizontal, placement.flipVertical);
105
+ const properties = `<xdr:spPr>${transform}${geometry}${paint}</xdr:spPr>`;
106
+ if (connector) {
107
+ const bindings = connection("stCxn", connector.startConnection, targets) + connection("endCxn", connector.endConnection, targets);
108
+ const props = `<xdr:nvCxnSpPr>${identity}${bindings ? `<xdr:cNvCxnSpPr>${bindings}</xdr:cNvCxnSpPr>` : "<xdr:cNvCxnSpPr/>"}</xdr:nvCxnSpPr>`;
109
+ return drawingAnchorXml(placement.anchor, `<xdr:cxnSp>${props}${properties}</xdr:cxnSp>`);
110
+ }
111
+ const props = `<xdr:nvSpPr>${identity}<xdr:cNvSpPr${textbox ? ' txBox="1"' : ""}/></xdr:nvSpPr>`;
112
+ return drawingAnchorXml(placement.anchor, `<xdr:sp>${props}${properties}${shapeText(text, style)}</xdr:sp>`);
113
+ }
@@ -0,0 +1,26 @@
1
+ import { formatWorkbookColumn, type WorkbookRange } from "@quirekit/workbook";
2
+
3
+ /** @param value - Untrusted cell, title, or reference text. @returns XML-safe text nodes or attribute content. */
4
+ export function chartXmlText(value: string): string {
5
+ // Replace XML-excluded control characters while retaining all printable cell text.
6
+ return Array.from(value, character => {
7
+ const point = character.codePointAt(0)!;
8
+ return point === 9 || point === 10 || point === 13 || (point >= 32 && point <= 0xd7ff)
9
+ || (point >= 0xe000 && point <= 0xfffd) || point >= 0x10000 ? character : "�";
10
+ }).join("").replaceAll("&", "&amp;").replaceAll("<", "&lt;").replaceAll(">", "&gt;").replaceAll('"', "&quot;");
11
+ }
12
+
13
+ /** @param range - Current stable worksheet rectangle. @param names - Visible names by sheet ID.
14
+ * @returns Absolute SpreadsheetML chart reference, with quoted worksheet names. */
15
+ export function chartFormula(range: WorkbookRange, names: ReadonlyMap<string, string>): string {
16
+ const sheet = names.get(range.sheetId);
17
+ if (sheet === undefined) throw new Error("图表引用的工作表不存在。");
18
+ const start = `$${formatWorkbookColumn(range.startColumn)}$${range.startRow + 1}`;
19
+ const end = `$${formatWorkbookColumn(range.endColumn)}$${range.endRow + 1}`;
20
+ return `'${sheet.replaceAll("'", "''")}'!${start}${end === start ? "" : ":" + end}`;
21
+ }
22
+
23
+ /** @param name - ChartML leaf tag name. @param value - Its native val attribute. @returns One serialized leaf. */
24
+ export function chartValue(name: string, value: string | number | boolean): string {
25
+ return `<c:${name} val="${typeof value === "boolean" ? Number(value) : value}"/>`;
26
+ }
@@ -0,0 +1,199 @@
1
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
2
+ import { openWorkbook, parseWorkbookRange, workbookChartTypes, type WorkbookSession, type WorkbookSnapshot } from "@quirekit/workbook";
3
+ import { expect, it } from "vitest";
4
+ import { createXlsx, openXlsx } from "../../index";
5
+
6
+ const workbookSeed: WorkbookSnapshot = {
7
+ version: 1, id: "book", revision: 0, name: "库存",
8
+ sheets: [
9
+ { id: "report", name: "Report", cells: [] },
10
+ { id: "source", name: "一季度'数据", cells: [
11
+ { row: 0, column: 1, input: { kind: "value", value: "到账<&>" } },
12
+ { row: 1, column: 0, input: { kind: "value", value: "华东" } },
13
+ { row: 2, column: 0, input: { kind: "value", value: "华南" } },
14
+ { row: 3, column: 0, input: { kind: "value", value: "华北" } },
15
+ { row: 1, column: 1, input: { kind: "formula", formula: "=2+3" } },
16
+ { row: 3, column: 1, input: { kind: "value", value: 0 } }
17
+ ] }
18
+ ]
19
+ };
20
+ const binding = {
21
+ categories: { sheetId: "source", range: "A2:A4" },
22
+ series: [{ nameCell: { sheetId: "source", range: "B1" }, values: { sheetId: "source", range: "B2:B4" } }]
23
+ };
24
+
25
+ /** @param workbook - Workbook being edited. @param name - Installed command. @param params - Chart or sheet edit.
26
+ * @param sheetId - Target sheet. @returns Published edit. */
27
+ async function commit(workbook: WorkbookSession, name: string, params: unknown, sheetId: string) {
28
+ return workbook.commit(workbook.prepare({ operationId: name + workbook.revision, baseRevision: workbook.revision,
29
+ commands: [{ name, target: parseWorkbookRange(sheetId, "B3"), params }] }).id);
30
+ }
31
+
32
+ it("writes native chart families with live references, sparse caches, durable identity and a normal reopen", async () => {
33
+ const workbook = await openWorkbook(workbookSeed);
34
+ try {
35
+ for (const type of workbookChartTypes.filter(type => type !== "combination")) {
36
+ const grouping = type === "column" ? "percentStacked" : "standard";
37
+ await commit(workbook, "createChart", { type, grouping, title: `到账 · ${type}`, binding, dataLabels: true }, "report");
38
+ }
39
+ const bytes = createXlsx(workbook.snapshot(), { result: () => ({ status: "value", value: 5 }) });
40
+ const parts = unzipSync(bytes);
41
+ const chart = strFromU8(parts["xl/charts/chart1.xml"]!);
42
+ expect(strFromU8(parts["[Content_Types].xml"]!)).toContain('PartName="/xl/drawings/drawing1.xml" ContentType="application/vnd.openxmlformats-officedocument.drawing+xml"');
43
+ expect(chart).toContain("'一季度''数据'!$B$2:$B$4");
44
+ expect(chart).toContain("到账&lt;&amp;&gt;");
45
+ expect(chart).toContain('<c:numFmt formatCode="0%" sourceLinked="0"/>');
46
+ expect(strFromU8(parts["xl/charts/chart6.xml"]!)).toContain('<c:showCatName val="1"/>');
47
+ expect(chart).toContain('<c:ptCount val="3"/><c:pt idx="0"><c:v>5</c:v></c:pt><c:pt idx="2"><c:v>0</c:v></c:pt>');
48
+ expect(strFromU8(parts["xl/drawings/drawing1.xml"]!)).toContain(workbook.charts()[0]!.id.toUpperCase());
49
+ const reopened = openXlsx("库存", bytes);
50
+ expect(reopened.restrictions).toEqual([]);
51
+ expect(reopened.snapshot.charts?.map(chart => [chart.id, chart.type, chart.title, chart.grouping]))
52
+ .toEqual(workbook.charts().map(chart => [chart.id, chart.type, chart.title, chart.grouping]));
53
+ expect(reopened.write(reopened.snapshot)).toEqual(bytes);
54
+
55
+ const next = await openWorkbook(reopened.snapshot, { calculation: async () => ({
56
+ async apply() {}, close() {}, read: () => ({ status: "value", value: 5 }), translate: formula => formula,
57
+ rewriteWorksheetReferences: formula => formula
58
+ }) });
59
+ try {
60
+ const report = next.worksheets()[0]!.id, data = next.worksheets()[1]!.id;
61
+ await commit(next, "renameWorksheet", { name: "新数据" }, data);
62
+ await commit(next, "updateChart", { id: next.charts()[0]!.id, title: "新标题" }, report);
63
+ const saved = reopened.write(next.snapshot(), { result: () => ({ status: "value", value: 7 }) });
64
+ const changed = unzipSync(saved);
65
+ expect(strFromU8(changed["xl/charts/chart1.xml"]!)).toContain("'新数据'!$B$2:$B$4");
66
+ expect(changed["xl/drawings/drawing1.xml"]).toEqual(parts["xl/drawings/drawing1.xml"]);
67
+ const again = openXlsx("库存", saved);
68
+ expect(again.restrictions).toEqual([]);
69
+ expect(again.snapshot.charts?.[0]?.title).toBe("新标题");
70
+ for (const chart of [...next.charts()]) await commit(next, "deleteChart", { id: chart.id }, report);
71
+ const cleared = unzipSync(reopened.write(next.snapshot()));
72
+ expect(Object.keys(cleared).some(path => path.startsWith("xl/charts/") || path.startsWith("xl/drawings/"))).toBe(false);
73
+ expect(cleared["xl/worksheets/_rels/sheet1.xml.rels"]).toBeUndefined();
74
+ expect(strFromU8(cleared["[Content_Types].xml"]!)).not.toContain("drawingml.");
75
+ } finally { await next.close(); }
76
+ } finally { await workbook.close(); }
77
+ });
78
+
79
+ it("retains unsupported native options and shared drawing references", async () => {
80
+ const workbook = await openWorkbook(workbookSeed);
81
+ try {
82
+ await commit(workbook, "createChart", { type: "line", binding }, "report");
83
+ const normal = unzipSync(createXlsx(workbook.snapshot(), { result: () => ({ status: "value", value: 5 }) }));
84
+ const chartPath = "xl/charts/chart1.xml", drawingPath = "xl/drawings/drawing1.xml";
85
+ const variants = [
86
+ [chartPath, "<c:scaling>", '<c:scaling><c:min val="1"/>'],
87
+ [chartPath, "</c:numCache>", '<c:extLst><c:ext uri="producer-cache"/></c:extLst></c:numCache>'],
88
+ [chartPath, "<c:formatCode>General</c:formatCode>", "<c:formatCode>0.00</c:formatCode>"],
89
+ [drawingPath, "<xdr:clientData/>", '<xdr:clientData><a:extLst/></xdr:clientData>'],
90
+ [drawingPath, "<xdr:colOff>", '<xdr:colOff xmlns:custom="urn:producer" custom:offset="different">'],
91
+ [drawingPath, "<xdr:cNvGraphicFramePr/>", '<xdr:cNvGraphicFramePr custom="unmodeled"/>']
92
+ ] as const;
93
+ for (const [path, source, replacement] of variants) {
94
+ const original = zipSync({ ...normal, [path]: strToU8(strFromU8(normal[path]!).replace(source, replacement)) });
95
+ const file = openXlsx("库存", original);
96
+ expect(file.restrictions, replacement).toContain("绘图或图表");
97
+ expect(file.charts).toHaveLength(1);
98
+ expect(file.write(file.snapshot)).toEqual(original);
99
+ }
100
+
101
+ const shared = zipSync({ ...normal, "xl/custom/_rels/other.xml.rels": strToU8(
102
+ '<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="ref" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart" Target="/xl/charts/chart1.xml"/></Relationships>'
103
+ ) });
104
+ const retained = openXlsx("库存", shared);
105
+ expect(retained.snapshot.charts).toBeUndefined();
106
+ expect(retained.restrictions).toContain("绘图关系共用部件或对象数量超限");
107
+ expect(retained.write(retained.snapshot)).toEqual(shared);
108
+ } finally { await workbook.close(); }
109
+ });
110
+
111
+ it("gives a copied worksheet its own drawings and saves it after its last chart is deleted", async () => {
112
+ const workbook = await openWorkbook({ ...workbookSeed, sheets: workbookSeed.sheets.map(sheet => ({
113
+ ...sheet, cells: sheet.cells.filter(({ input }) => input.kind !== "formula")
114
+ })) });
115
+ try {
116
+ await commit(workbook, "createChart", { type: "line", binding }, "report");
117
+ const original = openXlsx("库存", createXlsx(workbook.snapshot()));
118
+ const next = await openWorkbook(original.snapshot);
119
+ try {
120
+ const source = next.worksheets()[0]!.id;
121
+ const copyId = "00000000-0000-4000-8000-000000000100";
122
+ await commit(next, "duplicateWorksheet", { newSheetId: copyId, name: "Copy" }, source);
123
+ const copied = next.charts().find(chart => chart.anchor.sheetId === copyId)!;
124
+ const withBoth = openXlsx("库存", original.write(next.snapshot()));
125
+ expect(withBoth.restrictions).toEqual([]);
126
+ expect(withBoth.snapshot.charts?.map(chart => chart.id)).toEqual(next.charts().map(chart => chart.id));
127
+
128
+ await commit(next, "deleteChart", { id: copied.id }, copyId);
129
+ const saved = original.write(next.snapshot());
130
+ const reopened = openXlsx("库存", saved);
131
+ expect(reopened.restrictions).toEqual([]);
132
+ expect(reopened.snapshot.charts).toHaveLength(1);
133
+ expect(reopened.snapshot.charts?.[0]?.anchor.sheetId).toBe(source);
134
+ expect(strFromU8(unzipSync(saved)["xl/worksheets/sheet3.xml"]!)).not.toContain("drawing");
135
+ } finally { await next.close(); }
136
+ } finally { await workbook.close(); }
137
+ });
138
+
139
+ it("writes individually bound combination series and reopens their global order and explicit scales", async () => {
140
+ const workbook = await openWorkbook(workbookSeed);
141
+ try {
142
+ const axes = { primary: { min: 0, max: 300 }, secondary: { min: -0.25, max: 1, format: "0.0%" } };
143
+ await commit(workbook, "createChart", {
144
+ type: "combination", title: "金额与比例", valueAxes: axes, binding: { ...binding, series: [
145
+ { ...binding.series[0], plot: { type: "column", axis: "primary" } },
146
+ { name: "比例", values: { sheetId: "source", range: "C2:C4" }, plot: { type: "line", axis: "secondary" } },
147
+ { name: "预算", values: { sheetId: "source", range: "D2:D4" }, plot: { type: "column", axis: "primary" } }
148
+ ] }
149
+ }, "report");
150
+ const bytes = createXlsx(workbook.snapshot(), { result: () => ({ status: "value", value: 5 }) });
151
+ const parts = unzipSync(bytes);
152
+ const chart = strFromU8(parts["xl/charts/chart1.xml"]!);
153
+ const columnPlot = chart.match(/<c:barChart>.*?<\/c:barChart>/u)![0];
154
+ const linePlot = chart.match(/<c:lineChart>.*?<\/c:lineChart>/u)![0];
155
+ expect([...columnPlot.matchAll(/<c:order val="(\d+)"\/>/gu)].map(match => match[1])).toEqual(["0", "2"]);
156
+ expect(linePlot).toContain('<c:order val="1"/>');
157
+ expect(columnPlot.match(/<a:srgbClr val="([^"]+)"\/>/gu)).toEqual(['<a:srgbClr val="5B9BD5"/>', '<a:srgbClr val="A5A5A5"/>']);
158
+ expect(linePlot).toContain('<a:srgbClr val="ED7D31"/>');
159
+ expect(linePlot).toContain('<c:smooth val="0"/>');
160
+ expect(linePlot).toContain("'一季度''数据'!$C$2:$C$4");
161
+ expect(chart).toContain('<c:axPos val="r"/>');
162
+ expect(chart).toContain('<c:numFmt formatCode="0.0%" sourceLinked="0"/>');
163
+ expect(chart).toContain('<c:min val="-0.25"/>');
164
+
165
+ const file = openXlsx("库存", bytes);
166
+ expect(file.restrictions).toEqual([]);
167
+ const original = workbook.charts()[0]!;
168
+ const reopened = file.snapshot.charts?.[0];
169
+ expect(reopened).toMatchObject({ type: "combination", id: original.id, valueAxes: axes });
170
+ expect(reopened?.binding.series.map(series => series.plot)).toEqual(original.binding.series.map(series => series.plot));
171
+ expect(reopened?.binding.series.map(series => series.name ?? series.nameCell?.column)).toEqual([1, "比例", "预算"]);
172
+ expect(file.write(file.snapshot)).toEqual(bytes);
173
+
174
+ const editable = await openWorkbook(file.snapshot);
175
+ try {
176
+ const [report, data] = editable.worksheets();
177
+ await commit(editable, "updateChart", { id: original.id, grouping: "stacked", binding: {
178
+ categories: { sheetId: data!.id, range: "A2:A4" },
179
+ series: [
180
+ { values: { sheetId: data!.id, range: "B2:B4" }, plot: { type: "column", axis: "primary" } },
181
+ { values: { sheetId: data!.id, range: "C2:C4" }, plot: { type: "area", axis: "primary" } }
182
+ ]
183
+ } }, report!.id);
184
+ const shared = file.write(editable.snapshot(), { result: () => ({ status: "value", value: 5 }) });
185
+ const sharedChart = strFromU8(unzipSync(shared)["xl/charts/chart1.xml"]!);
186
+ expect(sharedChart).toContain("<c:areaChart>");
187
+ expect(sharedChart.match(/<c:valAx>/gu)).toHaveLength(1);
188
+ expect(openXlsx("同轴", shared).snapshot.charts).toEqual(editable.charts());
189
+ } finally { await editable.close(); }
190
+
191
+ const custom = zipSync({ ...parts, "xl/charts/chart1.xml": strToU8(chart.replace("</c:chartSpace>",
192
+ '<c:extLst><c:ext uri="unknown-style"/></c:extLst></c:chartSpace>')) });
193
+ const retained = openXlsx("库存", custom);
194
+ expect(retained.restrictions).toContain("绘图或图表");
195
+ expect(retained.charts[0]?.preview.plot).toMatchObject({ kind: "cartesian", yAxes: [{ max: 300 }, { max: 1 }],
196
+ series: [{ name: "到账<&>" }, { name: "比例" }, { name: "预算" }] });
197
+ expect(retained.write(retained.snapshot)).toEqual(custom);
198
+ } finally { await workbook.close(); }
199
+ });