@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,130 @@
1
+ import { createWorkbookCommentStore, sameWorkbookCommentThread, type WorkbookCommentThread, type WorkbookSnapshot } from "@quirekit/workbook";
2
+ import { editPartRelationships, relationshipsPath } from "../../opc/relationships";
3
+ import { child, children, contentTypeNs, parsePart, relationshipNs, rootOf, spreadNs, writePart } from "../../opc/xml";
4
+ import type { XlsxPackage } from "../../package/types";
5
+ import { writeXlsxLegacyComments, writeXlsxNoteDrawing } from "../legacy/write";
6
+ import { writeXlsxCommentPeople, writeXlsxCommentThreads } from "../thread/write";
7
+ import { commentContentTypes, commentReference, commentRoles, invalidXlsxComment } from "../xml";
8
+ import { writeXlsxCommentRanges } from "./ranges";
9
+
10
+ /** @param before - Retained source snapshot. @param after - Saved document. @returns Whether the comments require native writes. */
11
+ export function sameXlsxComments(before: WorkbookSnapshot | undefined, after: WorkbookSnapshot): boolean {
12
+ const original = before?.commentThreads ?? [], current = after.commentThreads ?? [];
13
+ if (original.length !== current.length) return false;
14
+ const byId = new Map(original.map(thread => [thread.id, thread]));
15
+ // Older writers omit note GUIDs. Each room replica can import a different
16
+ // generated ID from the same source while the original note stays unchanged.
17
+ const notes = new Map(original.filter(thread => thread.kind === "note").map(thread => [noteKey(thread), thread.messages[0]]));
18
+ return current.every(thread => {
19
+ if (thread.kind !== "note") return sameWorkbookCommentThread(byId.get(thread.id) ?? null, thread);
20
+ const saved = notes.get(noteKey(thread)), message = thread.messages[0];
21
+ return saved?.author.name === message.author.name && saved.text === message.text;
22
+ });
23
+ }
24
+
25
+ /** @param thread - Legacy note. @returns Its worksheet-qualified native anchor. */
26
+ function noteKey(thread: WorkbookCommentThread): string {
27
+ return JSON.stringify([thread.cell.sheetId, commentReference(thread.cell)]);
28
+ }
29
+
30
+ /** @param source - Original graph, when present. @param parts - Staged ZIP parts. @param snapshot - Committed workbook.
31
+ * @param paths - Final worksheet paths after directory edits. */
32
+ export function writeWorkbookComments(source: XlsxPackage, parts: Record<string, Uint8Array>, snapshot: WorkbookSnapshot,
33
+ paths: ReadonlyMap<string, string>): void {
34
+ if (sameXlsxComments(source.baseline, snapshot)) return;
35
+ const typesPath = "[Content_Types].xml";
36
+ const manifest = parsePart(parts[typesPath], typesPath);
37
+ const types = rootOf(manifest, contentTypeNs, "Types");
38
+ const native = editPartRelationships(parts, source.workbookPath);
39
+ const old = source.commentGraph;
40
+
41
+ // Dispose only parts owned by comments. Worksheet layout, charts and hyperlink
42
+ // relationships have already been staged and remain on the same native sheet.
43
+ if (old) {
44
+ if (old.peopleRelation) native.remove(old.peopleRelation);
45
+ for (const [path, ids] of old.worksheetRelations) {
46
+ if (!parts[path]) continue;
47
+ const links = editPartRelationships(parts, path);
48
+ for (const id of ids) links.remove(id);
49
+ links.write();
50
+ writeWorksheetCommentMetadata(parts, path, []);
51
+ }
52
+ for (const path of old.parts) delete parts[path];
53
+ for (const node of children(types, "Override")) {
54
+ if (old.parts.has((node.getAttribute("PartName") ?? "").slice(1))) types.removeChild(node);
55
+ }
56
+ }
57
+ const reserved = new Set(Object.keys(parts).map(path => path.toLowerCase()));
58
+ for (const node of children(types, "Override")) reserved.add((node.getAttribute("PartName") ?? "").slice(1).toLowerCase());
59
+ const folder = source.workbookPath.slice(0, source.workbookPath.lastIndexOf("/") + 1);
60
+ let serial = 1;
61
+ /** @param stem - Relative base path. @param suffix - Filename extension. @param type - OPC content type.
62
+ * @returns Newly registered part name. */
63
+ function allocate(stem: string, suffix: string, type: string): string {
64
+ let path: string;
65
+ do { path = folder + stem + serial++ + suffix; } while (reserved.has(path.toLowerCase()) || reserved.has(relationshipsPath(path).toLowerCase()));
66
+ reserved.add(path.toLowerCase());
67
+ const override = manifest.createElementNS(contentTypeNs, "Override");
68
+ override.setAttribute("PartName", "/" + path);
69
+ override.setAttribute("ContentType", type);
70
+ types.appendChild(override);
71
+ return path;
72
+ }
73
+
74
+ const groups = new Map<string, WorkbookCommentThread[]>();
75
+ const threads: WorkbookCommentThread[] = [];
76
+ for (const thread of createWorkbookCommentStore(snapshot.commentThreads ?? [], snapshot.sheets).list()) {
77
+ const path = paths.get(thread.cell.sheetId);
78
+ if (!path) throw invalidXlsxComment();
79
+ const group = groups.get(path) ?? [];
80
+ group.push(thread);
81
+ groups.set(path, group);
82
+ if (thread.kind === "thread") threads.push(thread);
83
+ }
84
+ let people: ReadonlyMap<string, string> = new Map();
85
+ if (threads.length) {
86
+ const path = allocate("persons/person", ".xml", commentContentTypes.people);
87
+ const directory = writeXlsxCommentPeople(path, threads, old?.people);
88
+ parts[path] = directory.bytes;
89
+ people = directory.ids;
90
+ native.add(commentRoles.people, "/" + path);
91
+ }
92
+ for (const [path, group] of groups) {
93
+ group.sort((left, right) => left.cell.row - right.cell.row || left.cell.column - right.cell.column);
94
+ const links = editPartRelationships(parts, path);
95
+ const legacy = allocate("comments/comment", ".xml", commentContentTypes.legacy);
96
+ const drawing = allocate("drawings/notes", ".vml", commentContentTypes.drawing);
97
+ parts[legacy] = writeXlsxLegacyComments(legacy, group);
98
+ parts[drawing] = writeXlsxNoteDrawing(group);
99
+ links.add(commentRoles.legacy, "/" + legacy);
100
+ writeWorksheetCommentMetadata(parts, path, group, links.add(commentRoles.drawing, "/" + drawing));
101
+ const discussions = group.filter(thread => thread.kind === "thread");
102
+ if (discussions.length) {
103
+ const modern = allocate("threadedComments/threadedComment", ".xml", commentContentTypes.thread);
104
+ parts[modern] = writeXlsxCommentThreads(modern, discussions, people);
105
+ links.add(commentRoles.thread, "/" + modern);
106
+ }
107
+ links.write();
108
+ }
109
+ native.write();
110
+ parts[typesPath] = writePart(manifest);
111
+ }
112
+
113
+ /** @param parts - Staged archive. @param path - Worksheet URI. @param threads - Final worksheet discussions.
114
+ * @param id - New drawing relationship ID, or omit to remove the note drawing. */
115
+ function writeWorksheetCommentMetadata(parts: Record<string, Uint8Array>, path: string, threads: readonly WorkbookCommentThread[], id?: string): void {
116
+ const document = parsePart(parts[path], path);
117
+ const sheet = rootOf(document, spreadNs, "worksheet");
118
+ const previous = child(sheet, "legacyDrawing");
119
+ if (previous) sheet.removeChild(previous);
120
+ if (id) {
121
+ const reference = document.createElementNS(spreadNs, "legacyDrawing");
122
+ reference.setAttributeNS(relationshipNs, "r:id", id);
123
+ const successor = children(sheet).find(element => [
124
+ "legacyDrawingHF", "picture", "oleObjects", "controls", "webPublishItems", "tableParts", "extLst"
125
+ ].includes(element.localName ?? ""));
126
+ sheet.insertBefore(reference, successor ?? null);
127
+ }
128
+ writeXlsxCommentRanges(sheet, threads);
129
+ parts[path] = writePart(document);
130
+ }
@@ -0,0 +1,69 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import type { WorkbookCommentAuthor, WorkbookCommentMessage, WorkbookCommentThread } from "@quirekit/workbook";
3
+ import { child, children, isTrue, parsePart, rootOf } from "../../opc/xml";
4
+ import { hasKnownAttributes } from "../../opc/shape";
5
+ import { decodeXlsxText } from "../../worksheet/text";
6
+ import type { XlsxCommentPerson, XlsxLegacyComment } from "../types";
7
+ import { commentAddress, commentReference, commentUuid, invalidXlsxComment, threadedCommentsNs } from "../xml";
8
+
9
+ /** @param bytes - Native directory bytes. @param path - Directory part name. @returns People by native ID. */
10
+ export function readXlsxCommentPeople(bytes: Uint8Array | undefined, path: string): ReadonlyMap<string, XlsxCommentPerson> {
11
+ const root = rootOf(parsePart(bytes, path), threadedCommentsNs, "personList");
12
+ const people = new Map<string, XlsxCommentPerson>();
13
+ for (const node of children(root)) {
14
+ if (node.namespaceURI !== threadedCommentsNs || node.localName !== "person" || children(node).length
15
+ || !hasKnownAttributes(node, ["id", "displayName", "userId", "providerId"])) throw invalidXlsxComment();
16
+ const id = commentUuid(node.getAttribute("id"));
17
+ const name = decodeXlsxText(node.getAttribute("displayName") ?? "").trim();
18
+ if (!id || people.has(id) || !name || name.length > 120) throw invalidXlsxComment();
19
+ people.set(id, { id, name, userId: node.getAttribute("userId") ?? undefined, providerId: node.getAttribute("providerId") ?? undefined });
20
+ }
21
+ return people;
22
+ }
23
+
24
+ /** @param bytes - Native discussions. @param path - Thread part name. @param sheetId - Owning worksheet.
25
+ * @param people - Imported persons. @param placeholders - Legacy note references corresponding to the root messages.
26
+ * @returns Complete threaded discussions and the placeholders they consume. */
27
+ export function readXlsxCommentThreads(bytes: Uint8Array | undefined, path: string, sheetId: string,
28
+ people: ReadonlyMap<string, WorkbookCommentAuthor>, placeholders: ReadonlyMap<string, XlsxLegacyComment>): WorkbookCommentThread[] {
29
+ const root = rootOf(parsePart(bytes, path), threadedCommentsNs, "ThreadedComments");
30
+ const entries = children(root).map(node => readMessage(node, people));
31
+ const roots = new Map<string, WorkbookCommentThread>();
32
+ const messages = new Map<string, WorkbookCommentMessage[]>();
33
+ for (const { message, parent, ref, done } of entries) {
34
+ if (parent) continue;
35
+ const placeholder = placeholders.get(message.id);
36
+ if (!placeholder || roots.has(message.id) || ref && commentReference(commentAddress(sheetId, ref)) !== commentReference(placeholder.cell)) {
37
+ throw invalidXlsxComment();
38
+ }
39
+ roots.set(message.id, { id: message.id, cell: placeholder.cell, kind: "thread", resolved: done, messages: [message] });
40
+ messages.set(message.id, []);
41
+ }
42
+ for (const { message, parent, ref, done } of entries) {
43
+ if (!parent) continue;
44
+ const thread = roots.get(parent);
45
+ if (!thread || done || ref && commentReference(commentAddress(sheetId, ref)) !== commentReference(thread.cell)) throw invalidXlsxComment();
46
+ messages.get(parent)!.push(message);
47
+ }
48
+ if (!roots.size || roots.size !== placeholders.size) throw invalidXlsxComment();
49
+ return [...roots.values()].map(thread => ({ ...thread, messages: [thread.messages[0], ...messages.get(thread.id)!] }));
50
+ }
51
+
52
+ /** @param node - Native threaded comment entry. @param people - Named directory.
53
+ * @returns Its message, source anchor and reply/resolve information. */
54
+ function readMessage(node: Element, people: ReadonlyMap<string, WorkbookCommentAuthor>) {
55
+ if (node.namespaceURI !== threadedCommentsNs || node.localName !== "threadedComment"
56
+ || !hasKnownAttributes(node, ["id", "personId", "parentId", "ref", "dT", "done"])) throw invalidXlsxComment();
57
+ const text = child(node, "text");
58
+ if (text?.namespaceURI !== threadedCommentsNs || children(node).length !== 1 || children(text).length) throw invalidXlsxComment();
59
+ const id = commentUuid(node.getAttribute("id"));
60
+ const author = people.get(commentUuid(node.getAttribute("personId")) ?? "");
61
+ const rawParent = node.getAttribute("parentId");
62
+ const parent = commentUuid(rawParent);
63
+ const done = node.getAttribute("done");
64
+ if (!id || !author || rawParent && !parent || done !== null && !["1", "0", "true", "false"].includes(done)) throw invalidXlsxComment();
65
+ const date = node.getAttribute("dT");
66
+ const createdAt = date ? Date.parse(/[zZ]$|[+-]\d{2}:\d{2}$/u.test(date) ? date : date + "Z") : undefined;
67
+ const message: WorkbookCommentMessage = { id, author, text: decodeXlsxText(text.textContent ?? ""), ...(createdAt !== undefined && { createdAt }) };
68
+ return { message, parent, ref: node.getAttribute("ref"), done: isTrue(done) };
69
+ }
@@ -0,0 +1,61 @@
1
+ import { strToU8 } from "fflate";
2
+ import type { WorkbookCommentThread } from "@quirekit/workbook";
3
+ import { v4 as uuidv4 } from "uuid";
4
+ import { parsePart, rootOf, writePart } from "../../opc/xml";
5
+ import { encodeXlsxText } from "../../worksheet/text";
6
+ import type { XlsxCommentPerson } from "../types";
7
+ import { commentGuid, commentReference, commentUuid, invalidXlsxComment, threadedCommentsNs } from "../xml";
8
+
9
+ /** @param path - Native people part path. @param threads - Discussions to save. @param prior - Native source identity mappings.
10
+ * @returns The people directory and consistent IDs to reference inside individual messages. */
11
+ export function writeXlsxCommentPeople(path: string, threads: readonly WorkbookCommentThread[], prior?: ReadonlyMap<string, XlsxCommentPerson>) {
12
+ const document = parsePart(strToU8('<personList xmlns="' + threadedCommentsNs + '"/>'), path);
13
+ const root = rootOf(document, threadedCommentsNs, "personList");
14
+ const ids = new Map<string, string>();
15
+ const allocated = new Set<string>();
16
+ for (const thread of threads) {
17
+ for (const { author } of thread.messages) {
18
+ if (ids.has(author.id)) continue;
19
+ const native = commentUuid(author.id);
20
+ const id = native && !allocated.has(native) ? native : uuidv4();
21
+ ids.set(author.id, id);
22
+ allocated.add(id);
23
+ const person = document.createElementNS(threadedCommentsNs, "person");
24
+ person.setAttribute("id", commentGuid(id));
25
+ person.setAttribute("displayName", encodeXlsxText(author.name));
26
+ const retained = prior?.get(id);
27
+ if (retained?.name === author.name) {
28
+ if (retained.userId !== undefined) person.setAttribute("userId", retained.userId);
29
+ if (retained.providerId !== undefined) person.setAttribute("providerId", retained.providerId);
30
+ }
31
+ root.appendChild(person);
32
+ }
33
+ }
34
+ return { bytes: writePart(document), ids };
35
+ }
36
+
37
+ /** @param path - Worksheet's modern comment part. @param threads - Canonical threads at worksheet coordinates.
38
+ * @param people - Native author IDs. @returns XLSX threaded comments XML. */
39
+ export function writeXlsxCommentThreads(path: string, threads: readonly WorkbookCommentThread[], people: ReadonlyMap<string, string>): Uint8Array {
40
+ const document = parsePart(strToU8('<ThreadedComments xmlns="' + threadedCommentsNs + '"/>'), path);
41
+ const root = rootOf(document, threadedCommentsNs, "ThreadedComments");
42
+ for (const thread of threads) {
43
+ const ref = commentReference(thread.cell);
44
+ for (const message of thread.messages) {
45
+ const id = people.get(message.author.id);
46
+ if (!id) throw invalidXlsxComment();
47
+ const element = document.createElementNS(threadedCommentsNs, "threadedComment");
48
+ element.setAttribute("ref", ref);
49
+ element.setAttribute("id", commentGuid(message.id));
50
+ element.setAttribute("personId", commentGuid(id));
51
+ if (message.id !== thread.id) element.setAttribute("parentId", commentGuid(thread.id));
52
+ else if (thread.resolved) element.setAttribute("done", "1");
53
+ if (message.createdAt !== undefined) element.setAttribute("dT", new Date(message.createdAt).toISOString());
54
+ const text = document.createElementNS(threadedCommentsNs, "text");
55
+ text.appendChild(document.createTextNode(encodeXlsxText(message.text)));
56
+ element.appendChild(text);
57
+ root.appendChild(element);
58
+ }
59
+ }
60
+ return writePart(document);
61
+ }
@@ -0,0 +1,43 @@
1
+ import type { WorkbookAddress, WorkbookCommentAuthor, WorkbookCommentThread } from "@quirekit/workbook";
2
+
3
+ /** Native person attributes retained with the source package. */
4
+ export interface XlsxCommentPerson extends WorkbookCommentAuthor {
5
+ /** Provider assigned person identifier, retained only in its original package. */
6
+ readonly userId?: string | undefined;
7
+ /** Provider identifying the directory that issued this person's ID. */
8
+ readonly providerId?: string | undefined;
9
+ }
10
+
11
+ /** Native legacy note or compatibility placeholder decoded for a worksheet. */
12
+ export interface XlsxLegacyComment {
13
+ /** Cell referenced by both comment and note drawing. */
14
+ readonly cell: WorkbookAddress;
15
+ /** Original display name or native threaded placeholder identifier. */
16
+ readonly author: string;
17
+ /** Decoded note text. */
18
+ readonly text: string;
19
+ /** Persistent native GUID when the producer supplied it. */
20
+ readonly id?: string | undefined;
21
+ }
22
+
23
+ /** Parts owned exclusively by the current workbook's comments. */
24
+ export interface XlsxCommentGraph {
25
+ /** Workbook relationship for the persons directory. */
26
+ readonly peopleRelation?: string | undefined;
27
+ /** Native identity mappings from the original file, excluded from the workbook model. */
28
+ readonly people: ReadonlyMap<string, XlsxCommentPerson>;
29
+ /** IDs of native note, VML and thread parts keyed by the owning worksheet part. */
30
+ readonly worksheetRelations: ReadonlyMap<string, ReadonlySet<string>>;
31
+ /** Worksheets with a managed legacy drawing element. */
32
+ readonly legacyDrawings: ReadonlySet<string>;
33
+ /** Part paths for safe replacement with their newly authored equivalents. */
34
+ readonly parts: ReadonlySet<string>;
35
+ }
36
+
37
+ /** Result of pairing XLSX native comment parts. */
38
+ export interface XlsxCommentImport {
39
+ /** Supported threads and legacy notes in worksheet order. */
40
+ readonly threads: readonly WorkbookCommentThread[];
41
+ /** Verified graph, if the original contained comments. */
42
+ readonly graph?: XlsxCommentGraph | undefined;
43
+ }
@@ -0,0 +1,50 @@
1
+ import { formatWorkbookColumn, parseWorkbookRange, type WorkbookAddress } from "@quirekit/workbook";
2
+ import { validate as validateUuid } from "uuid";
3
+ import { relationshipNs } from "../opc/xml";
4
+
5
+ /** Namespace for native threads and people. */
6
+ export const threadedCommentsNs = "http://schemas.microsoft.com/office/spreadsheetml/2018/threadedcomments";
7
+ /** Standard VML shape namespace. */
8
+ export const vmlNs = "urn:schemas-microsoft-com:vml";
9
+ /** Namespace for the Excel-specific VML client data. */
10
+ export const vmlExcelNs = "urn:schemas-microsoft-com:office:excel";
11
+ /** Namespace for VML office layout metadata. */
12
+ export const vmlOfficeNs = "urn:schemas-microsoft-com:office:office";
13
+ const microsoftRelationships = "http://schemas.microsoft.com/office/2017/10/relationships/";
14
+
15
+ /** Relationships that identify native comment parts. */
16
+ export const commentRoles = {
17
+ people: microsoftRelationships + "person", thread: microsoftRelationships + "threadedComment",
18
+ legacy: relationshipNs + "/comments", drawing: relationshipNs + "/vmlDrawing"
19
+ };
20
+ /** Expected media types when reading and writing these parts. */
21
+ export const commentContentTypes = {
22
+ people: "application/vnd.ms-excel.person+xml", thread: "application/vnd.ms-excel.threadedcomments+xml",
23
+ legacy: "application/vnd.openxmlformats-officedocument.spreadsheetml.comments+xml",
24
+ drawing: "application/vnd.openxmlformats-officedocument.vmlDrawing"
25
+ };
26
+
27
+ /** @param text - Value from a native identifier. @returns A canonical UUID, when present and valid. */
28
+ export function commentUuid(text: string | null | undefined): string | undefined {
29
+ if (!text) return undefined;
30
+ const value = text.startsWith("{") && text.endsWith("}") ? text.slice(1, -1) : text;
31
+ return validateUuid(value) ? value.toLowerCase() : undefined;
32
+ }
33
+
34
+ /** @param id - Workbook UUID. @returns Native Excel GUID spelling. */
35
+ export function commentGuid(id: string): string { return "{" + id.toUpperCase() + "}"; }
36
+
37
+ /** @param cell - Comment anchor. @returns Native cell reference. */
38
+ export function commentReference({ row, column }: WorkbookAddress): string {
39
+ return formatWorkbookColumn(column) + (row + 1);
40
+ }
41
+
42
+ /** @param sheetId - Current sheet identity. @param ref - Native single-cell reference. @returns Workbook anchor. */
43
+ export function commentAddress(sheetId: string, ref: string): WorkbookAddress {
44
+ if (!/^[A-Z]+[1-9][0-9]*$/iu.test(ref)) throw invalidXlsxComment();
45
+ const range = parseWorkbookRange(sheetId, ref);
46
+ return { sheetId, row: range.startRow, column: range.startColumn };
47
+ }
48
+
49
+ /** @returns Unsupported or inconsistent comment data. */
50
+ export function invalidXlsxComment(): Error { return new Error("存在无法安全写回的单元格评论或旧式批注。"); }
package/src/create.ts ADDED
@@ -0,0 +1,13 @@
1
+ import type { WorkbookSnapshot } from "@quirekit/workbook";
2
+ import { newXlsxPackage } from "./package/new";
3
+ import { writeXlsxPackage } from "./package/write";
4
+ import type { XlsxWriteOptions } from "./types";
5
+
6
+ /**
7
+ * @param snapshot - Authored workbook to save.
8
+ * @param options - Cache access for the saved formulas.
9
+ * @returns New standard XLSX file with editable cells, formulas and worksheets.
10
+ */
11
+ export function createXlsx(snapshot: WorkbookSnapshot, options: XlsxWriteOptions = {}): Uint8Array {
12
+ return writeXlsxPackage(newXlsxPackage(snapshot), snapshot, options);
13
+ }
@@ -0,0 +1,48 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { child, children, readIndex } from "../opc/xml";
3
+
4
+ const maxCachedPoints = 4096;
5
+
6
+ /** @param data - Chart series data holder. @returns Local category, value or name cache in point-index order. */
7
+ export function chartCache(data: Element | undefined): readonly (string | null)[] | null {
8
+ if (!data) return [];
9
+ const reference = child(data, "numRef") ?? child(data, "strRef");
10
+ const cache = reference ? child(reference, "numCache") ?? child(reference, "strCache")
11
+ : child(data, "numLit") ?? child(data, "strLit");
12
+ if (!cache) return child(data, "multiLvlStrRef") ? null : [];
13
+ const count = readIndex(child(cache, "ptCount"), "val") ?? 0;
14
+ const points = children(cache, "pt");
15
+ if (count > maxCachedPoints || points.length > maxCachedPoints) return null;
16
+ const values: (string | null)[] = Array.from({ length: count }, () => null);
17
+ for (const point of points) {
18
+ const index = readIndex(point, "idx");
19
+ if (index === undefined || index >= maxCachedPoints) return null;
20
+ while (values.length <= index) values.push(null);
21
+ values[index] = child(point, "v")?.textContent ?? null;
22
+ }
23
+ return values;
24
+ }
25
+
26
+ /** @param series - Source series. @param zero - Plot blank cells as zero.
27
+ * @returns Authored numeric cache, retaining gaps and rejecting unbounded data. */
28
+ export function chartValues(series: Element, zero: boolean): readonly (number | null)[] | null {
29
+ const values = chartCache(child(series, "val"));
30
+ return values && values.map(value => {
31
+ if (value === null || value.trim() === "") return zero ? 0 : null;
32
+ const number = Number(value);
33
+ return Number.isFinite(number) ? number : null;
34
+ });
35
+ }
36
+
37
+ /** @param cache - Explicit categories by source point index. @param count - Number of plotted values.
38
+ * @returns Exact category labels, or the implicit 1-based index sequence when omitted. */
39
+ export function chartCategories(cache: readonly (string | null)[], count: number): readonly string[] {
40
+ return Array.from({ length: Math.max(cache.length, count) }, (_, index) =>
41
+ cache.length === 0 ? String(index + 1) : cache[index] ?? "");
42
+ }
43
+
44
+ /** @param series - Source series. @returns Literal or cached series label. */
45
+ export function chartSeriesName(series: Element): string {
46
+ const name = child(series, "tx");
47
+ return (name && (child(name, "v")?.textContent ?? chartCache(name)?.[0])) ?? "";
48
+ }
@@ -0,0 +1,96 @@
1
+ /// <reference types="node" />
2
+
3
+ import { readFileSync } from "node:fs";
4
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
5
+ import { expect, test } from "vitest";
6
+ import { openXlsx } from "../package/read";
7
+
8
+ const original = Uint8Array.from(readFileSync(new URL("../../test/fixtures/native-combination-chart.xlsx", import.meta.url)));
9
+
10
+ /** @param name - Native part. @param edit - Change to its XML. @returns The modified regression input. */
11
+ function withPart(name: string, edit: (xml: string) => string): Uint8Array {
12
+ const parts = unzipSync(original);
13
+ parts[name] = strToU8(edit(strFromU8(parts[name]!)));
14
+ return zipSync(parts);
15
+ }
16
+
17
+ test("preserves dual and shared value axes, formatted fractions, and fixed native anchors", () => {
18
+ const file = openXlsx("收入与回款", original);
19
+ const [dual, shared] = file.charts;
20
+ const [data, target] = file.snapshot.sheets;
21
+ expect(file.charts).toHaveLength(2);
22
+ expect(dual?.anchor).toEqual({
23
+ sheetId: data?.id, from: { row: 5, column: 1, x: 3, y: 2 }, to: { row: 5, column: 1, x: 443, y: 262 }
24
+ });
25
+ expect(dual?.preview.plot).toMatchObject({
26
+ kind: "cartesian",
27
+ xAxes: [{ categories: ["一月", "二月", "三月"] }],
28
+ yAxes: [
29
+ { position: "left", min: 0, max: 6000, interval: 2000, numberFormat: { decimals: 0, useGrouping: true } },
30
+ { position: "right", min: 0, max: 0.4, interval: 0.1, gridlines: false, numberFormat: { decimals: 0, percent: true } }
31
+ ],
32
+ series: [
33
+ { name: "收入", kind: "bar", xAxis: 0, yAxis: 0, values: [2000, 4000, 3000], color: "#2568AD" },
34
+ { name: "回款比例", kind: "line", xAxis: 0, yAxis: 1, values: [0.1, 0.3, 0.2], color: "#CF4425" }
35
+ ]
36
+ });
37
+ expect(dual?.sources.map(({ role, range }) => [role, range.sheetId, range.startColumn, range.startRow, range.endRow])).toEqual([
38
+ ["categories", data?.id, 0, 1, 3], ["values", data?.id, 1, 1, 3], ["values", data?.id, 2, 1, 3]
39
+ ]);
40
+ expect(shared?.anchor).toEqual({
41
+ sheetId: target?.id, from: { row: 0, column: 0, x: 8, y: 128 }, to: { row: 0, column: 0, x: 448, y: 388 }
42
+ });
43
+ expect(shared?.preview.plot).toMatchObject({
44
+ yAxes: [expect.objectContaining({ max: 6000 })],
45
+ series: [{ kind: "bar", xAxis: 0, yAxis: 0 }, { kind: "line", xAxis: 0, yAxis: 0, values: [3200, 4400, 4800] }]
46
+ });
47
+ expect(file.restrictions).toContain("绘图或图表");
48
+ expect(file.snapshot.charts ?? []).toEqual([]);
49
+ expect(file.write(file.snapshot)).toEqual(original);
50
+ expect(file.original()).toEqual(original);
51
+ });
52
+
53
+ test("binds a separate hidden category axis using IDs even when the numeric axis nodes are reordered", () => {
54
+ const bytes = withPart("xl/charts/chart1.xml", xml => {
55
+ const [column, line] = xml.match(/<valAx>.*?<\/valAx>/gu)!;
56
+ const category = xml.match(/<catAx>.*?<\/catAx>/u)![0];
57
+ const secondary = category.replace('axId val="10"', 'axId val="20"').replace('crossAx val="100"', 'crossAx val="200"')
58
+ .replace('<axPos', '<delete val="1"/><axPos');
59
+ return xml.replace('<axId val="10"/><axId val="200"/>', '<axId val="20"/><axId val="200"/>')
60
+ .replace(column! + line!, line!.replace('crossAx val="10"', 'crossAx val="20"') + column! + secondary);
61
+ });
62
+ const file = openXlsx("组合图", bytes);
63
+ expect(file.charts[0]?.preview.plot).toMatchObject({
64
+ xAxes: [{ visible: true }, { visible: false, categories: ["一月", "二月", "三月"] }],
65
+ yAxes: [{ position: "left", max: 6000 }, { position: "right", max: 0.4 }],
66
+ series: [{ xAxis: 0, yAxis: 0 }, { xAxis: 1, yAxis: 1 }]
67
+ });
68
+ });
69
+
70
+ test("keeps charts with unresolved value axes in the original and continues with other valid charts", () => {
71
+ const bytes = withPart("xl/charts/chart1.xml", xml => xml.replace('<axId val="200"/>', '<axId val="999"/>'));
72
+ const file = openXlsx("组合图", bytes);
73
+ expect(file.charts.map(chart => chart.preview.presentation.title)).toEqual(["本期与目标"]);
74
+ expect(file.original()).toEqual(bytes);
75
+ });
76
+
77
+ test("uses native cell markers for a fixed chart frame with a zero-size transform", () => {
78
+ const bytes = withPart("xl/drawings/drawing1.xml", xml => xml
79
+ .replace("<oneCellAnchor>", '<twoCellAnchor editAs="absolute">')
80
+ .replace("</oneCellAnchor>", "</twoCellAnchor>")
81
+ .replace('<ext cx="4191000" cy="2476500"/>', "<to><col>6</col><colOff>28575</colOff><row>18</row><rowOff>19050</rowOff></to>")
82
+ .replace("<xfrm/>", '<xfrm xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"><a:off x="0" y="0"/><a:ext cx="0" cy="0"/></xfrm>'));
83
+ expect(openXlsx("固定图框", bytes).charts[0]?.anchor).toMatchObject({
84
+ from: { row: 5, column: 1, x: 3, y: 2 }, to: { row: 18, column: 6, x: 3, y: 2 }
85
+ });
86
+ });
87
+
88
+ test("preserves an empty cached series using the category labels of its shared axis", () => {
89
+ const bytes = withPart("xl/charts/chart1.xml", xml => xml.replace(/<lineChart>.*?<\/lineChart>/u, plot => plot
90
+ .replace(/<cat>.*?<\/cat>/u, "")
91
+ .replace(/(<numCache><formatCode>0%<\/formatCode><ptCount val="3"\/>).*?<\/numCache>/u, "$1</numCache>")));
92
+ expect(openXlsx("空缓存点", bytes).charts[0]?.preview.plot).toMatchObject({
93
+ xAxes: [{ categories: ["一月", "二月", "三月"] }],
94
+ series: [{ name: "收入", xAxis: 0 }, { name: "回款比例", xAxis: 0, values: [null, null, null] }]
95
+ });
96
+ });
@@ -0,0 +1,87 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import type { ChartPreviewPlot } from "@quirekit/chart";
3
+ import type { XlsxChart } from "../types";
4
+ import { child, children, isTrue, readIndex } from "../opc/xml";
5
+ import { chartCache, chartCategories, chartSeriesName, chartValues } from "./cache";
6
+ import { chartNamespace } from "./namespaces";
7
+ import { readCartesianPreview } from "./presentation/cartesian/plot";
8
+ import { readChartPlotLayout } from "./presentation/layout";
9
+ import { readChartPaint, readCircularSeriesPaint } from "./presentation/paint";
10
+ import { chartChild, chartPosition, chartSeriesInOrder, chartValue } from "./presentation/properties";
11
+ import { readChartSources } from "./sources";
12
+
13
+ const maximumSeries = 16;
14
+
15
+ /** @param title - Optional native title. @returns Plain text from the authored title. */
16
+ export function chartTitleText(title: Element | undefined): string {
17
+ const holder = title && child(title, "tx");
18
+ const rich = holder && child(holder, "rich");
19
+ if (!rich) return chartCache(holder)?.[0] ?? "";
20
+ return children(rich, "p").map(p => children(p, "r").map(r => child(r, "t")?.textContent ?? "").join("")).join("\n");
21
+ }
22
+
23
+ /** @param plot - Native pie or doughnut. @param area - Source plot area. @param nativeSeries - Drawing group members.
24
+ * @param zero - Whether blanks are zero. @param theme - Source workbook colors.
25
+ * @returns A preview of the circular cache and its source paint. */
26
+ function readCircularPreview(plot: Element, area: Element, nativeSeries: readonly Element[], zero: boolean,
27
+ theme: readonly string[]): ChartPreviewPlot | null {
28
+ const series = [];
29
+ for (const native of nativeSeries) {
30
+ const values = chartValues(native, zero);
31
+ const cache = chartCache(chartChild(native, "cat"));
32
+ if (!cache || !values?.length || !values.some(value => value !== null)) return null;
33
+ series.push({
34
+ name: chartSeriesName(native), values, categories: chartCategories(cache, values.length),
35
+ ...readCircularSeriesPaint(native, theme, values.length)
36
+ });
37
+ }
38
+ const labels = chartChild(plot, "dLbls") ?? chartChild(nativeSeries[0], "dLbls");
39
+ const size = readIndex(chartChild(plot, "holeSize"), "val");
40
+ const firstSliceAngle = readIndex(chartChild(plot, "firstSliceAng"), "val");
41
+ const layout = readChartPlotLayout(area);
42
+ return {
43
+ kind: plot.localName === "pieChart" ? "pie" : "doughnut", series,
44
+ categoryLabels: isTrue(chartValue(labels, "showCatName")),
45
+ ...(size !== undefined && size >= 10 && size <= 90 && { holeRatio: size / 100 }),
46
+ ...(firstSliceAngle !== undefined && firstSliceAngle <= 360 && { firstSliceAngle }),
47
+ ...(layout && { layout })
48
+ };
49
+ }
50
+
51
+ /** @param chart - Conventional 2D chart space. @param id - Chart part's identity. @param theme - Workbook's theme palette.
52
+ * @param sheetId - Worksheet owning the drawing. @param sheets - Workbook sheet IDs by name.
53
+ * @returns Static chart data and its local sheet references. */
54
+ export function readChart(chart: Element, id: string, theme: readonly string[], sheetId: string,
55
+ sheets: ReadonlyMap<string, string>): Omit<XlsxChart, "anchor"> | null {
56
+ const content = chartChild(chart, "chart");
57
+ const area = chartChild(content, "plotArea");
58
+ if (!content || !area) return null;
59
+ const plots = children(area).filter(node => node.namespaceURI === chartNamespace && node.localName?.endsWith("Chart"));
60
+ const first = plots[0];
61
+ if (!first || plots.length > maximumSeries) return null;
62
+ const nativeSeries = plots.flatMap(plot => children(plot, "ser").filter(node => node.namespaceURI === chartNamespace));
63
+ if (!nativeSeries.length || nativeSeries.length > maximumSeries) return null;
64
+
65
+ const circular = first.localName === "pieChart" || first.localName === "doughnutChart";
66
+ const blanks = chartValue(content, "dispBlanksAs");
67
+ const plot = circular && plots.length === 1 ? readCircularPreview(first, area, nativeSeries, blanks === "zero", theme)
68
+ : readCartesianPreview(area, plots, blanks, theme);
69
+ if (!plot) return null;
70
+ const labels = chartChild(first, "dLbls") ?? chartChild(nativeSeries[0], "dLbls");
71
+ const frame = readChartPaint(chartChild(chart, "spPr"), theme);
72
+ const legend = chartChild(content, "legend");
73
+ const axes = plot.kind === "cartesian" ? [...plot.xAxes, ...plot.yAxes] : [];
74
+ return {
75
+ sources: readChartSources(chartSeriesInOrder(nativeSeries), sheetId, sheets),
76
+ preview: {
77
+ id, revision: 0, plot, ...(frame && { frame }), style: { presetId: "simple-1", palette: theme.slice(4, 10), fontRole: "body" },
78
+ presentation: {
79
+ title: chartTitleText(chartChild(content, "title")), legend: legend ? chartPosition(legend, "legendPos") ?? "right" : "none",
80
+ dataLabels: isTrue(chartValue(labels, "showVal")),
81
+ categoryAxis: axes.some(axis => axis.categories !== undefined && axis.visible),
82
+ valueAxis: axes.some(axis => axis.categories === undefined && axis.visible),
83
+ gridlines: axes.some(axis => axis.categories === undefined && axis.gridlines)
84
+ }
85
+ }
86
+ };
87
+ }