@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,112 @@
1
+ import { copyWorkbookStructuredTables, createWorkbookStructuredFormulaProjection, isWorkbookDefinedName, workbookRangesOverlap,
2
+ type WorkbookAppearance, type WorkbookCell, type WorkbookSheet, type WorkbookSnapshot, type WorkbookSourceTable, type WorkbookStructuredTable } from "@quirekit/workbook";
3
+ import { verifyXlsxPartOwnership } from "../opc/ownership";
4
+ import type { XlsxSourceTable } from "./types";
5
+
6
+ /** OPC media type for SpreadsheetML tables. */
7
+ export const xlsxTableContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml";
8
+
9
+ /** @param snapshot - Authored workbook. @param tables - Table parts retained by the original file.
10
+ * @returns Sparse index of the header and totals rows. */
11
+ export function indexTableEdgeInputs(snapshot: WorkbookSnapshot, tables: readonly Pick<WorkbookSourceTable, "range" | "header" | "totals">[]) {
12
+ const sheets = new Map<string, Map<number, Map<number, WorkbookCell>>>();
13
+ for (const { range, header, totals } of tables) {
14
+ const rows = sheets.get(range.sheetId) ?? new Map();
15
+ if (header && !rows.has(range.startRow)) rows.set(range.startRow, new Map());
16
+ if (totals && !rows.has(range.endRow)) rows.set(range.endRow, new Map());
17
+ sheets.set(range.sheetId, rows);
18
+ }
19
+ for (const sheet of snapshot.sheets) {
20
+ const rows = sheets.get(sheet.id);
21
+ if (!rows?.size) continue;
22
+ for (const { row, column, input } of sheet.cells) rows.get(row)?.set(column, input);
23
+ }
24
+ return sheets;
25
+ }
26
+
27
+ /** @param sheet - Live worksheet that retains a table. @param table - Table definition with declared titles.
28
+ * @param edges - Indexed native header and totals rows.
29
+ * @returns Whether the table remains a distinct rectangle with the same authored headings. */
30
+ function matchesTable(sheet: WorkbookSheet | undefined, { header, range, columns }: Pick<WorkbookSourceTable, "header" | "range" | "columns">,
31
+ edges: ReturnType<typeof indexTableEdgeInputs>): boolean {
32
+ if (!sheet || !columns
33
+ || sheet.merges?.some(candidate => workbookRangesOverlap(candidate, range))
34
+ || sheet.autoFilter && workbookRangesOverlap(sheet.autoFilter.range, range)) return false;
35
+ if (!header) return true;
36
+ const titles = edges.get(sheet.id)?.get(range.startRow);
37
+ return columns.every((column, offset) => {
38
+ const input = titles?.get(range.startColumn + offset);
39
+ return input?.kind === "value" && input.value === column;
40
+ });
41
+ }
42
+
43
+ /** @param snapshot - Worksheet formulas and locations. @param appearance - Native named table metadata.
44
+ * @returns Whether the engine can cache the structured references without dropping any requested portion. */
45
+ export function supportsXlsxStructuredFormulas(snapshot: WorkbookSnapshot, appearance: WorkbookAppearance): boolean {
46
+ const names = new Map(snapshot.sheets.map(({ id, name }) => [id, name]));
47
+ const projection = createWorkbookStructuredFormulaProjection(appearance, id => names.get(id));
48
+ if (!projection.tables.length) return true;
49
+ return snapshot.sheets.every(({ id: sheetId, cells }) => cells.every(({ row, column, input }) =>
50
+ input.kind !== "formula" || projection.project(input.formula, { sheetId, row, column }) !== undefined));
51
+ }
52
+
53
+ /** @param parts - Exact original ZIP members. @param tables - Imported local table parts. @param snapshot - Original cells and names.
54
+ * @returns Whether edits can keep these table parts intact. */
55
+ export function canWriteXlsxSourceTables(parts: Readonly<Record<string, Uint8Array>>, tables: readonly XlsxSourceTable[],
56
+ snapshot: WorkbookSnapshot): boolean {
57
+ if (!tables.length) return true;
58
+ const owners = new Map<string, ReadonlySet<string>>(), types = new Map<string, string>();
59
+ const ids = new Set<number>(), names = new Set<string>(), internals = new Set<string>();
60
+ const defined = new Set(snapshot.definedNames?.map(name => name.name.toUpperCase()));
61
+ const sheets = new Map(snapshot.sheets.map(sheet => [sheet.id, sheet]));
62
+ const edges = indexTableEdgeInputs(snapshot, tables.map(table => table.layout));
63
+ for (const table of tables) {
64
+ const name = table.layout.name.toUpperCase(), internal = table.internalName.toUpperCase();
65
+ if (!table.dataWritable || ids.has(table.id) || names.has(name) || internals.has(internal) || defined.has(name)
66
+ || owners.has(table.path) || !isWorkbookDefinedName(table.internalName)
67
+ || snapshot.pivotTables?.some(pivot => workbookRangesOverlap(pivot.output, table.layout.range))
68
+ || !matchesTable(sheets.get(table.layout.range.sheetId), table.layout, edges)) return false;
69
+ ids.add(table.id);
70
+ names.add(name);
71
+ internals.add(internal);
72
+ owners.set(table.path, new Set([table.owner]));
73
+ types.set(table.path, xlsxTableContentType);
74
+ }
75
+ try { verifyXlsxPartOwnership(parts, owners, types); }
76
+ catch { return false; }
77
+ return true;
78
+ }
79
+
80
+ /** @param tables - Original writable table layouts. @returns Workbook definitions keyed to existing OPC parts. */
81
+ export function xlsxStructuredTableDefinitions(tables: readonly XlsxSourceTable[]): WorkbookStructuredTable[] {
82
+ return tables.map(({ layout: { id, name, range, header, totals, columns, filter }, sorts, hiddenTotals }) =>
83
+ ({ id: id!, name, range, header, totals, columns: columns!, showFilter: Boolean(filter),
84
+ ...(filter?.value.columns.length && { filter: filter.value }), ...(sorts && { sorts }), ...(hiddenTotals && { hiddenTotals }) }));
85
+ }
86
+
87
+ /** @param original - Native workbook state. @param next - Desired authored values.
88
+ * Verifies native table and cell semantics before emitting any table parts. */
89
+ export function assertXlsxStructuredTableWrites(original: WorkbookSnapshot | undefined, next: WorkbookSnapshot): void {
90
+ const source = original?.structuredTables ?? [];
91
+ const definitions = copyWorkbookStructuredTables(next.structuredTables ?? source, next.sheets);
92
+ if (!source.length && !definitions.length) return;
93
+ const afterDefinitions = new Map(definitions.map(table => [table.id, table]));
94
+ const beforeDefinitions = new Map(source.map(table => [table.id, table]));
95
+ const current = new Map(next.sheets.map(sheet => [sheet.id, sheet]));
96
+ const copies = new Set(next.sheets.flatMap(sheet => sheet.origin ? [sheet.origin.sheetId] : []));
97
+ const edges = indexTableEdgeInputs(next, definitions);
98
+ const names = new Set(next.definedNames?.map(name => name.name.toUpperCase()));
99
+ if (source.some(table => afterDefinitions.has(table.id) && copies.has(table.range.sheetId))) throw new Error("复制工作表前,请先转换其原生表。");
100
+ for (const table of definitions) {
101
+ const { id, header, name, range } = table;
102
+ const before = beforeDefinitions.get(id);
103
+ if (!matchesTable(current.get(range.sheetId), table, edges)
104
+ || next.formulaResults?.some(({ spill }) => spill?.values.length && workbookRangesOverlap(spill.range, range))
105
+ || next.pivotTables?.some(pivot => workbookRangesOverlap(pivot.output, range))
106
+ || before && (header !== before.header || range.sheetId !== before.range.sheetId
107
+ || range.startRow !== before.range.startRow || !workbookRangesOverlap(range, before.range)
108
+ || !header && (table.totals !== before.totals || range.startColumn !== before.range.startColumn
109
+ || range.endColumn !== before.range.endColumn || range.endRow !== before.range.endRow))
110
+ || names.has(name.toUpperCase())) throw new Error(`原生表「${name}」的表头、定义或范围无法按当前文件写回。`);
111
+ }
112
+ }
@@ -0,0 +1,274 @@
1
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
2
+ import { expect, it } from "vitest";
3
+ import { openWorkbook, parseWorkbookRange, type WorkbookSnapshot } from "@quirekit/workbook";
4
+ import { createXlsx, openXlsx } from "../index";
5
+ import { readTheme } from "../styles/color";
6
+ import { createXlsxBuiltinTableStyles } from "./styles/builtin";
7
+
8
+ const sheetPath = "xl/worksheets/sheet1.xml";
9
+ const sheetRelations = "xl/worksheets/_rels/sheet1.xml.rels";
10
+ const tablePath = "xl/tables/table1.xml";
11
+ const sheetNs = "http://schemas.openxmlformats.org/spreadsheetml/2006/main";
12
+ const relNs = "http://schemas.openxmlformats.org/officeDocument/2006/relationships";
13
+ const seed: WorkbookSnapshot = { version: 1, revision: 0, id: "ledger", name: "Ledger", sheets: [{ id: "sample", name: "Sample", cells: [
14
+ { row: 0, column: 0, input: { kind: "value", value: "Name" } },
15
+ { row: 0, column: 1, input: { kind: "value", value: "Amount" } },
16
+ { row: 1, column: 0, input: { kind: "value", value: 4.75 } },
17
+ { row: 1, column: 1, input: { kind: "value", value: 5.25 } }
18
+ ], formats: [
19
+ { row: 1, column: 1, format: { background: "#AACCEE", numberFormat: "0.000" } }
20
+ ] }] };
21
+
22
+ it("round-trips the new data of an ordinary imported table while keeping the original definition", async () => {
23
+ const bytes = pack(`<table xmlns="${sheetNs}" id="1" displayName="Ledger" ref="A1:B5"><autoFilter ref="A1:B5"/><tableColumns count="2"><tableColumn id="1" name="Name"/><tableColumn id="2" name="Amount"/></tableColumns><tableStyleInfo name="TableStyleLight9" showRowStripes="1"/></table>`);
24
+ const file = openXlsx("Ledger", bytes);
25
+ expect(file.restrictions).toEqual([]);
26
+ const sheetId = file.snapshot.sheets[0]!.id;
27
+ const book = await openWorkbook(file.snapshot, { appearance: file.appearance });
28
+ try {
29
+ expect(book.prepare({ operationId: "absent-totals", baseRevision: 0, commands: [
30
+ { name: "setCells", target: parseWorkbookRange(sheetId, "D1"), params: { formula: "=SUM(Ledger[#Totals])" } }
31
+ ] }).changedCells).toBe(1);
32
+ await book.commit(book.prepare({ operationId: "data", baseRevision: 0, commands: [
33
+ { name: "setCells", target: parseWorkbookRange(sheetId, "B2"), params: { value: 17.5 } }
34
+ ] }).id);
35
+ const output = file.write(book.snapshot());
36
+ const saved = unzipSync(output), original = unzipSync(bytes);
37
+ expect(saved[tablePath]).toEqual(original[tablePath]);
38
+ expect(saved[sheetRelations]).toEqual(original[sheetRelations]);
39
+ const reopened = openXlsx("Updated ledger", output);
40
+ expect(reopened.restrictions).toEqual([]);
41
+ expect(reopened.snapshot.sheets[0]?.cells).toContainEqual({ row: 1, column: 1, input: { kind: "value", value: 17.5 } });
42
+ await book.undo("undo-data");
43
+ expect(file.write(book.snapshot())).toEqual(bytes);
44
+ } finally { await book.close(); }
45
+ });
46
+
47
+ it("renames the physical header and native column under the original relationship and column ID", async () => {
48
+ const bytes = pack(`<table xmlns="${sheetNs}" id="1" displayName="Ledger" ref="A1:B5"><autoFilter ref="A1:B5"/><tableColumns count="2"><tableColumn id="7" name="Name"/><tableColumn id="12" name="Amount"/></tableColumns><tableStyleInfo name="TableStyleLight9" showRowStripes="1"/></table>`);
49
+ const original = unzipSync(bytes);
50
+ const file = openXlsx("Ledger", bytes);
51
+ const table = file.snapshot.structuredTables![0]!;
52
+ const book = await openWorkbook(file.snapshot, { appearance: file.appearance });
53
+ try {
54
+ await book.commit(book.prepare({ operationId: "rename-heading", baseRevision: 0, commands: [
55
+ { name: "setCells", target: parseWorkbookRange(table.range.sheetId, "B1"), params: { value: "Net [USD]" } }
56
+ ] }).id);
57
+ const output = file.write(book.snapshot());
58
+ const parts = unzipSync(output);
59
+ expect(parts[sheetRelations]).toEqual(original[sheetRelations]);
60
+ expect(strFromU8(parts[tablePath]!)).toContain('<tableColumn id="12" name="Net [USD]"/>');
61
+ expect(strFromU8(parts[tablePath]!)).toContain('<tableStyleInfo name="TableStyleLight9" showRowStripes="1"/>');
62
+ const reopened = openXlsx("Renamed", output);
63
+ expect(reopened.restrictions).toEqual([]);
64
+ expect(reopened.snapshot.structuredTables?.[0]).toMatchObject({ id: table.id, columns: ["Name", "Net [USD]"] });
65
+ expect(reopened.snapshot.sheets[0]?.cells).toContainEqual({ row: 0, column: 1, input: { kind: "value", value: "Net [USD]" } });
66
+ await book.undo("undo-heading");
67
+ expect(file.write(book.snapshot())).toEqual(bytes);
68
+ } finally { await book.close(); }
69
+ });
70
+
71
+ it("reads WPS multi-color table filters and saves both unfilled and combined selections", async () => {
72
+ const sheet = seed.sheets[0]!;
73
+ const range = parseWorkbookRange(sheet.id, "A1:B5");
74
+ const bytes = createXlsx({ ...seed, sheets: [{
75
+ ...sheet, cells: [...sheet.cells, ...[2, 3, 4].map(row => ({ row, column: 1, input: { kind: "value" as const, value: row } }))],
76
+ formats: [...sheet.formats!, { row: 3, column: 1, format: { background: "#FFFFFF" } }]
77
+ }], structuredTables: [{ id: "items", name: "Ledger", range, columns: ["Name", "Amount"], header: true, totals: false, showFilter: true }] });
78
+ const parts = unzipSync(bytes);
79
+ const noFill = '<dxf><fill><patternFill patternType="none"/></fill></dxf>';
80
+ const blueFill = '<dxf><fill><patternFill patternType="solid"><fgColor rgb="FFAACCEE"/><bgColor rgb="FF000000"/></patternFill></fill></dxf>';
81
+ parts["xl/styles.xml"] = strToU8(strFromU8(parts["xl/styles.xml"]!).replace("</styleSheet>", `<dxfs count="1">${blueFill}</dxfs></styleSheet>`));
82
+ parts[tablePath] = strToU8(strFromU8(parts[tablePath]!).replace('<autoFilter ref="A1:B5"/>',
83
+ `<autoFilter ref="A1:B5" xmlns:etc="http://www.wps.cn/officeDocument/2017/etCustomData" etc:filterBottomFollowUsedRange="0"><filterColumn colId="1"><colorFilter dxfId="0"/><extLst><colorFilter dxfId="0"/><colorFilter dxfId="1"/><dxfs count="2">${noFill}${blueFill}</dxfs></extLst></filterColumn></autoFilter>`));
84
+ parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!).replace(/<row r="([45])">/gu, '<row r="$1" hidden="1">'));
85
+ const file = openXlsx("WPS colors", zipSync(parts));
86
+ const table = file.snapshot.structuredTables![0]!;
87
+ const sheetId = table.range.sheetId;
88
+ expect(file.restrictions).toEqual([]);
89
+ expect(table.filter).toMatchObject({ hiddenRows: [3], columns: [{ column: 1, rule: { kind: "color", source: "fill", colors: [null, "#AACCEE"] } }] });
90
+ expect(file.appearance.sheets.get(sheetId)?.rows.get(4)?.hidden).toBe(true);
91
+ const book = await openWorkbook(file.snapshot, { appearance: file.appearance });
92
+ try {
93
+ const target = table.range;
94
+ for (const [selection, hiddenRows] of [[{ color: null }, [1, 3]], [{ colors: [null, "#FFFFFF"] }, [1]]] as const) {
95
+ await book.commit(book.prepare({ operationId: `set-colors-${book.revision}`, baseRevision: book.revision, commands: [{
96
+ name: "setStructuredTableFilter", target, params: { id: table.id, columns: [
97
+ { column: "B", rule: { kind: "color", source: "fill", ...selection } }
98
+ ] }
99
+ }] }).id);
100
+ const saved = file.write(book.snapshot());
101
+ const styles = strFromU8(unzipSync(saved)["xl/styles.xml"]!);
102
+ const tableXml = strFromU8(unzipSync(saved)[tablePath]!);
103
+ expect(tableXml).toContain("<colorFilter dxfId=");
104
+ if ("color" in selection) expect(styles).toContain(noFill);
105
+ else expect(tableXml).toContain('values="none #FFFFFF"');
106
+ const reopened = openXlsx("Saved colors", saved);
107
+ expect(reopened.restrictions).toEqual([]);
108
+ expect(reopened.snapshot.structuredTables?.[0]?.filter).toMatchObject({ hiddenRows,
109
+ columns: [{ column: 1, rule: { kind: "color", source: "fill", ...selection } }] });
110
+ expect(reopened.appearance.sheets.get(sheetId)?.rows.get(4)?.hidden).toBe(true);
111
+ }
112
+ } finally { await book.close(); }
113
+ });
114
+
115
+ it("reopens an applied native table filter and clears only its rows while preserving button settings", async () => {
116
+ const parts = unzipSync(pack(`<table xmlns="${sheetNs}" id="1" displayName="Ledger" ref="A1:B5"><autoFilter ref="A1:B5"><filterColumn colId="0" hiddenButton="1"><filters blank="1"/></filterColumn></autoFilter><tableColumns count="2"><tableColumn id="1" name="Name"/><tableColumn id="2" name="Amount"/></tableColumns></table>`));
117
+ parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!).replace('<row r="2">', '<row r="2" hidden="1">')
118
+ .replace("</sheetData>", '<row r="3" hidden="1"/></sheetData>'));
119
+ const file = openXlsx("Filtered ledger", zipSync(parts));
120
+ expect(file.restrictions).toEqual([]);
121
+ const table = file.snapshot.structuredTables![0]!;
122
+ expect(table.filter?.hiddenRows).toEqual([1]);
123
+ const sheetId = table.range.sheetId;
124
+ const book = await openWorkbook(file.snapshot, { appearance: file.appearance });
125
+ try {
126
+ expect(book.readAxisDimension(sheetId, "row", 1).hidden).toBe(false);
127
+ expect(book.readAxisDimension(sheetId, "row", 2).hidden).toBe(true);
128
+ await book.commit(book.prepare({ operationId: "clear", baseRevision: 0, commands: [
129
+ { name: "clearStructuredTableFilter", target: table.range, params: { id: table.id } }
130
+ ] }).id);
131
+ const saved = file.write(book.snapshot());
132
+ const written = unzipSync(saved);
133
+ expect(strFromU8(written[tablePath]!)).toContain('<filterColumn colId="0" hiddenButton="1"/>');
134
+ expect(written[sheetRelations]).toEqual(parts[sheetRelations]);
135
+ const reopened = openXlsx("Cleared ledger", saved);
136
+ expect(reopened.restrictions).toEqual([]);
137
+ expect(reopened.snapshot.structuredTables?.[0]?.filter).toBeUndefined();
138
+ expect(reopened.appearance.sheets.get(sheetId)?.rows.get(1)?.hidden).toBeFalsy();
139
+ expect(reopened.appearance.sheets.get(sheetId)?.rows.get(2)?.hidden).toBe(true);
140
+
141
+ await book.undo("restore-filter");
142
+ await book.commit(book.prepare({ operationId: "edit-filter-value", baseRevision: book.revision, commands: [
143
+ { name: "clearCells", target: parseWorkbookRange(sheetId, "A2"), params: {} }
144
+ ] }).id);
145
+ const beforeReapply = openXlsx("Saved mask", file.write(book.snapshot()));
146
+ expect(beforeReapply.snapshot.structuredTables?.[0]?.filter?.hiddenRows).toEqual([1]);
147
+ await book.commit(book.prepare({ operationId: "reapply", baseRevision: book.revision, commands: [
148
+ { name: "reapplyStructuredTableFilter", target: table.range, params: { id: table.id } }
149
+ ] }).id);
150
+ expect(book.filteredRows(sheetId)).toEqual([]);
151
+ expect(book.readAxisDimension(sheetId, "row", 2).hidden).toBe(true);
152
+ } finally { await book.close(); }
153
+ });
154
+
155
+ it("keeps the original cached formula when a source reference selects disjoint table sections", () => {
156
+ const parts = unzipSync(pack(`<table xmlns="${sheetNs}" id="1" displayName="Ledger" ref="A1:B5" totalsRowCount="1"><tableColumns count="2"><tableColumn id="1" name="Name"/><tableColumn id="2" name="Amount"/></tableColumns></table>`));
157
+ const workbookPath = "xl/workbook.xml";
158
+ parts[workbookPath] = strToU8(strFromU8(parts[workbookPath]!).replace('fullCalcOnLoad="1"', 'fullCalcOnLoad="0" calcCompleted="1"'));
159
+ parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!).replace("</row>",
160
+ '<c r="D1"><f>COUNT(Ledger[[#Headers],[#Totals],[Amount]])</f><v>0</v></c></row>'));
161
+ const bytes = zipSync(parts);
162
+ const file = openXlsx("Ledger", bytes);
163
+ expect(file.restrictions).toEqual(["结构化引用包含暂未支持的组合"]);
164
+ expect(file.snapshot.formulaResults).toContainEqual(expect.objectContaining({ row: 0, column: 3, result: { status: "value", value: 0 } }));
165
+ expect(file.write(file.snapshot)).toEqual(bytes);
166
+ });
167
+
168
+ it("writes a new native definition and updates its existing relationship after reopen", async () => {
169
+ const first = await openWorkbook(seed);
170
+ let bytes: Uint8Array;
171
+ try {
172
+ await first.commit(first.prepare({ operationId: "create-table", baseRevision: 0, commands: [
173
+ { name: "setStructuredTable", target: parseWorkbookRange("sample", "A1:B3"), params: { name: "Sales" } }
174
+ ] }).id);
175
+ bytes = createXlsx(first.snapshot());
176
+ } finally { await first.close(); }
177
+ const file = openXlsx("Ledger", bytes);
178
+ expect(file.restrictions).toEqual([]);
179
+ const before = file.snapshot.structuredTables?.[0]!;
180
+ expect(before).toMatchObject({ name: "Sales", columns: ["Name", "Amount"], showFilter: true });
181
+ const second = await openWorkbook(file.snapshot, { appearance: file.appearance });
182
+ try {
183
+ await second.commit(second.prepare({ operationId: "save-table", baseRevision: 0, commands: [
184
+ { name: "setStructuredTable", target: parseWorkbookRange(before.range.sheetId, "A1:C4"), params: { id: before.id, name: "Revenue", showFilter: false } }
185
+ ] }).id);
186
+ const saved = file.write(second.snapshot());
187
+ const parts = unzipSync(saved);
188
+ expect(parts[sheetRelations]).toEqual(unzipSync(bytes)[sheetRelations]);
189
+ expect(strFromU8(parts[tablePath]!)).toMatch(/ref="A1:C4"/u);
190
+ expect(strFromU8(parts[tablePath]!)).not.toContain("<autoFilter");
191
+ const reopened = openXlsx("Ledger", saved);
192
+ expect(reopened.restrictions).toEqual([]);
193
+ expect(reopened.snapshot.structuredTables?.[0]).toMatchObject({ name: "Revenue", columns: ["Name", "Amount", "Column3"], showFilter: false });
194
+ await second.undo("undo-definition");
195
+ expect(file.write(second.snapshot())).toEqual(bytes);
196
+ await second.commit(second.prepare({ operationId: "another-table", baseRevision: second.revision, commands: [
197
+ { name: "setStructuredTable", target: parseWorkbookRange(before.range.sheetId, "D1:E4"), params: { name: "Other" } }
198
+ ] }).id);
199
+ const combined = file.write(second.snapshot());
200
+ const reloaded = openXlsx("Ledger", combined);
201
+ expect(reloaded.restrictions).toEqual([]);
202
+ expect(reloaded.snapshot.structuredTables?.map(table => table.name)).toEqual(["Sales", "Other"]);
203
+ expect(unzipSync(combined)[tablePath]).toEqual(unzipSync(bytes)[tablePath]);
204
+ } finally { await second.close(); }
205
+ });
206
+
207
+ /** @param table - Actual SpreadsheetML table part. @param styles - Optional additions to the native shared styles.
208
+ * @param columns - Optional source metadata for default column formatting.
209
+ * @returns A workbook with a table relationship anchored in the first sheet. */
210
+ function pack(table: string, styles = "", columns = ""): Uint8Array {
211
+ const parts = unzipSync(createXlsx(seed));
212
+ parts[tablePath] = strToU8(table);
213
+ parts[sheetPath] = strToU8(strFromU8(parts[sheetPath]!).replace("<sheetData>", columns + "<sheetData>").replace("</worksheet>",
214
+ `<tableParts count="1"><tablePart xmlns:r="${relNs}" r:id="rId21"/></tableParts></worksheet>`));
215
+ parts[sheetRelations] = strToU8(`<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships"><Relationship Id="rId21" Type="${relNs}/table" Target="../tables/table1.xml"/></Relationships>`);
216
+ parts["[Content_Types].xml"] = strToU8(strFromU8(parts["[Content_Types].xml"]!).replace("</Types>",
217
+ '<Override PartName="/xl/tables/table1.xml" ContentType="application/vnd.openxmlformats-officedocument.spreadsheetml.table+xml"/></Types>'));
218
+ if (styles) parts["xl/styles.xml"] = strToU8(strFromU8(parts["xl/styles.xml"]!).replace("</styleSheet>", styles + "</styleSheet>"));
219
+ return zipSync(parts);
220
+ }
221
+
222
+ it("resolves all sixty ordinary table presets against the file theme", () => {
223
+ const theme = readTheme(undefined).map((color, index) => index === 4 ? "#5B9BD5" : color);
224
+ const preset = createXlsxBuiltinTableStyles(theme);
225
+ for (const [family, count] of [["light", 21], ["medium", 28], ["dark", 11]] as const) {
226
+ for (let i = 1; i <= count; i++) expect(preset(`tablestyle${family}${i}`)?.headerRow).toBeDefined();
227
+ expect(preset(`tablestyle${family}${count + 1}`)).toBeUndefined();
228
+ }
229
+ expect(preset("tablestylelight9")?.headerRow?.format).toEqual({ background: "#5B9BD5", color: "#FFFFFF", bold: true });
230
+ expect(preset("pivottablelight1")).toBeUndefined();
231
+ });
232
+
233
+ it("retains built-in table styling, direct cell styling and a native filter without changing the source package", async () => {
234
+ const bytes = pack(`<table xmlns="${sheetNs}" id="1" displayName="Ledger" name="Ledger" ref="A1:B5"><autoFilter ref="A1:B5"><filterColumn colId="1" hiddenButton="1"/></autoFilter><tableColumns count="2"><tableColumn id="1" name="Name"/><tableColumn id="2" name="Amount"/></tableColumns><tableStyleInfo name="TableStyleLight9" showRowStripes="1"/></table>`,
235
+ "", '<cols><col min="1" max="1" style="1"/></cols>');
236
+ const source = openXlsx("Ledger", bytes);
237
+ const id = source.snapshot.sheets[0]!.id;
238
+ const table = source.appearance.sheets.get(id)?.tables?.[0];
239
+ expect(table).toMatchObject({ name: "Ledger", range: parseWorkbookRange(id, "A1:B5"),
240
+ filter: { value: { range: parseWorkbookRange(id, "A1:B5"), columns: [] }, hiddenButtons: [1] } });
241
+ expect(source.snapshot.sheets[0]?.autoFilter).toBeUndefined();
242
+ const book = await openWorkbook(source.snapshot, { appearance: source.appearance, isEditable: () => false });
243
+ try {
244
+ expect(book.readFormat({ sheetId: id, row: 0, column: 0 })).toMatchObject({ background: "#4F81BD", color: "#FFFFFF", bold: true });
245
+ expect(book.readFormat({ sheetId: id, row: 1, column: 0 }).numberFormat).toBe("General");
246
+ expect(book.readFormat({ sheetId: id, row: 2, column: 0 }).borders?.top).toEqual({ stroke: "thin", color: "#4F81BD" });
247
+ expect(book.readFormat({ sheetId: id, row: 1, column: 1 })).toMatchObject({ background: "#AACCEE", numberFormat: "0.000" });
248
+ expect(book.readFormat({ sheetId: id, row: 5, column: 0 }).borders).toBeUndefined();
249
+ expect(source.restrictions).toEqual([]);
250
+ expect(source.write(book.snapshot())).toEqual(bytes);
251
+ } finally { await book.close(); }
252
+ });
253
+
254
+ it("applies custom stripe widths, column and header precedence and a differential number format", async () => {
255
+ const styles = `<dxfs count="3">
256
+ <dxf><fill><patternFill patternType="solid"><fgColor rgb="FF94ADDC"/></patternFill></fill></dxf>
257
+ <dxf><fill><patternFill patternType="solid"><fgColor rgb="FFECCC88"/></patternFill></fill><numFmt numFmtId="164" formatCode="0.00%"/></dxf>
258
+ <dxf><font><b/><color rgb="FFFAFAFA"/></font><fill><patternFill patternType="solid"><fgColor rgb="FF335566"/></patternFill></fill></dxf>
259
+ </dxfs><tableStyles count="1" defaultTableStyle="House"><tableStyle name="House" table="1" count="3">
260
+ <tableStyleElement type="headerRow" dxfId="2"/><tableStyleElement type="firstRowStripe" size="2" dxfId="1"/><tableStyleElement type="firstColumnStripe" dxfId="0"/>
261
+ </tableStyle></tableStyles>`;
262
+ const bytes = pack(`<table xmlns="${sheetNs}" id="1" displayName="Ledger" ref="A1:B5"><tableColumns count="2"><tableColumn id="1" name="Name"/><tableColumn id="2" name="Amount"/></tableColumns><tableStyleInfo showRowStripes="true" showColumnStripes="1"/></table>`, styles);
263
+ const source = openXlsx("Ledger", bytes);
264
+ const sheetId = source.snapshot.sheets[0]!.id;
265
+ const book = await openWorkbook(source.snapshot, { appearance: source.appearance, isEditable: () => false });
266
+ try {
267
+ expect(book.readFormat({ sheetId, row: 0, column: 0 })).toMatchObject({ background: "#335566", color: "#FAFAFA", bold: true });
268
+ expect(book.readFormat({ sheetId, row: 2, column: 0 })).toMatchObject({ background: "#ECCC88", numberFormat: "0.00%" });
269
+ expect(book.readFormat({ sheetId, row: 3, column: 0 }).background).toBe("#94ADDC");
270
+ expect(book.readFormat({ sheetId, row: 4, column: 0 }).background).toBe("#ECCC88");
271
+ expect(book.snapshot().sheets[0]?.cells).toHaveLength(4);
272
+ expect(source.write(book.snapshot())).toEqual(bytes);
273
+ } finally { await book.close(); }
274
+ });
@@ -0,0 +1,117 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { indexWorkbookRanges, parseWorkbookRange, workbookStructuredTableData,
3
+ type WorkbookRange, type WorkbookSourceTable, type WorkbookSourceTableFilter, type WorkbookStructuredTableSorts } from "@quirekit/workbook";
4
+ import { readRelationships, relationshipsPath } from "../opc/relationships";
5
+ import { child, children, isTrue, parsePart, readIndex, relationshipNs, rootOf, spreadNs } from "../opc/xml";
6
+ import { readXlsxAutoFilter } from "../worksheet/filters/read";
7
+ import { wpsFilterNamespace } from "../worksheet/filters/rules";
8
+ import type { XlsxFilterReadContext } from "../worksheet/filters/types";
9
+ import { readXlsxOwnerSort } from "../worksheet/sort/read";
10
+ import { hasKnownAttributes } from "../opc/shape";
11
+ import { readXlsxTableColumns, xlsxTableAllowsDataWrites } from "./definition";
12
+ import { readXlsxTableTotals } from "./totals";
13
+ import type { createXlsxTableStyleReader } from "./styles/read";
14
+ import type { XlsxSourceTable } from "./types";
15
+
16
+ /** @param table - Native table definition. @param range - Sheet rectangle with its heading.
17
+ * @param totals - Whether this table has a totals row. @param context - Source calendar and styles.
18
+ * @returns Understood filter limited to this table. */
19
+ function readFilter(table: Element, range: WorkbookRange, totals: boolean,
20
+ context: XlsxFilterReadContext): WorkbookSourceTableFilter | undefined {
21
+ try {
22
+ const filter = readXlsxAutoFilter(table, range.sheetId, true, context);
23
+ if (!filter || filter.range.startRow !== range.startRow || filter.range.endRow !== range.endRow - Number(totals)
24
+ || filter.range.startColumn !== range.startColumn || filter.range.endColumn !== range.endColumn) return;
25
+ const columns = children(child(table, "autoFilter")!, "filterColumn");
26
+ const hiddenButtons: number[] = [];
27
+ const seen = new Set<number>();
28
+ for (const column of columns) {
29
+ const index = readIndex(column, "colId");
30
+ if (index === undefined || seen.has(index) || index > range.endColumn - range.startColumn) return;
31
+ seen.add(index);
32
+ if (isTrue(column.getAttribute("hiddenButton")) || ["0", "false"].includes(column.getAttribute("showButton") ?? "")) {
33
+ hiddenButtons.push(range.startColumn + index);
34
+ }
35
+ }
36
+ return { value: filter, hiddenButtons };
37
+ } catch { return undefined; }
38
+ }
39
+
40
+ /** @param root - Parsed SpreadsheetML table. @param sheetId - Relationship owner.
41
+ * @param style - Workbook table style resolver. @param context - Source calendar and filter styles.
42
+ * @returns Source layout, when the range can be located. */
43
+ function readTable(root: Element, sheetId: string, style: ReturnType<typeof createXlsxTableStyleReader>,
44
+ context: XlsxFilterReadContext): WorkbookSourceTable | undefined {
45
+ const name = root.getAttribute("displayName") || root.getAttribute("name");
46
+ const serial = readIndex(root, "id");
47
+ if (!name || !serial) return;
48
+ const range = parseWorkbookRange(sheetId, root.getAttribute("ref") ?? "");
49
+ const headerRows = root.hasAttribute("headerRowCount") ? readIndex(root, "headerRowCount") : 1;
50
+ const totalRows = root.hasAttribute("totalsRowCount") ? readIndex(root, "totalsRowCount") : 0;
51
+ if (headerRows === undefined || totalRows === undefined || headerRows > 1 || totalRows > 1 || headerRows + totalRows > range.endRow - range.startRow + 1) return;
52
+ const fields = child(root, "tableColumns");
53
+ if (!fields || children(fields, "tableColumn").length !== range.endColumn - range.startColumn + 1) return;
54
+ const columns = readXlsxTableColumns(root, fields, range.endColumn - range.startColumn + 1);
55
+ const header = headerRows === 1, totals = totalRows === 1;
56
+ const filter = header ? readFilter(root, range, totals, context) : undefined;
57
+ return { id: `xlsx-table:${serial}`, name, range, header, totals, ...(columns && { columns }), elements: style(child(root, "tableStyleInfo")), ...(filter && { filter }) };
58
+ }
59
+
60
+ /** @param root - Native definition. @param layout - Validated table footprint and filter. @param context - Differential palette.
61
+ * @returns Criteria decoded independently for the table and filter owners. */
62
+ function readTableSorts(root: Element, layout: WorkbookSourceTable, context: XlsxFilterReadContext): WorkbookStructuredTableSorts | undefined {
63
+ const body = workbookStructuredTableData(layout);
64
+ if (!body) return;
65
+ const filter = child(root, "autoFilter");
66
+ const headedRange = layout.header ? { ...layout.range, endRow: body.endRow } : undefined;
67
+ const wpsHeader = layout.filter && filter?.getAttributeNS(wpsFilterNamespace, "filterBottomFollowUsedRange") === "0"
68
+ ? headedRange?.startRow : undefined;
69
+ const region = { body, headedRange, wpsHeader };
70
+ const table = readXlsxOwnerSort(root, body.sheetId, context.differentials, region);
71
+ const nested = layout.filter && filter && readXlsxOwnerSort(filter, body.sheetId, context.differentials, region);
72
+ if (table || nested) return { ...(table && { table }), ...(nested && { filter: nested }) };
73
+ }
74
+
75
+ /** @param worksheet - Worksheet XML. @param owner - Relationship owner in the XLSX package. @param sheetId - Stable sheet key.
76
+ * @param parts - Retained OPC archive. @param style - Source palette and style catalog adapter.
77
+ * @param context - Source calendar and filter styles.
78
+ * @returns Validated table layouts and their owned relationships, preserving the original XML. */
79
+ export function readXlsxTables(worksheet: Element, owner: string, sheetId: string, parts: Readonly<Record<string, Uint8Array>>,
80
+ style: ReturnType<typeof createXlsxTableStyleReader>, context: XlsxFilterReadContext) {
81
+ const container = child(worksheet, "tableParts");
82
+ if (container?.namespaceURI !== spreadNs) return;
83
+ const relPath = relationshipsPath(owner);
84
+ const nodes = children(container, "tablePart");
85
+ const records: XlsxSourceTable[] = [];
86
+ const ids = new Set<string>();
87
+ try {
88
+ const relations = readRelationships(parsePart(parts[relPath], relPath), owner);
89
+ const targets = new Set<string>();
90
+ for (const node of nodes) {
91
+ const id = node.getAttributeNS(relationshipNs, "id");
92
+ const relation = id ? relations.get(id) : undefined;
93
+ if (node.namespaceURI !== spreadNs || !id || !relation?.path || relation.type !== relationshipNs + "/table" || targets.has(relation.path)) continue;
94
+ targets.add(relation.path);
95
+ try {
96
+ const root = rootOf(parsePart(parts[relation.path], relation.path), spreadNs, "table");
97
+ const table = readTable(root, sheetId, style, context);
98
+ if (table) {
99
+ const sorts = readTableSorts(root, table, context);
100
+ const totals = readXlsxTableTotals(child(root, "tableColumns")!, table.range.startColumn);
101
+ records.push({ owner, path: relation.path, id: readIndex(root, "id")!, internalName: root.getAttribute("name") || table.name,
102
+ layout: table, ...(sorts && { sorts }), ...(!table.totals && totals?.length && { hiddenTotals: totals }),
103
+ dataWritable: totals !== undefined && xlsxTableAllowsDataWrites(root, table, sorts) && !parts[relationshipsPath(relation.path)]
104
+ && hasKnownAttributes(node, [], true) && children(node).length === 0 });
105
+ ids.add(id);
106
+ }
107
+ } catch { /* Malformed table parts stay in the original download. */ }
108
+ }
109
+ } catch { return undefined; }
110
+ const tables = records.map(({ layout }) => layout)
111
+ .sort((first, second) => first.range.startRow - second.range.startRow || first.range.startColumn - second.range.startColumn);
112
+ const intersect = indexWorkbookRanges(tables, table => table.range);
113
+ const layouts = tables.filter(table => !intersect(table.range, other => table !== other));
114
+ const supported = nodes.length > 0 && nodes.length === children(container).length && layouts.length === nodes.length
115
+ && hasKnownAttributes(container, ["count"]) && (!container.hasAttribute("count") || readIndex(container, "count") === nodes.length);
116
+ return { tables: layouts, ids, records, supported };
117
+ }
@@ -0,0 +1,55 @@
1
+ import type { WorkbookSnapshot } from "@quirekit/workbook";
2
+ import { editPartRelationships } 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 type { XlsxSourceTable } from "./types";
6
+
7
+ /** @param source - Original, verified OPC tables. @param parts - Staged archive before worksheet copies are made.
8
+ * @param snapshot - Complete table catalog, when provided by the workbook. */
9
+ export function removeXlsxStructuredTables(source: XlsxPackage, parts: Record<string, Uint8Array>, snapshot: WorkbookSnapshot): void {
10
+ if (snapshot.structuredTables === undefined || !source.baseline?.structuredTables?.length) return;
11
+ const active = new Set(snapshot.structuredTables.map(table => table.id));
12
+ const removed = new Set(source.baseline.structuredTables.filter(table => !active.has(table.id)).map(table => table.id));
13
+ const tables = (source.sourceTables ?? []).filter(record => record.layout.id && removed.has(record.layout.id));
14
+ if (!tables.length) return;
15
+ const byOwner = new Map<string, XlsxSourceTable[]>();
16
+ for (const table of tables) {
17
+ const entries = byOwner.get(table.owner) ?? [];
18
+ entries.push(table);
19
+ byOwner.set(table.owner, entries);
20
+ }
21
+
22
+ // The relationship IDs belong to the original worksheet. Preserve all other children in its table container.
23
+ for (const [owner, records] of byOwner) {
24
+ const document = parsePart(parts[owner], owner);
25
+ const worksheet = rootOf(document, spreadNs, "worksheet");
26
+ const container = child(worksheet, "tableParts");
27
+ if (!container) throw new Error("待转换的原生表缺少所属工作表声明。");
28
+ const relations = editPartRelationships(parts, owner);
29
+ const links = new Map([...relations.entries.values()].filter(entry => entry.path && entry.type === relationshipNs + "/table")
30
+ .map(entry => [entry.path!, entry.id]));
31
+ const nodes = new Map(children(container, "tablePart").map(entry => [entry.getAttributeNS(relationshipNs, "id"), entry]));
32
+ for (const record of records) {
33
+ const id = links.get(record.path), node = id && nodes.get(id);
34
+ if (!id || !node) throw new Error("待转换的原生表缺少所属工作表关系。");
35
+ container.removeChild(node);
36
+ relations.remove(id);
37
+ }
38
+ const count = children(container, "tablePart").length;
39
+ if (count) container.setAttribute("count", String(count));
40
+ else worksheet.removeChild(container);
41
+ relations.write();
42
+ parts[owner] = writePart(document);
43
+ }
44
+
45
+ // Remove only the overrides and files for the verified, exclusive parts.
46
+ const path = "[Content_Types].xml";
47
+ const document = parsePart(parts[path], path);
48
+ const types = rootOf(document, contentTypeNs, "Types");
49
+ const removedParts = new Set(tables.map(table => "/" + table.path));
50
+ for (const entry of children(types, "Override")) {
51
+ if (removedParts.has(entry.getAttribute("PartName") ?? "")) types.removeChild(entry);
52
+ }
53
+ for (const table of tables) delete parts[table.path];
54
+ parts[path] = writePart(document);
55
+ }