@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,95 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { hasKnownAttributes } from "../../opc/shape";
3
+ import { child, children, spreadNs } from "../../opc/xml";
4
+
5
+ /** Office 2010 enhanced conditional formats. */
6
+ export const xlsxConditionalNamespace = "http://schemas.microsoft.com/office/spreadsheetml/2009/9/main";
7
+ /** Spreadsheet formula and range operands inside Office extensions. */
8
+ export const xlsxConditionalOperands = "http://schemas.microsoft.com/office/excel/2006/main";
9
+ /** Legacy rule link to an enhanced data bar. */
10
+ export const xlsxConditionalReferenceUri = "{B025F937-C7B1-47D3-B67F-A62EFF666E3E}";
11
+ /** Worksheet extension that stores enhanced conditional formatting. */
12
+ export const xlsxConditionalExtensionUri = "{78C0D931-6437-407D-A8EE-F0AAD7539E65}";
13
+
14
+ /** @param extension - Worksheet extension. @returns Whether it owns enhanced conditional formats. */
15
+ export function isXlsxConditionalExtension(extension: Element): boolean {
16
+ return extension.localName === "ext" && extension.namespaceURI === spreadNs
17
+ && extension.getAttribute("uri")?.toUpperCase() === xlsxConditionalExtensionUri;
18
+ }
19
+
20
+ /** @param worksheet - Source worksheet. @returns Extended condition groups by native ID, or undefined if they cannot be matched. */
21
+ export function xlsxConditionExtensions(worksheet: Element): ReadonlyMap<string, Element> | undefined {
22
+ const root = child(worksheet, "extLst");
23
+ const matches = root ? children(root, "ext").filter(isXlsxConditionalExtension) : [];
24
+ const index = new Map<string, Element>();
25
+ if (!matches.length) return index;
26
+ const extension = matches[0]!;
27
+ const list = child(extension, "conditionalFormattings");
28
+ if (matches.length !== 1 || list?.namespaceURI !== xlsxConditionalNamespace || children(extension).length !== 1
29
+ || !hasKnownAttributes(extension, ["uri"]) || !hasKnownAttributes(list, [])) return;
30
+ for (const container of children(list)) {
31
+ if (container.localName !== "conditionalFormatting" || container.namespaceURI !== xlsxConditionalNamespace
32
+ || !hasKnownAttributes(container, [])) return;
33
+ const members = children(container), range = members.at(-1);
34
+ if (range?.localName !== "sqref" || range.namespaceURI !== xlsxConditionalOperands || !hasKnownAttributes(range, [])
35
+ || children(range).length || members.length < 2) return;
36
+ for (const rule of members.slice(0, -1)) {
37
+ const priority = rule.getAttribute("priority");
38
+ const id = rule.getAttribute("id")?.toUpperCase() || (priority ? "PRIORITY:" + priority : undefined);
39
+ if (rule.localName !== "cfRule" || rule.namespaceURI !== xlsxConditionalNamespace || !id || index.has(id)) return;
40
+ index.set(id, rule);
41
+ }
42
+ }
43
+ return index;
44
+ }
45
+
46
+ /** @param rule - Standard fallback rule. @returns ID linking the fallback to its x14 record. */
47
+ export function xlsxDataBarExtensionId(rule: Element): string | undefined {
48
+ const list = child(rule, "extLst"), ext = list && child(list, "ext"), ref = ext && child(ext, "id");
49
+ if (!list || !ext || children(list).length !== 1 || children(ext).length !== 1 || ref?.namespaceURI !== xlsxConditionalNamespace
50
+ || ext.namespaceURI !== spreadNs || ext.getAttribute("uri")?.toUpperCase() !== xlsxConditionalReferenceUri
51
+ || !hasKnownAttributes(list, []) || !hasKnownAttributes(ext, ["uri"]) || !hasKnownAttributes(ref, []) || children(ref).length) return;
52
+ return ref.textContent?.trim().toUpperCase() || undefined;
53
+ }
54
+
55
+ /** @param rule - Standard fallback rule. @param sqref - Its target range. @param source - Indexed extended targets.
56
+ * @returns The paired x14 bar, when its identity and ranges agree. */
57
+ export function xlsxDataBarExtension(rule: Element, sqref: string, source: ReadonlyMap<string, Element>): Element | undefined {
58
+ const id = xlsxDataBarExtensionId(rule);
59
+ const extended = id ? source.get(id) : undefined;
60
+ if (!extended || extended.getAttribute("type") !== "dataBar" || !hasKnownAttributes(extended, ["type", "id"]) || children(extended).length !== 1) return;
61
+ const range = child(extended.parentNode as Element, "sqref");
62
+ const bar = child(extended, "dataBar");
63
+ if (bar?.namespaceURI !== xlsxConditionalNamespace || normalizeSqref(range?.textContent ?? "") !== normalizeSqref(sqref)) return;
64
+ return bar;
65
+ }
66
+
67
+ /** @param owner - XML parent. @param namespace - Child namespace. @param name - Qualified name.
68
+ * @param text - Optional native character content. @returns Attached XML element. */
69
+ export function appendXlsxConditionalElement(owner: Element, namespace: string, name: string, text?: string): Element {
70
+ const element = owner.ownerDocument!.createElementNS(namespace, name);
71
+ if (text !== undefined) element.appendChild(owner.ownerDocument!.createTextNode(text));
72
+ owner.appendChild(element);
73
+ return element;
74
+ }
75
+
76
+ /** @param worksheet - Writable sheet with base conditional rules installed.
77
+ * @param groups - Standalone enhanced rules and companions of base rules. */
78
+ export function writeXlsxConditionalExtensions(worksheet: Element, groups: readonly Element[]): void {
79
+ const existing = child(worksheet, "extLst");
80
+ if (existing) for (const previous of children(existing).filter(isXlsxConditionalExtension)) existing.removeChild(previous);
81
+ if (!groups.length) {
82
+ if (existing && !children(existing).length) worksheet.removeChild(existing);
83
+ return;
84
+ }
85
+ const append = appendXlsxConditionalElement;
86
+ const wrapper = append(existing ?? append(worksheet, spreadNs, "extLst"), spreadNs, "ext");
87
+ wrapper.setAttribute("uri", xlsxConditionalExtensionUri);
88
+ const list = append(wrapper, xlsxConditionalNamespace, "x14:conditionalFormattings");
89
+ for (const group of groups) list.appendChild(group);
90
+ }
91
+
92
+ /** @param ranges - Native references in one sheet. @returns Threshold coverage with standard spacing and case. */
93
+ function normalizeSqref(ranges: string): string {
94
+ return ranges.trim().replace(/\$/gu, "").replace(/\s+/gu, " ").toUpperCase();
95
+ }
@@ -0,0 +1,69 @@
1
+ import type { Document, Element } from "@xmldom/xmldom";
2
+ import { isWorkbookIconIdentity, workbookConditionalIconSetSizes, type WorkbookConditionalIconIdentity } from "@quirekit/workbook";
3
+ import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
4
+ import { children, readIndex, spreadNs } from "../../opc/xml";
5
+ import { xlsxConditionalNamespace } from "./extensions";
6
+ import { xlsxExtendedIconSets } from "./icon-set";
7
+
8
+ const markupCompatibility = "http://schemas.openxmlformats.org/markup-compatibility/2006";
9
+ const namespaceDeclarations = "http://www.w3.org/2000/xmlns/";
10
+
11
+ /** @param node - Standard condition or markup compatibility wrapper. @param name - Entry expected by its owner.
12
+ * @returns A supported native choice, when the wrapper declares only a known x14 condition and optional fallback. */
13
+ export function readXlsxIconChoice(node: Element, name: "iconFilter" | "sortCondition"): Element | undefined {
14
+ if (node.localName === name && node.namespaceURI === spreadNs) return node;
15
+ if (node.localName !== "AlternateContent" || node.namespaceURI !== markupCompatibility || !hasKnownAttributes(node, [])
16
+ || !hasKnownChildren(node, ["Choice", "Fallback"])) return;
17
+ const [choice, fallback] = children(node);
18
+ if (choice?.localName !== "Choice" || !hasKnownAttributes(choice, ["Requires"])
19
+ || !hasKnownChildren(choice, [name], xlsxConditionalNamespace)) return;
20
+ const prefix = choice.getAttribute("Requires")?.trim();
21
+ if (!prefix || /\s/u.test(prefix) || choice.lookupNamespaceURI(prefix) !== xlsxConditionalNamespace) return;
22
+ const fallbackName = name === "iconFilter" ? "customFilters" : "sortCondition";
23
+ if (fallback && (fallback.localName !== "Fallback" || !hasKnownAttributes(fallback, [])
24
+ || !hasKnownChildren(fallback, [fallbackName], spreadNs))) return;
25
+ return children(choice)[0];
26
+ }
27
+
28
+ /** @param node - Validated condition element. @param extended - Whether the owner uses the Office 2010 icon set.
29
+ * @returns Its glyph or null for no icon, or undefined when invalid. */
30
+ export function readXlsxIconReference(node: Element, extended = node.namespaceURI === xlsxConditionalNamespace): WorkbookConditionalIconIdentity | null | undefined {
31
+ if (!extended && node.namespaceURI !== spreadNs) return;
32
+ const set = node.hasAttribute("iconSet") ? node.getAttribute("iconSet") : "3Arrows";
33
+ if (!set || !Object.hasOwn(workbookConditionalIconSetSizes, set)) return;
34
+ if (!extended && xlsxExtendedIconSets.has(set as WorkbookConditionalIconIdentity["set"])) return;
35
+ if (!node.hasAttribute("iconId")) return extended ? undefined : null;
36
+ const icon = { set, index: readIndex(node, "iconId") };
37
+ return isWorkbookIconIdentity(icon) ? icon : undefined;
38
+ }
39
+
40
+ /** @param document - Part that will contain the reference. @param tag - Native condition element.
41
+ * @param icon - Selected glyph, or null for no glyph. @returns The leaf and any standard compatibility wrapper. */
42
+ export function makeXlsxIconReference(document: Document, tag: "iconFilter" | "sortCondition",
43
+ icon: WorkbookConditionalIconIdentity | null) {
44
+ const extended = Boolean(icon && xlsxExtendedIconSets.has(icon.set));
45
+ const leaf = document.createElementNS(extended ? xlsxConditionalNamespace : spreadNs, extended ? `x14:${tag}` : tag);
46
+ if (icon || tag === "iconFilter") leaf.setAttribute("iconSet", icon?.set ?? "3Arrows");
47
+ if (icon) leaf.setAttribute("iconId", String(icon.index));
48
+ if (!extended) return { leaf, content: leaf };
49
+ const content = document.createElementNS(markupCompatibility, "mc:AlternateContent");
50
+ const choice = document.createElementNS(markupCompatibility, "mc:Choice");
51
+ choice.setAttributeNS(namespaceDeclarations, "xmlns:x14", xlsxConditionalNamespace);
52
+ choice.setAttribute("Requires", "x14");
53
+ choice.appendChild(leaf);
54
+ content.appendChild(choice);
55
+ if (tag === "iconFilter") {
56
+ // Older readers keep the saved hidden flags and can clear this permissive fallback.
57
+ const fallback = document.createElementNS(markupCompatibility, "mc:Fallback");
58
+ const filters = document.createElementNS(spreadNs, "customFilters");
59
+ for (const operator of ["equal", "notEqual"]) {
60
+ const condition = document.createElementNS(spreadNs, "customFilter");
61
+ if (operator !== "equal") condition.setAttribute("operator", operator);
62
+ condition.setAttribute("val", "");
63
+ filters.appendChild(condition);
64
+ }
65
+ fallback.appendChild(filters);
66
+ content.appendChild(fallback);
67
+ }
68
+ return { leaf, content };
69
+ }
@@ -0,0 +1,60 @@
1
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
2
+ import { openWorkbook, parseWorkbookRange, type WorkbookConditionalFormat, type WorkbookSnapshot } from "@quirekit/workbook";
3
+ import { expect, it } from "vitest";
4
+ import { createXlsx, openXlsx } from "../../index";
5
+
6
+ const amounts = parseWorkbookRange("amounts", "B2:B5");
7
+ const formats: readonly WorkbookConditionalFormat[] = [
8
+ { id: "stars", ranges: [parseWorkbookRange("amounts", "C2:C5")], style: {}, stopIfTrue: false,
9
+ predicate: { kind: "iconSet", set: "3Stars", reverse: false, showValue: true, thresholds: [
10
+ { type: "percentile", value: 30, inclusive: true }, { type: "formula", formula: "=$B$4", inclusive: false }
11
+ ] } },
12
+ { id: "arrows", ranges: [amounts], style: {}, stopIfTrue: false,
13
+ predicate: { kind: "iconSet", set: "5Arrows", reverse: true, showValue: false, thresholds: [
14
+ { type: "number", value: 15, inclusive: true }, { type: "number", value: 25, inclusive: false },
15
+ { type: "percent", value: 60, inclusive: true }, { type: "formula", formula: "=$B$5", inclusive: false }
16
+ ] } }
17
+ ];
18
+ const sample: WorkbookSnapshot = { id: "icon-sets", name: "Amounts", revision: 0, version: 1, sheets: [
19
+ { id: "amounts", name: "Amounts", conditionalFormats: formats, cells: [10, 20, 40, 80].map((value, index) => ({
20
+ row: index + 1, column: 1, input: { kind: "value" as const, value }
21
+ })) }
22
+ ] };
23
+ const sheetPart = "xl/worksheets/sheet1.xml";
24
+
25
+ it("round-trips native and extended icon rules, their shared priority and exact thresholds", async () => {
26
+ const source = createXlsx(sample);
27
+ const xml = strFromU8(unzipSync(source)[sheetPart]!);
28
+ expect(xml).toContain('<iconSet iconSet="5Arrows" showValue="0" reverse="1">');
29
+ expect(xml).toContain('<cfvo type="num" gte="0" val="25"/>');
30
+ expect(xml).toContain('<cfvo type="formula" gte="0" val="$B$5"/>');
31
+ expect(xml).toContain('<x14:iconSet iconSet="3Stars">');
32
+ expect(xml).toContain('<x14:cfvo type="formula" gte="0"><xm:f');
33
+ const opened = openXlsx("Native icons", source);
34
+ const sheet = opened.snapshot.sheets[0]!;
35
+ expect(opened.restrictions).toEqual([]);
36
+ expect(sheet.conditionalFormats?.map(({ predicate }) => predicate)).toEqual(formats.map(({ predicate }) => predicate));
37
+ const book = await openWorkbook(opened.snapshot);
38
+ try {
39
+ const rule = sheet.conditionalFormats![0]!;
40
+ await book.commit(book.prepare({ operationId: "remove-star-rule", baseRevision: 0, commands: [
41
+ { name: "removeConditionalFormat", target: rule.ranges[0]!, params: { id: rule.id } }
42
+ ] }).id);
43
+ const saved = opened.write(book.snapshot());
44
+ expect(strFromU8(unzipSync(saved)[sheetPart]!)).not.toContain("x14:conditionalFormatting");
45
+ expect(openXlsx("Remaining arrows", saved).snapshot.sheets[0]?.conditionalFormats?.map(({ predicate }) => predicate))
46
+ .toEqual([formats[1]!.predicate]);
47
+ await book.undo("restore-star-rule");
48
+ expect(opened.write(book.snapshot())).toEqual(source);
49
+ } finally { await book.close(); }
50
+ });
51
+
52
+ it("preserves unknown custom icons and reads independent supported rule regions", () => {
53
+ const parts = unzipSync(createXlsx(sample));
54
+ parts[sheetPart] = strToU8(strFromU8(parts[sheetPart]!).replace('iconSet="3Stars"', 'iconSet="3Stars" custom="1"'));
55
+ const source = zipSync(parts), imported = openXlsx("Unknown extended icons", source);
56
+ expect(imported.restrictions).toContain("条件格式包含暂未支持的规则或样式");
57
+ expect(imported.appearance.sheets.get(imported.snapshot.sheets[0]!.id)?.conditionalPreviews?.map(rule => rule.kind === "format" && rule.format.predicate))
58
+ .toEqual([formats[1]!.predicate]);
59
+ expect(imported.write(imported.snapshot)).toEqual(source);
60
+ });
@@ -0,0 +1,79 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { formatWorkbookRange, workbookConditionalIconSetSizes,
3
+ type WorkbookConditionalFormat, type WorkbookConditionalIconSet, type WorkbookConditionalIconSetName, type WorkbookConditionalIconThreshold } from "@quirekit/workbook";
4
+ import { v4 as uuidv4 } from "uuid";
5
+ import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
6
+ import { children, spreadNs } from "../../opc/xml";
7
+ import { appendXlsxConditionalElement as append, xlsxConditionalNamespace, xlsxConditionalOperands } from "./extensions";
8
+ import { readXlsxConditionalFlag as flag, readXlsxNumericThreshold, writeXlsxThresholdOperand } from "./threshold";
9
+
10
+ /** Presets introduced in the Office 2010 worksheet extension. */
11
+ export const xlsxExtendedIconSets: ReadonlySet<WorkbookConditionalIconSetName> = new Set(["3Stars", "3Triangles", "5Boxes"]);
12
+
13
+ /** @param bound - Native threshold. @param extended - Whether its value uses a child formula.
14
+ * @param legacyPercentile - Base icon set using a global percentile flag.
15
+ * @returns The rule's threshold, including the boundary comparator. */
16
+ function readThreshold(bound: Element, extended: boolean, legacyPercentile: boolean): WorkbookConditionalIconThreshold | undefined {
17
+ if (!hasKnownAttributes(bound, extended ? ["type", "gte"] : ["type", "gte", "val"])
18
+ || !hasKnownChildren(bound, extended ? ["f"] : [], bound.namespaceURI, { f: xlsxConditionalOperands })) return;
19
+ const [expression] = children(bound);
20
+ if (expression && (!hasKnownAttributes(expression, []) || !hasKnownChildren(expression, []))) return;
21
+ const nativeType = bound.getAttribute("type");
22
+ const type = legacyPercentile && nativeType === "num" ? "percentile" : nativeType;
23
+ const text = (extended ? expression?.textContent : bound.getAttribute("val"))?.trim() ?? "";
24
+ const operand = readXlsxNumericThreshold(type, text);
25
+ return operand && { ...operand, inclusive: flag(bound, "gte", true) };
26
+ }
27
+
28
+ /** @param rule - Standalone native icon rule. @returns An editable preset with the native comparison semantics. */
29
+ export function readXlsxIconSet(rule: Element): WorkbookConditionalIconSet | undefined {
30
+ if (rule.getAttribute("type") !== "iconSet") return;
31
+ const namespace = rule.namespaceURI, extended = namespace === xlsxConditionalNamespace;
32
+ if ((!extended && namespace !== spreadNs)
33
+ || !hasKnownAttributes(rule, extended ? ["type", "priority", "stopIfTrue", "id"] : ["type", "priority", "stopIfTrue"])
34
+ || !hasKnownChildren(rule, ["iconSet"])) return;
35
+ const [native] = children(rule);
36
+ if (!native || !hasKnownAttributes(native, extended ? ["iconSet", "showValue", "reverse", "percent", "custom"]
37
+ : ["iconSet", "showValue", "reverse", "percent"]) || flag(native, "custom")) return;
38
+ const set = (native.hasAttribute("iconSet") ? native.getAttribute("iconSet") : "3TrafficLights1") as WorkbookConditionalIconSetName;
39
+ if (!Object.hasOwn(workbookConditionalIconSetSizes, set) || (!extended && xlsxExtendedIconSets.has(set))) return;
40
+ const bounds = children(native);
41
+ if (bounds.length !== workbookConditionalIconSetSizes[set] || bounds.some(bound => bound.localName !== "cfvo" || bound.namespaceURI !== namespace)) return;
42
+ const percentile = !extended && flag(native, "percent");
43
+ const thresholds = bounds.slice(1).map(bound => readThreshold(bound, extended, percentile));
44
+ if (!thresholds.every(operand => operand !== undefined)) return;
45
+ return { kind: "iconSet", set, thresholds, showValue: flag(native, "showValue", true), reverse: flag(native, "reverse") };
46
+ }
47
+
48
+ /** @param rule - Native conditional rule. @param icons - Published icon settings. */
49
+ export function writeXlsxIconSet(rule: Element, icons: WorkbookConditionalIconSet): void {
50
+ const extended = rule.namespaceURI === xlsxConditionalNamespace;
51
+ const namespace = extended ? xlsxConditionalNamespace : spreadNs, prefix = extended ? "x14:" : "";
52
+ rule.setAttribute("type", "iconSet");
53
+ const node = append(rule, namespace, prefix + "iconSet");
54
+ node.setAttribute("iconSet", icons.set);
55
+ if (!icons.showValue) node.setAttribute("showValue", "0");
56
+ if (icons.reverse) node.setAttribute("reverse", "1");
57
+ const lowest = { type: "percent", value: 0, inclusive: true } as const;
58
+ for (const bound of [lowest, ...icons.thresholds]) {
59
+ const value = append(node, namespace, prefix + "cfvo");
60
+ value.setAttribute("type", bound.type === "number" ? "num" : bound.type);
61
+ if (!bound.inclusive) value.setAttribute("gte", "0");
62
+ const operand = writeXlsxThresholdOperand(bound, extended)!;
63
+ if (extended) append(value, xlsxConditionalOperands, "xm:f", operand);
64
+ else value.setAttribute("val", operand);
65
+ }
66
+ }
67
+
68
+ /** @param worksheet - Source worksheet. @param format - Actual rule and ranges. @param priority - Global one-based rank.
69
+ * @returns The standalone rule group collected into the worksheet's x14 extension. */
70
+ export function writeXlsxExtendedIconSet(worksheet: Element, format: WorkbookConditionalFormat, priority: number): Element {
71
+ if (format.predicate.kind !== "iconSet") throw new Error("Expected an icon rule.");
72
+ const group = worksheet.ownerDocument!.createElementNS(xlsxConditionalNamespace, "x14:conditionalFormatting");
73
+ const rule = append(group, xlsxConditionalNamespace, "x14:cfRule");
74
+ rule.setAttribute("priority", String(priority));
75
+ rule.setAttribute("id", "{" + uuidv4().toUpperCase() + "}");
76
+ writeXlsxIconSet(rule, format.predicate);
77
+ append(group, xlsxConditionalOperands, "xm:sqref", format.ranges.map(formatWorkbookRange).join(" "));
78
+ return group;
79
+ }
@@ -0,0 +1,44 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import { formatWorkbookColumn, scanWorkbookFormula, workbookFormulaFunctionName,
3
+ type WorkbookConditionalFormulaPreview, type WorkbookRange } from "@quirekit/workbook";
4
+ import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
5
+ import { child, readIndex } from "../../opc/xml";
6
+ import type { XlsxConditionalContext } from "./types";
7
+
8
+ const localFunctions = new Set([
9
+ "ABS", "AND", "AVERAGE", "COLUMN", "COUNT", "COUNTA", "COUNTIF", "COUNTIFS", "DATE", "DAY", "EXACT",
10
+ "FALSE", "IF", "IFERROR", "ISBLANK", "ISERROR", "ISNUMBER", "ISTEXT", "LEFT", "LEN", "LOWER", "MAX",
11
+ "MIN", "MOD", "MONTH", "NOT", "OR", "RIGHT", "ROUND", "ROUNDDOWN", "ROUNDUP", "ROW", "SUM", "SUMIF",
12
+ "SUMIFS", "TODAY", "TRIM", "TRUE", "UPPER", "WEEKDAY", "YEAR"
13
+ ]);
14
+
15
+ /** @param formula - Normalized predicate. @returns Whether it uses local formula syntax supported for source preview. */
16
+ function isLocalPredicate(formula: string): boolean {
17
+ if (formula.length > 8_192 || formula.length < 2) return false;
18
+ const tokens = [...scanWorkbookFormula(formula)];
19
+ return tokens.every(({ text, kind }, index) => {
20
+ if (kind === "opaque") return !text.startsWith("[") && (!text.startsWith("'") || !/[\[\]:|]/u.test(text));
21
+ if (text === "|") return false;
22
+ return kind !== "word" || tokens[index + 1]?.text !== "(" || localFunctions.has(workbookFormulaFunctionName(text));
23
+ });
24
+ }
25
+
26
+ /** @param rule - Source condition. @param anchor - Top-left rectangle establishing formula offsets.
27
+ * @param context - Retained styles and names. @returns Supported formula predicate and its conditional appearance. */
28
+ export function readXlsxConditionalFormula(rule: Element, anchor: WorkbookRange, context: XlsxConditionalContext):
29
+ Pick<WorkbookConditionalFormulaPreview, "formula" | "style" | "clearBorders"> | undefined {
30
+ const style = context.previewStyles[readIndex(rule, "dxfId") ?? -1];
31
+ const element = child(rule, "formula");
32
+ const type = rule.getAttribute("type");
33
+ if (!style || !element || !hasKnownChildren(rule, ["formula"]) || !hasKnownChildren(element, []) || !hasKnownAttributes(element, [])) return;
34
+ const fields = ["type", "dxfId", "priority", "stopIfTrue"];
35
+ const source = element.textContent?.trim().replace(/^=/u, "") ?? "";
36
+ if (type === "expression" && hasKnownAttributes(rule, fields) && source && isLocalPredicate("=" + source)) {
37
+ const formula = context.resolveNames("=" + source, anchor);
38
+ return formula && { ...style, formula } || undefined;
39
+ }
40
+ if (type === "cellIs" && hasKnownAttributes(rule, [...fields, "operator"]) && rule.getAttribute("operator") === "equal" && source === '""') {
41
+ const cell = formatWorkbookColumn(anchor.startColumn) + (anchor.startRow + 1);
42
+ return { ...style, formula: `=OR(ISBLANK(${cell}),AND(ISTEXT(${cell}),${cell}=""))` };
43
+ }
44
+ }
@@ -0,0 +1,185 @@
1
+ import type { Element } from "@xmldom/xmldom";
2
+ import {
3
+ copyWorkbookConditionalFormats, formatWorkbookSpillReferences, maximumWorkbookConditionalFormats, maximumWorkbookConditionalRanges, parseWorkbookRange,
4
+ workbookConditionalThresholdFormulas,
5
+ workbookConditionalOperators, workbookRangeSize, workbookRangesOverlap, workbookTransactionCellLimit,
6
+ type WorkbookConditionalFormat, type WorkbookConditionalOperator, type WorkbookConditionalPredicate,
7
+ type WorkbookConditionalPreviewRule, type WorkbookRange
8
+ } from "@quirekit/workbook";
9
+ import { hasKnownAttributes, hasKnownChildren } from "../../opc/shape";
10
+ import { child, children, readIndex, spreadNs } from "../../opc/xml";
11
+ import { styleColorReader } from "../../styles/color";
12
+ import { readXlsxDifferential } from "../../styles/differential";
13
+ import type { XlsxDifferentialStyle } from "../../styles/types";
14
+ import { xlsxConditionExtensions, xlsxDataBarExtensionId } from "./extensions";
15
+ import { readXlsxConditionalBar } from "./data-bar";
16
+ import { readXlsxColorScale } from "./color-scale";
17
+ import { readXlsxIconSet } from "./icon-set";
18
+ import { readXlsxConditionalFormula } from "./preview";
19
+ import { readXlsxComputedTextRule, readXlsxLiteralTextRule } from "./text";
20
+ import { readXlsxConditionalFlag as flag } from "./threshold";
21
+ import type { XlsxConditionalContext, XlsxConditionalRead } from "./types";
22
+
23
+ /** @param styleSheet - Parsed styles part. @param theme - Parsed theme colors. @returns Differential records by their original indices. */
24
+ export function readXlsxDifferentials(styleSheet: Element | undefined, theme: readonly string[]): readonly (XlsxDifferentialStyle | undefined)[] {
25
+ const dxfs = styleSheet && child(styleSheet, "dxfs");
26
+ if (!dxfs) return [];
27
+ const resolve = styleColorReader(child(styleSheet, "colors"), theme);
28
+ return children(dxfs).map(node => node.localName === "dxf" ? readXlsxDifferential(node, resolve) : undefined);
29
+ }
30
+
31
+ /** @param node - Formula element. @returns A finite literal number, excluding dynamic formulas. */
32
+ function operand(node: Element): number {
33
+ const text = node.textContent?.trim() ?? "";
34
+ if (!hasKnownChildren(node, []) || !hasKnownAttributes(node, []) || !/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/iu.test(text) || !Number.isFinite(Number(text))) {
35
+ throw new Error("Unsupported conditional formatting operand.");
36
+ }
37
+ return Number(text);
38
+ }
39
+
40
+ /** @param node - Native rule. @param anchor - First region as stored in the source.
41
+ * @param context - Workbook names and styles. @returns A round-trippable predicate. */
42
+ function readPredicate(node: Element, anchor: WorkbookRange, context: XlsxConditionalContext): WorkbookConditionalPredicate {
43
+ const type = node.getAttribute("type");
44
+ const generic = ["type", "dxfId", "priority", "stopIfTrue"];
45
+ const literal = readXlsxLiteralTextRule(node, anchor);
46
+ if (literal) return literal;
47
+ if (type === "cellIs" && hasKnownAttributes(node, [...generic, "operator"])) {
48
+ const operator = node.getAttribute("operator") as WorkbookConditionalOperator;
49
+ const formulas = children(node);
50
+ const between = operator === "between" || operator === "notBetween";
51
+ if (workbookConditionalOperators.includes(operator) && formulas.length === (between ? 2 : 1)
52
+ && formulas.every(item => item.localName === "formula" && item.namespaceURI === spreadNs)) {
53
+ return { kind: "number", operator, first: operand(formulas[0]!), ...(between && { second: operand(formulas[1]!) }) };
54
+ }
55
+ }
56
+ if (type === "expression" && hasKnownAttributes(node, generic) && hasKnownChildren(node, ["formula"])) {
57
+ const expression = children(node);
58
+ const value = expression[0];
59
+ if (expression.length === 1 && value && hasKnownChildren(value, []) && hasKnownAttributes(value, [])) {
60
+ const source = value.textContent?.trim().replace(/^=/u, "") ?? "";
61
+ const formula = formatWorkbookSpillReferences("=" + source, "postfix").formula;
62
+ // Relative defined names can be approximated for display while their original syntax remains in the package.
63
+ if (context.resolveNames(formula, anchor) === formula) return { kind: "formula", formula };
64
+ }
65
+ }
66
+ if (hasKnownChildren(node, [])) {
67
+ if (hasKnownAttributes(node, generic)) {
68
+ if (type === "duplicateValues") return { kind: "duplicate" };
69
+ if (type === "uniqueValues") return { kind: "unique" };
70
+ }
71
+ if (type === "top10" && hasKnownAttributes(node, [...generic, "rank", "bottom", "percent"])) {
72
+ const count = readIndex(node, "rank");
73
+ if (count) return { kind: "rank", count, bottom: flag(node, "bottom"), percent: flag(node, "percent") };
74
+ }
75
+ if (type === "aboveAverage" && hasKnownAttributes(node, [...generic, "aboveAverage", "equalAverage", "stdDev"])
76
+ && (!node.hasAttribute("stdDev") || node.getAttribute("stdDev") === "0")) {
77
+ return { kind: "average", below: !flag(node, "aboveAverage", true), inclusive: flag(node, "equalAverage") };
78
+ }
79
+ }
80
+ throw new Error("Unsupported conditional formatting predicate.");
81
+ }
82
+
83
+ /** @param sheetId - Workbook worksheet. @param sqref - Space-separated native refs. @returns Validated authored region order. */
84
+ function conditionalRanges(sheetId: string, sqref: string): readonly WorkbookRange[] {
85
+ const refs = sqref.split(/\s+/u);
86
+ if (refs.length > maximumWorkbookConditionalRanges) throw new Error("Too many conditional formatting regions.");
87
+ return refs.map(range => parseWorkbookRange(sheetId, range));
88
+ }
89
+
90
+ /** @param worksheet - Native worksheet. @param sheetId - Stable owner. @param context - Source styles, palette and names.
91
+ * @param progress - Native pairs already represented by progress validation rules.
92
+ * @returns Ordered editable rules, or the sound subset of a read-only source sheet. */
93
+ export function readXlsxConditionalFormats(worksheet: Element, sheetId: string, context: XlsxConditionalContext,
94
+ progress?: ReadonlySet<Element>): XlsxConditionalRead {
95
+ const records = new Map<number, { ranges: readonly WorkbookRange[]; rule?: WorkbookConditionalPreviewRule | undefined }>();
96
+ const priorities = new Set<number>();
97
+ const extensions = xlsxConditionExtensions(worksheet);
98
+ if (!extensions) return {};
99
+ const extensionReferences = new Set<string>();
100
+ try {
101
+ for (const container of children(worksheet, "conditionalFormatting")) {
102
+ const rules = children(container);
103
+ if (container.namespaceURI !== spreadNs || !hasKnownAttributes(container, ["sqref", "pivot"]) || flag(container, "pivot") || !rules.length) return {};
104
+ const sqref = container.getAttribute("sqref")?.trim() ?? "";
105
+ const ranges = conditionalRanges(sheetId, sqref);
106
+ for (const rule of rules) {
107
+ if (rule.namespaceURI !== spreadNs || rule.localName !== "cfRule") return {};
108
+ const priority = readIndex(rule, "priority");
109
+ if (!priority || priorities.has(priority) || priorities.size === maximumWorkbookConditionalFormats) return {};
110
+ priorities.add(priority);
111
+ const extension = xlsxDataBarExtensionId(rule);
112
+ if (extension) {
113
+ if (extensionReferences.has(extension)) return {};
114
+ extensionReferences.add(extension);
115
+ }
116
+ if (progress?.has(rule)) continue;
117
+ try {
118
+ const shape = { id: `rule-${priority}`, ranges, stopIfTrue: flag(rule, "stopIfTrue") };
119
+ const type = rule.getAttribute("type");
120
+ const visual = type === "dataBar" ? readXlsxConditionalBar(rule, sqref, extensions, context.color)
121
+ : type === "colorScale" ? readXlsxColorScale(rule, context.color) : readXlsxIconSet(rule);
122
+ if (visual && workbookConditionalThresholdFormulas(visual).some(formula => context.resolveNames(formula, ranges[0]!) !== formula)) {
123
+ throw new Error("Unsupported relative name in a conditional threshold.");
124
+ }
125
+ const format = visual ? copyWorkbookConditionalFormats(sheetId, [{ ...shape, predicate: visual, style: {} }])[0]
126
+ : modelConditionalFormat(sheetId, rule, shape, context);
127
+ if (format) {
128
+ records.set(priority, { ranges, rule: { kind: "format", format } });
129
+ continue;
130
+ }
131
+ const formula = readXlsxConditionalFormula(rule, ranges[0]!, context);
132
+ records.set(priority, { ranges, rule: formula ? { ...shape, ...formula, kind: "formula" } : undefined });
133
+ } catch { records.set(priority, { ranges }); }
134
+ }
135
+ }
136
+ // Standalone enhanced rules share priorities with base rules. A companion data bar has no independent priority.
137
+ for (const [extension, rule] of extensions) {
138
+ if (extensionReferences.has(extension)) continue;
139
+ const priority = readIndex(rule, "priority");
140
+ if (!priority || priorities.has(priority) || priorities.size === maximumWorkbookConditionalFormats) return {};
141
+ priorities.add(priority);
142
+ const sqref = child(rule.parentNode as Element, "sqref")?.textContent?.trim() ?? "";
143
+ const ranges = conditionalRanges(sheetId, sqref);
144
+ try {
145
+ const icons = readXlsxIconSet(rule);
146
+ const native = icons && workbookConditionalThresholdFormulas(icons).every(formula => context.resolveNames(formula, ranges[0]!) === formula)
147
+ ? { predicate: icons, style: {} } : readXlsxComputedTextRule(rule, ranges[0]!, context);
148
+ const format = native && copyWorkbookConditionalFormats(sheetId, [
149
+ { ...native, id: `rule-${priority}`, ranges, stopIfTrue: flag(rule, "stopIfTrue") }
150
+ ])[0];
151
+ records.set(priority, { ranges, rule: format ? { kind: "format", format } : undefined });
152
+ } catch { records.set(priority, { ranges }); }
153
+ }
154
+ } catch { return {}; }
155
+
156
+ // Unknown predecessors may override or stop an otherwise readable rule. Carry their footprints
157
+ // forward, including regions of skipped rules whose range-wide statistics must stay intact.
158
+ const sorted = [...records.entries()].sort(([first], [second]) => first - second);
159
+ const unknown: WorkbookRange[] = [], previews: WorkbookConditionalPreviewRule[] = [];
160
+ const formats: WorkbookConditionalFormat[] = [];
161
+ let workload = 0;
162
+ for (const [, { ranges, rule }] of sorted) {
163
+ const cells = ranges.reduce((sum, range) => sum + workbookRangeSize(range), 0);
164
+ if (!rule || cells > workbookTransactionCellLimit || workload + cells > workbookTransactionCellLimit * 10
165
+ || ranges.some((range, index) => ranges.slice(0, index).some(other => workbookRangesOverlap(range, other))
166
+ || unknown.some(other => workbookRangesOverlap(range, other)))) {
167
+ unknown.push(...ranges);
168
+ continue;
169
+ }
170
+ workload += cells;
171
+ previews.push(rule);
172
+ if (rule.kind === "format") formats.push(rule.format);
173
+ }
174
+ return formats.length === sorted.length ? { formats: copyWorkbookConditionalFormats(sheetId, formats) } : { previews };
175
+ }
176
+
177
+ /** @param sheetId - Target worksheet. @param rule - Native source. @param shape - Validated identity and coordinates.
178
+ * @param context - Native differential styles and name bindings. @returns A round-trippable rule, when supported. */
179
+ function modelConditionalFormat(sheetId: string, rule: Element, shape: Pick<WorkbookConditionalFormat, "id" | "ranges" | "stopIfTrue">,
180
+ context: XlsxConditionalContext): WorkbookConditionalFormat | undefined {
181
+ const style = context.styles[readIndex(rule, "dxfId") ?? -1];
182
+ if (!style || style.progressPercent || style.noFill) return;
183
+ try { return copyWorkbookConditionalFormats(sheetId, [{ ...shape, style, predicate: readPredicate(rule, shape.ranges[0]!, context) }])[0]; }
184
+ catch { return undefined; }
185
+ }
@@ -0,0 +1,71 @@
1
+ import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
2
+ import { openWorkbook, parseWorkbookRange, type WorkbookConditionalFormat, type WorkbookSnapshot } from "@quirekit/workbook";
3
+ import { expect, it } from "vitest";
4
+ import { createXlsx, openXlsx } from "../../index";
5
+
6
+ const target = parseWorkbookRange("orders", "A2:A5");
7
+ const fills = { background: "#AABBCC", color: "#442266" };
8
+ const formats: WorkbookConditionalFormat[] = [
9
+ { id: "prefix", ranges: [target, parseWorkbookRange("orders", "D2:D5")], stopIfTrue: true, style: fills,
10
+ predicate: { kind: "text", operator: "beginsWith", operand: { kind: "formula", formula: "=$B2" } } },
11
+ { id: "bar", ranges: [parseWorkbookRange("orders", "C2:C5")], stopIfTrue: false, style: {},
12
+ predicate: { kind: "dataBar", minimum: { type: "automatic" }, maximum: { type: "number", value: 50 },
13
+ axis: "automatic", gradient: false, showValue: true, color: "#245684" } },
14
+ { id: "contains", ranges: [target], stopIfTrue: false, style: fills,
15
+ predicate: { kind: "text", operator: "contains", operand: { kind: "literal", value: ' PH? "tag" ' } } },
16
+ { id: "not-contains", ranges: [target], stopIfTrue: false, style: fills,
17
+ predicate: { kind: "text", operator: "notContains", operand: { kind: "literal", value: "~?" } } },
18
+ { id: "suffix", ranges: [target], stopIfTrue: false, style: fills,
19
+ predicate: { kind: "text", operator: "endsWith", operand: { kind: "literal", value: "尾" } } }
20
+ ];
21
+ const seed: WorkbookSnapshot = { id: "native-text", name: "Orders", revision: 0, version: 1, sheets: [
22
+ { id: "orders", name: "Orders", conditionalFormats: formats, cells: [
23
+ { row: 1, column: 0, input: { kind: "value", value: "Alpha" } }, { row: 1, column: 1, input: { kind: "value", value: "Al" } }
24
+ ] }
25
+ ] };
26
+ const sheetPart = "xl/worksheets/sheet1.xml";
27
+
28
+ it("keeps standard text rules and WPS-style computed operands in one native priority order", async () => {
29
+ const source = createXlsx(seed);
30
+ const xml = strFromU8(unzipSync(source)[sheetPart]!);
31
+ expect(xml).toContain('<cfRule type="containsText" operator="containsText" text=" PH? &quot;tag&quot; " dxfId="0" priority="3">');
32
+ expect(xml).toContain('<formula>ISERROR(SEARCH("~?",A2))</formula>');
33
+ expect(xml).toContain('<formula>RIGHT(A2,LEN("尾"))="尾"</formula>');
34
+ expect(xml).toContain('type="beginsWith" operator="beginsWith" priority="1" stopIfTrue="1"');
35
+ expect(xml).toContain("LEFT(A2,LEN($B2))=($B2)");
36
+ const file = openXlsx("Native text", source);
37
+ const sheet = file.snapshot.sheets[0]!;
38
+ expect(file.restrictions).toEqual([]);
39
+ expect(sheet.conditionalFormats?.map(({ predicate }) => predicate)).toEqual(formats.map(({ predicate }) => predicate));
40
+ expect(sheet.conditionalFormats?.[0]?.ranges).toEqual(["A2:A5", "D2:D5"].map(a1 => parseWorkbookRange(sheet.id, a1)));
41
+ const book = await openWorkbook(file.snapshot);
42
+ try {
43
+ const prefix = sheet.conditionalFormats![0]!;
44
+ await book.commit(book.prepare({ operationId: "remove-computed-text", baseRevision: 0, commands: [
45
+ { name: "removeConditionalFormat", target: prefix.ranges[0]!, params: { id: prefix.id } }
46
+ ] }).id);
47
+ const saved = file.write(book.snapshot());
48
+ expect(strFromU8(unzipSync(saved)[sheetPart]!)).not.toContain("LEFT(A2,LEN(");
49
+ expect(openXlsx("Remaining conditions", saved).snapshot.sheets[0]?.conditionalFormats?.map(rule => rule.predicate))
50
+ .toEqual(formats.slice(1).map(rule => rule.predicate));
51
+ await book.undo("restore-computed-text");
52
+ expect(file.write(book.snapshot())).toEqual(source);
53
+ } finally { await book.close(); }
54
+ });
55
+
56
+ it("reads producer expression variants and preserves a mismatched native text condition", () => {
57
+ const parts = unzipSync(createXlsx(seed));
58
+ const native = strFromU8(parts[sheetPart]!);
59
+ parts[sheetPart] = strToU8(native.replace("LEFT(A2,LEN($B2))=($B2)", "LEFT(A2,LEN($B2))=$B2")
60
+ .replace('type="containsText" operator="containsText"', 'type="containsText" operator="between"'));
61
+ const fromProducer = openXlsx("WPS text", zipSync(parts));
62
+ expect(fromProducer.restrictions).toEqual([]);
63
+ expect(fromProducer.snapshot.sheets[0]?.conditionalFormats?.[0]?.predicate).toEqual(formats[0]!.predicate);
64
+ parts[sheetPart] = strToU8(native.replace("LEFT(A2,LEN($B2))=($B2)", "FALSE()"));
65
+ const original = zipSync(parts);
66
+ const unsupported = openXlsx("Source condition", original);
67
+ expect(unsupported.restrictions).toContain("条件格式包含暂未支持的规则或样式");
68
+ expect(unsupported.appearance.sheets.get(unsupported.snapshot.sheets[0]!.id)?.conditionalPreviews?.map(rule => rule.kind === "format" && rule.format.predicate.kind))
69
+ .toEqual(["dataBar"]);
70
+ expect(unsupported.write(unsupported.snapshot)).toEqual(original);
71
+ });