@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,136 @@
|
|
|
1
|
+
import { openWorkbook, parseWorkbookRange, 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
|
+
import { xlsxFilterUidNs, xlsxTableColumnUidNs } from "../../../opc/revision";
|
|
6
|
+
import { xlsxNamedViewContentType, xlsxNamedViewNs, xlsxNamedViewRelationship } from "./xml";
|
|
7
|
+
|
|
8
|
+
const id = "00000000-0000-4000-8000-000000000abc";
|
|
9
|
+
const source: WorkbookSnapshot = { version: 1, revision: 0, id: "stock", name: "Stock", sheets: [{
|
|
10
|
+
id: "sheet", name: "Stock", cells: [
|
|
11
|
+
{ row: 0, column: 0, input: { kind: "value", value: "Status" } },
|
|
12
|
+
{ row: 1, column: 0, input: { kind: "value", value: "Open" } },
|
|
13
|
+
{ row: 2, column: 0, input: { kind: "value", value: "Paid" } },
|
|
14
|
+
{ row: 0, column: 2, input: { kind: "value", value: "Amount" } },
|
|
15
|
+
{ row: 1, column: 2, input: { kind: "value", value: 25 } },
|
|
16
|
+
{ row: 2, column: 2, input: { kind: "value", value: 16 } }
|
|
17
|
+
], autoFilter: { range: parseWorkbookRange("sheet", "A1:A3"), columns: [], hiddenRows: [] }
|
|
18
|
+
}], structuredTables: [{ id: "money", name: "Amounts", range: parseWorkbookRange("sheet", "C1:C3"), header: true,
|
|
19
|
+
totals: false, columns: ["Amount"], showFilter: true }] };
|
|
20
|
+
const sheetPath = "xl/worksheets/sheet1.xml";
|
|
21
|
+
const relPath = "xl/worksheets/_rels/sheet1.xml.rels";
|
|
22
|
+
const namedPath = "xl/namedSheetViews/namedSheetView1.xml";
|
|
23
|
+
const independentView = { id, name: "Open & billed", filters: [
|
|
24
|
+
{ range: { startRow: 0, endRow: 2, startColumn: 0, endColumn: 0 },
|
|
25
|
+
columns: [{ column: 0, rule: { kind: "values" as const, values: ["Open"], blanks: false } }],
|
|
26
|
+
sort: { keys: [{ column: "A", direction: "desc" as const, customList: ["Open", "Paid"] }], caseSensitive: true, sortMethod: "stroke" as const } },
|
|
27
|
+
{ tableId: "money", range: { startRow: 0, endRow: 2, startColumn: 2, endColumn: 2 },
|
|
28
|
+
columns: [{ column: 2, rule: { kind: "color" as const, source: "fill" as const, color: "#FFAA33" } }],
|
|
29
|
+
sort: { keys: [
|
|
30
|
+
{ column: "C", source: "fill" as const, color: null, position: "first" as const },
|
|
31
|
+
{ column: "C", icon: { set: "3Stars" as const, index: 1 }, position: "last" as const },
|
|
32
|
+
{ column: "C", icon: null, position: "first" as const },
|
|
33
|
+
{ column: "C", direction: "asc" as const }
|
|
34
|
+
] } }
|
|
35
|
+
] };
|
|
36
|
+
|
|
37
|
+
it("writes an implicit view part for ordinary and table scopes without changing shared filter rows", async () => {
|
|
38
|
+
const workbook = await openWorkbook(source);
|
|
39
|
+
try {
|
|
40
|
+
const seed = workbook.snapshot();
|
|
41
|
+
const view = { ...workbook.worksheetView("sheet"), namedViews: [independentView] };
|
|
42
|
+
const xlsx = createXlsx({ ...seed, sheets: [{ ...seed.sheets[0]!, view }] });
|
|
43
|
+
const parts = unzipSync(xlsx);
|
|
44
|
+
const named = strFromU8(parts[namedPath]!);
|
|
45
|
+
expect(named).toContain(`xmlns:xnsv="${xlsxNamedViewNs}"`);
|
|
46
|
+
expect(named).toContain('tableId="0"');
|
|
47
|
+
expect(named).toContain('tableId="1"');
|
|
48
|
+
expect(named).toContain('ref="C1:C3"');
|
|
49
|
+
expect(named).toContain("<xnsv:dxf>");
|
|
50
|
+
expect(named).toContain('rgb="FFFFAA33"');
|
|
51
|
+
expect(named).toContain('<xnsv:sortRules caseSensitive="1" sortMethod="stroke">');
|
|
52
|
+
expect(named).toMatch(/<xnsv:sortCondition[^>]*ref="A2:A3"[^>]*customList="Open,Paid"/u);
|
|
53
|
+
expect(named).toContain('iconSet="3Stars"');
|
|
54
|
+
expect(strFromU8(parts[sheetPath]!)).not.toContain('hidden="1"');
|
|
55
|
+
expect(strFromU8(parts[relPath]!)).toContain(xlsxNamedViewRelationship);
|
|
56
|
+
expect(strFromU8(parts["[Content_Types].xml"]!)).toContain(xlsxNamedViewContentType);
|
|
57
|
+
|
|
58
|
+
const file = openXlsx("Native views", xlsx);
|
|
59
|
+
const sheet = file.snapshot.sheets[0]!;
|
|
60
|
+
expect(file.restrictions).toEqual([]);
|
|
61
|
+
expect(sheet.view?.namedViews).toEqual([{ ...independentView, filters: [
|
|
62
|
+
independentView.filters[0], { ...independentView.filters[1], tableId: file.snapshot.structuredTables![0]!.id }
|
|
63
|
+
] }]);
|
|
64
|
+
const reopened = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
65
|
+
try {
|
|
66
|
+
const candidate = reopened.prepare({ baseRevision: reopened.revision, operationId: "delete-view", commands: [
|
|
67
|
+
{ name: "setWorksheetNamedView", target: parseWorkbookRange(sheet.id, "A1"), params: { action: "delete", id } }
|
|
68
|
+
] });
|
|
69
|
+
await reopened.commit(candidate.id);
|
|
70
|
+
const removed = unzipSync(file.write(reopened.snapshot()));
|
|
71
|
+
expect(removed[namedPath]).toBeUndefined();
|
|
72
|
+
expect(strFromU8(removed[relPath]!)).not.toContain(xlsxNamedViewRelationship);
|
|
73
|
+
expect(removed[sheetPath]).toEqual(parts[sheetPath]);
|
|
74
|
+
expect(openXlsx("Removed", zipSync(removed)).restrictions).toEqual([]);
|
|
75
|
+
} finally { await reopened.close(); }
|
|
76
|
+
} finally { await workbook.close(); }
|
|
77
|
+
});
|
|
78
|
+
|
|
79
|
+
it("preserves a native view with rich sort rules as an opaque part under the existing file restrictions", () => {
|
|
80
|
+
const parts = unzipSync(createXlsx({ ...source, sheets: [{ ...source.sheets[0]!, view: {
|
|
81
|
+
freeze: { rows: 0, columns: 0 }, showGridlines: true, showHeadings: true, zoomPercent: 100, namedViews: [independentView]
|
|
82
|
+
} }] }));
|
|
83
|
+
parts[namedPath] = strToU8(strFromU8(parts[namedPath]!).replace("<xnsv:sortRule colId=\"0\">",
|
|
84
|
+
"<xnsv:sortRule colId=\"0\"><xnsv:richSortCondition/>"));
|
|
85
|
+
const bytes = zipSync(parts);
|
|
86
|
+
const file = openXlsx("Preserved", bytes);
|
|
87
|
+
expect(file.restrictions).toContain("命名工作表视图包含暂未支持的规则");
|
|
88
|
+
expect(file.snapshot.sheets[0]?.view?.namedViews).toBeUndefined();
|
|
89
|
+
expect(file.write(file.snapshot)).toEqual(bytes);
|
|
90
|
+
});
|
|
91
|
+
|
|
92
|
+
it("reconciles Excel filter and column UIDs ahead of the fallback numeric IDs", async () => {
|
|
93
|
+
const parts = unzipSync(createXlsx(source));
|
|
94
|
+
const filterId = "{14411C01-C1B3-46DA-8B2F-31C8FC0BDC54}";
|
|
95
|
+
const columnId = "{49FB4CAB-3DD8-4E18-90EC-78533BE777B5}";
|
|
96
|
+
const tablePath = "xl/tables/table1.xml";
|
|
97
|
+
const sheetRels = `<Relationship Id="rId22" Type="${xlsxNamedViewRelationship}" Target="../namedSheetViews/namedSheetView1.xml"/>`;
|
|
98
|
+
parts[tablePath] = strToU8(strFromU8(parts[tablePath]!).replace("<table ", `<table xmlns:xr="${xlsxFilterUidNs}" xmlns:xr3="${xlsxTableColumnUidNs}" xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" mc:Ignorable="xr xr3" `)
|
|
99
|
+
.replace("<autoFilter ", `<autoFilter xr:uid="${filterId}" `).replace("<tableColumn ", `<tableColumn xr3:uid="${columnId}" `));
|
|
100
|
+
parts[relPath] = strToU8(strFromU8(parts[relPath]!).replace("</Relationships>", sheetRels + "</Relationships>"));
|
|
101
|
+
parts["[Content_Types].xml"] = strToU8(strFromU8(parts["[Content_Types].xml"]!).replace("</Types>",
|
|
102
|
+
`<Override PartName="/${namedPath}" ContentType="${xlsxNamedViewContentType}"/></Types>`));
|
|
103
|
+
parts[namedPath] = strToU8(`<namedSheetViews xmlns="${xlsxNamedViewNs}" xmlns:x="http://schemas.openxmlformats.org/spreadsheetml/2006/main">
|
|
104
|
+
<namedSheetView name="Billed" id="{${id.toUpperCase()}}">
|
|
105
|
+
<nsvFilter filterId="${filterId}" tableId="999" ref="A9:B63">
|
|
106
|
+
<columnFilter id="${columnId}" colId="9">
|
|
107
|
+
<filter colId="9"><x:customFilters><x:customFilter operator="greaterThan" val="20"/></x:customFilters></filter>
|
|
108
|
+
</columnFilter>
|
|
109
|
+
<sortRules>
|
|
110
|
+
<sortRule id="${columnId}" colId="9"><sortCondition ref="J2:J20" descending="1"/></sortRule>
|
|
111
|
+
</sortRules>
|
|
112
|
+
</nsvFilter>
|
|
113
|
+
</namedSheetView>
|
|
114
|
+
</namedSheetViews>`);
|
|
115
|
+
const file = openXlsx("Native revision identifiers", zipSync(parts));
|
|
116
|
+
expect(file.restrictions).toEqual([]);
|
|
117
|
+
const table = file.snapshot.structuredTables![0]!;
|
|
118
|
+
const workbook = await openWorkbook(file.snapshot, { appearance: file.appearance });
|
|
119
|
+
try {
|
|
120
|
+
expect(workbook.worksheetView(table.range.sheetId).namedViews).toMatchObject([{ name: "Billed", filters: [{
|
|
121
|
+
tableId: table.id, range: { startRow: 0, endRow: 2, startColumn: 2, endColumn: 2 },
|
|
122
|
+
columns: [{ column: 2, rule: { kind: "custom", conditions: [{ operator: "gt", value: "20" }] } }],
|
|
123
|
+
sort: { keys: [{ column: "C", direction: "desc" }] }
|
|
124
|
+
}] }]);
|
|
125
|
+
const candidate = workbook.prepare({ operationId: "update-table-filter", baseRevision: workbook.revision,
|
|
126
|
+
commands: [{ name: "setStructuredTableFilter", target: table.range, params: { id: table.id, columns: [
|
|
127
|
+
{ column: "C", rule: { kind: "values", values: ["25"], blanks: false } }
|
|
128
|
+
] } }] });
|
|
129
|
+
await workbook.commit(candidate.id);
|
|
130
|
+
const rewritten = file.write(workbook.snapshot());
|
|
131
|
+
const after = unzipSync(rewritten);
|
|
132
|
+
expect(after[namedPath]).toEqual(parts[namedPath]);
|
|
133
|
+
expect(strFromU8(after[tablePath]!)).toContain(`xr:uid="${filterId}"`);
|
|
134
|
+
expect(openXlsx("Updated owner", rewritten).snapshot.sheets[0]?.view?.namedViews).toEqual(workbook.worksheetView(table.range.sheetId).namedViews);
|
|
135
|
+
} finally { await workbook.close(); }
|
|
136
|
+
});
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookColumn, maximumWorkbookSortKeys, parseWorkbookColumn, workbookFilterSortBody,
|
|
3
|
+
type WorkbookNamedViewSort, type WorkbookRange } from "@quirekit/workbook";
|
|
4
|
+
import { hasKnownAttributes, hasKnownChildren } from "../../../opc/shape";
|
|
5
|
+
import { child, children, readIndex } from "../../../opc/xml";
|
|
6
|
+
import { readXlsxDifferential, writeXlsxDifferential } from "../../../styles/differential";
|
|
7
|
+
import type { XlsxFilterReadContext } from "../../filters/types";
|
|
8
|
+
import { readXlsxSortCondition, readXlsxSortSettings } from "../../sort/read";
|
|
9
|
+
import { writeXlsxSortCondition } from "../../sort/write";
|
|
10
|
+
import type { XlsxNamedViewFilterOwner } from "./types";
|
|
11
|
+
import { appendXlsxNamedViewElement, readXlsxNamedViewColumn, unsupportedXlsxNamedView, xlsxNamedViewNs } from "./xml";
|
|
12
|
+
|
|
13
|
+
/** @param node - Native ordered sort rules. @param owner - Reconciled AutoFilter including the heading.
|
|
14
|
+
* @param context - Source differential colors. @returns The independent row order, when rules are present. */
|
|
15
|
+
export function readXlsxNamedViewSort(node: Element, owner: XlsxNamedViewFilterOwner, context: XlsxFilterReadContext): WorkbookNamedViewSort | undefined {
|
|
16
|
+
const settings = readXlsxSortSettings(node);
|
|
17
|
+
const records = children(node);
|
|
18
|
+
if (!settings || !hasKnownAttributes(node, ["caseSensitive", "sortMethod"]) || records.length > maximumWorkbookSortKeys
|
|
19
|
+
|| records.some(record => record.namespaceURI !== xlsxNamedViewNs || record.localName !== "sortRule")) throw unsupportedXlsxNamedView();
|
|
20
|
+
const keys = records.flatMap(record => {
|
|
21
|
+
const entries = children(record);
|
|
22
|
+
const condition = child(record, "sortCondition");
|
|
23
|
+
const dxf = child(record, "dxf");
|
|
24
|
+
if (!hasKnownAttributes(record, ["colId", "id"]) || !hasKnownChildren(record, ["dxf", "sortCondition"], xlsxNamedViewNs)
|
|
25
|
+
|| entries.length !== Number(Boolean(condition)) + Number(Boolean(dxf))) throw unsupportedXlsxNamedView();
|
|
26
|
+
const column = owner.range.startColumn + readXlsxNamedViewColumn(record, owner);
|
|
27
|
+
if (!condition && !dxf) return [];
|
|
28
|
+
if (!condition || Boolean(dxf) !== condition.hasAttribute("dxfId")) throw unsupportedXlsxNamedView();
|
|
29
|
+
const style = dxf && readXlsxDifferential(dxf, context.resolveColor, xlsxNamedViewNs);
|
|
30
|
+
if (dxf && (!style || readIndex(condition, "dxfId") === undefined)) throw unsupportedXlsxNamedView();
|
|
31
|
+
const native = condition.cloneNode(true) as Element;
|
|
32
|
+
if (dxf) native.setAttribute("dxfId", "0");
|
|
33
|
+
// Reconciliation resolves the column before reading its key. A stored lane can precede a table resize or move.
|
|
34
|
+
const key = readXlsxSortCondition(native, owner.range, false, style ? [style] : [], undefined, column);
|
|
35
|
+
if (!key) throw unsupportedXlsxNamedView();
|
|
36
|
+
return [{ column: formatWorkbookColumn(key.index), ...key.order }];
|
|
37
|
+
});
|
|
38
|
+
if (keys.length) return { ...settings, keys };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** @param owner - Named filter scope. @param range - Its current filter area. @param sort - Sort criteria to write. */
|
|
42
|
+
export function writeXlsxNamedViewSort(owner: Element, range: WorkbookRange, sort: WorkbookNamedViewSort): void {
|
|
43
|
+
const rules = appendXlsxNamedViewElement(owner, "sortRules");
|
|
44
|
+
if (sort.caseSensitive) rules.setAttribute("caseSensitive", "1");
|
|
45
|
+
if (sort.sortMethod) rules.setAttribute("sortMethod", sort.sortMethod);
|
|
46
|
+
for (const key of sort.keys) {
|
|
47
|
+
const rule = appendXlsxNamedViewElement(rules, "sortRule");
|
|
48
|
+
rule.setAttribute("colId", String(parseWorkbookColumn(key.column) - range.startColumn));
|
|
49
|
+
const condition = appendXlsxNamedViewElement(rule, "sortCondition");
|
|
50
|
+
writeXlsxSortCondition(condition, workbookFilterSortBody(range) ?? range, key, style => {
|
|
51
|
+
const document = rule.ownerDocument!;
|
|
52
|
+
const dxf = writeXlsxDifferential(document, style, document.createElementNS(xlsxNamedViewNs, "xnsv:dxf"));
|
|
53
|
+
rule.insertBefore(dxf, condition);
|
|
54
|
+
return 0;
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { WorkbookAutoFilter } from "@quirekit/workbook";
|
|
2
|
+
|
|
3
|
+
/** One current filter's geometry and optional reconciliation identifiers from the package. */
|
|
4
|
+
export interface XlsxNamedViewFilterOwner {
|
|
5
|
+
/** Excel's zero for a worksheet filter or native table serial. */
|
|
6
|
+
readonly serial: number;
|
|
7
|
+
/** Workbook identity of the table, when this is a table filter. */
|
|
8
|
+
readonly tableId?: string | undefined;
|
|
9
|
+
/** Optional Excel revision UID of the whole filter. */
|
|
10
|
+
readonly uid?: string | undefined;
|
|
11
|
+
/** Column revision UIDs in physical table order. */
|
|
12
|
+
readonly columnUids?: readonly (string | undefined)[] | undefined;
|
|
13
|
+
/** Filter area in current coordinates. */
|
|
14
|
+
readonly range: WorkbookAutoFilter["range"];
|
|
15
|
+
}
|
|
@@ -0,0 +1,107 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { sameWorkbookNamedViews, type WorkbookNamedSheetView, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
3
|
+
import { strToU8 } from "fflate";
|
|
4
|
+
import { v4 as uuidv4 } from "uuid";
|
|
5
|
+
import { editPartRelationships } from "../../../opc/relationships";
|
|
6
|
+
import { children, contentTypeNs, parsePart, rootOf, writePart } from "../../../opc/xml";
|
|
7
|
+
import type { XlsxPackage } from "../../../package/types";
|
|
8
|
+
import { writeXlsxDifferential } from "../../../styles/differential";
|
|
9
|
+
import { makeXlsxAutoFilter } from "../../filters/write";
|
|
10
|
+
import { writeXlsxNamedViewSort } from "./sort";
|
|
11
|
+
import { appendXlsxNamedViewElement as add, xlsxNamedViewContentType, xlsxNamedViewNs, xlsxNamedViewRelationship, xlsxViewGuid } from "./xml";
|
|
12
|
+
|
|
13
|
+
/** @param sheetId - Current worksheet. @param views - Workbook definitions. @param tableSerials - Native table IDs after writing tables.
|
|
14
|
+
* @param path - Part location. @returns Native XML with no session state. */
|
|
15
|
+
function writeDefinitions(sheetId: string, views: readonly WorkbookNamedSheetView[], tableSerials: ReadonlyMap<string, number>, path: string): Uint8Array {
|
|
16
|
+
const document = parsePart(strToU8(`<xnsv:namedSheetViews xmlns:xnsv="${xlsxNamedViewNs}"/>`), path);
|
|
17
|
+
const root = document.documentElement!;
|
|
18
|
+
const owners = new Map<string | undefined, string>();
|
|
19
|
+
for (const { id, name, filters } of views) {
|
|
20
|
+
const view = add(root, "namedSheetView");
|
|
21
|
+
view.setAttribute("id", xlsxViewGuid(id));
|
|
22
|
+
view.setAttribute("name", name);
|
|
23
|
+
for (const filter of filters) {
|
|
24
|
+
const tableId = filter.tableId === undefined ? 0 : tableSerials.get(filter.tableId);
|
|
25
|
+
if (tableId === undefined) throw new Error("命名视图的原生表不存在。");
|
|
26
|
+
const ownerId = owners.get(filter.tableId) ?? xlsxViewGuid(uuidv4());
|
|
27
|
+
owners.set(filter.tableId, ownerId);
|
|
28
|
+
const scope = add(view, "nsvFilter");
|
|
29
|
+
const styles: Element[] = [];
|
|
30
|
+
const native = makeXlsxAutoFilter(document, { range: { ...filter.range, sheetId }, columns: filter.columns, hiddenRows: [] }, style => {
|
|
31
|
+
styles.push(writeXlsxDifferential(document, style, document.createElementNS(xlsxNamedViewNs, "xnsv:dxf")));
|
|
32
|
+
return 0;
|
|
33
|
+
});
|
|
34
|
+
scope.setAttribute("tableId", String(tableId));
|
|
35
|
+
scope.setAttribute("filterId", ownerId);
|
|
36
|
+
scope.setAttribute("ref", native.getAttribute("ref")!);
|
|
37
|
+
let styleIndex = 0;
|
|
38
|
+
for (const column of children(native, "filterColumn")) {
|
|
39
|
+
const record = add(scope, "columnFilter");
|
|
40
|
+
const index = column.getAttribute("colId")!;
|
|
41
|
+
record.setAttribute("colId", index);
|
|
42
|
+
const members = children(column);
|
|
43
|
+
if (members[0]?.localName === "colorFilter") record.appendChild(styles[styleIndex++]!);
|
|
44
|
+
const criteria = add(record, "filter");
|
|
45
|
+
criteria.setAttribute("colId", index);
|
|
46
|
+
for (const member of members) criteria.appendChild(member);
|
|
47
|
+
}
|
|
48
|
+
if (filter.sort) writeXlsxNamedViewSort(scope, { ...filter.range, sheetId }, filter.sort);
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return writePart(document);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @param source - Original workbook and owned view parts. @param parts - Output archive.
|
|
55
|
+
* @param paths - Final worksheet package paths. @param snapshot - Committed state.
|
|
56
|
+
* @param tableSerials - Workbook table identities mapped to native numeric IDs. */
|
|
57
|
+
export function writeWorkbookNamedViews(source: XlsxPackage, parts: Record<string, Uint8Array>, paths: ReadonlyMap<string, string>,
|
|
58
|
+
snapshot: WorkbookSnapshot, tableSerials: ReadonlyMap<string, number>): void {
|
|
59
|
+
const previous = new Map(source.baseline?.sheets.map(({ id, view }) => [id, view?.namedViews]));
|
|
60
|
+
const changed = snapshot.sheets.filter(sheet => !sameWorkbookNamedViews(previous.get(sheet.id), sheet.view?.namedViews));
|
|
61
|
+
const removed = [...(source.namedViewPaths ?? [])].filter(([id]) => !paths.has(id));
|
|
62
|
+
if (!changed.length && !removed.length) return;
|
|
63
|
+
|
|
64
|
+
const manifestPath = "[Content_Types].xml";
|
|
65
|
+
const manifest = parsePart(parts[manifestPath], manifestPath);
|
|
66
|
+
const types = rootOf(manifest, contentTypeNs, "Types");
|
|
67
|
+
const overrides = new Map(children(types, "Override").map(node => [node.getAttribute("PartName"), node]));
|
|
68
|
+
const reserved = new Set([...Object.keys(parts), ...Array.from(overrides.keys(), name => name?.slice(1) ?? "")].map(name => name.toLowerCase()));
|
|
69
|
+
const directory = source.workbookPath.slice(0, source.workbookPath.lastIndexOf("/") + 1);
|
|
70
|
+
let serial = 1;
|
|
71
|
+
/** @param path - An exclusively owned definition part no longer referenced. */
|
|
72
|
+
function remove(path: string): void {
|
|
73
|
+
delete parts[path];
|
|
74
|
+
const override = overrides.get("/" + path);
|
|
75
|
+
if (override) types.removeChild(override);
|
|
76
|
+
}
|
|
77
|
+
for (const [, path] of removed) remove(path);
|
|
78
|
+
for (const { id, view } of changed) {
|
|
79
|
+
const sheetPath = paths.get(id)!;
|
|
80
|
+
const relations = editPartRelationships(parts, sheetPath);
|
|
81
|
+
const before = source.namedViewPaths?.get(id);
|
|
82
|
+
const views = view?.namedViews;
|
|
83
|
+
if (!views?.length) {
|
|
84
|
+
if (!before) continue;
|
|
85
|
+
const relation = [...relations.entries.values()].find(entry => entry.path === before && entry.type === xlsxNamedViewRelationship);
|
|
86
|
+
if (!relation) throw new Error("命名视图关系缺失。");
|
|
87
|
+
relations.remove(relation.id);
|
|
88
|
+
relations.write();
|
|
89
|
+
remove(before);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
let path = before;
|
|
93
|
+
if (!path) {
|
|
94
|
+
do { path = `${directory}namedSheetViews/namedSheetView${serial++}.xml`; }
|
|
95
|
+
while (reserved.has(path.toLowerCase()));
|
|
96
|
+
reserved.add(path.toLowerCase());
|
|
97
|
+
relations.add(xlsxNamedViewRelationship, "/" + path.split("/").map(encodeURIComponent).join("/"));
|
|
98
|
+
relations.write();
|
|
99
|
+
const override = manifest.createElementNS(contentTypeNs, "Override");
|
|
100
|
+
override.setAttribute("PartName", "/" + path);
|
|
101
|
+
override.setAttribute("ContentType", xlsxNamedViewContentType);
|
|
102
|
+
types.appendChild(override);
|
|
103
|
+
}
|
|
104
|
+
parts[path] = writeDefinitions(id, views, tableSerials, path);
|
|
105
|
+
}
|
|
106
|
+
parts[manifestPath] = writePart(manifest);
|
|
107
|
+
}
|
|
@@ -0,0 +1,33 @@
|
|
|
1
|
+
/** Native package relationship and media type for one worksheet's saved view definitions. */
|
|
2
|
+
export const xlsxNamedViewRelationship = "http://schemas.microsoft.com/office/2019/04/relationships/namedSheetView";
|
|
3
|
+
export const xlsxNamedViewContentType = "application/vnd.ms-excel.namedsheetviews+xml";
|
|
4
|
+
export const xlsxNamedViewNs = "http://schemas.microsoft.com/office/spreadsheetml/2019/namedsheetviews";
|
|
5
|
+
|
|
6
|
+
/** @returns The diagnostic retained when a definition cannot be rewritten faithfully. */
|
|
7
|
+
export function unsupportedXlsxNamedView(): Error { return new Error("命名视图包含暂未支持的筛选或排序定义。"); }
|
|
8
|
+
|
|
9
|
+
/** @param id - Workbook GUID without braces. @returns SpreadsheetML's GUID spelling. */
|
|
10
|
+
export function xlsxViewGuid(id: string): string { return `{${id.toUpperCase()}}`; }
|
|
11
|
+
import type { Element } from "@xmldom/xmldom";
|
|
12
|
+
import { readXlsxRevisionGuid } from "../../../opc/revision";
|
|
13
|
+
import { readIndex } from "../../../opc/xml";
|
|
14
|
+
import type { XlsxNamedViewFilterOwner } from "./types";
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
/** @param parent - View definition parent. @param name - Local element name. @returns The inserted element. */
|
|
18
|
+
export function appendXlsxNamedViewElement(parent: Element, name: string): Element {
|
|
19
|
+
const node = parent.ownerDocument!.createElementNS(xlsxNamedViewNs, "xnsv:" + name);
|
|
20
|
+
parent.appendChild(node);
|
|
21
|
+
return node;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** @param node - Named filter or sort column record. @param owner - Reconciled AutoFilter.
|
|
25
|
+
* @returns Relative column index, giving native table column identities precedence. */
|
|
26
|
+
export function readXlsxNamedViewColumn(node: Element, owner: XlsxNamedViewFilterOwner): number {
|
|
27
|
+
const id = readXlsxRevisionGuid(node.getAttribute("id"));
|
|
28
|
+
if (node.hasAttribute("id") && !id) throw unsupportedXlsxNamedView();
|
|
29
|
+
const matches = id === undefined ? [] : (owner.columnUids ?? []).flatMap((uid, index) => uid === id ? [index] : []);
|
|
30
|
+
const index = matches.length === 1 ? matches[0] : matches.length === 0 ? readIndex(node, "colId") : undefined;
|
|
31
|
+
if (index === undefined || index > owner.range.endColumn - owner.range.startColumn) throw unsupportedXlsxNamedView();
|
|
32
|
+
return index;
|
|
33
|
+
}
|
|
@@ -0,0 +1,75 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookColumn, type WorkbookFrozenPanes, type WorkbookViewAnchor, type WorkbookWorksheetView } from "@quirekit/workbook";
|
|
3
|
+
import { child, children, spreadNs } from "../../opc/xml";
|
|
4
|
+
import { xlsxViewCell } from "./coordinates";
|
|
5
|
+
|
|
6
|
+
/** @param point - Logical viewport coordinate. @returns Native cell reference. */
|
|
7
|
+
function cellRef(point: WorkbookViewAnchor): string {
|
|
8
|
+
return formatWorkbookColumn(point.column) + (point.row + 1);
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** @param settings - Saved view. @returns Whether the view has a frozen region. */
|
|
12
|
+
function isFrozen(settings: WorkbookWorksheetView): boolean {
|
|
13
|
+
return settings.freeze.rows > 0 || settings.freeze.columns > 0;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
/** @param cell - Primary cell. @param freeze - Frozen prefix on each axis.
|
|
17
|
+
* @returns Its SpreadsheetML pane name, including the normalized single-axis names. */
|
|
18
|
+
function paneForCell(cell: WorkbookViewAnchor, { rows, columns }: WorkbookFrozenPanes): string {
|
|
19
|
+
const side = columns > 0 && cell.column >= columns ? "Right" : "Left";
|
|
20
|
+
return (rows > 0 && cell.row >= rows ? "bottom" : "top") + side;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @param node - Saved active selection. @param fallback - First scrolling cell.
|
|
24
|
+
* @returns Restorable cell for the rebuilt pane partition. */
|
|
25
|
+
function activeCell(node: Element | undefined, fallback: WorkbookViewAnchor): WorkbookViewAnchor {
|
|
26
|
+
if (!node) return fallback;
|
|
27
|
+
try { return xlsxViewCell(node, "activeCell") ?? fallback; }
|
|
28
|
+
catch { return fallback; }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @param worksheetView - Editable saved view. @param before - Previous settings. @param after - Committed settings. */
|
|
32
|
+
export function writeXlsxPane(worksheetView: Element, before: WorkbookWorksheetView, after: WorkbookWorksheetView): void {
|
|
33
|
+
const oldPane = child(worksheetView, "pane");
|
|
34
|
+
const { rows, columns } = after.freeze;
|
|
35
|
+
const body = after.scrollAnchor ?? { row: rows, column: columns };
|
|
36
|
+
const frozen = isFrozen(after);
|
|
37
|
+
if (!frozen && after.scrollAnchor) worksheetView.setAttribute("topLeftCell", cellRef(after.scrollAnchor));
|
|
38
|
+
else worksheetView.removeAttribute("topLeftCell");
|
|
39
|
+
if (!frozen && !oldPane) return;
|
|
40
|
+
|
|
41
|
+
// A body scroll can change independently of the pane partition and its saved selections.
|
|
42
|
+
if (oldPane && frozen && rows === before.freeze.rows && columns === before.freeze.columns) {
|
|
43
|
+
oldPane.setAttribute("topLeftCell", cellRef(body));
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
const document = worksheetView.ownerDocument!;
|
|
48
|
+
const selections = children(worksheetView, "selection");
|
|
49
|
+
const oldActive = oldPane?.getAttribute("activePane") || "topLeft";
|
|
50
|
+
const selected = selections.find(selection => (selection.getAttribute("pane") || "topLeft") === oldActive) ?? selections[0];
|
|
51
|
+
const cell = activeCell(selected, body);
|
|
52
|
+
for (const selection of selections) if (selection !== selected) worksheetView.removeChild(selection);
|
|
53
|
+
|
|
54
|
+
const selection = selected ?? document.createElementNS(spreadNs, "selection");
|
|
55
|
+
const reference = cellRef(cell);
|
|
56
|
+
selection.setAttribute("activeCell", reference);
|
|
57
|
+
if (!selected?.getAttribute("sqref")) selection.setAttribute("sqref", reference);
|
|
58
|
+
const afterSelections = children(worksheetView).find(node => ["pivotSelection", "extLst"].includes(node.localName ?? ""));
|
|
59
|
+
if (!selected) worksheetView.insertBefore(selection, afterSelections ?? null);
|
|
60
|
+
if (oldPane) worksheetView.removeChild(oldPane);
|
|
61
|
+
if (!frozen) {
|
|
62
|
+
selection.removeAttribute("pane");
|
|
63
|
+
return;
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
const pane = document.createElementNS(spreadNs, "pane");
|
|
67
|
+
const name = paneForCell(cell, after.freeze);
|
|
68
|
+
if (columns > 0) pane.setAttribute("xSplit", String(columns));
|
|
69
|
+
if (rows > 0) pane.setAttribute("ySplit", String(rows));
|
|
70
|
+
pane.setAttribute("topLeftCell", cellRef(body));
|
|
71
|
+
pane.setAttribute("activePane", name);
|
|
72
|
+
pane.setAttribute("state", "frozen");
|
|
73
|
+
selection.setAttribute("pane", name);
|
|
74
|
+
worksheetView.insertBefore(pane, selection);
|
|
75
|
+
}
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import {
|
|
3
|
+
copyWorkbookWorksheetView, defaultWorkbookWorksheetView, maximumWorkbookZoomPercent, minimumWorkbookZoomPercent,
|
|
4
|
+
workbookColumns, workbookRows, type WorkbookFrozenPanes, type WorkbookViewAnchor, type WorkbookWorksheetView
|
|
5
|
+
} from "@quirekit/workbook";
|
|
6
|
+
import { child, children, isTrue } from "../../opc/xml";
|
|
7
|
+
import { isNormalXlsxView, primaryXlsxWorksheetView, xlsxViewCell } from "./coordinates";
|
|
8
|
+
|
|
9
|
+
/** @param view - Native view. @returns A supported leading pane or null for other kinds of splits. */
|
|
10
|
+
export function readXlsxFrozenPanes(view: Element): WorkbookFrozenPanes | null {
|
|
11
|
+
const pane = child(view, "pane");
|
|
12
|
+
if (!isNormalXlsxView(view) || isTrue(view.getAttribute("rightToLeft")) || isTrue(view.getAttribute("windowProtection"))) return null;
|
|
13
|
+
if (!pane) return defaultWorkbookWorksheetView.freeze;
|
|
14
|
+
if (pane.getAttribute("state") !== "frozen" || children(view, "pane").length !== 1 || child(view, "pivotSelection")) return null;
|
|
15
|
+
const rows = Number(pane.getAttribute("ySplit") || 0);
|
|
16
|
+
const columns = Number(pane.getAttribute("xSplit") || 0);
|
|
17
|
+
if (!rows && !columns || !Number.isInteger(rows) || rows < 0 || rows >= workbookRows
|
|
18
|
+
|| !Number.isInteger(columns) || columns < 0 || columns >= workbookColumns) return null;
|
|
19
|
+
try {
|
|
20
|
+
const start = xlsxViewCell(view, "topLeftCell");
|
|
21
|
+
const body = xlsxViewCell(pane, "topLeftCell");
|
|
22
|
+
if (start && (rows > 0 && start.row > 0 || columns > 0 && start.column > 0)) return null;
|
|
23
|
+
if (body && (body.row < rows || body.column < columns)) return null;
|
|
24
|
+
} catch { return null; }
|
|
25
|
+
return { rows, columns };
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/** @param view - Primary sheet view. @returns Optional native position of its scrollable body. */
|
|
29
|
+
function scrollAnchor(view: Element): WorkbookViewAnchor | undefined {
|
|
30
|
+
const pane = child(view, "pane");
|
|
31
|
+
try { return (pane && xlsxViewCell(pane, "topLeftCell")) ?? xlsxViewCell(view, "topLeftCell"); }
|
|
32
|
+
catch { return undefined; }
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/** @param view - Imported worksheet view. @returns Supported normal zoom, using the standard default when absent. */
|
|
36
|
+
function zoomPercent(view: Element): number {
|
|
37
|
+
const value = Number((isNormalXlsxView(view) && view.getAttribute("zoomScale")) || view.getAttribute("zoomScaleNormal"));
|
|
38
|
+
return Number.isInteger(value) && value >= minimumWorkbookZoomPercent && value <= maximumWorkbookZoomPercent
|
|
39
|
+
? value : defaultWorkbookWorksheetView.zoomPercent;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param root - Original worksheet. @returns The settings represented in the QuireKit normal view. */
|
|
43
|
+
export function readXlsxWorksheetView(root: Element): WorkbookWorksheetView | undefined {
|
|
44
|
+
const primary = primaryXlsxWorksheetView(root);
|
|
45
|
+
if (!primary) return;
|
|
46
|
+
const freeze = readXlsxFrozenPanes(primary);
|
|
47
|
+
const view = copyWorkbookWorksheetView({
|
|
48
|
+
freeze: freeze ?? defaultWorkbookWorksheetView.freeze,
|
|
49
|
+
showGridlines: !["0", "false"].includes(primary.getAttribute("showGridLines") ?? ""),
|
|
50
|
+
showHeadings: !["0", "false"].includes(primary.getAttribute("showRowColHeaders") ?? ""),
|
|
51
|
+
zoomPercent: zoomPercent(primary),
|
|
52
|
+
scrollAnchor: freeze ? scrollAnchor(primary) : undefined
|
|
53
|
+
});
|
|
54
|
+
return view === defaultWorkbookWorksheetView ? undefined : view;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/** @param root - Original worksheet. @returns A reason its native panes cannot be replaced. */
|
|
58
|
+
export function xlsxFreezeRestriction(root: Element): string | undefined {
|
|
59
|
+
const primary = primaryXlsxWorksheetView(root);
|
|
60
|
+
if (primary && !readXlsxFrozenPanes(primary)) return "源文件含拆分窗格、非前缀冻结或专用视图。";
|
|
61
|
+
}
|
|
@@ -0,0 +1,57 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { formatWorkbookRange, mapWorkbookRange, type WorkbookAxisSplice, type WorkbookRange } from "@quirekit/workbook";
|
|
3
|
+
import { child, children } from "../../opc/xml";
|
|
4
|
+
import { primaryXlsxWorksheetView, xlsxViewReferences, xlsxWorksheetViews } from "./coordinates";
|
|
5
|
+
import { readXlsxFrozenPanes } from "./read";
|
|
6
|
+
|
|
7
|
+
/** @param root - Imported worksheet. @returns Reason its saved views cannot yet be structurally changed. */
|
|
8
|
+
export function worksheetViewRestriction(root: Element): string | undefined {
|
|
9
|
+
const primary = primaryXlsxWorksheetView(root);
|
|
10
|
+
for (const view of xlsxWorksheetViews(root)) {
|
|
11
|
+
if (child(view, "pane") && (view !== primary || !readXlsxFrozenPanes(view))) return "未支持的冻结或拆分窗格";
|
|
12
|
+
try {
|
|
13
|
+
xlsxViewReferences(view, "topLeftCell", "");
|
|
14
|
+
for (const selection of children(view, "selection")) {
|
|
15
|
+
xlsxViewReferences(selection, "activeCell", "");
|
|
16
|
+
xlsxViewReferences(selection, "sqref", "");
|
|
17
|
+
}
|
|
18
|
+
} catch { return "工作表视图位置"; }
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
/** @param range - Original cell or interval. @param splice - Position change.
|
|
23
|
+
* @returns First surviving cell, or the first cell at the removed axis position. */
|
|
24
|
+
function anchor(range: WorkbookRange, splice: WorkbookAxisSplice): WorkbookRange {
|
|
25
|
+
const mapped = mapWorkbookRange(range, splice);
|
|
26
|
+
const row = mapped?.startRow ?? (splice.axis === "row" ? splice.index : range.startRow);
|
|
27
|
+
const column = mapped?.startColumn ?? (splice.axis === "column" ? splice.index : range.startColumn);
|
|
28
|
+
return { sheetId: splice.sheetId, startRow: row, endRow: row, startColumn: column, endColumn: column };
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/** @param root - Worksheet whose content has moved. @param splice - Same change in the saved view coordinate space. */
|
|
32
|
+
export function relocateWorksheetViews(root: Element, splice: WorkbookAxisSplice): void {
|
|
33
|
+
for (const view of xlsxWorksheetViews(root)) {
|
|
34
|
+
const corner = xlsxViewReferences(view, "topLeftCell", splice.sheetId)[0];
|
|
35
|
+
// The canonical view writer rebases the primary pane from the same sheet-level transaction.
|
|
36
|
+
if (corner && !child(view, "pane")) view.setAttribute("topLeftCell", formatWorkbookRange(anchor(corner, splice)));
|
|
37
|
+
for (const selection of children(view, "selection")) {
|
|
38
|
+
const selections = xlsxViewReferences(selection, "sqref", splice.sheetId);
|
|
39
|
+
const active = xlsxViewReferences(selection, "activeCell", splice.sheetId)[0] ?? selections[0];
|
|
40
|
+
if (!active) continue;
|
|
41
|
+
const mapped = selections.map(range => mapWorkbookRange(range, splice)).filter(range => range !== null);
|
|
42
|
+
let focus = anchor(active, splice);
|
|
43
|
+
let index = mapped.findIndex(range => focus.startRow >= range.startRow && focus.startRow <= range.endRow
|
|
44
|
+
&& focus.startColumn >= range.startColumn && focus.startColumn <= range.endColumn);
|
|
45
|
+
if (index < 0) {
|
|
46
|
+
const first = mapped[0];
|
|
47
|
+
if (first) focus = { ...first, endRow: first.startRow, endColumn: first.startColumn };
|
|
48
|
+
else mapped.push(focus);
|
|
49
|
+
index = 0;
|
|
50
|
+
}
|
|
51
|
+
selection.setAttribute("activeCell", formatWorkbookRange(focus));
|
|
52
|
+
selection.setAttribute("sqref", mapped.map(formatWorkbookRange).join(" "));
|
|
53
|
+
selection.removeAttribute("activeCellId");
|
|
54
|
+
if (index > 0) selection.setAttribute("activeCellId", String(index));
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
@@ -0,0 +1,91 @@
|
|
|
1
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
2
|
+
import { openWorkbook, parseWorkbookRange, type WorkbookSession, type WorkbookSnapshot } from "@quirekit/workbook";
|
|
3
|
+
import { expect, it } from "vitest";
|
|
4
|
+
import { createXlsx, openXlsx } from "../../index";
|
|
5
|
+
|
|
6
|
+
const path = "xl/worksheets/sheet1.xml";
|
|
7
|
+
const initial: WorkbookSnapshot = {
|
|
8
|
+
version: 1, id: "list", name: "Inventory", revision: 0,
|
|
9
|
+
sheets: [
|
|
10
|
+
{ id: "stock", name: "Stock", cells: [{ row: 2, column: 1, input: { kind: "formula", formula: "=6+6" } }] },
|
|
11
|
+
{ id: "notes", name: "Notes", cells: [] }
|
|
12
|
+
]
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
/** @param view - Native view children. @returns Source parts with a cached formula and untouched view settings. */
|
|
16
|
+
function source(view: string): Uint8Array {
|
|
17
|
+
const parts = unzipSync(createXlsx(initial, { result: () => ({ status: "value", value: 12 }) }));
|
|
18
|
+
parts[path] = strToU8(strFromU8(parts[path]!).replace("<sheetData>",
|
|
19
|
+
'<sheetViews><sheetView workbookViewId="0" showZeros="0">' + view + '</sheetView></sheetViews><sheetData>'));
|
|
20
|
+
return zipSync(parts);
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/** @param workbook - Live workbook. @param id - Target sheet. @param name - Command.
|
|
24
|
+
* @param range - A1 range for the operation. @param params - Valid command input. @returns Result of publishing the edit. */
|
|
25
|
+
function edit(workbook: WorkbookSession, id: string, name: string, range: string, params: unknown = {}) {
|
|
26
|
+
const candidate = workbook.prepare({ baseRevision: workbook.revision, operationId: name + workbook.revision,
|
|
27
|
+
commands: [{ name, target: parseWorkbookRange(id, range), params }] });
|
|
28
|
+
return workbook.commit(candidate.id);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
it("preserves formula caches, unrelated parts and window settings across view-only writes", async () => {
|
|
32
|
+
const original = source('<selection activeCell="B3" sqref="B3:C3"/>');
|
|
33
|
+
const file = openXlsx("Inventory", original);
|
|
34
|
+
const id = file.snapshot.sheets[0]!.id;
|
|
35
|
+
const workbook = await openWorkbook(file.snapshot);
|
|
36
|
+
try {
|
|
37
|
+
const settings = { freeze: { rows: 2, columns: 1 }, showGridlines: false, showHeadings: false, zoomPercent: 150 };
|
|
38
|
+
await edit(workbook, id, "setWorksheetView", "B3", settings);
|
|
39
|
+
const bytes = file.write(workbook.snapshot());
|
|
40
|
+
const parts = unzipSync(bytes);
|
|
41
|
+
const xml = strFromU8(parts[path]!);
|
|
42
|
+
expect(xml).toContain('showZeros="0" showGridLines="0" showRowColHeaders="0" zoomScaleNormal="150" zoomScale="150"');
|
|
43
|
+
expect(xml).toContain('<pane xSplit="1" ySplit="2" topLeftCell="B3" activePane="bottomRight" state="frozen"/>');
|
|
44
|
+
expect(xml).toContain('<selection activeCell="B3" sqref="B3:C3" pane="bottomRight"/>');
|
|
45
|
+
expect(xml).toContain("<f>6+6</f><v>12</v>");
|
|
46
|
+
expect(strFromU8(parts["xl/workbook.xml"]!)).toContain("<bookViews><workbookView/></bookViews><sheets>");
|
|
47
|
+
expect(parts["xl/worksheets/sheet2.xml"]).toEqual(unzipSync(original)["xl/worksheets/sheet2.xml"]);
|
|
48
|
+
expect(openXlsx("Round trip", bytes).snapshot.sheets[0]?.view).toEqual(settings);
|
|
49
|
+
await workbook.undo("undo-worksheet-view");
|
|
50
|
+
expect(file.write(workbook.snapshot())).toEqual(original);
|
|
51
|
+
} finally { await workbook.close(); }
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
it("relocates an imported normal frozen pane and clears its pane-specific selection on unfreeze", async () => {
|
|
55
|
+
const file = openXlsx("Inventory", source('<pane xSplit="1" ySplit="2" topLeftCell="C7" activePane="bottomRight" state="frozen"/>'
|
|
56
|
+
+ '<selection pane="bottomRight" activeCell="B3" sqref="B3"/>'));
|
|
57
|
+
const id = file.snapshot.sheets[0]!.id;
|
|
58
|
+
const workbook = await openWorkbook(file.snapshot, { axisRestrictions: file.axisRestrictions, freezeRestrictions: file.freezeRestrictions });
|
|
59
|
+
try {
|
|
60
|
+
expect(file.axisRestrictions.has(id)).toBe(false);
|
|
61
|
+
expect(workbook.worksheetView(id)).toMatchObject({ freeze: { rows: 2, columns: 1 }, scrollAnchor: { row: 6, column: 2 } });
|
|
62
|
+
await edit(workbook, id, "clearCells", "B3");
|
|
63
|
+
await edit(workbook, id, "insertRows", "A2");
|
|
64
|
+
const moved = file.write(workbook.snapshot());
|
|
65
|
+
expect(strFromU8(unzipSync(moved)[path]!)).toContain('ySplit="3" topLeftCell="C8"');
|
|
66
|
+
expect(openXlsx("Moved", moved).snapshot.sheets[0]?.view).toMatchObject({ freeze: { rows: 3, columns: 1 }, scrollAnchor: { row: 7, column: 2 } });
|
|
67
|
+
await edit(workbook, id, "setWorksheetView", "A1", { freeze: { rows: 0, columns: 0 } });
|
|
68
|
+
const cleared = file.write(workbook.snapshot());
|
|
69
|
+
const xml = strFromU8(unzipSync(cleared)[path]!);
|
|
70
|
+
expect(xml).not.toContain("<pane");
|
|
71
|
+
expect(xml).not.toContain('pane="bottomRight"');
|
|
72
|
+
expect(xml).toContain('topLeftCell="C8"');
|
|
73
|
+
expect(openXlsx("Unfrozen", cleared).snapshot.sheets[0]?.view).toMatchObject({ freeze: { rows: 0, columns: 0 } });
|
|
74
|
+
} finally { await workbook.close(); }
|
|
75
|
+
});
|
|
76
|
+
|
|
77
|
+
it("changes ordinary view flags while preserving unhandled splits", async () => {
|
|
78
|
+
const pane = '<pane xSplit="725" topLeftCell="D1" activePane="topRight" state="split"/>';
|
|
79
|
+
const file = openXlsx("Inventory", source(pane));
|
|
80
|
+
const id = file.snapshot.sheets[0]!.id;
|
|
81
|
+
const workbook = await openWorkbook(file.snapshot, { freezeRestrictions: file.freezeRestrictions });
|
|
82
|
+
try {
|
|
83
|
+
expect(workbook.freezeRestriction(id)).toContain("拆分");
|
|
84
|
+
expect(() => edit(workbook, id, "setWorksheetView", "B2", { freeze: { rows: 1, columns: 1 } })).toThrow(/拆分/u);
|
|
85
|
+
await edit(workbook, id, "setWorksheetView", "B2", { showGridlines: false, zoomPercent: 85 });
|
|
86
|
+
const xml = strFromU8(unzipSync(file.write(workbook.snapshot()))[path]!);
|
|
87
|
+
expect(xml).toContain(pane);
|
|
88
|
+
expect(xml).toContain('showGridLines="0"');
|
|
89
|
+
expect(xml).toContain('zoomScale="85"');
|
|
90
|
+
} finally { await workbook.close(); }
|
|
91
|
+
});
|