@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,109 @@
1
+ import type { ChartGrouping, ChartPreviewCategorySeries, ChartPreviewPlot } from "@quirekit/chart";
2
+ import type { Element } from "@xmldom/xmldom";
3
+ import { children, isTrue } from "../../../opc/xml";
4
+ import { chartCache, chartCategories, chartSeriesName, chartValues } from "../../cache";
5
+ import { chartNamespace } from "../../namespaces";
6
+ import { readChartPaint } from "../paint";
7
+ import { chartChild, chartSeriesInOrder, chartValue } from "../properties";
8
+ import { chartAxisPositions, readCartesianAxis, readCartesianAxisPairs } from "./axes";
9
+
10
+ const cartesianKinds = { barChart: "bar", lineChart: "line", areaChart: "area" } as const;
11
+
12
+ /** @param plot - Native Cartesian group. @returns Its neutral series kind when supported. */
13
+ function plotKind(plot: Element): ChartPreviewCategorySeries["kind"] | undefined {
14
+ const name = plot.localName;
15
+ return name && Object.hasOwn(cartesianKinds, name) ? cartesianKinds[name as keyof typeof cartesianKinds] : undefined;
16
+ }
17
+
18
+ /** @param plot - Native group. @returns Grouping policy for the renderer. */
19
+ function plotGrouping(plot: Element): ChartGrouping {
20
+ const value = chartValue(plot, "grouping");
21
+ return value === "stacked" || value === "percentStacked" ? value : "standard";
22
+ }
23
+
24
+ /** @param left - Existing category sequence. @param right - Incoming sequence.
25
+ * @returns The longer sequence when they share the same category order. */
26
+ function mergeCategories(left: readonly string[] | undefined, right: readonly string[]): readonly string[] | undefined {
27
+ if (!left) return right;
28
+ const [shorter, longer] = left.length < right.length ? [left, right] : [right, left];
29
+ return shorter.every((label, index) => label === longer[index]) ? longer : undefined;
30
+ }
31
+
32
+ /** @param native - Source series. @param plot - Its source plot. @param kind - Renderer series kind.
33
+ * @param theme - Workbook theme palette. @returns Native presentation properties supported by the renderer. */
34
+ function seriesPresentation(native: Element, plot: Element, kind: ChartPreviewCategorySeries["kind"], theme: readonly string[]) {
35
+ const paint = readChartPaint(chartChild(native, "spPr"), theme);
36
+ const color = kind === "line" ? paint?.outline?.color : paint?.fill;
37
+ const labels = chartValue(chartChild(native, "dLbls"), "showVal") ?? chartValue(chartChild(plot, "dLbls"), "showVal");
38
+ const symbol = chartValue(chartChild(native, "marker"), "symbol");
39
+ const plotMarker = chartValue(plot, "marker");
40
+ return {
41
+ ...(color && { color }), dataLabels: isTrue(labels),
42
+ markers: kind === "line" && (symbol ? symbol !== "none" : plotMarker == null || isTrue(plotMarker)),
43
+ smooth: isTrue(chartValue(native, "smooth") ?? chartValue(plot, "smooth"))
44
+ };
45
+ }
46
+
47
+ /** @param area - Native plot area. @param plots - Its chart groups in source order.
48
+ * @param blanks - Source missing point policy. @param theme - Workbook theme colors.
49
+ * @returns The bound categorical chart, or null for an unsafe or unmodeled combination. */
50
+ export function readCartesianPreview(area: Element, plots: readonly Element[], blanks: string | null | undefined,
51
+ theme: readonly string[]): Extract<ChartPreviewPlot, { kind: "cartesian" }> | null {
52
+ const pairs = readCartesianAxisPairs(area, plots);
53
+ if (!pairs) return null;
54
+ const categoryNodes = [...new Set(pairs.map(pair => pair.category))];
55
+ const valueNodes = [...new Set(pairs.map(pair => pair.value))];
56
+ const horizontal = chartValue(plots[0], "barDir") === "bar";
57
+ const combination = plots.length > 1;
58
+ if (categoryNodes.length > 2 || valueNodes.length > 2) return null;
59
+ if (combination && (categoryNodes.some(node => node?.localName === "dateAx")
60
+ || valueNodes.some(node => chartChild(chartChild(node, "scaling"), "logBase")))) return null;
61
+
62
+ const seriesByNode = new Map<Element, ChartPreviewCategorySeries>();
63
+ const labelsByAxis: (readonly string[] | undefined)[] = [];
64
+ const pointsByAxis: number[] = [];
65
+ const percentByAxis: (boolean | undefined)[] = [];
66
+
67
+ // Build a common category sequence inside each bound axis; each plot retains its own stack.
68
+ for (const [group, plot] of plots.entries()) {
69
+ const kind = plotKind(plot);
70
+ if (!kind || (kind === "bar" && chartValue(plot, "barDir") === "bar") !== horizontal) return null;
71
+ const categoryIndex = categoryNodes.indexOf(pairs[group]!.category);
72
+ const valueIndex = valueNodes.indexOf(pairs[group]!.value);
73
+ const grouping = plotGrouping(plot);
74
+ const percent = grouping === "percentStacked";
75
+ if (percentByAxis[valueIndex] !== undefined && percentByAxis[valueIndex] !== percent) return null;
76
+ percentByAxis[valueIndex] = percent;
77
+
78
+ const nativeSeries = children(plot, "ser").filter(node => node.namespaceURI === chartNamespace);
79
+ if (!nativeSeries.length) return null;
80
+ for (const native of nativeSeries) {
81
+ const values = chartValues(native, blanks === "zero");
82
+ const cache = chartCache(chartChild(native, "cat"));
83
+ if (!cache || !values?.length) return null;
84
+ pointsByAxis[categoryIndex] = Math.max(pointsByAxis[categoryIndex] ?? 0, values.length);
85
+ if (cache.length) {
86
+ const labels = mergeCategories(labelsByAxis[categoryIndex], chartCategories(cache, cache.length));
87
+ if (!labels) return null;
88
+ labelsByAxis[categoryIndex] = labels;
89
+ }
90
+
91
+ seriesByNode.set(native, {
92
+ name: chartSeriesName(native), values, kind, group, grouping, horizontal, connectNulls: blanks === "span",
93
+ xAxis: horizontal ? valueIndex : categoryIndex, yAxis: horizontal ? categoryIndex : valueIndex,
94
+ ...seriesPresentation(native, plot, kind, theme)
95
+ });
96
+ }
97
+ }
98
+
99
+ const series = chartSeriesInOrder([...seriesByNode.keys()]).map(node => seriesByNode.get(node)!);
100
+ if (series.every(item => item.values.every(value => value === null))) return null;
101
+
102
+ const categoryPositions = chartAxisPositions(categoryNodes, !horizontal);
103
+ const valuePositions = chartAxisPositions(valueNodes, horizontal);
104
+ const categoryAxes = categoryNodes.map((node, index) =>
105
+ readCartesianAxis(node, categoryPositions[index], chartCategories(labelsByAxis[index] ?? [], pointsByAxis[index]!), false, combination));
106
+ const valueAxes = valueNodes.map((node, index) =>
107
+ readCartesianAxis(node, valuePositions[index], undefined, percentByAxis[index] === true, combination));
108
+ return { kind: "cartesian", xAxes: horizontal ? valueAxes : categoryAxes, yAxes: horizontal ? categoryAxes : valueAxes, series };
109
+ }
@@ -0,0 +1,9 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+
3
+ /** Native categorical and numeric axes bound by one chart plot group. */
4
+ export interface CartesianAxisPair {
5
+ /** Category axis, or the implicit axis of a standalone legacy plot. */
6
+ readonly category: Element | undefined;
7
+ /** Value axis, or the implicit axis of a standalone legacy plot. */
8
+ readonly value: Element | undefined;
9
+ }
@@ -0,0 +1,29 @@
1
+ import type { ChartPreviewLayoutValue, ChartPreviewPlotLayout } from "@quirekit/chart";
2
+ import type { Element } from "@xmldom/xmldom";
3
+ import { child } from "../../opc/xml";
4
+ import { chartNamespace } from "../namespaces";
5
+
6
+ const measurements = [["x", "x"], ["y", "y"], ["w", "width"], ["h", "height"]] as const;
7
+ const decimal = /^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/iu;
8
+
9
+ /** @param area - Circular plot area. @returns Known manual coordinates in chart-relative units. */
10
+ export function readChartPlotLayout(area: Element): ChartPreviewPlotLayout | undefined {
11
+ const layout = child(area, "layout");
12
+ const manual = layout && child(layout, "manualLayout");
13
+ if (manual?.namespaceURI !== chartNamespace) return;
14
+ const target = child(manual, "layoutTarget")?.getAttribute("val");
15
+ if (target && target !== "inner" && target !== "outer") return;
16
+ const result: Partial<Record<keyof ChartPreviewPlotLayout, ChartPreviewLayoutValue>> = {};
17
+ for (const [name, property] of measurements) {
18
+ const node = child(manual, name);
19
+ if (!node) continue;
20
+ const mode = child(manual, name + "Mode")?.getAttribute("val") || "factor";
21
+ const raw = node.getAttribute("val")?.trim() ?? "";
22
+ const fraction = decimal.test(raw) ? Number(raw) : NaN;
23
+ const size = property === "width" || property === "height";
24
+ if ((mode !== "factor" && mode !== "edge") || !Number.isFinite(fraction) || fraction > 1
25
+ || (size ? fraction <= 0 : fraction < (mode === "edge" ? 0 : -1))) return;
26
+ result[property] = { mode, fraction };
27
+ }
28
+ return Object.keys(result).length ? result : undefined;
29
+ }
@@ -0,0 +1,56 @@
1
+ import type { ChartPreviewPaint, ChartPreviewPieSeries } from "@quirekit/chart";
2
+ import type { Element } from "@xmldom/xmldom";
3
+ import { child, children, readIndex } from "../../opc/xml";
4
+ import { drawingThemeColor } from "../../styles/color";
5
+ import { chartNamespace, drawingMainNamespace } from "../namespaces";
6
+
7
+ /** @param node - Native DrawingML shape or line properties. @param name - Direct drawing child.
8
+ * @returns The requested member in the DrawingML namespace. */
9
+ function drawingChild(node: Element, name: string): Element | undefined {
10
+ return children(node, name).find(element => element.namespaceURI === drawingMainNamespace);
11
+ }
12
+
13
+ /** @param node - Shape or outline properties. @param theme - Resolved workbook colors.
14
+ * @returns Explicit solid paint or transparency, if representable. */
15
+ function drawingFill(node: Element, theme: readonly string[]): string | null | undefined {
16
+ if (drawingChild(node, "noFill")) return null;
17
+ const solid = drawingChild(node, "solidFill");
18
+ if (!solid) return;
19
+ const color = children(solid)[0];
20
+ if (!color || color.namespaceURI !== drawingMainNamespace || children(color).length) return;
21
+ const value = color.getAttribute("val");
22
+ if (!value) return;
23
+ if (color.localName === "schemeClr") return drawingThemeColor(theme, value);
24
+ if (color.localName === "srgbClr" && /^[a-f\d]{6}$/iu.test(value)) return "#" + value.toUpperCase();
25
+ }
26
+
27
+ /** @param shape - ChartML shape properties. @param theme - Resolved workbook colors.
28
+ * @returns The explicitly authored solid or transparent components. */
29
+ export function readChartPaint(shape: Element | undefined, theme: readonly string[]): ChartPreviewPaint | undefined {
30
+ if (shape?.namespaceURI !== chartNamespace) return;
31
+ const fill = drawingFill(shape, theme);
32
+ const line = drawingChild(shape, "ln");
33
+ const color = line && drawingFill(line, theme);
34
+ const dash = line && drawingChild(line, "prstDash")?.getAttribute("val");
35
+ const emu = readIndex(line, "w");
36
+ const outline = color === null ? null : color && (!dash || dash === "solid") && line && !drawingChild(line, "custDash")
37
+ ? { color, width: (emu ?? 0) / 9525 } : undefined;
38
+ if (fill === undefined && outline === undefined) return;
39
+ return { ...(fill !== undefined && { fill }), ...(outline !== undefined && { outline }) };
40
+ }
41
+
42
+ /** @param series - Original pie or doughnut series. @param theme - Resolved workbook colors.
43
+ * @param count - Validated value count. @returns Explicit series and slice paint on the cached data. */
44
+ export function readCircularSeriesPaint(series: Element, theme: readonly string[], count: number): Pick<ChartPreviewPieSeries, "paint" | "points"> {
45
+ const paint = readChartPaint(child(series, "spPr"), theme);
46
+ const points: Record<number, ChartPreviewPaint> = {};
47
+ let styled = false;
48
+ for (const node of children(series, "dPt")) {
49
+ if (node.namespaceURI !== chartNamespace) continue;
50
+ const index = readIndex(child(node, "idx"), "val");
51
+ if (index === undefined || index >= count) continue;
52
+ const point = readChartPaint(child(node, "spPr"), theme);
53
+ if (point) { points[index] = point; styled = true; }
54
+ }
55
+ return { ...(paint && { paint }), ...(styled && { points }) };
56
+ }
@@ -0,0 +1,31 @@
1
+ import type { ChartPreviewAxis } from "@quirekit/chart";
2
+ import type { Element } from "@xmldom/xmldom";
3
+ import { children, readIndex } from "../../opc/xml";
4
+ import { chartNamespace } from "../namespaces";
5
+
6
+ const positions = { t: "top", b: "bottom", l: "left", r: "right" } as const;
7
+
8
+ /** @param node - Optional native chart element. @param name - Direct ChartML child.
9
+ * @returns The matched element in the chart namespace. */
10
+ export function chartChild(node: Element | undefined, name: string): Element | undefined {
11
+ return node && children(node, name).find(element => element.namespaceURI === chartNamespace);
12
+ }
13
+
14
+ /** @param node - Optional value holder. @param key - Child with a val attribute. @returns Its lexical value. */
15
+ export function chartValue(node: Element | undefined, key: string): string | null | undefined {
16
+ return chartChild(node, key)?.getAttribute("val");
17
+ }
18
+
19
+ /** @param node - Chart axis or legend. @param key - Position element. @returns Authored placement. */
20
+ export function chartPosition(node: Element | undefined, key: string): ChartPreviewAxis["position"] {
21
+ const value = chartValue(node, key);
22
+ return value && Object.hasOwn(positions, value) ? positions[value as keyof typeof positions] : undefined;
23
+ }
24
+
25
+ /** @param series - Series elements collected from one or more plot groups.
26
+ * @returns Authored global order when every series has a unique order, otherwise source order. */
27
+ export function chartSeriesInOrder(series: readonly Element[]): readonly Element[] {
28
+ const orders = series.map(node => readIndex(chartChild(node, "order"), "val"));
29
+ if (orders.includes(undefined) || new Set(orders).size !== series.length) return series;
30
+ return series.map((node, index) => ({ node, order: orders[index]! })).sort((a, b) => a.order - b.order).map(({ node }) => node);
31
+ }
@@ -0,0 +1,85 @@
1
+ import type { WorkbookFloatingShape } from "@quirekit/workbook";
2
+ import type { Element } from "@xmldom/xmldom";
3
+ import type { XlsxImageAssetReader } from "../image/types";
4
+ import { readRelationships, relationshipsPath } from "../opc/relationships";
5
+ import { child, children, parsePart, relationshipNs, rootOf } from "../opc/xml";
6
+ import type { PackageRelationship } from "../opc/types";
7
+ import type { XlsxChart, XlsxFloatingPicture } from "../types";
8
+ import { drawingElement, readDrawingAnchor } from "./placement/anchor";
9
+ import { readChart } from "./chart";
10
+ import { chartNamespace, drawingNamespace } from "./namespaces";
11
+ import { readDrawingPicture } from "./picture";
12
+ import { readWorksheetShape } from "./shapes/read";
13
+ import type { XlsxWorksheetShapeTheme } from "./shapes/types";
14
+ import type { XlsxDrawingLayout } from "./placement/types";
15
+
16
+ /** @param parts - Local OPC archive. @param owner - Part referencing another member. @returns Its relationships by ID. */
17
+ export function drawingPartRelationships(parts: Readonly<Record<string, Uint8Array>>, owner: string): ReadonlyMap<string, PackageRelationship> {
18
+ const path = relationshipsPath(owner);
19
+ return parts[path] ? readRelationships(parsePart(parts[path], path), owner) : new Map();
20
+ }
21
+
22
+ /** @param relationships - Already resolved OPC relationships. @param element - Element referencing its ID.
23
+ * @param kind - Last segment of the required relationship type. @returns Valid internal target, if present. */
24
+ export function relatedDrawingPath(relationships: ReadonlyMap<string, PackageRelationship>, element: Element, kind: string): string | undefined {
25
+ const id = element.getAttributeNS(relationshipNs, "id");
26
+ const relation = id ? relationships.get(id) : undefined;
27
+ return relation?.type.endsWith("/" + kind) ? relation.path ?? undefined : undefined;
28
+ }
29
+
30
+ /** @param parts - Local OPC archive. @param path - Worksheet part. @param worksheet - Worksheet root.
31
+ * @param sheetId - Workbook-relative sheet identity. @param theme - Workbook theme colors.
32
+ * @param sheets - Workbook sheet IDs by name. @param image - Bounded embedded media resolver.
33
+ * @param shapeTheme - Workbook shape formatting references. @param layout - Native worksheet metrics.
34
+ * @returns Previewable original drawings with their source stacking positions. */
35
+ export function readSheetDrawings(parts: Readonly<Record<string, Uint8Array>>, path: string, worksheet: Element,
36
+ sheetId: string, theme: readonly string[], sheets: ReadonlyMap<string, string>, image: XlsxImageAssetReader, shapeTheme: XlsxWorksheetShapeTheme,
37
+ layout: XlsxDrawingLayout) {
38
+ const result = { charts: [] as XlsxChart[], pictures: [] as XlsxFloatingPicture[], shapes: [] as WorkbookFloatingShape[] };
39
+ const drawingRef = child(worksheet, "drawing");
40
+ if (!drawingRef) return result;
41
+ let anchors: Element[];
42
+ let relationships: ReadonlyMap<string, PackageRelationship>;
43
+ try {
44
+ const target = relatedDrawingPath(drawingPartRelationships(parts, path), drawingRef, "drawing");
45
+ if (!target) return result;
46
+ relationships = drawingPartRelationships(parts, target);
47
+ anchors = children(rootOf(parsePart(parts[target], target), drawingNamespace, "wsDr"));
48
+ } catch { return result; }
49
+
50
+ const previews = new Map<string, Omit<XlsxChart, "anchor"> | null>();
51
+ for (const [order, node] of anchors.entries()) {
52
+ if (node.namespaceURI !== drawingNamespace) continue;
53
+ const pic = child(node, "pic");
54
+ if (pic) {
55
+ const picture = readDrawingPicture(node, pic, sheetId, order, relationships, image, layout);
56
+ if (picture) result.pictures.push(picture);
57
+ continue;
58
+ }
59
+ const object = drawingElement(node, "sp", drawingNamespace) ?? drawingElement(node, "cxnSp", drawingNamespace);
60
+ if (object) {
61
+ const frame = readWorksheetShape(node, object, sheetId, order, shapeTheme, layout, true);
62
+ if (frame) result.shapes.push(frame.shape);
63
+ continue;
64
+ }
65
+ const frame = drawingElement(node, "graphicFrame", drawingNamespace);
66
+ const graphic = drawingElement(frame, "graphic");
67
+ const reference = drawingElement(drawingElement(graphic, "graphicData"), "chart", chartNamespace);
68
+ if (!reference) continue;
69
+ const anchor = readDrawingAnchor(node, drawingElement(frame, "xfrm", drawingNamespace), sheetId);
70
+ if (!anchor) continue;
71
+ try {
72
+ const target = relatedDrawingPath(relationships, reference, "chart");
73
+ if (!target) continue;
74
+ let chart = previews.get(target);
75
+ if (chart === undefined) {
76
+ // Cache the part once when several native drawing frames reference it.
77
+ previews.set(target, null);
78
+ chart = readChart(rootOf(parsePart(parts[target], target), chartNamespace, "chartSpace"), target, theme, sheetId, sheets);
79
+ previews.set(target, chart);
80
+ }
81
+ if (chart) result.charts.push({ ...chart, anchor, order });
82
+ } catch { /* An unreadable chart remains in the downloaded original package. */ }
83
+ }
84
+ return result;
85
+ }
@@ -0,0 +1,55 @@
1
+ import { workbookLineEndSizes, workbookLineEndTypes, type WorkbookShapeConnection, type WorkbookShapeConnector } from "@quirekit/workbook";
2
+ import type { Element } from "@xmldom/xmldom";
3
+ import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
4
+ import { child, children, readIndex } from "../../opc/xml";
5
+ import { drawingMainNamespace } from "../namespaces";
6
+ import type { XlsxWorksheetShapeTheme } from "./types";
7
+
8
+ /** @param properties - Nonvisual connector properties. @param resolve - Recognized target ID in the current drawing.
9
+ * @returns Both optional bindings, or undefined when the references must remain in the source. */
10
+ export function readWorksheetShapeConnections(properties: Element, resolve: ((frameId: number) => string | undefined) | undefined):
11
+ Pick<WorkbookShapeConnector, "startConnection" | "endConnection"> | undefined {
12
+ /** @param tag - Native endpoint property. @returns A resolved attachment, no declared attachment, or null for unsupported markup. */
13
+ function binding(tag: "stCxn" | "endCxn"): WorkbookShapeConnection | undefined | null {
14
+ const matches = children(properties, tag);
15
+ if (!matches.length) return;
16
+ const node = matches[0]!;
17
+ const id = readIndex(node, "id"), index = node.getAttribute("idx") ?? "";
18
+ const shapeId = id && resolve?.(id);
19
+ if (matches.length !== 1 || !shapeId || !/^\d+$/u.test(index) || Number(index) > 4_294_967_295
20
+ || !hasKnownAttributes(node, ["id", "idx"]) || !hasKnownChildren(node, [])) return null;
21
+ return { shapeId, site: Number(index) };
22
+ }
23
+ const startConnection = binding("stCxn"), endConnection = binding("endCxn");
24
+ if (startConnection === null || endConnection === null) return;
25
+ return { ...(startConnection && { startConnection }), ...(endConnection && { endConnection }) };
26
+ }
27
+
28
+ /** @param node - Native marker or absence of one. @returns Canonical marker, undefined for none, or null for unsupported data. */
29
+ function readLineEnd(node: Element | undefined): WorkbookShapeConnector["headEnd"] | null {
30
+ if (!node) return;
31
+ const type = node.getAttribute("type") ?? "none";
32
+ const width = node.getAttribute("w") || "med", length = node.getAttribute("len") || "med";
33
+ if (node.namespaceURI !== drawingMainNamespace || !hasKnownAttributes(node, ["type", "w", "len"]) || !hasKnownChildren(node, [])) return null;
34
+ if (type === "none") return;
35
+ const shape = workbookLineEndTypes.find(value => value === type);
36
+ const across = workbookLineEndSizes.find(value => value === width), along = workbookLineEndSizes.find(value => value === length);
37
+ return shape && across && along ? { type: shape, width: across, length: along } : null;
38
+ }
39
+
40
+ /** @param props - Direct drawing appearance. @param refs - Drawing style references. @param theme - Source format scheme.
41
+ * @param transform - Native reflections. @param inverse - Whether the original line runs from bottom left to top right.
42
+ * @returns Free connector metadata without merging out unrecognized geometry. */
43
+ export function readWorksheetShapeConnector(props: Element, refs: Element | undefined, theme: XlsxWorksheetShapeTheme,
44
+ transform: Element | undefined, inverse: boolean): WorkbookShapeConnector | undefined {
45
+ const line = child(props, "ln"), lineIndex = readIndex(refs && child(refs, "lnRef"), "idx");
46
+ const inherited = lineIndex ? theme.lines[lineIndex - 1] : undefined;
47
+ const headEnd = readLineEnd((line && child(line, "headEnd")) ?? (inherited && child(inherited, "headEnd")));
48
+ const tailEnd = readLineEnd((line && child(line, "tailEnd")) ?? (inherited && child(inherited, "tailEnd")));
49
+ if (headEnd === null || tailEnd === null) return;
50
+ return {
51
+ flipHorizontal: ["1", "true"].includes(transform?.getAttribute("flipH") ?? ""),
52
+ flipVertical: ["1", "true"].includes(transform?.getAttribute("flipV") ?? "") !== inverse,
53
+ ...(headEnd && { headEnd }), ...(tailEnd && { tailEnd })
54
+ };
55
+ }
@@ -0,0 +1,108 @@
1
+ import type { WorkbookShapeStyle } from "@quirekit/workbook";
2
+ import type { Element } from "@xmldom/xmldom";
3
+ import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
4
+ import { child, children, readIndex } from "../../opc/xml";
5
+ import { drawingThemeColor, tintXlsxColor } from "../../styles/color";
6
+ import { drawingMainNamespace, emuPerCssPixel } from "../namespaces";
7
+ import type { XlsxWorksheetShapeTheme } from "./types";
8
+
9
+ /** @param root - Native theme root. @param colors - Workbook palette already resolved by the styles codec.
10
+ * @returns Context for resolving solid shape style references. */
11
+ export function worksheetShapeTheme(root: Element | undefined, colors: readonly string[]): XlsxWorksheetShapeTheme {
12
+ const elements = root && child(root, "themeElements");
13
+ const format = elements && child(elements, "fmtScheme"), fonts = elements && child(elements, "fontScheme");
14
+ /** @param role - Theme font role. @returns Concrete typeface if available. */
15
+ function face(role: "majorFont" | "minorFont"): string | undefined {
16
+ const family = fonts && child(fonts, role);
17
+ return family && child(family, "latin")?.getAttribute("typeface") || undefined;
18
+ }
19
+ const major = face("majorFont"), minor = face("minorFont");
20
+ const fills = format && child(format, "fillStyleLst"), lines = format && child(format, "lnStyleLst");
21
+ return { colors, fills: fills ? children(fills) : [], lines: lines ? children(lines) : [],
22
+ fonts: { ...(major && { major }), ...(minor && { minor }) } };
23
+ }
24
+
25
+ /** @param parent - Single color holder. @param theme - Native theme palette. @param placeholder - Reference color for a format-scheme style.
26
+ * @returns Resolved opaque paint, or undefined for an unmapped color. */
27
+ export function worksheetShapeColor(parent: Element, theme: XlsxWorksheetShapeTheme, placeholder?: string): string | undefined {
28
+ const members = children(parent), color = members[0];
29
+ if (!color || members.length !== 1 || color.namespaceURI !== drawingMainNamespace) return;
30
+ const value = color.getAttribute("val") ?? "";
31
+ const raw = color.localName === "schemeClr" ? value === "phClr" ? placeholder : drawingThemeColor(theme.colors, value)
32
+ : color.localName === "srgbClr" && /^[a-f\d]{6}$/iu.test(value) ? "#" + value.toUpperCase() : undefined;
33
+ if (!raw || !hasKnownAttributes(color, ["val"])) return;
34
+ let result = raw;
35
+ for (const modifier of children(color)) {
36
+ const units = readIndex(modifier, "val");
37
+ if (modifier.namespaceURI !== drawingMainNamespace || units === undefined || units > 100000
38
+ || !hasKnownAttributes(modifier, ["val"]) || !hasKnownChildren(modifier, [])) return;
39
+ if (modifier.localName === "lumMod") result = tintXlsxColor(result, units / 100000 - 1);
40
+ else if (modifier.localName === "shade" || modifier.localName === "tint") {
41
+ const ratio = units / 100000, mixed = modifier.localName === "tint" ? 255 : 0;
42
+ result = "#" + [1, 3, 5].map(index => Math.round(parseInt(result.slice(index, index + 2), 16) * ratio + mixed * (1 - ratio))
43
+ .toString(16).padStart(2, "0").toUpperCase()).join("");
44
+ } else if (modifier.localName !== "alpha" || units !== 100000) return;
45
+ }
46
+ return result;
47
+ }
48
+
49
+ /** @param fill - Native opaque or transparent fill element. @param theme - Workbook theme. @param placeholder - Reference color.
50
+ * @returns Solid paint, null for no paint, or undefined if unsupported. */
51
+ function solid(fill: Element, theme: XlsxWorksheetShapeTheme, placeholder?: string): string | null | undefined {
52
+ if (fill.namespaceURI !== drawingMainNamespace || !hasKnownAttributes(fill, [])) return;
53
+ if (fill.localName === "noFill" && hasKnownChildren(fill, [])) return null;
54
+ if (fill.localName === "solidFill") return worksheetShapeColor(fill, theme, placeholder);
55
+ }
56
+
57
+ /** @param line - Native outline. @param theme - Workbook theme. @param placeholder - Referenced line color.
58
+ * @param connector - Enable native line-end children. @param inherited - Referenced theme outline.
59
+ * @returns Visible paint and width in CSS pixels, if recognized. */
60
+ function outline(line: Element, theme: XlsxWorksheetShapeTheme, placeholder: string | undefined, connector: boolean,
61
+ inherited?: Pick<WorkbookShapeStyle, "stroke" | "strokeWidth">): Pick<WorkbookShapeStyle, "stroke" | "strokeWidth"> | undefined {
62
+ if (line.namespaceURI !== drawingMainNamespace || !hasKnownAttributes(line, ["w", "cap", "cmpd", "algn"])
63
+ || !hasKnownChildren(line, ["solidFill", "noFill", "prstDash", "miter", ...(connector ? ["headEnd", "tailEnd"] : [])])
64
+ || !["", "flat"].includes(line.getAttribute("cap") ?? "") || !["", "sng"].includes(line.getAttribute("cmpd") ?? "")
65
+ || !["", "ctr"].includes(line.getAttribute("algn") ?? "")) return;
66
+ const dash = child(line, "prstDash"), join = child(line, "miter");
67
+ if (dash && (dash.getAttribute("val") !== "solid" || !hasKnownAttributes(dash, ["val"]) || !hasKnownChildren(dash, []))) return;
68
+ if (join && (!hasKnownAttributes(join, ["lim"]) || !hasKnownChildren(join, []))) return;
69
+ const noFill = child(line, "noFill"), fill = child(line, "solidFill") ?? noFill;
70
+ if (noFill && fill !== noFill) return;
71
+ const paint = fill ? solid(fill, theme, placeholder) : inherited ? inherited.stroke : placeholder;
72
+ const width = readIndex(line, "w");
73
+ if (paint === undefined || width === undefined && line.hasAttribute("w")) return;
74
+ return { stroke: paint, strokeWidth: width === undefined ? inherited?.strokeWidth ?? 1 : width / emuPerCssPixel };
75
+ }
76
+
77
+ /** @param props - Native shape properties. @param refs - Optional theme style pointers. @param theme - Workbook appearance.
78
+ * @param base - Style defaults for missing text properties. @param connector - Native open path with end markers.
79
+ * @returns The fully resolved solid model if all paints map. */
80
+ export function readWorksheetShapePaint(props: Element, refs: Element | undefined, theme: XlsxWorksheetShapeTheme,
81
+ base: WorkbookShapeStyle, connector = false): WorkbookShapeStyle | undefined {
82
+ if (refs && (!hasKnownAttributes(refs, []) || !hasKnownChildren(refs, ["fillRef", "lnRef", "effectRef", "fontRef"], drawingMainNamespace))) return;
83
+ const fillRef = refs && child(refs, "fillRef"), lineRef = refs && child(refs, "lnRef");
84
+ const effect = refs && child(refs, "effectRef"), fontRef = refs && child(refs, "fontRef");
85
+ if (effect && (effect.getAttribute("idx") !== "0" || !hasKnownAttributes(effect, ["idx"]))) return;
86
+
87
+ const fillNode = child(props, "solidFill") ?? child(props, "noFill");
88
+ const fillIndex = readIndex(fillRef, "idx"), lineIndex = readIndex(lineRef, "idx");
89
+ if (fillRef && (fillIndex === undefined || !hasKnownAttributes(fillRef, ["idx"]))
90
+ || lineRef && (lineIndex === undefined || !hasKnownAttributes(lineRef, ["idx"]))) return;
91
+ const themedFill = fillIndex ? theme.fills[fillIndex - 1] : undefined;
92
+ const themedLine = lineIndex ? theme.lines[lineIndex - 1] : undefined;
93
+ const fill = fillNode ? solid(fillNode, theme) : themedFill && fillRef ? solid(themedFill, theme, worksheetShapeColor(fillRef, theme))
94
+ : fillIndex ? undefined : null;
95
+ const line = child(props, "ln");
96
+ const inherited = themedLine && lineRef && (!line || connector)
97
+ ? outline(themedLine, theme, worksheetShapeColor(lineRef, theme), connector) : undefined;
98
+ // WPS can write only the arrows in the direct outline, retaining the base width and paint from the theme.
99
+ const stroke = line ? outline(line, theme, undefined, connector, inherited)
100
+ : inherited ?? (lineIndex ? undefined : { stroke: null, strokeWidth: 1 });
101
+ if (fill === undefined || !stroke) return;
102
+ const font = fontRef?.getAttribute("idx");
103
+ if (fontRef && (!hasKnownAttributes(fontRef, ["idx"]) || !["major", "minor", "none"].includes(font ?? ""))) return;
104
+ const color = fontRef ? worksheetShapeColor(fontRef, theme) : base.color;
105
+ if (!color) return;
106
+ const family = font === "major" || font === "minor" ? theme.fonts[font] : base.font;
107
+ return { ...base, fill, ...stroke, color, ...(family && { font: family }) };
108
+ }
@@ -0,0 +1,89 @@
1
+ import { copyWorkbookFloatingShape, defaultWorkbookShapeStyle, isWorkbookConnectorPreset, workbookShapePresets, type WorkbookShapePreset } from "@quirekit/workbook";
2
+ import type { Element } from "@xmldom/xmldom";
3
+ import { v4 as uuidv4 } from "uuid";
4
+ import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
5
+ import { child, children, readIndex } from "../../opc/xml";
6
+ import { drawingCreationId } from "../identity";
7
+ import { drawingMainNamespace, drawingNamespace } from "../namespaces";
8
+ import { readDrawingRotation, readXlsxDrawingPlacement } from "../placement/transform";
9
+ import type { XlsxDrawingLayout } from "../placement/types";
10
+ import type { XlsxShapePart } from "../types";
11
+ import { readWorksheetShapeConnections, readWorksheetShapeConnector } from "./connector";
12
+ import { readWorksheetShapePaint } from "./paint";
13
+ import { readWorksheetShapeText } from "./text";
14
+ import type { XlsxWorksheetShapeTheme } from "./types";
15
+
16
+ const knownPresets = new Set<string>(workbookShapePresets);
17
+
18
+ /** @param guides - Native preset adjustments. @returns Supported literal guide arguments. */
19
+ function adjustments(guides: Element | undefined): Readonly<Record<string, number>> | undefined {
20
+ if (!guides) return {};
21
+ if (!hasKnownAttributes(guides, [])) return;
22
+ const result = new Map<string, number>();
23
+ for (const entry of children(guides)) {
24
+ const name = entry.getAttribute("name"), value = /^val (-?\d+)$/u.exec(entry.getAttribute("fmla") ?? "");
25
+ if (entry.namespaceURI !== drawingMainNamespace || entry.localName !== "gd" || !name || !value || result.has(name)
26
+ || !hasKnownAttributes(entry, ["name", "fmla"]) || !hasKnownChildren(entry, [])) return;
27
+ result.set(name, Number(value[1]));
28
+ }
29
+ return Object.fromEntries(result);
30
+ }
31
+
32
+ /** @param transform - Native transform. @param connector - Permit the reflected direction of a connector.
33
+ * @returns Whether the frame implies all retained geometry. */
34
+ function plainTransform(transform: Element | undefined, connector: boolean): boolean {
35
+ return !transform || hasKnownAttributes(transform, connector ? ["rot", "flipH", "flipV"] : ["rot"])
36
+ && (!connector || ["flipH", "flipV"].every(name => ["", "0", "1", "true", "false"].includes(transform.getAttribute(name) ?? "")))
37
+ && hasKnownChildren(transform, ["off", "ext"])
38
+ && children(transform).every(part => hasKnownAttributes(part, part.localName === "off" ? ["x", "y"] : ["cx", "cy"])
39
+ && hasKnownChildren(part, []) && Array.from(part.attributes).filter(attr => !attr.namespaceURI).every(attr => /^-?\d+$/u.test(attr.value)));
40
+ }
41
+
42
+ /** @param placement - Native anchor. @param shape - Native shape member. @param sheetId - Worksheet identity.
43
+ * @param order - Drawing paint order. @param theme - Source palette and styles. @param layout - Native worksheet metrics.
44
+ * @param preview - Permit preview of bound connector geometry while retaining original connection references.
45
+ * @param targets - Numeric frame identities for eligible worksheet drawing objects.
46
+ * @returns A supported anchored preset. */
47
+ export function readWorksheetShape(placement: Element, shape: Element, sheetId: string, order: number,
48
+ theme: XlsxWorksheetShapeTheme, layout: XlsxDrawingLayout, preview = false, targets?: ReadonlyMap<number, string>): XlsxShapePart | undefined {
49
+ const connector = shape.localName === "cxnSp";
50
+ const nonvisualName = connector ? "nvCxnSpPr" : "nvSpPr", kindName = connector ? "cNvCxnSpPr" : "cNvSpPr";
51
+ if (shape.namespaceURI !== drawingNamespace || !hasKnownAttributes(shape, connector ? ["macro"] : ["macro", "textlink"])
52
+ || shape.getAttribute("macro") || shape.getAttribute("textlink")
53
+ || !hasKnownChildren(shape, [nonvisualName, "spPr", "style", ...(connector ? [] : ["txBody"])])) return;
54
+ const nonvisual = child(shape, nonvisualName), props = nonvisual && child(nonvisual, "cNvPr"), kind = nonvisual && child(nonvisual, kindName);
55
+ const properties = child(shape, "spPr"), native = properties && child(properties, "prstGeom"), transform = properties && child(properties, "xfrm");
56
+ if (!nonvisual || !props || !kind || !properties || !native || !plainTransform(transform, connector)
57
+ || !hasKnownAttributes(nonvisual, []) || !hasKnownChildren(nonvisual, ["cNvPr", kindName])
58
+ || !hasKnownAttributes(kind, connector ? [] : ["txBox"])
59
+ || !hasKnownChildren(kind, connector ? ["stCxn", "endCxn", ...(preview ? ["cxnSpLocks"] : [])] : [], drawingMainNamespace)
60
+ || !hasKnownAttributes(properties, []) || !hasKnownChildren(properties, ["xfrm", "prstGeom", "solidFill", "noFill", "ln"], drawingMainNamespace)
61
+ || child(properties, "solidFill") && child(properties, "noFill")
62
+ || !hasKnownAttributes(native, ["prst"]) || !hasKnownChildren(native, ["avLst"])) return;
63
+ const form = kind.getAttribute("txBox") || "0", name = native.getAttribute("prst") ?? "";
64
+ if (!["0", "1", "true", "false"].includes(form) || name === "textBox" || !knownPresets.has(name)) return;
65
+ const textBox = form === "1" || form === "true";
66
+ if (textBox && name !== "rect") return;
67
+ const inverse = connector && name === "lineInv";
68
+ const preset = (textBox ? "textBox" : inverse ? "line" : name) as WorkbookShapePreset;
69
+ if (connector && !isWorkbookConnectorPreset(preset)) return;
70
+ const guides = adjustments(child(native, "avLst"));
71
+ const rotation = readDrawingRotation(transform);
72
+ if (rotation === null) return;
73
+ const bindings = !connector || preview ? {} : readWorksheetShapeConnections(kind, id => targets?.get(id));
74
+ if (!bindings) return;
75
+ const bound = Boolean(bindings.startConnection || bindings.endConnection);
76
+ if (bound && rotation) return;
77
+ const anchor = readXlsxDrawingPlacement(placement, transform, sheetId, rotation, layout, connector, bound);
78
+ const frameId = readIndex(props, "id"), id = drawingCreationId(props, ["id", "name", "descr"]);
79
+ const refs = child(shape, "style");
80
+ const line = connector ? readWorksheetShapeConnector(properties, refs, theme, transform, inverse) : undefined;
81
+ const paint = readWorksheetShapePaint(properties, refs, theme, defaultWorkbookShapeStyle(preset), connector);
82
+ const content = paint && (connector ? { text: "", style: paint } : readWorksheetShapeText(child(shape, "txBody"), paint, theme));
83
+ if (!anchor || !frameId || id === null || !guides || !content || connector && !line) return;
84
+ try {
85
+ return { shape: copyWorkbookFloatingShape({ id: id ?? uuidv4(), anchor, order, preset, name: props.getAttribute("name") ?? "",
86
+ alt: props.getAttribute("descr") || undefined, rotation, adjustments: guides, ...content,
87
+ ...(line && { connector: { ...line, ...bindings } }) }), frameId };
88
+ } catch { /* An unsupported native shape stays in its original package. */ }
89
+ }