@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.
- package/LICENSE.md +21 -0
- package/THIRD_PARTY_NOTICES.md +150 -0
- package/dist/index.d.mts +122 -0
- package/dist/index.d.mts.map +1 -0
- package/dist/index.mjs +19167 -0
- package/dist/index.mjs.map +1 -0
- package/licenses/saxes.LICENSE +64 -0
- package/licenses/xmlchars.LICENSE +18 -0
- package/package.json +52 -3
- package/src/bundle.ts +17 -0
- package/src/comments/legacy/read.ts +68 -0
- package/src/comments/legacy/write.ts +64 -0
- package/src/comments/package/ranges.ts +78 -0
- package/src/comments/package/read.ts +95 -0
- package/src/comments/package/roundtrip.test.ts +106 -0
- package/src/comments/package/write.ts +130 -0
- package/src/comments/thread/read.ts +69 -0
- package/src/comments/thread/write.ts +61 -0
- package/src/comments/types.ts +43 -0
- package/src/comments/xml.ts +50 -0
- package/src/create.ts +13 -0
- package/src/drawing/cache.ts +48 -0
- package/src/drawing/chart.test.ts +96 -0
- package/src/drawing/chart.ts +87 -0
- package/src/drawing/definition/plots.ts +76 -0
- package/src/drawing/definition/read.ts +65 -0
- package/src/drawing/definition/shape.ts +40 -0
- package/src/drawing/definition/types.ts +24 -0
- package/src/drawing/editable-picture.ts +80 -0
- package/src/drawing/graph.ts +148 -0
- package/src/drawing/identity.ts +22 -0
- package/src/drawing/import.ts +133 -0
- package/src/drawing/namespaces.ts +11 -0
- package/src/drawing/picture.test.ts +98 -0
- package/src/drawing/picture.ts +54 -0
- package/src/drawing/placement/anchor.ts +71 -0
- package/src/drawing/placement/axes.ts +113 -0
- package/src/drawing/placement/marker.ts +16 -0
- package/src/drawing/placement/transform.ts +132 -0
- package/src/drawing/placement/types.ts +20 -0
- package/src/drawing/presentation/cartesian/axes.ts +103 -0
- package/src/drawing/presentation/cartesian/plot.ts +109 -0
- package/src/drawing/presentation/cartesian/types.ts +9 -0
- package/src/drawing/presentation/layout.ts +29 -0
- package/src/drawing/presentation/paint.ts +56 -0
- package/src/drawing/presentation/properties.ts +31 -0
- package/src/drawing/read.ts +85 -0
- package/src/drawing/shapes/connector.ts +55 -0
- package/src/drawing/shapes/paint.ts +108 -0
- package/src/drawing/shapes/read.ts +89 -0
- package/src/drawing/shapes/text.ts +89 -0
- package/src/drawing/shapes/types.ts +13 -0
- package/src/drawing/sources.test.ts +27 -0
- package/src/drawing/sources.ts +43 -0
- package/src/drawing/types.ts +54 -0
- package/src/drawing/worksheet-connector.test.ts +135 -0
- package/src/drawing/worksheet-shape.test.ts +61 -0
- package/src/drawing/write/anchor.ts +17 -0
- package/src/drawing/write/axes.ts +23 -0
- package/src/drawing/write/chart.ts +56 -0
- package/src/drawing/write/drawing.ts +61 -0
- package/src/drawing/write/pictures.ts +68 -0
- package/src/drawing/write/series.ts +43 -0
- package/src/drawing/write/shapes.ts +113 -0
- package/src/drawing/write/text.ts +26 -0
- package/src/drawing/write/workbook.test.ts +199 -0
- package/src/drawing/write/workbook.ts +217 -0
- package/src/external-links/formulas.ts +21 -0
- package/src/external-links/read.test.ts +93 -0
- package/src/external-links/read.ts +104 -0
- package/src/external-links/types.ts +9 -0
- package/src/external-links/write.ts +120 -0
- package/src/image/excel.ts +122 -0
- package/src/image/native.ts +21 -0
- package/src/image/ownership.ts +77 -0
- package/src/image/parts.ts +45 -0
- package/src/image/raster.ts +25 -0
- package/src/image/read.test.ts +95 -0
- package/src/image/read.ts +66 -0
- package/src/image/relationships.ts +26 -0
- package/src/image/types.ts +48 -0
- package/src/image/wps.ts +43 -0
- package/src/image/write.test.ts +53 -0
- package/src/image/write.ts +118 -0
- package/src/index.ts +6 -0
- package/src/metadata/dynamic-array.ts +105 -0
- package/src/metadata/package.ts +75 -0
- package/src/metadata/types.ts +7 -0
- package/src/opc/archive.ts +26 -0
- package/src/opc/ownership.ts +40 -0
- package/src/opc/relationships.ts +98 -0
- package/src/opc/revision.ts +28 -0
- package/src/opc/shape.ts +23 -0
- package/src/opc/types.ts +13 -0
- package/src/opc/xml.test.ts +49 -0
- package/src/opc/xml.ts +128 -0
- package/src/optimization/blanks.ts +53 -0
- package/src/optimization/optimize.test.ts +117 -0
- package/src/optimization/optimize.ts +41 -0
- package/src/optimization/package.ts +65 -0
- package/src/optimization/rules.ts +46 -0
- package/src/optimization/styles.ts +76 -0
- package/src/optimization/types.ts +33 -0
- package/src/package/assembly.test.ts +117 -0
- package/src/package/calculation-metadata.test.ts +85 -0
- package/src/package/calculation-metadata.ts +88 -0
- package/src/package/checkboxes.ts +37 -0
- package/src/package/cleanup.test.ts +61 -0
- package/src/package/dashboard.test.ts +53 -0
- package/src/package/dashboard.ts +84 -0
- package/src/package/extensions.ts +16 -0
- package/src/package/merge-recipes.ts +84 -0
- package/src/package/names/conditional.ts +64 -0
- package/src/package/names/defined.test.ts +52 -0
- package/src/package/names/defined.ts +75 -0
- package/src/package/names/filter.ts +68 -0
- package/src/package/names/print-layout.ts +62 -0
- package/src/package/names/print.ts +62 -0
- package/src/package/new.ts +46 -0
- package/src/package/open/appearance.ts +46 -0
- package/src/package/open/directory.ts +61 -0
- package/src/package/open/restrictions.ts +27 -0
- package/src/package/open/snapshot.test.ts +48 -0
- package/src/package/open/snapshot.ts +34 -0
- package/src/package/open/source-write.ts +130 -0
- package/src/package/open/types.ts +73 -0
- package/src/package/open/worksheets.ts +149 -0
- package/src/package/positions.ts +40 -0
- package/src/package/read.ts +143 -0
- package/src/package/save/types.ts +57 -0
- package/src/package/save/worksheets.ts +126 -0
- package/src/package/selection-copy.test.ts +70 -0
- package/src/package/styles.ts +39 -0
- package/src/package/types.ts +52 -0
- package/src/package/workbook-views.ts +34 -0
- package/src/package/worksheets.test.ts +190 -0
- package/src/package/worksheets.ts +162 -0
- package/src/package/write.ts +175 -0
- package/src/pivot/cache/calculated.ts +34 -0
- package/src/pivot/cache/dates.ts +124 -0
- package/src/pivot/cache/groups.ts +11 -0
- package/src/pivot/cache/members.ts +99 -0
- package/src/pivot/cache/numbers.ts +63 -0
- package/src/pivot/cache/read.ts +131 -0
- package/src/pivot/cache/time.ts +20 -0
- package/src/pivot/cache/values.ts +43 -0
- package/src/pivot/cache/write.ts +117 -0
- package/src/pivot/definition/axes.ts +35 -0
- package/src/pivot/definition/dates.ts +87 -0
- package/src/pivot/definition/display.ts +86 -0
- package/src/pivot/definition/extension.ts +57 -0
- package/src/pivot/definition/field-settings/caption.ts +38 -0
- package/src/pivot/definition/field-settings/comparison.ts +47 -0
- package/src/pivot/definition/field-settings/field.ts +66 -0
- package/src/pivot/definition/field-settings/filters.ts +86 -0
- package/src/pivot/definition/field-settings/measure.ts +79 -0
- package/src/pivot/definition/field-settings/types.ts +19 -0
- package/src/pivot/definition/functions.ts +21 -0
- package/src/pivot/definition/items.ts +144 -0
- package/src/pivot/definition/members.ts +98 -0
- package/src/pivot/definition/numbers.ts +19 -0
- package/src/pivot/definition/presentation.ts +52 -0
- package/src/pivot/definition/read.ts +143 -0
- package/src/pivot/definition/report-layout.ts +39 -0
- package/src/pivot/definition/write.ts +157 -0
- package/src/pivot/package/calculated.test.ts +103 -0
- package/src/pivot/package/dates.test.ts +266 -0
- package/src/pivot/package/display.test.ts +133 -0
- package/src/pivot/package/field-settings.test.ts +59 -0
- package/src/pivot/package/layout.test.ts +148 -0
- package/src/pivot/package/measure-settings.test.ts +85 -0
- package/src/pivot/package/members.test.ts +167 -0
- package/src/pivot/package/numbers.test.ts +120 -0
- package/src/pivot/package/read.ts +93 -0
- package/src/pivot/package/roundtrip.test.ts +244 -0
- package/src/pivot/package/write.ts +103 -0
- package/src/pivot/types.ts +36 -0
- package/src/pivot/xml.ts +50 -0
- package/src/presentation.test.ts +186 -0
- package/src/roundtrip.test.ts +72 -0
- package/src/styles/checkbox/bags.ts +85 -0
- package/src/styles/checkbox/style.ts +45 -0
- package/src/styles/checkbox/types.ts +7 -0
- package/src/styles/color.ts +64 -0
- package/src/styles/differential-preview.ts +60 -0
- package/src/styles/differential.ts +119 -0
- package/src/styles/numbers.ts +9 -0
- package/src/styles/parts.ts +107 -0
- package/src/styles/read.ts +95 -0
- package/src/styles/reference.ts +14 -0
- package/src/styles/types.ts +9 -0
- package/src/styles/write.test.ts +88 -0
- package/src/styles/write.ts +162 -0
- package/src/table/conversion.test.ts +73 -0
- package/src/table/definition.ts +89 -0
- package/src/table/filter.ts +42 -0
- package/src/table/ownership.ts +112 -0
- package/src/table/read.test.ts +274 -0
- package/src/table/read.ts +117 -0
- package/src/table/remove.ts +55 -0
- package/src/table/sort.test.ts +79 -0
- package/src/table/styles/builtin.ts +40 -0
- package/src/table/styles/differential.ts +55 -0
- package/src/table/styles/preset-data.ts +17 -0
- package/src/table/styles/presets/dark.ts +104 -0
- package/src/table/styles/presets/light-grid.ts +68 -0
- package/src/table/styles/presets/light.ts +145 -0
- package/src/table/styles/presets/medium-edges.ts +131 -0
- package/src/table/styles/presets/medium.ts +131 -0
- package/src/table/styles/read.ts +70 -0
- package/src/table/styles/types.ts +27 -0
- package/src/table/totals.test.ts +77 -0
- package/src/table/totals.ts +79 -0
- package/src/table/types.ts +21 -0
- package/src/table/write.ts +189 -0
- package/src/types.ts +74 -0
- package/src/value/date.ts +21 -0
- package/src/worksheet/appearance.ts +55 -0
- package/src/worksheet/axis.test.ts +185 -0
- package/src/worksheet/axis.ts +131 -0
- package/src/worksheet/background/read.ts +41 -0
- package/src/worksheet/background/roundtrip.test.ts +77 -0
- package/src/worksheet/background/write.ts +96 -0
- package/src/worksheet/cell-shift.ts +44 -0
- package/src/worksheet/cells.ts +75 -0
- package/src/worksheet/checkbox/formats.ts +53 -0
- package/src/worksheet/checkbox/ranges.ts +112 -0
- package/src/worksheet/checkbox/write.test.ts +62 -0
- package/src/worksheet/conditional/color-scale.ts +61 -0
- package/src/worksheet/conditional/data-bar.ts +76 -0
- package/src/worksheet/conditional/extensions.ts +95 -0
- package/src/worksheet/conditional/icon-reference.ts +69 -0
- package/src/worksheet/conditional/icon-set.test.ts +60 -0
- package/src/worksheet/conditional/icon-set.ts +79 -0
- package/src/worksheet/conditional/preview.ts +44 -0
- package/src/worksheet/conditional/read.ts +185 -0
- package/src/worksheet/conditional/text.test.ts +71 -0
- package/src/worksheet/conditional/text.ts +122 -0
- package/src/worksheet/conditional/threshold.ts +47 -0
- package/src/worksheet/conditional/types.ts +20 -0
- package/src/worksheet/conditional/write-bar.ts +66 -0
- package/src/worksheet/conditional/write.test.ts +218 -0
- package/src/worksheet/conditional/write.ts +103 -0
- package/src/worksheet/copied-axis.ts +70 -0
- package/src/worksheet/data/rows.ts +59 -0
- package/src/worksheet/data/source.test.ts +68 -0
- package/src/worksheet/data/source.ts +31 -0
- package/src/worksheet/data/types.ts +9 -0
- package/src/worksheet/data.test.ts +314 -0
- package/src/worksheet/dimensions/columns.ts +87 -0
- package/src/worksheet/dimensions/write.test.ts +110 -0
- package/src/worksheet/dimensions/write.ts +36 -0
- package/src/worksheet/filters/advanced.test.ts +57 -0
- package/src/worksheet/filters/color.ts +105 -0
- package/src/worksheet/filters/icon.test.ts +83 -0
- package/src/worksheet/filters/icon.ts +39 -0
- package/src/worksheet/filters/read.ts +114 -0
- package/src/worksheet/filters/relative-dates.ts +47 -0
- package/src/worksheet/filters/restore-icons.ts +33 -0
- package/src/worksheet/filters/restore.ts +169 -0
- package/src/worksheet/filters/rules.ts +23 -0
- package/src/worksheet/filters/types.ts +23 -0
- package/src/worksheet/filters/visibility.ts +188 -0
- package/src/worksheet/filters/write.ts +121 -0
- package/src/worksheet/formula/cache.ts +29 -0
- package/src/worksheet/formula/external-results.test.ts +39 -0
- package/src/worksheet/formula/functions.ts +29 -0
- package/src/worksheet/formula/prefix.ts +27 -0
- package/src/worksheet/formula/shared/read.test.ts +121 -0
- package/src/worksheet/formula/shared/read.ts +94 -0
- package/src/worksheet/formula/shared/references.ts +100 -0
- package/src/worksheet/formula/shared/types.ts +21 -0
- package/src/worksheet/formula/spill-read.ts +54 -0
- package/src/worksheet/formula/spill-write.ts +32 -0
- package/src/worksheet/formula/spill.test.ts +101 -0
- package/src/worksheet/formula/write.test.ts +26 -0
- package/src/worksheet/hyperlinks/location.ts +59 -0
- package/src/worksheet/hyperlinks/model.ts +22 -0
- package/src/worksheet/hyperlinks/read.ts +70 -0
- package/src/worksheet/hyperlinks/types.ts +21 -0
- package/src/worksheet/hyperlinks/write.test.ts +203 -0
- package/src/worksheet/hyperlinks/write.ts +51 -0
- package/src/worksheet/merge.test.ts +58 -0
- package/src/worksheet/merge.ts +61 -0
- package/src/worksheet/outline/columns.ts +46 -0
- package/src/worksheet/outline/metadata.ts +68 -0
- package/src/worksheet/outline/native.ts +81 -0
- package/src/worksheet/outline/read.ts +50 -0
- package/src/worksheet/outline/roundtrip.test.ts +73 -0
- package/src/worksheet/outline/types.ts +37 -0
- package/src/worksheet/outline/write.ts +110 -0
- package/src/worksheet/positions.test.ts +46 -0
- package/src/worksheet/positions.ts +48 -0
- package/src/worksheet/print/breaks.ts +72 -0
- package/src/worksheet/print/elements.ts +16 -0
- package/src/worksheet/print/page-text.ts +139 -0
- package/src/worksheet/print/setup.test.ts +141 -0
- package/src/worksheet/print/setup.ts +116 -0
- package/src/worksheet/progress/read.ts +73 -0
- package/src/worksheet/progress/solid.ts +26 -0
- package/src/worksheet/progress/types.ts +11 -0
- package/src/worksheet/progress/write.test.ts +63 -0
- package/src/worksheet/progress/write.ts +46 -0
- package/src/worksheet/read.ts +197 -0
- package/src/worksheet/rich-text.test.ts +41 -0
- package/src/worksheet/rich-text.ts +76 -0
- package/src/worksheet/sort/read.ts +115 -0
- package/src/worksheet/sort/relocate.ts +62 -0
- package/src/worksheet/sort/roundtrip.test.ts +116 -0
- package/src/worksheet/sort/types.ts +11 -0
- package/src/worksheet/sort/write.ts +77 -0
- package/src/worksheet/template.ts +9 -0
- package/src/worksheet/text.ts +33 -0
- package/src/worksheet/validation/extended.ts +36 -0
- package/src/worksheet/validation/image.ts +7 -0
- package/src/worksheet/validation/list-options/portable.ts +90 -0
- package/src/worksheet/validation/list-options/types.ts +14 -0
- package/src/worksheet/validation/list-options/wps.ts +51 -0
- package/src/worksheet/validation/read.ts +162 -0
- package/src/worksheet/validation/text.ts +13 -0
- package/src/worksheet/validation/write.test.ts +259 -0
- package/src/worksheet/validation/write.ts +99 -0
- package/src/worksheet/view/coordinates.ts +39 -0
- package/src/worksheet/view/named/read.ts +116 -0
- package/src/worksheet/view/named/roundtrip.test.ts +136 -0
- package/src/worksheet/view/named/sort.ts +57 -0
- package/src/worksheet/view/named/types.ts +15 -0
- package/src/worksheet/view/named/write.ts +107 -0
- package/src/worksheet/view/named/xml.ts +33 -0
- package/src/worksheet/view/panes.ts +75 -0
- package/src/worksheet/view/read.ts +61 -0
- package/src/worksheet/view/relocate.ts +57 -0
- package/src/worksheet/view/write.test.ts +91 -0
- package/src/worksheet/view/write.ts +57 -0
- package/src/worksheet/write.ts +86 -0
- package/README.md +0 -3
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookRange, formatWorkbookSpillReferences, scanWorkbookFormula, workbookConditionalCellFormula,
|
|
3
|
+
type WorkbookConditionalFormat, type WorkbookConditionalText, type WorkbookConditionalTextOperator, type WorkbookRange } 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 { readXlsxDifferential, writeXlsxDifferential } from "../../styles/differential";
|
|
8
|
+
import { decodeXlsxText, encodeXlsxText } from "../text";
|
|
9
|
+
import { appendXlsxConditionalElement as append, xlsxConditionalNamespace, xlsxConditionalOperands } from "./extensions";
|
|
10
|
+
import type { XlsxConditionalContext } from "./types";
|
|
11
|
+
|
|
12
|
+
const nativeTypes: Record<WorkbookConditionalTextOperator, string> = {
|
|
13
|
+
contains: "containsText", notContains: "notContainsText", beginsWith: "beginsWith", endsWith: "endsWith"
|
|
14
|
+
};
|
|
15
|
+
|
|
16
|
+
/** @param rule - Native conditional rule. @returns The comparison indicated by its rule type. */
|
|
17
|
+
function textOperator(rule: Element): WorkbookConditionalTextOperator | undefined {
|
|
18
|
+
const type = rule.getAttribute("type");
|
|
19
|
+
return (Object.keys(nativeTypes) as WorkbookConditionalTextOperator[]).find(key => nativeTypes[key] === type);
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param operator - Authored text comparison. @returns SpreadsheetML operator metadata. */
|
|
23
|
+
function nativeOperator(operator: WorkbookConditionalTextOperator): string {
|
|
24
|
+
return operator === "contains" ? "containsText" : operator;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @param source - Serialized formula expression. @returns A comparison key preserving quoted values and token boundaries. */
|
|
28
|
+
function tokenKey(source: string): string {
|
|
29
|
+
return JSON.stringify([...scanWorkbookFormula(source)].map(token => token.kind === "word" ? token.text.toUpperCase() : token.text));
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @param value - Native operand element. @returns Its plain expression text when fully understood. */
|
|
33
|
+
function formulaText(value: Element): string | undefined {
|
|
34
|
+
return hasKnownAttributes(value, []) && hasKnownChildren(value, []) ? value.textContent?.trim().replace(/^=/u, "") : undefined;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @param predicate - Canonical text condition. @param anchor - First source region.
|
|
38
|
+
* @returns Native comparison expression without its leading equals sign. */
|
|
39
|
+
function comparisonBody(predicate: WorkbookConditionalText, anchor: WorkbookRange): string {
|
|
40
|
+
return formatWorkbookSpillReferences(workbookConditionalCellFormula({ predicate, ranges: [anchor] })!, "function").formula.slice(1);
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** @param rule - Standard rule with a literal operand. @param anchor - Its first authored region.
|
|
44
|
+
* @returns Verified native text condition without assuming that its metadata overrides an unrelated formula. */
|
|
45
|
+
export function readXlsxLiteralTextRule(rule: Element, anchor: WorkbookRange): WorkbookConditionalText | undefined {
|
|
46
|
+
const operator = textOperator(rule), raw = rule.getAttribute("text");
|
|
47
|
+
if (!operator || !raw || !hasKnownAttributes(rule, ["type", "dxfId", "priority", "stopIfTrue", "operator", "text"])
|
|
48
|
+
|| !hasKnownChildren(rule, ["formula"])) return;
|
|
49
|
+
const predicate: WorkbookConditionalText = { kind: "text", operator, operand: { kind: "literal", value: decodeXlsxText(raw) } };
|
|
50
|
+
const [expression] = children(rule);
|
|
51
|
+
if (!expression) return !rule.hasAttribute("operator") || rule.getAttribute("operator") === nativeOperator(operator) ? predicate : undefined;
|
|
52
|
+
const source = formulaText(expression);
|
|
53
|
+
if (!source) return;
|
|
54
|
+
const expected = comparisonBody(predicate, anchor);
|
|
55
|
+
const equivalent = operator === "contains" ? expected.replace(/^NOT\(ISERROR\((SEARCH\(.*\))\)\)$/su, "ISNUMBER($1)") : expected;
|
|
56
|
+
const key = tokenKey(source);
|
|
57
|
+
if (key === tokenKey(expected) || key === tokenKey(equivalent)) return predicate;
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/** @param formula - Text operand. @returns Whether a producer can omit its outer parentheses after an equals comparison. */
|
|
61
|
+
function safeBareOperand(formula: string): boolean {
|
|
62
|
+
let nested = 0;
|
|
63
|
+
for (const { text } of scanWorkbookFormula(formula)) {
|
|
64
|
+
if (text === "(") nested++;
|
|
65
|
+
else if (text === ")") nested--;
|
|
66
|
+
else if (!nested && /^[<=>]$/u.test(text)) return false;
|
|
67
|
+
}
|
|
68
|
+
return true;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @param rule - Standalone Office 2010 rule. @param anchor - Its first authored source region.
|
|
72
|
+
* @param context - Name and theme mappings. @returns Portable rule details when both input and predicate agree. */
|
|
73
|
+
export function readXlsxComputedTextRule(rule: Element, anchor: WorkbookRange, context: XlsxConditionalContext):
|
|
74
|
+
Pick<WorkbookConditionalFormat, "predicate" | "style"> | undefined {
|
|
75
|
+
const operator = textOperator(rule);
|
|
76
|
+
if (!operator || !hasKnownAttributes(rule, ["type", "priority", "stopIfTrue", "operator", "id"])) return;
|
|
77
|
+
const [expression, operand, dxf, extra] = children(rule);
|
|
78
|
+
if (extra || expression?.localName !== "f" || expression.namespaceURI !== xlsxConditionalOperands
|
|
79
|
+
|| operand?.localName !== "f" || operand.namespaceURI !== xlsxConditionalOperands
|
|
80
|
+
|| dxf?.localName !== "dxf" || dxf.namespaceURI !== xlsxConditionalNamespace) return;
|
|
81
|
+
const source = formulaText(expression), raw = formulaText(operand);
|
|
82
|
+
if (!source || !raw) return;
|
|
83
|
+
const formula = formatWorkbookSpillReferences("=" + raw, "postfix").formula;
|
|
84
|
+
if (context.resolveNames(formula, anchor) !== formula) return;
|
|
85
|
+
const style = readXlsxDifferential(dxf, context.color, xlsxConditionalNamespace);
|
|
86
|
+
if (!style || style.noFill || style.progressPercent) return;
|
|
87
|
+
const predicate: WorkbookConditionalText = { kind: "text", operator, operand: { kind: "formula", formula } };
|
|
88
|
+
const expected = comparisonBody(predicate, anchor);
|
|
89
|
+
const key = tokenKey(source);
|
|
90
|
+
const wrapped = "(" + raw + ")";
|
|
91
|
+
const unparenthesized = (operator === "beginsWith" || operator === "endsWith") && expected.endsWith(wrapped) && safeBareOperand(raw)
|
|
92
|
+
? expected.slice(0, -wrapped.length) + raw : expected;
|
|
93
|
+
if (key === tokenKey(expected) || key === tokenKey(unparenthesized)) return { predicate, style };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** @param node - Standard worksheet rule. @param predicate - Literal comparison. @param anchor - First application region. */
|
|
97
|
+
export function writeXlsxLiteralTextRule(node: Element, predicate: WorkbookConditionalText, anchor: WorkbookRange): void {
|
|
98
|
+
if (predicate.operand.kind !== "literal") throw new Error("Use an extended worksheet rule for a computed text operand.");
|
|
99
|
+
node.setAttribute("type", nativeTypes[predicate.operator]);
|
|
100
|
+
node.setAttribute("operator", nativeOperator(predicate.operator));
|
|
101
|
+
node.setAttribute("text", encodeXlsxText(predicate.operand.value));
|
|
102
|
+
append(node, spreadNs, "formula", comparisonBody(predicate, anchor));
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** @param worksheet - Owning worksheet. @param rule - Full formatting rule. @param priority - Native precedence.
|
|
106
|
+
* @returns A standalone extended rule that keeps the authored formula available in the rule editor. */
|
|
107
|
+
export function writeXlsxComputedTextRule(worksheet: Element, rule: WorkbookConditionalFormat, priority: number): Element {
|
|
108
|
+
const { predicate, ranges, style, stopIfTrue } = rule, { ownerDocument } = worksheet;
|
|
109
|
+
if (predicate.kind !== "text" || predicate.operand.kind !== "formula") throw new Error("Expected a text rule with a computed operand.");
|
|
110
|
+
const group = ownerDocument!.createElementNS(xlsxConditionalNamespace, "x14:conditionalFormatting");
|
|
111
|
+
const native = append(group, xlsxConditionalNamespace, "x14:cfRule");
|
|
112
|
+
native.setAttribute("id", "{" + uuidv4().toUpperCase() + "}");
|
|
113
|
+
native.setAttribute("type", nativeTypes[predicate.operator]);
|
|
114
|
+
native.setAttribute("operator", nativeOperator(predicate.operator));
|
|
115
|
+
native.setAttribute("priority", String(priority));
|
|
116
|
+
if (stopIfTrue) native.setAttribute("stopIfTrue", "1");
|
|
117
|
+
append(native, xlsxConditionalOperands, "xm:f", comparisonBody(predicate, ranges[0]!));
|
|
118
|
+
append(native, xlsxConditionalOperands, "xm:f", formatWorkbookSpillReferences(predicate.operand.formula, "function").formula.slice(1));
|
|
119
|
+
writeXlsxDifferential(ownerDocument!, style, append(native, xlsxConditionalNamespace, "x14:dxf"));
|
|
120
|
+
append(group, xlsxConditionalOperands, "xm:sqref", ranges.map(formatWorkbookRange).join(" "));
|
|
121
|
+
return group;
|
|
122
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { fixWorkbookFormulaReferences, formatWorkbookSpillReferences,
|
|
3
|
+
type WorkbookConditionalBarBound, type WorkbookConditionalColorStop, type WorkbookConditionalFormulaBound,
|
|
4
|
+
type WorkbookConditionalNumericBound } from "@quirekit/workbook";
|
|
5
|
+
|
|
6
|
+
/** @param node - Native attribute owner. @param name - Boolean field. @param fallback - Defined default.
|
|
7
|
+
* @returns Explicit or default flag, rejecting malformed values. */
|
|
8
|
+
export function readXlsxConditionalFlag(node: Element, name: string, fallback = false): boolean {
|
|
9
|
+
if (!node.hasAttribute(name)) return fallback;
|
|
10
|
+
const value = node.getAttribute(name);
|
|
11
|
+
if (value === "1" || value === "true") return true;
|
|
12
|
+
if (value === "0" || value === "false") return false;
|
|
13
|
+
throw new Error("Unsupported conditional formatting flag.");
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** @param raw - Standard val attribute or x14 formula text. @returns An authored formula with one leading equals sign. */
|
|
17
|
+
export function readXlsxThresholdFormula(raw: string): WorkbookConditionalFormulaBound {
|
|
18
|
+
return { type: "formula", formula: formatWorkbookSpillReferences("=" + raw.trim().replace(/^=/u, ""), "postfix").formula };
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param type - Native threshold type. @param text - Its standard or extended operand.
|
|
22
|
+
* @returns A numeric or formula threshold, independent of where it is used. */
|
|
23
|
+
export function readXlsxNumericThreshold(type: string | null, text: string):
|
|
24
|
+
WorkbookConditionalNumericBound | WorkbookConditionalFormulaBound | undefined {
|
|
25
|
+
if (type === "formula") return readXlsxThresholdFormula(text);
|
|
26
|
+
if (type !== "num" && type !== "percent" && type !== "percentile") return;
|
|
27
|
+
const value = Number(text);
|
|
28
|
+
if (!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/iu.test(text) || !Number.isFinite(value)) return;
|
|
29
|
+
return { type: type === "num" ? "number" : type, value };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @param bound - Validated numeric threshold. @param extended - Whether the x14 absolute-reference grammar applies.
|
|
33
|
+
* @returns Serialized operand, when the threshold is not implicit. */
|
|
34
|
+
export function writeXlsxThresholdOperand(bound: WorkbookConditionalBarBound | WorkbookConditionalColorStop, extended = false): string | undefined {
|
|
35
|
+
if (bound.type === "formula") {
|
|
36
|
+
const formula = extended ? fixWorkbookFormulaReferences(bound.formula) : bound.formula;
|
|
37
|
+
return formatWorkbookSpillReferences(formula, "function").formula.slice(1);
|
|
38
|
+
}
|
|
39
|
+
if ("value" in bound) return String(bound.value);
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param base - Standard fallback. @param extension - Enhanced threshold with the same rule priority.
|
|
43
|
+
* @returns Native x14 meaning, keeping authored relative coordinates when the two expressions agree. */
|
|
44
|
+
export function pairedXlsxThreshold(base: WorkbookConditionalBarBound, extension: WorkbookConditionalBarBound): WorkbookConditionalBarBound {
|
|
45
|
+
return base.type === "formula" && extension.type === "formula"
|
|
46
|
+
&& fixWorkbookFormulaReferences(base.formula) === fixWorkbookFormulaReferences(extension.formula) ? base : extension;
|
|
47
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { WorkbookConditionalFormat, WorkbookConditionalFormulaPreview, WorkbookConditionalPreviewRule, WorkbookRange } from "@quirekit/workbook";
|
|
2
|
+
import type { styleColorReader } from "../../styles/color";
|
|
3
|
+
import type { XlsxDifferentialStyle } from "../../styles/types";
|
|
4
|
+
|
|
5
|
+
/** Palette and names available when reading a worksheet's rules. */
|
|
6
|
+
export interface XlsxConditionalContext {
|
|
7
|
+
/** Differential records that can be written back. */
|
|
8
|
+
readonly styles: readonly (XlsxDifferentialStyle | undefined)[];
|
|
9
|
+
/** Read-only differential records at the same source indices. */
|
|
10
|
+
readonly previewStyles: readonly (Pick<WorkbookConditionalFormulaPreview, "style" | "clearBorders"> | undefined)[];
|
|
11
|
+
/** Resolves a source palette color. */
|
|
12
|
+
readonly color: ReturnType<typeof styleColorReader>;
|
|
13
|
+
/** @param source - Formula at the first source region. @param anchor - Its source region. @returns A mapped local formula. */
|
|
14
|
+
resolveNames(source: string, anchor: WorkbookRange): string | undefined;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Mutually exclusive native write support and source-only projection. */
|
|
18
|
+
export type XlsxConditionalRead =
|
|
19
|
+
| { readonly formats: readonly WorkbookConditionalFormat[]; readonly previews?: undefined }
|
|
20
|
+
| { readonly formats?: undefined; readonly previews?: readonly WorkbookConditionalPreviewRule[] };
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import type { WorkbookConditionalBarBound, WorkbookConditionalDataBar } from "@quirekit/workbook";
|
|
3
|
+
import { v4 as uuidv4 } from "uuid";
|
|
4
|
+
import { spreadNs } from "../../opc/xml";
|
|
5
|
+
import { appendXlsxConditionalElement as append, xlsxConditionalNamespace, xlsxConditionalOperands, xlsxConditionalReferenceUri } from "./extensions";
|
|
6
|
+
import { writeXlsxThresholdOperand } from "./threshold";
|
|
7
|
+
|
|
8
|
+
/** @param owner - Data bar. @param bound - Authored endpoint. @param first - Lower versus upper threshold.
|
|
9
|
+
* @param extended - Office 2010 rule with independent automatic threshold types. */
|
|
10
|
+
function writeBound(owner: Element, bound: WorkbookConditionalBarBound, first: boolean, extended: boolean): void {
|
|
11
|
+
const external = bound.type === "automatic" && extended ? first ? "autoMin" : "autoMax"
|
|
12
|
+
: bound.type === "automatic" || bound.type === "extreme" ? first ? "min" : "max" : bound.type === "number" ? "num" : bound.type;
|
|
13
|
+
const node = append(owner, extended ? xlsxConditionalNamespace : spreadNs, extended ? "x14:cfvo" : "cfvo");
|
|
14
|
+
node.setAttribute("type", external);
|
|
15
|
+
const operand = writeXlsxThresholdOperand(bound, extended);
|
|
16
|
+
if (operand !== undefined) {
|
|
17
|
+
if (extended) append(node, xlsxConditionalOperands, "xm:f", operand);
|
|
18
|
+
else node.setAttribute("val", operand);
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param parent - Bar payload. @param name - Qualified native color element. @param color - Opaque canonical RGB. */
|
|
23
|
+
function appendColor(parent: Element, name: string, color: string): void {
|
|
24
|
+
append(parent, parent.namespaceURI!, name).setAttribute("rgb", "FF" + color.slice(1));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @param native - Base priority rule in the sheet. @param rule - Canonical bar settings. @param sqref - Matching native region list.
|
|
28
|
+
* @returns An Office 2010 companion group where the standard rule cannot retain the display semantics. */
|
|
29
|
+
export function writeXlsxDataBar(native: Element, rule: WorkbookConditionalDataBar, sqref: string): Element | undefined {
|
|
30
|
+
const { minimum, maximum, color, negativeColor, axis, gradient, showValue } = rule;
|
|
31
|
+
const extended = minimum.type === "automatic" || maximum.type === "automatic" || axis !== "none" || !gradient || negativeColor !== undefined;
|
|
32
|
+
const shortest = rule.minLength ?? 0, longest = rule.maxLength ?? 100;
|
|
33
|
+
const legacyLengths = extended && shortest === 0 && longest === 100;
|
|
34
|
+
native.setAttribute("type", "dataBar");
|
|
35
|
+
const fallback = append(native, spreadNs, "dataBar");
|
|
36
|
+
fallback.setAttribute("minLength", String(legacyLengths ? 10 : shortest));
|
|
37
|
+
fallback.setAttribute("maxLength", String(legacyLengths ? 90 : longest));
|
|
38
|
+
fallback.setAttribute("showValue", showValue ? "1" : "0");
|
|
39
|
+
writeBound(fallback, minimum, true, false);
|
|
40
|
+
writeBound(fallback, maximum, false, false);
|
|
41
|
+
appendColor(fallback, "color", color);
|
|
42
|
+
if (!extended) return;
|
|
43
|
+
|
|
44
|
+
// Both readers see the same application ranges and rule order. The enhanced member supplies display-only fields.
|
|
45
|
+
const id = "{" + uuidv4().toUpperCase() + "}";
|
|
46
|
+
const reference = append(append(native, spreadNs, "extLst"), spreadNs, "ext");
|
|
47
|
+
reference.setAttribute("uri", xlsxConditionalReferenceUri);
|
|
48
|
+
append(reference, xlsxConditionalNamespace, "x14:id", id);
|
|
49
|
+
const group = native.ownerDocument!.createElementNS(xlsxConditionalNamespace, "x14:conditionalFormatting");
|
|
50
|
+
const companion = append(group, xlsxConditionalNamespace, "x14:cfRule");
|
|
51
|
+
companion.setAttribute("type", "dataBar");
|
|
52
|
+
companion.setAttribute("id", id);
|
|
53
|
+
const bar = append(companion, xlsxConditionalNamespace, "x14:dataBar");
|
|
54
|
+
bar.setAttribute("minLength", String(shortest));
|
|
55
|
+
bar.setAttribute("maxLength", String(longest));
|
|
56
|
+
bar.setAttribute("showValue", showValue ? "1" : "0");
|
|
57
|
+
bar.setAttribute("gradient", gradient ? "1" : "0");
|
|
58
|
+
bar.setAttribute("axisPosition", axis);
|
|
59
|
+
bar.setAttribute("negativeBarColorSameAsPositive", negativeColor ? "0" : "1");
|
|
60
|
+
writeBound(bar, minimum, true, true);
|
|
61
|
+
writeBound(bar, maximum, false, true);
|
|
62
|
+
if (negativeColor) appendColor(bar, "x14:negativeFillColor", negativeColor);
|
|
63
|
+
if (axis !== "none") appendColor(bar, "x14:axisColor", rule.axisColor ?? "#000000");
|
|
64
|
+
append(group, xlsxConditionalOperands, "xm:sqref", sqref);
|
|
65
|
+
return group;
|
|
66
|
+
}
|
|
@@ -0,0 +1,218 @@
|
|
|
1
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
2
|
+
import { expect, it } from "vitest";
|
|
3
|
+
import { openWorkbook, parseWorkbookRange, type WorkbookConditionalColorScale, type WorkbookConditionalDataBar, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
4
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
5
|
+
|
|
6
|
+
const seed: WorkbookSnapshot = { version: 1, id: "book", name: "Orders", revision: 0, sheets: [
|
|
7
|
+
{ id: "orders", name: "Orders", cells: [12, 8, 12, 6].map((value, row) => ({ row, column: 0, input: { kind: "value", value } })),
|
|
8
|
+
conditionalFormats: [
|
|
9
|
+
{ id: "high", ranges: [parseWorkbookRange("orders", "A1:A4")], predicate: { kind: "rank", count: 2, bottom: false, percent: false },
|
|
10
|
+
style: { bold: false, background: "#FFF4BE" }, stopIfTrue: true },
|
|
11
|
+
{ id: "dupes", ranges: [parseWorkbookRange("orders", "A1:A4"), parseWorkbookRange("orders", "C1:C4")],
|
|
12
|
+
predicate: { kind: "duplicate" }, style: { color: "#812632" }, stopIfTrue: false }
|
|
13
|
+
] },
|
|
14
|
+
{ id: "retained", name: "Retained", cells: [{ row: 0, column: 0, input: { kind: "value", value: "Keep" } }] }
|
|
15
|
+
] };
|
|
16
|
+
const sheetPart = "xl/worksheets/sheet1.xml";
|
|
17
|
+
const untouched = "xl/worksheets/sheet2.xml";
|
|
18
|
+
|
|
19
|
+
it("writes and reopens native color scales, and preserves unsupported formula thresholds from the source", async () => {
|
|
20
|
+
const basis = seed.sheets[0]!;
|
|
21
|
+
const predicate: WorkbookConditionalColorScale = { kind: "colorScale", stops: [
|
|
22
|
+
{ type: "minimum", color: "#203060" }, { type: "percentile", value: 50, color: "#A06070" }, { type: "maximum", color: "#F0E0A0" }
|
|
23
|
+
] };
|
|
24
|
+
const bytes = createXlsx({ ...seed, sheets: [{ ...basis, conditionalFormats: [{ id: "scale", predicate, style: {},
|
|
25
|
+
stopIfTrue: false, ranges: [parseWorkbookRange(basis.id, "A1:A4"), parseWorkbookRange(basis.id, "C1:C4")] }] }, seed.sheets[1]!] });
|
|
26
|
+
const parts = unzipSync(bytes);
|
|
27
|
+
const native = strFromU8(parts[sheetPart]!);
|
|
28
|
+
expect(native).toContain('<cfRule type="colorScale" priority="1"><colorScale><cfvo type="min"/><cfvo type="percentile" val="50"/><cfvo type="max"/>');
|
|
29
|
+
expect(native).toContain('<color rgb="FF203060"/><color rgb="FFA06070"/><color rgb="FFF0E0A0"/></colorScale>');
|
|
30
|
+
const source = openXlsx("Color scale", bytes);
|
|
31
|
+
expect(source.restrictions).toEqual([]);
|
|
32
|
+
const sheetId = source.snapshot.sheets[0]!.id;
|
|
33
|
+
const book = await openWorkbook(source.snapshot, { appearance: source.appearance });
|
|
34
|
+
try {
|
|
35
|
+
const [original] = book.conditionalFormats(sheetId);
|
|
36
|
+
expect(original).toMatchObject({ predicate, style: {}, ranges: ["A1:A4", "C1:C4"].map(text => parseWorkbookRange(sheetId, text)) });
|
|
37
|
+
const edited = { kind: "colorScale", stops: [{ type: "number", value: 3, color: "#101810" }, { type: "percent", value: 80, color: "#F1F0CF" }] };
|
|
38
|
+
await book.commit(book.prepare({ operationId: "scale-edit", baseRevision: 0, commands: [
|
|
39
|
+
{ name: "setConditionalFormat", target: parseWorkbookRange(sheetId, "A1:A4"), params: { id: original!.id, predicate: edited } }
|
|
40
|
+
] }).id);
|
|
41
|
+
const saved = source.write(book.snapshot());
|
|
42
|
+
expect(unzipSync(saved)[untouched]).toEqual(parts[untouched]);
|
|
43
|
+
expect(openXlsx("Edited scale", saved).snapshot.sheets[0]?.conditionalFormats?.[0]?.predicate).toEqual(edited);
|
|
44
|
+
await book.undo("undo-scale-edit");
|
|
45
|
+
expect(source.write(book.snapshot())).toEqual(bytes);
|
|
46
|
+
} finally { await book.close(); }
|
|
47
|
+
|
|
48
|
+
parts[sheetPart] = strToU8(native.replace('<cfvo type="percentile" val="50"/>', '<cfvo type="formula" val="[External.xlsx]Sheet1!$A$1"/>'));
|
|
49
|
+
const formulaSource = zipSync(parts);
|
|
50
|
+
const original = openXlsx("Source-only scale", formulaSource);
|
|
51
|
+
expect(original.restrictions).toContain("条件格式包含暂未支持的规则或样式");
|
|
52
|
+
expect(original.write(original.snapshot)).toEqual(formulaSource);
|
|
53
|
+
});
|
|
54
|
+
|
|
55
|
+
it("round-trips worksheet formula thresholds through base rules and paired data bars", () => {
|
|
56
|
+
const basis = seed.sheets[0]!;
|
|
57
|
+
const scale: WorkbookConditionalColorScale = { kind: "colorScale", stops: [
|
|
58
|
+
{ type: "minimum", color: "#203060" }, { type: "formula", formula: "=AVERAGE(A1:A4)", color: "#A06070" },
|
|
59
|
+
{ type: "maximum", color: "#F0E0A0" }
|
|
60
|
+
] };
|
|
61
|
+
const bar: WorkbookConditionalDataBar = { kind: "dataBar", minimum: { type: "automatic" },
|
|
62
|
+
maximum: { type: "formula", formula: "=MAX(A1:A$4)+5" },
|
|
63
|
+
color: "#3869AF", axis: "middle", gradient: false, showValue: false };
|
|
64
|
+
const bytes = createXlsx({ ...seed, sheets: [{ ...basis, conditionalFormats: [scale, bar].map((predicate, index) => ({
|
|
65
|
+
id: ["scale", "bar"][index]!, ranges: [parseWorkbookRange(basis.id, "A1:A4")], predicate, style: {}, stopIfTrue: false
|
|
66
|
+
})) }, seed.sheets[1]!] });
|
|
67
|
+
const native = strFromU8(unzipSync(bytes)[sheetPart]!);
|
|
68
|
+
expect(native).toContain('<cfvo type="formula" val="AVERAGE(A1:A4)"/>');
|
|
69
|
+
expect(native).toContain('<cfvo type="formula" val="MAX(A1:A$4)+5"/>');
|
|
70
|
+
expect(native).toMatch(/<x14:cfvo type="formula"><xm:f\b[^>]*>MAX\(\$A\$1:\$A\$4\)\+5<\/xm:f><\/x14:cfvo>/u);
|
|
71
|
+
const opened = openXlsx("Formula thresholds", bytes);
|
|
72
|
+
expect(opened.restrictions).toEqual([]);
|
|
73
|
+
expect(opened.snapshot.sheets[0]?.conditionalFormats?.map(rule => rule.predicate)).toEqual([scale, bar]);
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it("keeps prioritized conditional formats native, relocates areas and preserves untouched worksheet bytes", async () => {
|
|
77
|
+
const initial = createXlsx(seed);
|
|
78
|
+
const file = openXlsx("Orders", initial);
|
|
79
|
+
expect(file.restrictions).toEqual([]);
|
|
80
|
+
const sheetId = file.snapshot.sheets[0]!.id;
|
|
81
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance, axisRestrictions: file.axisRestrictions });
|
|
82
|
+
try {
|
|
83
|
+
const rules = workbook.conditionalFormats(sheetId);
|
|
84
|
+
expect(rules[0]).toMatchObject({ predicate: { kind: "rank", count: 2 }, stopIfTrue: true, style: { bold: false, background: "#FFF4BE" } });
|
|
85
|
+
expect(rules[1]?.ranges).toHaveLength(2);
|
|
86
|
+
const candidate = workbook.prepare({ operationId: "insert", baseRevision: 0,
|
|
87
|
+
commands: [{ name: "insertRows", target: parseWorkbookRange(sheetId, "A2"), params: {} }] });
|
|
88
|
+
await workbook.commit(candidate.id);
|
|
89
|
+
const output = file.write(workbook.snapshot());
|
|
90
|
+
const parts = unzipSync(output);
|
|
91
|
+
expect(strFromU8(parts[sheetPart]!)).toContain('sqref="A1:A5 C1:C5"');
|
|
92
|
+
expect(strFromU8(parts["xl/styles.xml"]!)).toMatch(/<dxfs count="2">.*<b val="0".*<bgColor rgb="FFFFF4BE"/su);
|
|
93
|
+
expect(parts[untouched]).toEqual(unzipSync(initial)[untouched]);
|
|
94
|
+
const reopened = openXlsx("Changed", output);
|
|
95
|
+
expect(reopened.restrictions).toEqual([]);
|
|
96
|
+
expect(reopened.snapshot.sheets[0]?.conditionalFormats?.[1]?.ranges[1]?.endRow).toBe(4);
|
|
97
|
+
await workbook.undo("undo-insert");
|
|
98
|
+
expect(file.write(workbook.snapshot())).toEqual(initial);
|
|
99
|
+
} finally { await workbook.close(); }
|
|
100
|
+
});
|
|
101
|
+
|
|
102
|
+
it("opens and updates an expression alongside an ordinary rule in native XLSX", async () => {
|
|
103
|
+
const parts = unzipSync(createXlsx(seed));
|
|
104
|
+
parts[sheetPart] = strToU8(strFromU8(parts[sheetPart]!).replace('type="duplicateValues"', 'type="expression"').replace(
|
|
105
|
+
/(<cfRule type="expression"[^>]*?)\/>/u, "$1><formula>$A1>1</formula></cfRule>"
|
|
106
|
+
));
|
|
107
|
+
const bytes = zipSync(parts);
|
|
108
|
+
const file = openXlsx("Expression", bytes);
|
|
109
|
+
expect(file.restrictions).toEqual([]);
|
|
110
|
+
const sheetId = file.snapshot.sheets[0]!.id;
|
|
111
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
112
|
+
const book = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
113
|
+
try {
|
|
114
|
+
const previous = book.conditionalFormats(sheetId)[1]!;
|
|
115
|
+
expect(previous).toMatchObject({ predicate: { kind: "formula", formula: "=$A1>1" }, style: { color: "#812632" } });
|
|
116
|
+
const formula = '=AND($A1>=3,C$1<10)';
|
|
117
|
+
await book.commit(book.prepare({ operationId: "formula-edit", baseRevision: book.revision, commands: [
|
|
118
|
+
{ name: "setConditionalFormat", target: parseWorkbookRange(sheetId, "C1:C3"), params: { id: previous.id,
|
|
119
|
+
ranges: ["C1:C3", "A1:A2"], predicate: { kind: "formula", formula }, style: previous.style, stopIfTrue: true, position: 1 } }
|
|
120
|
+
] }).id);
|
|
121
|
+
const output = file.write(book.snapshot());
|
|
122
|
+
const saved = unzipSync(output);
|
|
123
|
+
expect(strFromU8(saved[sheetPart]!)).toContain('sqref="C1:C3 A1:A2"');
|
|
124
|
+
expect(strFromU8(saved[sheetPart]!)).toContain('<formula>AND($A1>=3,C$1<10)</formula>');
|
|
125
|
+
expect(saved[untouched]).toEqual(parts[untouched]);
|
|
126
|
+
const reopened = openXlsx("Edited expression", output);
|
|
127
|
+
expect(reopened.restrictions).toEqual([]);
|
|
128
|
+
expect(reopened.snapshot.sheets[0]?.conditionalFormats?.[0]).toMatchObject({ predicate: { kind: "formula", formula },
|
|
129
|
+
stopIfTrue: true, ranges: [parseWorkbookRange(sheetId, "C1:C3"), parseWorkbookRange(sheetId, "A1:A2")] });
|
|
130
|
+
await book.undo("undo-expression");
|
|
131
|
+
expect(file.write(book.snapshot())).toEqual(bytes);
|
|
132
|
+
} finally { await book.close(); }
|
|
133
|
+
});
|
|
134
|
+
|
|
135
|
+
it("keeps readable source rules outside the precedence of unknown rules", () => {
|
|
136
|
+
const parts = unzipSync(createXlsx(seed));
|
|
137
|
+
const rules = [
|
|
138
|
+
'<conditionalFormatting sqref="B1:B3"><cfRule type="expression" dxfId="0" priority="8" stopIfTrue="1"><formula>WEBSERVICE(A1)</formula></cfRule></conditionalFormatting>',
|
|
139
|
+
'<conditionalFormatting sqref="A1:B3"><cfRule type="expression" dxfId="1" priority="9"><formula>MOD(ROW(),2)=1</formula></cfRule></conditionalFormatting>',
|
|
140
|
+
'<conditionalFormatting sqref="A1:A3"><cfRule type="duplicateValues" dxfId="1" priority="10"/></conditionalFormatting>',
|
|
141
|
+
'<conditionalFormatting sqref="C1:C3"><cfRule type="cellIs" dxfId="1" priority="11" operator="equal"><formula>""</formula></cfRule></conditionalFormatting>'
|
|
142
|
+
];
|
|
143
|
+
parts[sheetPart] = strToU8(strFromU8(parts[sheetPart]!).replace(/<conditionalFormatting\b[^]*?<\/conditionalFormatting>/gu, "")
|
|
144
|
+
.replace("</worksheet>", rules.reverse().join("") + "</worksheet>"));
|
|
145
|
+
const bytes = zipSync(parts);
|
|
146
|
+
const file = openXlsx("Restricted", bytes);
|
|
147
|
+
const first = file.snapshot.sheets[0]!;
|
|
148
|
+
expect(file.restrictions).toContain("条件格式包含暂未支持的规则或样式");
|
|
149
|
+
expect(file.appearance.sheets.get(first.id)?.conditionalPreviews).toMatchObject([
|
|
150
|
+
{ id: "rule-11", kind: "formula", formula: '=OR(ISBLANK(C1),AND(ISTEXT(C1),C1=""))' }
|
|
151
|
+
]);
|
|
152
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
153
|
+
expect(() => file.write({ ...file.snapshot, sheets: [{ ...first, cells: [] }, file.snapshot.sheets[1]!] })).toThrow("原文件仅可原样下载");
|
|
154
|
+
});
|
|
155
|
+
|
|
156
|
+
it("projects local mixed references, differential borders and fixed numeric bars", () => {
|
|
157
|
+
const parts = unzipSync(createXlsx(seed));
|
|
158
|
+
const workbookPart = "xl/workbook.xml";
|
|
159
|
+
const stylesPart = "xl/styles.xml";
|
|
160
|
+
parts[workbookPart] = strToU8(strFromU8(parts[workbookPart]!).replace("</workbook>",
|
|
161
|
+
'<definedNames><definedName name="row_amount" localSheetId="0">Orders!$A1</definedName></definedNames></workbook>'));
|
|
162
|
+
parts[stylesPart] = strToU8(strFromU8(parts[stylesPart]!).replace('<dxfs count="2">', '<dxfs count="3">').replace("</dxfs>",
|
|
163
|
+
'<dxf><border><left style="thin"><color rgb="FFC00000"/></left><right/><vertical/></border></dxf></dxfs>'));
|
|
164
|
+
parts[sheetPart] = strToU8(strFromU8(parts[sheetPart]!).replace("</worksheet>", [
|
|
165
|
+
'<conditionalFormatting sqref="B3:C4"><cfRule type="expression" dxfId="2" priority="3"><formula>row_amount>B$1</formula></cfRule></conditionalFormatting>',
|
|
166
|
+
'<conditionalFormatting sqref="D2:D5"><cfRule type="dataBar" priority="5"><dataBar minLength="0" maxLength="100" showValue="0"><cfvo type="num" val="0"/><cfvo type="num" val="1"/><color rgb="FF123456"/></dataBar></cfRule></conditionalFormatting>',
|
|
167
|
+
"</worksheet>"
|
|
168
|
+
].join("")));
|
|
169
|
+
const file = openXlsx("Tasks", zipSync(parts));
|
|
170
|
+
const sheet = file.snapshot.sheets[0]!;
|
|
171
|
+
expect(file.appearance.sheets.get(sheet.id)?.conditionalPreviews?.slice(-2)).toMatchObject([
|
|
172
|
+
{ kind: "formula", formula: "=$A3>B$1", clearBorders: ["right"], style: { borders: { left: { color: "#C00000", stroke: "thin" } } } },
|
|
173
|
+
{ kind: "format", format: { predicate: { kind: "dataBar", minimum: { type: "number", value: 0 }, maximum: { type: "number", value: 1 },
|
|
174
|
+
color: "#123456", gradient: true, showValue: false } } }
|
|
175
|
+
]);
|
|
176
|
+
});
|
|
177
|
+
|
|
178
|
+
it("keeps enhanced data bars editable, relocates their ranges and removes deleted companion records", async () => {
|
|
179
|
+
const base = seed.sheets[0]!;
|
|
180
|
+
const bar: WorkbookConditionalDataBar = { kind: "dataBar", minimum: { type: "automatic" }, maximum: { type: "percentile", value: 90 },
|
|
181
|
+
axis: "middle", gradient: false, showValue: false, color: "#3869AF", negativeColor: "#C84752" };
|
|
182
|
+
const initial = createXlsx({ ...seed, sheets: [{ ...base, conditionalFormats: [
|
|
183
|
+
{ id: "bar", ranges: [parseWorkbookRange("orders", "A1:A4"), parseWorkbookRange("orders", "C1:C4")], predicate: bar, style: {}, stopIfTrue: false },
|
|
184
|
+
...base.conditionalFormats!
|
|
185
|
+
] }, seed.sheets[1]!] });
|
|
186
|
+
const input = unzipSync(initial);
|
|
187
|
+
const native = strFromU8(input[sheetPart]!);
|
|
188
|
+
expect(native).toContain('<dataBar minLength="10" maxLength="90" showValue="0">');
|
|
189
|
+
expect(native).toContain('<x14:cfvo type="autoMin"/>');
|
|
190
|
+
expect(native).toMatch(/<x14:dataBar minLength="0" maxLength="100" showValue="0" gradient="0" axisPosition="middle"/u);
|
|
191
|
+
expect(native).toMatch(/<x14:negativeFillColor rgb="FFC84752"/u);
|
|
192
|
+
const file = openXlsx("Editable bars", initial);
|
|
193
|
+
expect(file.restrictions).toEqual([]);
|
|
194
|
+
expect(file.axisRestrictions.size).toBe(0);
|
|
195
|
+
const id = file.snapshot.sheets[0]!.id;
|
|
196
|
+
const book = await openWorkbook(file.snapshot, { appearance: file.appearance, axisRestrictions: file.axisRestrictions });
|
|
197
|
+
try {
|
|
198
|
+
expect(book.conditionalFormats(id)[0]?.predicate).toEqual(bar);
|
|
199
|
+
const target = parseWorkbookRange(id, "A2");
|
|
200
|
+
const shifted = book.prepare({ operationId: "shift-bars", baseRevision: book.revision,
|
|
201
|
+
commands: [{ name: "insertRows", target, params: {} }] });
|
|
202
|
+
await book.commit(shifted.id);
|
|
203
|
+
const saved = file.write(book.snapshot());
|
|
204
|
+
const reread = openXlsx("Moved bars", saved);
|
|
205
|
+
expect(reread.restrictions).toEqual([]);
|
|
206
|
+
expect(reread.snapshot.sheets[0]?.conditionalFormats?.[0]).toMatchObject({ predicate: bar, ranges: [
|
|
207
|
+
parseWorkbookRange(id, "A1:A5"), parseWorkbookRange(id, "C1:C5")
|
|
208
|
+
] });
|
|
209
|
+
expect(unzipSync(saved)[untouched]).toEqual(input[untouched]);
|
|
210
|
+
const remove = book.prepare({ operationId: "remove-bars", baseRevision: book.revision, commands: [
|
|
211
|
+
{ name: "removeConditionalFormat", target, params: { id: book.conditionalFormats(id)[0]!.id } }
|
|
212
|
+
] });
|
|
213
|
+
await book.commit(remove.id);
|
|
214
|
+
const cleared = file.write(book.snapshot());
|
|
215
|
+
expect(strFromU8(unzipSync(cleared)[sheetPart]!)).not.toMatch(/conditionalFormattings|dataBar/u);
|
|
216
|
+
expect(openXlsx("Cleared", cleared).restrictions).toEqual([]);
|
|
217
|
+
} finally { await book.close(); }
|
|
218
|
+
});
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { copyWorkbookConditionalFormats, formatWorkbookRange, formatWorkbookSpillReferences, type WorkbookConditionalFormat, type WorkbookConditionalPredicate,
|
|
3
|
+
type WorkbookProgressValidationRule, type WorkbookRange } from "@quirekit/workbook";
|
|
4
|
+
import { children, spreadNs } from "../../opc/xml";
|
|
5
|
+
import type { XlsxDifferentialStyle } from "../../styles/types";
|
|
6
|
+
import { writeXlsxProgressFormats } from "../progress/write";
|
|
7
|
+
import { writeXlsxDataBar } from "./write-bar";
|
|
8
|
+
import { writeXlsxColorScale } from "./color-scale";
|
|
9
|
+
import { writeXlsxExtendedIconSet, writeXlsxIconSet, xlsxExtendedIconSets } from "./icon-set";
|
|
10
|
+
import { writeXlsxConditionalExtensions } from "./extensions";
|
|
11
|
+
import { writeXlsxComputedTextRule, writeXlsxLiteralTextRule } from "./text";
|
|
12
|
+
|
|
13
|
+
const later = new Set([
|
|
14
|
+
"dataValidations", "hyperlinks", "printOptions", "pageMargins", "pageSetup", "headerFooter", "rowBreaks",
|
|
15
|
+
"colBreaks", "customProperties", "cellWatches", "ignoredErrors", "smartTags", "drawing", "legacyDrawing",
|
|
16
|
+
"legacyDrawingHF", "picture", "oleObjects", "controls", "webPublishItems", "tableParts", "extLst"
|
|
17
|
+
]);
|
|
18
|
+
|
|
19
|
+
/** @param node - Native cfRule element. @param text - Formula without its leading equals sign. */
|
|
20
|
+
function appendFormula(node: Element, text: string): void {
|
|
21
|
+
const formula = node.ownerDocument!.createElementNS(spreadNs, "formula");
|
|
22
|
+
formula.appendChild(node.ownerDocument!.createTextNode(text));
|
|
23
|
+
node.appendChild(formula);
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param node - Native cfRule element. @param test - Workbook predicate. @param anchor - Rule's first source region. */
|
|
27
|
+
function writePredicate(node: Element, test: Exclude<WorkbookConditionalPredicate, { kind: "dataBar" | "colorScale" | "iconSet" }>, anchor: WorkbookRange): void {
|
|
28
|
+
switch (test.kind) {
|
|
29
|
+
case "duplicate":
|
|
30
|
+
case "unique":
|
|
31
|
+
node.setAttribute("type", test.kind === "duplicate" ? "duplicateValues" : "uniqueValues");
|
|
32
|
+
break;
|
|
33
|
+
case "number":
|
|
34
|
+
node.setAttribute("type", "cellIs");
|
|
35
|
+
node.setAttribute("operator", test.operator);
|
|
36
|
+
for (const value of [test.first, test.second]) {
|
|
37
|
+
if (value === undefined) continue;
|
|
38
|
+
appendFormula(node, String(value));
|
|
39
|
+
}
|
|
40
|
+
break;
|
|
41
|
+
case "formula":
|
|
42
|
+
node.setAttribute("type", "expression");
|
|
43
|
+
appendFormula(node, formatWorkbookSpillReferences(test.formula, "function").formula.slice(1));
|
|
44
|
+
break;
|
|
45
|
+
case "text":
|
|
46
|
+
writeXlsxLiteralTextRule(node, test, anchor);
|
|
47
|
+
break;
|
|
48
|
+
case "rank":
|
|
49
|
+
node.setAttribute("type", "top10");
|
|
50
|
+
node.setAttribute("rank", String(test.count));
|
|
51
|
+
if (test.bottom) node.setAttribute("bottom", "1");
|
|
52
|
+
if (test.percent) node.setAttribute("percent", "1");
|
|
53
|
+
break;
|
|
54
|
+
case "average":
|
|
55
|
+
node.setAttribute("type", "aboveAverage");
|
|
56
|
+
if (test.below) node.setAttribute("aboveAverage", "0");
|
|
57
|
+
if (test.inclusive) node.setAttribute("equalAverage", "1");
|
|
58
|
+
break;
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
/** @param worksheet - Final native worksheet. @param sheetId - Owner identity. @param rules - Committed conditional formats.
|
|
63
|
+
* @param register - Adds a shared differential record and returns its index. @param progress - Progress projected into native rules. */
|
|
64
|
+
export function writeXlsxConditionalFormats(worksheet: Element, sheetId: string, rules: readonly WorkbookConditionalFormat[],
|
|
65
|
+
register: (style: XlsxDifferentialStyle) => number, progress: readonly WorkbookProgressValidationRule[] = []): void {
|
|
66
|
+
const sorted = copyWorkbookConditionalFormats(sheetId, rules);
|
|
67
|
+
const document = worksheet.ownerDocument!;
|
|
68
|
+
for (const previous of children(worksheet, "conditionalFormatting")) worksheet.removeChild(previous);
|
|
69
|
+
const next = children(worksheet).find(node => later.has(node.localName ?? "")) ?? null;
|
|
70
|
+
const first = progress.length ? writeXlsxProgressFormats(worksheet, next, progress, register({ progressPercent: true })) : 1;
|
|
71
|
+
const extensions: Element[] = [];
|
|
72
|
+
for (const [index, rule] of sorted.entries()) {
|
|
73
|
+
const priority = index + first;
|
|
74
|
+
if (rule.predicate.kind === "text" && rule.predicate.operand.kind === "formula") {
|
|
75
|
+
extensions.push(writeXlsxComputedTextRule(worksheet, rule, priority));
|
|
76
|
+
continue;
|
|
77
|
+
}
|
|
78
|
+
if (rule.predicate.kind === "iconSet" && xlsxExtendedIconSets.has(rule.predicate.set)) {
|
|
79
|
+
extensions.push(writeXlsxExtendedIconSet(worksheet, rule, priority));
|
|
80
|
+
continue;
|
|
81
|
+
}
|
|
82
|
+
const container = document.createElementNS(spreadNs, "conditionalFormatting");
|
|
83
|
+
const sqref = rule.ranges.map(formatWorkbookRange).join(" ");
|
|
84
|
+
container.setAttribute("sqref", sqref);
|
|
85
|
+
const native = document.createElementNS(spreadNs, "cfRule");
|
|
86
|
+
if (rule.predicate.kind === "dataBar") {
|
|
87
|
+
const extension = writeXlsxDataBar(native, rule.predicate, sqref);
|
|
88
|
+
if (extension) extensions.push(extension);
|
|
89
|
+
} else if (rule.predicate.kind === "colorScale") {
|
|
90
|
+
writeXlsxColorScale(native, rule.predicate);
|
|
91
|
+
} else if (rule.predicate.kind === "iconSet") {
|
|
92
|
+
writeXlsxIconSet(native, rule.predicate);
|
|
93
|
+
} else {
|
|
94
|
+
writePredicate(native, rule.predicate, rule.ranges[0]!);
|
|
95
|
+
native.setAttribute("dxfId", String(register(rule.style)));
|
|
96
|
+
}
|
|
97
|
+
native.setAttribute("priority", String(priority));
|
|
98
|
+
if (rule.stopIfTrue) native.setAttribute("stopIfTrue", "1");
|
|
99
|
+
container.appendChild(native);
|
|
100
|
+
worksheet.insertBefore(container, next);
|
|
101
|
+
}
|
|
102
|
+
writeXlsxConditionalExtensions(worksheet, extensions);
|
|
103
|
+
}
|