@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,81 @@
|
|
|
1
|
+
import { appendWorkbookOutlineLevel, maximumWorkbookOutlineDepth, workbookAxisLength, workbookColumns,
|
|
2
|
+
workbookOutlineSpanAt, workbookOutlineTopology, workbookRows, type WorkbookDimensionAxis, type WorkbookOutlineLevel } from "@quirekit/workbook";
|
|
3
|
+
import type { Element } from "@xmldom/xmldom";
|
|
4
|
+
import { child, children, isTrue, readIndex } from "../../opc/xml";
|
|
5
|
+
import { indexRows } from "../positions";
|
|
6
|
+
import type { XlsxNativeOutlineAxis } from "./types";
|
|
7
|
+
|
|
8
|
+
/** @param axis - Worksheet dimension.
|
|
9
|
+
* @returns Attribute storing summary placement. */
|
|
10
|
+
export function xlsxSummaryAttribute(axis: WorkbookDimensionAxis): "summaryBelow" | "summaryRight" {
|
|
11
|
+
return axis === "row" ? "summaryBelow" : "summaryRight";
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
/** @param axis - Worksheet dimension. @param summaryBefore - Whether the summary precedes details.
|
|
15
|
+
* @param group - Group at one level. @returns Native marker position, clamped at worksheet edges. */
|
|
16
|
+
export function xlsxOutlineMarker(axis: WorkbookDimensionAxis, summaryBefore: boolean,
|
|
17
|
+
{ first, last }: Pick<WorkbookOutlineLevel, "first" | "last">): number {
|
|
18
|
+
return summaryBefore ? Math.max(0, first - 1) : Math.min(workbookAxisLength(axis) - 1, last + 1);
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
/** @param node - Native row or column element. @returns Supported detail depth. */
|
|
22
|
+
function nativeDepth(node: Element): number {
|
|
23
|
+
if (!node.hasAttribute("outlineLevel")) return 0;
|
|
24
|
+
const depth = readIndex(node, "outlineLevel");
|
|
25
|
+
if (depth === undefined || depth > maximumWorkbookOutlineDepth) throw new Error("Invalid SpreadsheetML outline level.");
|
|
26
|
+
return depth;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** @param root - Native worksheet. @param axis - Axis to read. @returns Native outline flags, if defined. */
|
|
30
|
+
export function readXlsxNativeOutline(root: Element, axis: WorkbookDimensionAxis): XlsxNativeOutlineAxis | undefined {
|
|
31
|
+
const attribute = xlsxSummaryAttribute(axis);
|
|
32
|
+
const outlinePr = child(child(root, "sheetPr") ?? root, "outlinePr");
|
|
33
|
+
const summaryBefore = ["0", "false"].includes(outlinePr?.getAttribute(attribute) ?? "");
|
|
34
|
+
const levels: WorkbookOutlineLevel[] = [], hidden: WorkbookOutlineLevel[] = [];
|
|
35
|
+
const markers = new Set<number>();
|
|
36
|
+
if (axis === "row") {
|
|
37
|
+
const data = child(root, "sheetData");
|
|
38
|
+
if (data && children(data, "row").some(row => row.hasAttribute("outlineLevel") || isTrue(row.getAttribute("collapsed")))) {
|
|
39
|
+
for (const [row, node] of [...indexRows(data)].sort(([a], [b]) => a - b)) {
|
|
40
|
+
if (!Number.isSafeInteger(row) || row < 0 || row >= workbookRows) throw new Error("Invalid SpreadsheetML outline row.");
|
|
41
|
+
appendWorkbookOutlineLevel(levels, { first: row, last: row, level: nativeDepth(node) });
|
|
42
|
+
if (isTrue(node.getAttribute("hidden"))) appendWorkbookOutlineLevel(hidden, { first: row, last: row, level: 1 });
|
|
43
|
+
if (isTrue(node.getAttribute("collapsed"))) markers.add(row);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
} else {
|
|
47
|
+
const records = children(child(root, "cols") ?? root, "col");
|
|
48
|
+
if (records.some(col => col.hasAttribute("outlineLevel") || isTrue(col.getAttribute("collapsed")))) {
|
|
49
|
+
const attributes = new Uint8Array(workbookColumns);
|
|
50
|
+
for (const node of records) {
|
|
51
|
+
const min = readIndex(node, "min"), max = readIndex(node, "max");
|
|
52
|
+
if (!min || !max || max < min || max > workbookColumns) throw new Error("Invalid SpreadsheetML outline columns.");
|
|
53
|
+
const flags = (isTrue(node.getAttribute("hidden")) ? 8 : 0) | (isTrue(node.getAttribute("collapsed")) ? 16 : 0);
|
|
54
|
+
attributes.fill(nativeDepth(node) | flags, min - 1, max);
|
|
55
|
+
}
|
|
56
|
+
for (const [column, flags] of attributes.entries()) {
|
|
57
|
+
appendWorkbookOutlineLevel(levels, { first: column, last: column, level: flags & 7 });
|
|
58
|
+
if (flags & 8) appendWorkbookOutlineLevel(hidden, { first: column, last: column, level: 1 });
|
|
59
|
+
if (flags & 16) markers.add(column);
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
if (!levels.length && !markers.size && !outlinePr?.hasAttribute(attribute)) return;
|
|
64
|
+
return { summaryBefore, levels, hidden, markers };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
/** @param axis - Worksheet dimension. @param source - Native outline data.
|
|
68
|
+
* @returns Groups consistent with both the marker and their hidden details, in order of depth. */
|
|
69
|
+
export function xlsxNativeFoldCandidates(axis: WorkbookDimensionAxis, source: XlsxNativeOutlineAxis): WorkbookOutlineLevel[] {
|
|
70
|
+
return workbookOutlineTopology(source.levels).filter(group => source.markers.has(xlsxOutlineMarker(axis, source.summaryBefore, group))
|
|
71
|
+
&& (workbookOutlineSpanAt(source.hidden, group.first)?.last ?? -1) >= group.last);
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
/** @param axis - Worksheet dimension. @param source - Native outline flags.
|
|
75
|
+
* @returns One outermost eligible group per marker when the file carries no additional attribution. */
|
|
76
|
+
export function inferXlsxNativeFolds(axis: WorkbookDimensionAxis, source: XlsxNativeOutlineAxis): WorkbookOutlineLevel[] {
|
|
77
|
+
const unmatched = new Set(source.markers);
|
|
78
|
+
const groups = xlsxNativeFoldCandidates(axis, source).filter(group => unmatched.delete(xlsxOutlineMarker(axis, source.summaryBefore, group)));
|
|
79
|
+
if (unmatched.size) throw new Error("SpreadsheetML collapse marker has no corresponding hidden outline.");
|
|
80
|
+
return groups;
|
|
81
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { copyWorkbookOutline, workbookOutlineHidden, workbookOutlineSpanAt, type WorkbookColumnAppearance, type WorkbookDimensionAxis } from "@quirekit/workbook";
|
|
2
|
+
import type { Element } from "@xmldom/xmldom";
|
|
3
|
+
import { readXlsxOutlineMetadata } from "./metadata";
|
|
4
|
+
import { inferXlsxNativeFolds, readXlsxNativeOutline } from "./native";
|
|
5
|
+
import type { XlsxOutlineAttribution } from "./types";
|
|
6
|
+
|
|
7
|
+
/** @param root - Native worksheet. @param restrictions - Features requiring source preservation.
|
|
8
|
+
* @returns Worksheet outline and any independently hidden details. */
|
|
9
|
+
export function readXlsxWorksheetOutline(root: Element, restrictions: Set<string>) {
|
|
10
|
+
const axes = {};
|
|
11
|
+
const manual: { -readonly [Axis in WorkbookDimensionAxis]?: XlsxOutlineAttribution[Axis] } = {};
|
|
12
|
+
for (const axis of ["row", "column"] as const) {
|
|
13
|
+
try {
|
|
14
|
+
const native = readXlsxNativeOutline(root, axis);
|
|
15
|
+
if (!native) continue;
|
|
16
|
+
const attribution = readXlsxOutlineMetadata(root, axis, native);
|
|
17
|
+
const collapsed = attribution?.folds ?? inferXlsxNativeFolds(axis, native);
|
|
18
|
+
Object.assign(axes, { [axis]: { summaryBefore: native.summaryBefore, levels: native.levels, collapsed } });
|
|
19
|
+
manual[axis] = attribution?.manual;
|
|
20
|
+
} catch {
|
|
21
|
+
restrictions.add("行列大纲包含暂未支持的隐藏标志或层级");
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
return { outline: copyWorkbookOutline(axes), manual };
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
/** @param columns - Imported column geometry. @param model - Parsed outline and hidden attribution.
|
|
28
|
+
* @returns Column appearance with hidden flags owned only by manual visibility. */
|
|
29
|
+
export function xlsxOutlineColumnAppearance(columns: readonly WorkbookColumnAppearance[], model: ReturnType<typeof readXlsxWorksheetOutline>):
|
|
30
|
+
readonly WorkbookColumnAppearance[] {
|
|
31
|
+
const folds = workbookOutlineHidden(model.outline?.column);
|
|
32
|
+
if (!folds.length) return columns;
|
|
33
|
+
const manual = model.manual.column ?? [];
|
|
34
|
+
return columns.flatMap(column => {
|
|
35
|
+
if (!column.hidden) return [column];
|
|
36
|
+
const result: WorkbookColumnAppearance[] = [];
|
|
37
|
+
for (let first = column.first; first <= column.last;) {
|
|
38
|
+
const hidden = !workbookOutlineSpanAt(folds, first) || !!workbookOutlineSpanAt(manual, first);
|
|
39
|
+
let last = first;
|
|
40
|
+
while (last < column.last) {
|
|
41
|
+
const following = !workbookOutlineSpanAt(folds, last + 1) || !!workbookOutlineSpanAt(manual, last + 1);
|
|
42
|
+
if (following !== hidden) break;
|
|
43
|
+
last++;
|
|
44
|
+
}
|
|
45
|
+
result.push({ ...column, first, last, hidden });
|
|
46
|
+
first = last + 1;
|
|
47
|
+
}
|
|
48
|
+
return result;
|
|
49
|
+
});
|
|
50
|
+
}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { openWorkbook, parseWorkbookRange, workbookOutlineGroups, type WorkbookSession, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
2
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
5
|
+
|
|
6
|
+
const path = "xl/worksheets/sheet1.xml";
|
|
7
|
+
const seed: WorkbookSnapshot = { version: 1, revision: 0, id: "outline", name: "Outline", sheets: [
|
|
8
|
+
{ id: "report", name: "Report", cells: ["Region", "East", "East", "West", "West"].map((value, row) =>
|
|
9
|
+
({ row, column: 0, input: { kind: "value", value } })) }
|
|
10
|
+
] };
|
|
11
|
+
|
|
12
|
+
/** @param book - Open worksheet. @param name - Command. @param cells - Worksheet addresses.
|
|
13
|
+
* @param params - Command parameters. @returns Committed receipt. */
|
|
14
|
+
function edit(book: WorkbookSession, name: string, cells: string, params: unknown) {
|
|
15
|
+
const sheetId = book.worksheets()[0]!.id;
|
|
16
|
+
return book.commit(book.prepare({ operationId: name + book.revision, baseRevision: book.revision,
|
|
17
|
+
commands: [{ name, target: parseWorkbookRange(sheetId, cells), params }] }).id);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
it("reads WPS-style preceding and Excel-style trailing summaries from native records", async () => {
|
|
21
|
+
const parts = unzipSync(createXlsx(seed));
|
|
22
|
+
parts[path] = strToU8(strFromU8(parts[path]!)
|
|
23
|
+
.replace("<sheetFormatPr", '<sheetPr><outlinePr summaryBelow="0" summaryRight="1"/></sheetPr><sheetFormatPr')
|
|
24
|
+
.replace("<sheetData>", '<cols><col min="2" max="3" width="18" outlineLevel="1" hidden="1"/><col min="4" max="4" collapsed="1"/></cols><sheetData>')
|
|
25
|
+
.replace('<row r="1">', '<row r="1" collapsed="1">')
|
|
26
|
+
.replace('<row r="2">', '<row r="2" outlineLevel="1" hidden="1" ht="25">')
|
|
27
|
+
.replace('<row r="3">', '<row r="3" outlineLevel="1" hidden="1">')
|
|
28
|
+
.replace('<row r="4">', '<row r="4" hidden="1">'));
|
|
29
|
+
const bytes = zipSync(parts);
|
|
30
|
+
const file = openXlsx("Native outline", bytes);
|
|
31
|
+
const sheet = file.snapshot.sheets[0]!;
|
|
32
|
+
expect(file.restrictions).toEqual([]);
|
|
33
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
34
|
+
expect(sheet.dimensions?.outline?.row?.summaryBefore).toBe(true);
|
|
35
|
+
expect(sheet.dimensions?.outline?.column?.summaryBefore).toBe(false);
|
|
36
|
+
expect(workbookOutlineGroups(sheet.dimensions?.outline?.row)).toEqual([{ first: 1, last: 2, level: 1, collapsed: true }]);
|
|
37
|
+
const book = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
38
|
+
try {
|
|
39
|
+
await edit(book, "setWorksheetGroupCollapsed", "A2:A3", { axis: "row", level: 1, collapsed: false });
|
|
40
|
+
await edit(book, "setWorksheetGroupCollapsed", "B1:C1", { axis: "column", level: 1, collapsed: false });
|
|
41
|
+
const reopened = openXlsx("Reopened", file.write(book.snapshot()));
|
|
42
|
+
const layout = reopened.appearance.sheets.get(sheet.id)!;
|
|
43
|
+
expect(layout.rows.get(1)).toMatchObject({ hidden: false, size: 25 * 4 / 3 });
|
|
44
|
+
expect(layout.rows.get(3)?.hidden).toBe(true);
|
|
45
|
+
expect(layout.columns[0]).toMatchObject({ first: 1, last: 2, hidden: false, size: 18 });
|
|
46
|
+
expect(workbookOutlineGroups(reopened.snapshot.sheets[0]?.dimensions?.outline?.column)[0]?.collapsed).toBe(false);
|
|
47
|
+
} finally { await book.close(); }
|
|
48
|
+
});
|
|
49
|
+
|
|
50
|
+
it("reopens distinct fold, filter and manual causes even when nested groups share a native marker", async () => {
|
|
51
|
+
const book = await openWorkbook(seed);
|
|
52
|
+
try {
|
|
53
|
+
await edit(book, "groupWorksheetAxis", "A2:A5", { axis: "row" });
|
|
54
|
+
await edit(book, "groupWorksheetAxis", "A2:A3", { axis: "row" });
|
|
55
|
+
await edit(book, "setWorksheetGroupCollapsed", "A2:A3", { axis: "row", level: 2, collapsed: true });
|
|
56
|
+
await edit(book, "setWorksheetGroupCollapsed", "A2:A5", { axis: "row", level: 1, collapsed: true });
|
|
57
|
+
await edit(book, "setWorksheetDimension", "A2", { axis: "row", hidden: true });
|
|
58
|
+
await edit(book, "setWorksheetFilter", "A1:A5", { columns: [{ column: "A", rule: { kind: "values", values: ["East"], blanks: false } }] });
|
|
59
|
+
const file = openXlsx("Three causes", createXlsx(book.snapshot()));
|
|
60
|
+
expect(file.restrictions).toEqual([]);
|
|
61
|
+
const session = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
62
|
+
try {
|
|
63
|
+
const sheetId = session.worksheets()[0]!.id;
|
|
64
|
+
expect(session.autoFilter(sheetId)?.hiddenRows).toEqual([3, 4]);
|
|
65
|
+
expect(session.readAxisDimension(sheetId, "row", 1).hidden).toBe(true);
|
|
66
|
+
expect(session.readAxisDimension(sheetId, "row", 2).hidden).toBe(false);
|
|
67
|
+
await edit(session, "setWorksheetGroupCollapsed", "A2:A5", { axis: "row", level: 1, collapsed: false });
|
|
68
|
+
expect(workbookOutlineGroups(session.worksheetOutline(sheetId)?.row)).toMatchObject([{ collapsed: false }, { collapsed: true }]);
|
|
69
|
+
await edit(session, "showWorksheetOutlineLevel", "A1", { axis: "row", level: 3 });
|
|
70
|
+
expect([1, 2, 3, 4].map(row => session.isCellHidden({ sheetId, row, column: 0 }))).toEqual([true, false, true, true]);
|
|
71
|
+
} finally { await session.close(); }
|
|
72
|
+
} finally { await book.close(); }
|
|
73
|
+
});
|
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
import type { WorkbookAxisOutline, WorkbookAxisSpan, WorkbookDimensionSpan, WorkbookOutlineLevel } from "@quirekit/workbook";
|
|
2
|
+
|
|
3
|
+
/** Outline information directly expressed in one native axis. */
|
|
4
|
+
export interface XlsxNativeOutlineAxis {
|
|
5
|
+
/** Summary direction from the worksheet's outline properties. */
|
|
6
|
+
readonly summaryBefore: boolean;
|
|
7
|
+
/** Native detail levels. */
|
|
8
|
+
readonly levels: readonly WorkbookOutlineLevel[];
|
|
9
|
+
/** Positions carrying a positive native hidden flag. */
|
|
10
|
+
readonly hidden: readonly WorkbookAxisSpan[];
|
|
11
|
+
/** Summary positions carrying a collapse marker. */
|
|
12
|
+
readonly markers: ReadonlySet<number>;
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** Manual visibility that would otherwise be conflated with a native fold. */
|
|
16
|
+
export interface XlsxOutlineAttribution {
|
|
17
|
+
/** Hand-hidden rows within folds. */
|
|
18
|
+
readonly row?: readonly WorkbookAxisSpan[] | undefined;
|
|
19
|
+
/** Hand-hidden columns within folds. */
|
|
20
|
+
readonly column?: readonly WorkbookAxisSpan[] | undefined;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** Detached supplemental data for one axis of a worksheet. */
|
|
24
|
+
export interface XlsxOutlineAxisMetadata {
|
|
25
|
+
/** Exact groups with an independent collapsed state. */
|
|
26
|
+
readonly folds: WorkbookAxisOutline["collapsed"];
|
|
27
|
+
/** Manual hidden positions within those groups. */
|
|
28
|
+
readonly manual: readonly WorkbookAxisSpan[];
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** A column record segment that may also carry independent outline fields. */
|
|
32
|
+
export interface XlsxColumnLayoutSpan extends WorkbookDimensionSpan {
|
|
33
|
+
/** Zero clears the prior native detail depth. */
|
|
34
|
+
readonly outlineLevel?: number;
|
|
35
|
+
/** Explicit false clears the summary marker. */
|
|
36
|
+
readonly collapsed?: boolean;
|
|
37
|
+
}
|
|
@@ -0,0 +1,110 @@
|
|
|
1
|
+
import { defaultWorkbookDimensions, workbookManualHiddenRows, workbookOutlineHidden, workbookOutlineKey, workbookOutlineSpanAt,
|
|
2
|
+
type WorkbookAxisOutline, type WorkbookDimensionAxis, type WorkbookAxisSpan, type WorkbookSheet, type WorkbookSheetAppearance } from "@quirekit/workbook";
|
|
3
|
+
import type { Element } from "@xmldom/xmldom";
|
|
4
|
+
import { child, children, spreadNs } from "../../opc/xml";
|
|
5
|
+
import { appendOrdered, indexRows } from "../positions";
|
|
6
|
+
import { writeXlsxOutlineColumns, xlsxManuallyHiddenColumns } from "./columns";
|
|
7
|
+
import { writeXlsxOutlineMetadata } from "./metadata";
|
|
8
|
+
import { inferXlsxNativeFolds, readXlsxNativeOutline, xlsxOutlineMarker, xlsxSummaryAttribute } from "./native";
|
|
9
|
+
import type { XlsxOutlineAxisMetadata } from "./types";
|
|
10
|
+
|
|
11
|
+
/** @param root - Worksheet in final coordinates. @param sheet - Authoritative worksheet state. */
|
|
12
|
+
function writeProperties(root: Element, sheet: WorkbookSheet): void {
|
|
13
|
+
const document = root.ownerDocument!;
|
|
14
|
+
const outline = sheet.dimensions?.outline;
|
|
15
|
+
if (outline) {
|
|
16
|
+
let properties = child(root, "sheetPr");
|
|
17
|
+
if (!properties) {
|
|
18
|
+
properties = document.createElementNS(spreadNs, "sheetPr");
|
|
19
|
+
root.insertBefore(properties, root.firstChild);
|
|
20
|
+
}
|
|
21
|
+
let layout = child(properties, "outlinePr");
|
|
22
|
+
if (!layout) {
|
|
23
|
+
layout = document.createElementNS(spreadNs, "outlinePr");
|
|
24
|
+
properties.insertBefore(layout, child(properties, "pageSetUpPr") ?? null);
|
|
25
|
+
}
|
|
26
|
+
for (const axis of ["row", "column"] as const) {
|
|
27
|
+
const settings = outline[axis];
|
|
28
|
+
if (settings) layout.setAttribute(xlsxSummaryAttribute(axis), settings.summaryBefore ? "0" : "1");
|
|
29
|
+
}
|
|
30
|
+
}
|
|
31
|
+
let format = child(root, "sheetFormatPr");
|
|
32
|
+
if (!format && outline) {
|
|
33
|
+
format = document.createElementNS(spreadNs, "sheetFormatPr");
|
|
34
|
+
format.setAttribute("defaultRowHeight", String(defaultWorkbookDimensions.row));
|
|
35
|
+
root.insertBefore(format, children(root).find(node => node.localName === "cols" || node.localName === "sheetData") ?? null);
|
|
36
|
+
}
|
|
37
|
+
for (const [axis, key] of [["row", "outlineLevelRow"], ["column", "outlineLevelCol"]] as const) {
|
|
38
|
+
const level = outline?.[axis]?.levels.reduce((maximum, entry) => Math.max(maximum, entry.level), 0);
|
|
39
|
+
if (level) format?.setAttribute(key, String(level));
|
|
40
|
+
else format?.removeAttribute(key);
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/** @param root - Worksheet with existing row elements. @param outline - Committed row grouping.
|
|
45
|
+
* @param manual - Hand-hidden rows. @param filter - Independent filter mask. */
|
|
46
|
+
function writeRows(root: Element, outline: WorkbookAxisOutline | undefined, manual: ReadonlySet<number>, filter: ReadonlySet<number>): void {
|
|
47
|
+
const data = child(root, "sheetData")!;
|
|
48
|
+
const document = root.ownerDocument!;
|
|
49
|
+
const rows = indexRows(data);
|
|
50
|
+
const changed = new Set<number>();
|
|
51
|
+
for (const [row, node] of rows) if (node.hasAttribute("outlineLevel") || node.hasAttribute("collapsed")) changed.add(row);
|
|
52
|
+
for (const { first, last } of outline?.levels ?? []) for (let row = first; row <= last; row++) changed.add(row);
|
|
53
|
+
const markers = new Set(outline?.collapsed.map(group => xlsxOutlineMarker("row", outline.summaryBefore, group)));
|
|
54
|
+
for (const marker of markers) changed.add(marker);
|
|
55
|
+
const folded = workbookOutlineHidden(outline);
|
|
56
|
+
for (const row of changed) {
|
|
57
|
+
const node = rows.get(row) ?? document.createElementNS(spreadNs, "row");
|
|
58
|
+
node.setAttribute("r", String(row + 1));
|
|
59
|
+
const depth = workbookOutlineSpanAt(outline?.levels ?? [], row)?.level;
|
|
60
|
+
if (depth) node.setAttribute("outlineLevel", String(depth));
|
|
61
|
+
else node.removeAttribute("outlineLevel");
|
|
62
|
+
if (markers.has(row)) node.setAttribute("collapsed", "1");
|
|
63
|
+
else node.removeAttribute("collapsed");
|
|
64
|
+
if (manual.has(row) || filter.has(row) || workbookOutlineSpanAt(folded, row)) node.setAttribute("hidden", "1");
|
|
65
|
+
else node.removeAttribute("hidden");
|
|
66
|
+
rows.set(row, node);
|
|
67
|
+
}
|
|
68
|
+
appendOrdered(data, rows);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @param root - Written native part. @param axis - Grouped axis. @param outline - Desired independent folds.
|
|
72
|
+
* @param isManual - Whether a position is hand-hidden. @returns Supplemental details lost in standard SpreadsheetML. */
|
|
73
|
+
function metadata(root: Element, axis: WorkbookDimensionAxis, outline: WorkbookAxisOutline | undefined,
|
|
74
|
+
isManual: (position: number) => boolean): XlsxOutlineAxisMetadata | undefined {
|
|
75
|
+
if (!outline?.collapsed.length) return;
|
|
76
|
+
const manual: WorkbookAxisSpan[] = [];
|
|
77
|
+
for (const { first, last } of workbookOutlineHidden(outline)) {
|
|
78
|
+
let start = -1;
|
|
79
|
+
for (let position = first; position <= last; position++) {
|
|
80
|
+
if (isManual(position)) {
|
|
81
|
+
if (start < 0) start = position;
|
|
82
|
+
} else if (start >= 0) {
|
|
83
|
+
manual.push({ first: start, last: position - 1 });
|
|
84
|
+
start = -1;
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
if (start >= 0) manual.push({ first: start, last });
|
|
88
|
+
}
|
|
89
|
+
const inferred = inferXlsxNativeFolds(axis, readXlsxNativeOutline(root, axis)!);
|
|
90
|
+
const differs = inferred.length !== outline.collapsed.length || inferred.some((group, index) =>
|
|
91
|
+
workbookOutlineKey(group) !== workbookOutlineKey(outline.collapsed[index]!));
|
|
92
|
+
return manual.length || differs ? { folds: outline.collapsed, manual } : undefined;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
/** @param root - Worksheet after its positional edits. @param sheet - Outline and physical layout to persist.
|
|
96
|
+
* @param appearance - Retained appearance in current coordinates, with only manual visibility.
|
|
97
|
+
* @param filteredRows - Combined row mask from the worksheet and table filters. */
|
|
98
|
+
export function writeXlsxWorksheetOutline(root: Element, sheet: WorkbookSheet, appearance: WorkbookSheetAppearance | undefined,
|
|
99
|
+
filteredRows: readonly number[]): void {
|
|
100
|
+
const outline = sheet.dimensions?.outline;
|
|
101
|
+
const manualRows = workbookManualHiddenRows(appearance, sheet.dimensions?.rows ?? []);
|
|
102
|
+
const manualColumns = xlsxManuallyHiddenColumns(appearance, sheet.dimensions);
|
|
103
|
+
writeProperties(root, sheet);
|
|
104
|
+
writeRows(root, outline?.row, manualRows, new Set(filteredRows));
|
|
105
|
+
writeXlsxOutlineColumns(root, outline?.column, manualColumns);
|
|
106
|
+
writeXlsxOutlineMetadata(root, {
|
|
107
|
+
row: metadata(root, "row", outline?.row, row => manualRows.has(row)),
|
|
108
|
+
column: metadata(root, "column", outline?.column, column => !!manualColumns[column])
|
|
109
|
+
});
|
|
110
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
import { strToU8 } from "fflate";
|
|
2
|
+
import { expect, it, vi } from "vitest";
|
|
3
|
+
import { child, children, parsePart, spreadNs } from "../opc/xml";
|
|
4
|
+
import { appendOrdered, indexRows } from "./positions";
|
|
5
|
+
|
|
6
|
+
it("inserts only the missing row and keeps ordered source rows and the extension in place", () => {
|
|
7
|
+
const document = parsePart(strToU8(`<sheetData xmlns="${spreadNs}">
|
|
8
|
+
<row r="1" ht="24" customHeight="1"/>
|
|
9
|
+
<row r="3" hidden="1"/>
|
|
10
|
+
<extLst/>
|
|
11
|
+
</sheetData>`), "sheet1.xml");
|
|
12
|
+
const data = document.documentElement!;
|
|
13
|
+
const rows = indexRows(data);
|
|
14
|
+
const original = [...rows.values()];
|
|
15
|
+
const extension = child(data, "extLst");
|
|
16
|
+
const inserted = document.createElementNS(spreadNs, "row");
|
|
17
|
+
inserted.setAttribute("r", "2");
|
|
18
|
+
rows.set(1, inserted);
|
|
19
|
+
const insert = vi.spyOn(data, "insertBefore");
|
|
20
|
+
|
|
21
|
+
appendOrdered(data, rows);
|
|
22
|
+
|
|
23
|
+
expect(insert).toHaveBeenCalledTimes(1);
|
|
24
|
+
expect(children(data)).toEqual([original[0], inserted, original[1], extension]);
|
|
25
|
+
expect(original[0]?.getAttribute("ht")).toBe("24");
|
|
26
|
+
expect(original[1]?.getAttribute("hidden")).toBe("1");
|
|
27
|
+
insert.mockRestore();
|
|
28
|
+
});
|
|
29
|
+
|
|
30
|
+
it("appends new rows in order when creating or extending a sheet", () => {
|
|
31
|
+
const document = parsePart(strToU8(`<sheetData xmlns="${spreadNs}"><row r="1"/></sheetData>`), "sheet1.xml");
|
|
32
|
+
const data = document.documentElement!;
|
|
33
|
+
const rows = indexRows(data);
|
|
34
|
+
for (const row of [2, 1]) {
|
|
35
|
+
const element = document.createElementNS(spreadNs, "row");
|
|
36
|
+
element.setAttribute("r", String(row + 1));
|
|
37
|
+
rows.set(row, element);
|
|
38
|
+
}
|
|
39
|
+
const insert = vi.spyOn(data, "insertBefore");
|
|
40
|
+
|
|
41
|
+
appendOrdered(data, rows);
|
|
42
|
+
|
|
43
|
+
expect(insert.mock.calls.map(([node, reference]) => [node, reference])).toEqual([[rows.get(1), null], [rows.get(2), null]]);
|
|
44
|
+
expect(children(data).map(row => row.getAttribute("r"))).toEqual(["1", "2", "3"]);
|
|
45
|
+
insert.mockRestore();
|
|
46
|
+
});
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
import type { Element, Node } from "@xmldom/xmldom";
|
|
2
|
+
import { parseWorkbookRange } from "@quirekit/workbook";
|
|
3
|
+
import { child, children } from "../opc/xml";
|
|
4
|
+
|
|
5
|
+
/** @param data - Worksheet sheetData. @returns Row elements by worksheet position. */
|
|
6
|
+
export function indexRows(data: Element): Map<number, Element> {
|
|
7
|
+
let next = 0;
|
|
8
|
+
return new Map(children(data, "row").map(node => {
|
|
9
|
+
const row = node.hasAttribute("r") ? Number(node.getAttribute("r")) - 1 : next;
|
|
10
|
+
next = row + 1;
|
|
11
|
+
return [row, node];
|
|
12
|
+
}));
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** @param row - Worksheet row. @returns Cell elements by absolute column. */
|
|
16
|
+
export function indexCells(row: Element): Map<number, Element> {
|
|
17
|
+
let next = 0;
|
|
18
|
+
return new Map(children(row, "c").map(node => {
|
|
19
|
+
const ref = node.getAttribute("r");
|
|
20
|
+
const column = ref ? parseWorkbookRange("", ref).startColumn : next;
|
|
21
|
+
next = column + 1;
|
|
22
|
+
return [column, node];
|
|
23
|
+
}));
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param parent - Element owning sorted data children. @param nodes - Elements keyed by position. */
|
|
27
|
+
export function appendOrdered(parent: Element, nodes: ReadonlyMap<number, Element>): void {
|
|
28
|
+
const ordered = [...nodes].sort(([left], [right]) => left - right);
|
|
29
|
+
const elements = new Set<Node>(nodes.values());
|
|
30
|
+
const extension = child(parent, "extLst");
|
|
31
|
+
let next: Node | null = extension ?? null;
|
|
32
|
+
// The ordered elements occupy the suffix before extLst, after the other source children.
|
|
33
|
+
for (let sibling = extension ? extension.previousSibling : parent.lastChild;
|
|
34
|
+
sibling && (elements.has(sibling) || isIndentation(sibling)); sibling = sibling.previousSibling) {
|
|
35
|
+
next = sibling;
|
|
36
|
+
}
|
|
37
|
+
// Reattaching a node rebuilds the XML child list. Keep correctly placed nodes attached and append new trailing nodes in order.
|
|
38
|
+
for (const [, node] of ordered) {
|
|
39
|
+
while (next && isIndentation(next)) next = next.nextSibling;
|
|
40
|
+
if (node !== next) parent.insertBefore(node, next);
|
|
41
|
+
next = node.nextSibling;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/** @param node - Worksheet child. @returns Whether it contains only XML indentation. */
|
|
46
|
+
function isIndentation(node: Node): boolean {
|
|
47
|
+
return node.nodeType === 3 && /^[\t\n\r ]*$/u.test(node.nodeValue ?? "");
|
|
48
|
+
}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { maximumWorkbookPrintBreaks, workbookColumns, workbookRows } from "@quirekit/workbook";
|
|
3
|
+
import { child, children, isTrue, readIndex, spreadNs } from "../../opc/xml";
|
|
4
|
+
import { afterXlsxPrintElements, ensureXlsxPrintElement } from "./elements";
|
|
5
|
+
|
|
6
|
+
/** @param sheet - Source worksheet. @param axis - Direction of the broken grid axis.
|
|
7
|
+
* @returns Manual full-axis boundaries supported by the workbook. */
|
|
8
|
+
export function readXlsxPrintBreaks(sheet: Element, axis: "row" | "column"): number[] {
|
|
9
|
+
const name = axis === "row" ? "rowBreaks" : "colBreaks";
|
|
10
|
+
const records = children(sheet, name);
|
|
11
|
+
if (!records.length) return [];
|
|
12
|
+
const [node] = records;
|
|
13
|
+
const error = "工作表含局部或数据透视表原生分页符。";
|
|
14
|
+
if (records.length !== 1 || node!.namespaceURI !== spreadNs ||
|
|
15
|
+
Array.from(node!.attributes).some(attr => attr.namespaceURI || !["count", "manualBreakCount"].includes(attr.name))) {
|
|
16
|
+
throw new Error(error);
|
|
17
|
+
}
|
|
18
|
+
const orthogonalEnd = (axis === "row" ? workbookColumns : workbookRows) - 1;
|
|
19
|
+
const length = axis === "row" ? workbookRows : workbookColumns;
|
|
20
|
+
const breaks: number[] = [];
|
|
21
|
+
for (const item of children(node!)) {
|
|
22
|
+
const manual = item.getAttribute("man"), pivot = item.getAttribute("pt");
|
|
23
|
+
if (item.localName !== "brk" || item.namespaceURI !== spreadNs || children(item).length || isTrue(pivot)
|
|
24
|
+
|| Array.from(item.attributes).some(attr => attr.namespaceURI || !["id", "min", "max", "man", "pt"].includes(attr.name))
|
|
25
|
+
|| [manual, pivot].some(value => value !== null && !["0", "1", "false", "true"].includes(value))) throw new Error(error);
|
|
26
|
+
if (!isTrue(manual)) continue;
|
|
27
|
+
const position = readIndex(item, "id");
|
|
28
|
+
const min = item.hasAttribute("min") ? readIndex(item, "min") : 0;
|
|
29
|
+
if (!position || position >= length || min !== 0 || readIndex(item, "max") !== orthogonalEnd) throw new Error(error);
|
|
30
|
+
breaks.push(position);
|
|
31
|
+
if (breaks.length > maximumWorkbookPrintBreaks) throw new Error("工作表含超过 1026 个手工分页符。");
|
|
32
|
+
}
|
|
33
|
+
return breaks;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
/** @param sheet - Mutable worksheet. @param axis - Break axis. @param breaks - Authored boundary positions. */
|
|
37
|
+
export function writeXlsxPrintBreaks(sheet: Element, axis: "row" | "column", breaks?: readonly number[]): void {
|
|
38
|
+
const row = axis === "row";
|
|
39
|
+
const name = row ? "rowBreaks" : "colBreaks";
|
|
40
|
+
const prior = child(sheet, name);
|
|
41
|
+
if (prior) sheet.removeChild(prior);
|
|
42
|
+
if (!breaks?.length) return;
|
|
43
|
+
const node = ensureXlsxPrintElement(sheet, name, row ? ["colBreaks", ...afterXlsxPrintElements] : afterXlsxPrintElements);
|
|
44
|
+
node.setAttribute("count", String(breaks.length));
|
|
45
|
+
node.setAttribute("manualBreakCount", String(breaks.length));
|
|
46
|
+
for (const position of breaks) {
|
|
47
|
+
const item = sheet.ownerDocument!.createElementNS(spreadNs, "brk");
|
|
48
|
+
item.setAttribute("id", String(position));
|
|
49
|
+
item.setAttribute("min", "0");
|
|
50
|
+
item.setAttribute("max", String((row ? workbookColumns : workbookRows) - 1));
|
|
51
|
+
item.setAttribute("man", "1");
|
|
52
|
+
node.appendChild(item);
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
/** @param sheet - Native sheet after a dimension or coordinate edit. */
|
|
57
|
+
export function discardXlsxAutomaticPrintBreaks(sheet: Element): void {
|
|
58
|
+
for (const name of ["rowBreaks", "colBreaks"]) {
|
|
59
|
+
const node = child(sheet, name);
|
|
60
|
+
if (!node) continue;
|
|
61
|
+
const records = children(node, "brk");
|
|
62
|
+
const automatic = records.filter(record => !isTrue(record.getAttribute("man")));
|
|
63
|
+
if (!automatic.length) continue;
|
|
64
|
+
if (automatic.length === records.length) sheet.removeChild(node);
|
|
65
|
+
else {
|
|
66
|
+
for (const record of automatic) node.removeChild(record);
|
|
67
|
+
const count = String(records.length - automatic.length);
|
|
68
|
+
node.setAttribute("count", count);
|
|
69
|
+
node.setAttribute("manualBreakCount", count);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { child, children, spreadNs } from "../../opc/xml";
|
|
3
|
+
|
|
4
|
+
/** Worksheet elements following column breaks in SpreadsheetML order. */
|
|
5
|
+
export const afterXlsxPrintElements = ["customProperties", "cellWatches", "ignoredErrors", "smartTags", "drawing",
|
|
6
|
+
"legacyDrawing", "legacyDrawingHF", "picture", "oleObjects", "controls", "webPublishItems", "tableParts", "extLst"];
|
|
7
|
+
|
|
8
|
+
/** @param owner - Native worksheet or properties. @param name - Child element. @param subsequent - Following children in schema order.
|
|
9
|
+
* @returns Existing or correctly placed SpreadsheetML element. */
|
|
10
|
+
export function ensureXlsxPrintElement(owner: Element, name: string, subsequent: readonly string[] = []): Element {
|
|
11
|
+
const current = child(owner, name);
|
|
12
|
+
if (current) return current;
|
|
13
|
+
const node = owner.ownerDocument!.createElementNS(spreadNs, name);
|
|
14
|
+
owner.insertBefore(node, children(owner).find(candidate => subsequent.includes(candidate.localName ?? "")) ?? null);
|
|
15
|
+
return node;
|
|
16
|
+
}
|