@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,98 @@
|
|
|
1
|
+
/// <reference types="node" />
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { openWorkbook, parseWorkbookRange } from "@quirekit/workbook";
|
|
5
|
+
import { strFromU8, strToU8, unzipSync, zipSync } from "fflate";
|
|
6
|
+
import { expect, test } from "vitest";
|
|
7
|
+
import { openXlsx } from "../package/read";
|
|
8
|
+
|
|
9
|
+
test("projects embedded pictures in source order with the native anchor modes and preserves the original drawing", () => {
|
|
10
|
+
const bytes = Uint8Array.from(readFileSync(new URL("../../test/fixtures/floating-pictures.xlsx", import.meta.url)));
|
|
11
|
+
const source = openXlsx("浮动图片", bytes);
|
|
12
|
+
const pictures = source.pictures!;
|
|
13
|
+
const [sheet] = source.snapshot.sheets;
|
|
14
|
+
expect(sheet?.cells[0]?.input).toEqual({ kind: "value", value: "图片位置" });
|
|
15
|
+
expect(pictures.map(({ order, anchor: { sheetId, from, to } }) => [order, sheetId, from, to])).toEqual([
|
|
16
|
+
[0, sheet?.id, { row: 1, column: 1, x: 4, y: 2 }, { row: 1, column: 1, x: 88, y: 16 }],
|
|
17
|
+
[1, sheet?.id, { row: 6, column: 0, x: 5, y: 2 }, { row: 6, column: 1, x: 20, y: 16 }],
|
|
18
|
+
[3, sheet?.id, { row: 0, column: 0, x: 10, y: 143 }, { row: 0, column: 0, x: 86, y: 157 }],
|
|
19
|
+
[4, sheet?.id, { row: 39, column: 0, x: 4, y: 2 }, { row: 39, column: 0, x: 100, y: 14 }],
|
|
20
|
+
[5, sheet?.id, { row: 0, column: 0, x: 4, y: 164 }, { row: 0, column: 0, x: 100, y: 176 }]
|
|
21
|
+
]);
|
|
22
|
+
expect(pictures[1]?.picture).toMatchObject({ crop: { left: 0.1, top: 0, right: 0, bottom: 0 }, flipHorizontal: true });
|
|
23
|
+
for (const { picture } of pictures) expect(picture.asset).toBe(pictures[0]?.picture.asset);
|
|
24
|
+
expect(pictures[0]?.picture.asset).toMatchObject({ mimeType: "image/png", width: 30, height: 12 });
|
|
25
|
+
expect(source.restrictions).toContain("绘图或图表");
|
|
26
|
+
expect(source.write(source.snapshot)).toEqual(bytes);
|
|
27
|
+
const edited = { ...source.snapshot, sheets: source.snapshot.sheets.map((item, index) => index === 0
|
|
28
|
+
? { ...item, cells: [{ row: 0, column: 0, input: { kind: "value" as const, value: "改动" } }] } : item) };
|
|
29
|
+
expect(() => source.write(edited)).toThrow("仅可原样下载");
|
|
30
|
+
expect(source.original()).toEqual(bytes);
|
|
31
|
+
});
|
|
32
|
+
|
|
33
|
+
test("round-trips native XlsxWriter pictures and shares one drawing with an editable chart", async () => {
|
|
34
|
+
const original = new Uint8Array(readFileSync(new URL("../../test/fixtures/native-floating-pictures.xlsx", import.meta.url)));
|
|
35
|
+
const native = unzipSync(original), drawingPart = "xl/drawings/drawing1.xml";
|
|
36
|
+
native[drawingPart] = strToU8(strFromU8(native[drawingPart]!)
|
|
37
|
+
// The native 270° frame swaps the 128 × 72 pixel source around the same center.
|
|
38
|
+
.replace("<xdr:colOff>47625</xdr:colOff><xdr:row>1</xdr:row><xdr:rowOff>38100</xdr:rowOff>",
|
|
39
|
+
"<xdr:colOff>314325</xdr:colOff><xdr:row>1</xdr:row><xdr:rowOff>152400</xdr:rowOff>")
|
|
40
|
+
.replace("<xdr:to><xdr:col>3</xdr:col><xdr:colOff>47625</xdr:colOff><xdr:row>4</xdr:row><xdr:rowOff>152400</xdr:rowOff>",
|
|
41
|
+
"<xdr:to><xdr:col>2</xdr:col><xdr:colOff>390525</xdr:colOff><xdr:row>8</xdr:row><xdr:rowOff>38100</xdr:rowOff>")
|
|
42
|
+
.replace("<a:xfrm>", '<a:xfrm rot="-5400000" flipH="1">')
|
|
43
|
+
.replace('y="228600"', 'y="609600"')
|
|
44
|
+
.replace("<a:stretch>", '<a:srcRect l="12500"/><a:stretch>'));
|
|
45
|
+
const bytes = zipSync(native);
|
|
46
|
+
const source = openXlsx("Native", bytes);
|
|
47
|
+
const sheetId = source.snapshot.sheets[0]!.id;
|
|
48
|
+
expect(source.restrictions).toEqual([]);
|
|
49
|
+
expect(source.write(source.snapshot)).toEqual(bytes);
|
|
50
|
+
const [png, jpeg] = source.snapshot.pictures!;
|
|
51
|
+
expect(png).toMatchObject({ name: "Picture 1", alt: "合成测试图片", rotation: 270, flipHorizontal: true, crop: { left: 0.125 }, anchor: {
|
|
52
|
+
from: { row: 3, column: 1, x: 5, y: 4 }, to: { row: 6, column: 3, x: 5, y: 16 } } });
|
|
53
|
+
expect(source.snapshot.imageAssets?.map(media => media.mimeType)).toEqual(["image/png", "image/jpeg"]);
|
|
54
|
+
expect(openXlsx("Independent reader", bytes).snapshot.imageAssets).toEqual(source.snapshot.imageAssets);
|
|
55
|
+
const workbook = await openWorkbook(source.snapshot);
|
|
56
|
+
try {
|
|
57
|
+
const chart = workbook.prepare({ operationId: "chart-after-pictures", baseRevision: 0, commands: [{
|
|
58
|
+
name: "createChart", target: parseWorkbookRange(sheetId, "A1:A3"), params: { type: "column", title: "Alongside pictures" }
|
|
59
|
+
}] });
|
|
60
|
+
await workbook.commit(chart.id);
|
|
61
|
+
const update = workbook.prepare({ operationId: "update-native-picture", baseRevision: 1, commands: [{
|
|
62
|
+
name: "updateFloatingPicture", target: parseWorkbookRange(sheetId, "B4:D7"), params: { id: png!.id, alt: "已移动", rotation: 45.25,
|
|
63
|
+
position: { from: { cell: "C5", x: 3, y: 2 }, to: { cell: "E8", x: 3, y: 14 } } }
|
|
64
|
+
}] });
|
|
65
|
+
await workbook.commit(update.id);
|
|
66
|
+
const output = source.write(workbook.snapshot());
|
|
67
|
+
const parts = unzipSync(output);
|
|
68
|
+
const drawing = strFromU8(parts["xl/drawings/drawing1.xml"]!);
|
|
69
|
+
expect(drawing).toContain('rot="2715000"');
|
|
70
|
+
expect(drawing).toContain("<xdr:from><xdr:col>2</xdr:col><xdr:colOff>295275</xdr:colOff><xdr:row>2</xdr:row><xdr:rowOff>133350</xdr:rowOff>");
|
|
71
|
+
expect(drawing).toContain('<a:ext cx="1219200" cy="685800"/>');
|
|
72
|
+
expect(drawing.lastIndexOf("<xdr:pic>")).toBeLessThan(drawing.indexOf("<xdr:graphicFrame>"));
|
|
73
|
+
expect(parts["xl/media/image1.png"]).toEqual(unzipSync(bytes)["xl/media/image1.png"]);
|
|
74
|
+
const reopened = openXlsx("Edited", output);
|
|
75
|
+
expect(reopened.restrictions).toEqual([]);
|
|
76
|
+
expect(reopened.snapshot.pictures).toMatchObject([{ id: png!.id, alt: "已移动", order: 0, rotation: 45.25, flipHorizontal: true, crop: { left: 0.125 },
|
|
77
|
+
anchor: { from: { row: 4, column: 2, x: 3, y: 2 } } }, { id: jpeg!.id, order: 1 }]);
|
|
78
|
+
expect(reopened.snapshot.charts).toMatchObject([{ title: "Alongside pictures", order: 2 }]);
|
|
79
|
+
expect(openXlsx("Second room member", output).write(reopened.snapshot)).toEqual(output);
|
|
80
|
+
const resized = reopened.write({ ...reopened.snapshot, sheets: reopened.snapshot.sheets.map(sheet => ({
|
|
81
|
+
...sheet, dimensions: { ...sheet.dimensions, rows: [], columns: [{ first: 2, last: 2, size: 16.25 }] }
|
|
82
|
+
})) });
|
|
83
|
+
expect(strFromU8(unzipSync(resized)[drawingPart]!)).not.toBe(drawing);
|
|
84
|
+
expect(openXlsx("Resized columns", resized).snapshot.pictures).toEqual(reopened.snapshot.pictures);
|
|
85
|
+
const originalPicture = reopened.snapshot.pictures![0]!;
|
|
86
|
+
const atOrigin = { ...originalPicture, rotation: 90, anchor: { sheetId,
|
|
87
|
+
from: { row: 0, column: 0, x: 0, y: 0 }, to: { row: 3, column: 2, x: 0, y: 12 } } };
|
|
88
|
+
const nearEdge = reopened.write({ ...reopened.snapshot, pictures: [atOrigin, reopened.snapshot.pictures![1]!] });
|
|
89
|
+
const edgeXml = strFromU8(unzipSync(nearEdge)[drawingPart]!);
|
|
90
|
+
expect(edgeXml).toContain("<xdr:from><xdr:col>0</xdr:col><xdr:colOff>266700</xdr:colOff><xdr:row>0</xdr:row><xdr:rowOff>0</xdr:rowOff>");
|
|
91
|
+
expect(openXlsx("Sheet edge", nearEdge).snapshot.pictures?.[0]).toEqual(atOrigin);
|
|
92
|
+
const withoutPng = reopened.write({ ...reopened.snapshot, pictures: reopened.snapshot.pictures?.slice(1) });
|
|
93
|
+
const remaining = unzipSync(withoutPng);
|
|
94
|
+
expect(remaining["xl/media/image1.png"]).toBeUndefined();
|
|
95
|
+
expect(remaining["xl/media/image2.jpeg"]).toBeDefined();
|
|
96
|
+
expect(openXlsx("Remaining", withoutPng).snapshot.charts).toHaveLength(1);
|
|
97
|
+
} finally { await workbook.close(); }
|
|
98
|
+
});
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import type { WorkbookPictureCrop } from "@quirekit/workbook";
|
|
3
|
+
import type { XlsxImageAssetReader } from "../image/types";
|
|
4
|
+
import type { PackageRelationship } from "../opc/types";
|
|
5
|
+
import { isTrue, relationshipNs } from "../opc/xml";
|
|
6
|
+
import type { XlsxFloatingPicture } from "../types";
|
|
7
|
+
import { drawingElement } from "./placement/anchor";
|
|
8
|
+
import { drawingNamespace } from "./namespaces";
|
|
9
|
+
import { readDrawingRotation, readXlsxDrawingPlacement } from "./placement/transform";
|
|
10
|
+
import type { XlsxDrawingLayout } from "./placement/types";
|
|
11
|
+
|
|
12
|
+
/** @param node - Relative DrawingML rectangle. @returns Margins, or null when malformed or outside the raster. */
|
|
13
|
+
function cropOf(node: Element | undefined): WorkbookPictureCrop | null {
|
|
14
|
+
/** @param name - A margin attribute. @returns A fraction in the source image. */
|
|
15
|
+
function fraction(name: string): number {
|
|
16
|
+
const value = node?.getAttribute(name)?.trim();
|
|
17
|
+
if (!value) return 0;
|
|
18
|
+
if (/^\d+$/u.test(value)) return Number(value) / 100000;
|
|
19
|
+
if (/^\d+(?:\.\d+)?%$/u.test(value)) return Number(value.slice(0, -1)) / 100;
|
|
20
|
+
return NaN;
|
|
21
|
+
}
|
|
22
|
+
const left = fraction("l"), top = fraction("t"), right = fraction("r"), bottom = fraction("b");
|
|
23
|
+
return left + right < 1 && top + bottom < 1 ? { left, top, right, bottom } : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param node - A worksheet anchor. @param pic - Its direct picture child. @param sheetId - Source sheet.
|
|
27
|
+
* @param order - Zero-based source drawing order. @param relationships - Resolved drawing relationships.
|
|
28
|
+
* @param image - Bounded package-local media resolver. @param layout - Native worksheet metrics. @returns A previewable floating raster. */
|
|
29
|
+
export function readDrawingPicture(node: Element, pic: Element, sheetId: string, order: number,
|
|
30
|
+
relationships: ReadonlyMap<string, PackageRelationship>, image: XlsxImageAssetReader, layout: XlsxDrawingLayout): XlsxFloatingPicture | undefined {
|
|
31
|
+
if (pic.namespaceURI !== drawingNamespace) return undefined;
|
|
32
|
+
const properties = drawingElement(drawingElement(pic, "nvPicPr", drawingNamespace), "cNvPr", drawingNamespace);
|
|
33
|
+
const shape = drawingElement(pic, "spPr", drawingNamespace);
|
|
34
|
+
const transform = drawingElement(shape, "xfrm");
|
|
35
|
+
const rotation = readDrawingRotation(transform);
|
|
36
|
+
const preset = drawingElement(shape, "prstGeom")?.getAttribute("prst");
|
|
37
|
+
if (isTrue(properties?.getAttribute("hidden")) || rotation === null
|
|
38
|
+
|| (preset && preset !== "rect") || drawingElement(shape, "custGeom")) return undefined;
|
|
39
|
+
|
|
40
|
+
const fill = drawingElement(pic, "blipFill", drawingNamespace);
|
|
41
|
+
const stretch = drawingElement(fill, "stretch");
|
|
42
|
+
if (!stretch || drawingElement(fill, "tile")) return undefined;
|
|
43
|
+
const inset = cropOf(drawingElement(stretch, "fillRect"));
|
|
44
|
+
const crop = cropOf(drawingElement(fill, "srcRect"));
|
|
45
|
+
if (!crop || !inset || Object.values(inset).some(Boolean)) return undefined;
|
|
46
|
+
const id = drawingElement(fill, "blip")?.getAttributeNS(relationshipNs, "embed");
|
|
47
|
+
const asset = id ? image(relationships.get(id)) : undefined;
|
|
48
|
+
const anchor = readXlsxDrawingPlacement(node, transform, sheetId, rotation, layout);
|
|
49
|
+
if (!asset || !anchor) return undefined;
|
|
50
|
+
const alt = properties?.getAttribute("descr") || properties?.getAttribute("title");
|
|
51
|
+
return { anchor, order, picture: { asset, ...(rotation && { rotation }), ...(alt && { alt }), ...(Object.values(crop).some(Boolean) && { crop }),
|
|
52
|
+
...(isTrue(transform?.getAttribute("flipH")) && { flipHorizontal: true }),
|
|
53
|
+
...(isTrue(transform?.getAttribute("flipV")) && { flipVertical: true }) } };
|
|
54
|
+
}
|
|
@@ -0,0 +1,71 @@
|
|
|
1
|
+
import type { WorkbookDrawingAnchor, WorkbookDrawingPoint } from "@quirekit/workbook";
|
|
2
|
+
import type { Element } from "@xmldom/xmldom";
|
|
3
|
+
import { children } from "../../opc/xml";
|
|
4
|
+
import { readDrawingMarker } from "./marker";
|
|
5
|
+
import { drawingMainNamespace, drawingNamespace, emuPerCssPixel } from "../namespaces";
|
|
6
|
+
|
|
7
|
+
/** @param parent - Optional parent in either DrawingML namespace. @param name - Child local name.
|
|
8
|
+
* @param namespace - Namespace owning the element. @returns Matching direct child. */
|
|
9
|
+
export function drawingElement(parent: Element | undefined, name: string, namespace = drawingMainNamespace): Element | undefined {
|
|
10
|
+
return parent && children(parent, name).find(child => child.namespaceURI === namespace);
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** @param node - Native coordinate element. @param key - Coordinate or extent attribute. @returns Unscaled CSS pixels. */
|
|
14
|
+
function pixels(node: Element | undefined, key: string): number {
|
|
15
|
+
const value = node?.getAttribute(key)?.trim();
|
|
16
|
+
const units = value && /^[+-]?\d+$/u.test(value) ? Number(value) : NaN;
|
|
17
|
+
return Number.isSafeInteger(units) ? units / emuPerCssPixel : NaN;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** @param location - The fixed position in worksheet pixels. @returns A marker relative to the sheet origin. */
|
|
21
|
+
function origin(location: Element | undefined): WorkbookDrawingPoint | null {
|
|
22
|
+
const x = pixels(location, "x"), y = pixels(location, "y");
|
|
23
|
+
return Number.isFinite(x) && Number.isFinite(y) ? { row: 0, column: 0, x, y } : null;
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/** @param from - Origin or relative cell marker. @param extent - Fixed native width and height. @param allowFlat - Allow one zero axis.
|
|
27
|
+
* @returns Far corner relative to the same marker. */
|
|
28
|
+
function fixedCorner(from: WorkbookDrawingPoint | null, extent: Element | undefined, allowFlat: boolean): WorkbookDrawingPoint | null {
|
|
29
|
+
const width = pixels(extent, "cx"), height = pixels(extent, "cy");
|
|
30
|
+
const spans = allowFlat ? width >= 0 && height >= 0 && width + height > 0 : width > 0 && height > 0;
|
|
31
|
+
return from && spans ? { ...from, x: from.x + width, y: from.y + height } : null;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param node - Native anchor variant. @param transform - Shape position and extent. @param sheetId - Source sheet.
|
|
35
|
+
* @param allowFlat - Permit one coincident axis of a connector. @param allowPoint - Keep coincident bindings.
|
|
36
|
+
* @returns Two corners expressed as independent pixel offsets from their respective cells. */
|
|
37
|
+
export function readDrawingAnchor(node: Element, transform: Element | undefined, sheetId: string, allowFlat = false,
|
|
38
|
+
allowPoint = false): WorkbookDrawingAnchor | undefined {
|
|
39
|
+
let from = readDrawingMarker(drawingElement(node, "from", drawingNamespace));
|
|
40
|
+
let to: WorkbookDrawingPoint | null;
|
|
41
|
+
const behavior = node.getAttribute("editAs");
|
|
42
|
+
switch (node.localName) {
|
|
43
|
+
case "oneCellAnchor":
|
|
44
|
+
to = fixedCorner(from, drawingElement(node, "ext", drawingNamespace), allowFlat);
|
|
45
|
+
break;
|
|
46
|
+
case "absoluteAnchor":
|
|
47
|
+
from = origin(drawingElement(node, "pos", drawingNamespace));
|
|
48
|
+
to = fixedCorner(from, drawingElement(node, "ext", drawingNamespace), allowFlat);
|
|
49
|
+
break;
|
|
50
|
+
case "twoCellAnchor": {
|
|
51
|
+
const end = readDrawingMarker(drawingElement(node, "to", drawingNamespace));
|
|
52
|
+
const extent = drawingElement(transform, "ext");
|
|
53
|
+
if (behavior === "absolute") {
|
|
54
|
+
const fixed = origin(drawingElement(transform, "off"));
|
|
55
|
+
to = fixedCorner(fixed, extent, allowFlat);
|
|
56
|
+
// Some producers use zero-sized transforms and encode the original frame in the markers.
|
|
57
|
+
if (to) from = fixed;
|
|
58
|
+
else to = end;
|
|
59
|
+
} else {
|
|
60
|
+
to = behavior === "oneCell" ? fixedCorner(from, extent, allowFlat) ?? end : end;
|
|
61
|
+
}
|
|
62
|
+
break;
|
|
63
|
+
}
|
|
64
|
+
default: return undefined;
|
|
65
|
+
}
|
|
66
|
+
if (!from || !to) return;
|
|
67
|
+
const across = to.column - from.column || to.x - from.x;
|
|
68
|
+
const down = to.row - from.row || to.y - from.y;
|
|
69
|
+
if (allowFlat ? across < 0 || down < 0 || (!allowPoint && !across && !down) : across <= 0 || down <= 0) return;
|
|
70
|
+
return { sheetId, from, to };
|
|
71
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
import { defaultWorkbookDimensions, workbookColumnPixels, workbookColumns, workbookRows,
|
|
2
|
+
type WorkbookDrawingPoint, type WorkbookSheetAppearance } from "@quirekit/workbook";
|
|
3
|
+
import type { Element } from "@xmldom/xmldom";
|
|
4
|
+
import { child, children, readIndex } from "../../opc/xml";
|
|
5
|
+
import { readRowAppearance, readSheetAppearance } from "../../worksheet/appearance";
|
|
6
|
+
import { emuPerCssPixel } from "../namespaces";
|
|
7
|
+
import type { XlsxDrawingLayout } from "./types";
|
|
8
|
+
|
|
9
|
+
/** Default reference width for digit-based XLSX dimensions when the file has no usable measurement. */
|
|
10
|
+
export const defaultXlsxDrawingDigitWidth = 7;
|
|
11
|
+
|
|
12
|
+
/** Prefix geometry for a native worksheet axis, including hidden cells. */
|
|
13
|
+
interface NativeDrawingAxis {
|
|
14
|
+
/** @param index - Boundary index. @returns Its unscaled absolute position in EMUs. */
|
|
15
|
+
offset(index: number): number;
|
|
16
|
+
/** @param position - Native absolute coordinate. @returns A cell index and relative CSS-pixel offset. */
|
|
17
|
+
marker(position: number): readonly [index: number, offset: number];
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** @param count - Length of the physical axis. @param offset - Absolute leading edge of a cell.
|
|
21
|
+
* @returns A bidirectional coordinate projection. */
|
|
22
|
+
function nativeAxis(count: number, offset: NativeDrawingAxis["offset"]): NativeDrawingAxis {
|
|
23
|
+
return { offset, marker(position) {
|
|
24
|
+
let low = 0, high = count;
|
|
25
|
+
while (low + 1 < high) {
|
|
26
|
+
const next = (low + high) >>> 1;
|
|
27
|
+
if (offset(next) <= position) low = next;
|
|
28
|
+
else high = next;
|
|
29
|
+
}
|
|
30
|
+
return [low, (position - offset(low)) / emuPerCssPixel];
|
|
31
|
+
} };
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/** @param appearance - Saved default and sparse row dimensions. @returns Lookup without expanding the entire row axis. */
|
|
35
|
+
function rowAxis(appearance: WorkbookSheetAppearance): NativeDrawingAxis {
|
|
36
|
+
const base = Math.round((appearance.defaultRowHeight ?? defaultWorkbookDimensions.row * 4 / 3) * emuPerCssPixel);
|
|
37
|
+
const corrections = [...appearance.rows.entries()].sort(([left], [right]) => left - right);
|
|
38
|
+
const delta = [0];
|
|
39
|
+
for (const [, row] of corrections) {
|
|
40
|
+
const size = row.hidden ? 0 : row.size === undefined ? base : Math.round(row.size * emuPerCssPixel);
|
|
41
|
+
delta.push(delta.at(-1)! + size - base);
|
|
42
|
+
}
|
|
43
|
+
return nativeAxis(workbookRows, index => {
|
|
44
|
+
let low = 0, high = corrections.length;
|
|
45
|
+
while (low < high) {
|
|
46
|
+
const middle = (low + high) >>> 1;
|
|
47
|
+
if (corrections[middle]![0] < index) low = middle + 1;
|
|
48
|
+
else high = middle;
|
|
49
|
+
}
|
|
50
|
+
return index * base + delta[low]!;
|
|
51
|
+
});
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/** @param appearance - Saved column size and visibility. @param digitWidth - Normal digit width in CSS pixels.
|
|
55
|
+
* @returns Contiguous prefix values in EMUs. */
|
|
56
|
+
function columnAxis(appearance: WorkbookSheetAppearance, digitWidth: number): NativeDrawingAxis {
|
|
57
|
+
const width = appearance.defaultColumnWidth;
|
|
58
|
+
// Native files without an explicit default use the traditional Excel column width with padding.
|
|
59
|
+
const standard = width === undefined ? Math.round(8.43 * digitWidth) + 5 : workbookColumnPixels(width, digitWidth);
|
|
60
|
+
const edges = new Float64Array(workbookColumns + 1);
|
|
61
|
+
edges.fill(standard * emuPerCssPixel, 1);
|
|
62
|
+
// As in the grid, the first matching source range owns the width for overlapping records.
|
|
63
|
+
for (let index = appearance.columns.length - 1; index >= 0; index--) {
|
|
64
|
+
const { first, last, size, hidden } = appearance.columns[index]!;
|
|
65
|
+
edges.fill(hidden ? 0 : (size === undefined ? standard : workbookColumnPixels(size, digitWidth)) * emuPerCssPixel, first + 1, last + 2);
|
|
66
|
+
}
|
|
67
|
+
for (let index = 1; index < edges.length; index++) edges[index] = edges[index]! + edges[index - 1]!;
|
|
68
|
+
return nativeAxis(workbookColumns, index => edges[index]!);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/** @param appearance - Layout saved in the worksheet. @returns Lazily resolved physical geometry for the selected font metric. */
|
|
72
|
+
export function createXlsxDrawingLayout(appearance: WorkbookSheetAppearance): XlsxDrawingLayout {
|
|
73
|
+
let rows: NativeDrawingAxis | undefined;
|
|
74
|
+
const widths = new Map<number, NativeDrawingAxis>();
|
|
75
|
+
return (requested = defaultXlsxDrawingDigitWidth) => {
|
|
76
|
+
const digitWidth = Number.isInteger(requested) && requested >= 1 && requested <= 256 ? requested : defaultXlsxDrawingDigitWidth;
|
|
77
|
+
const row = rows ??= rowAxis(appearance);
|
|
78
|
+
let column = widths.get(digitWidth);
|
|
79
|
+
if (!column) {
|
|
80
|
+
column = columnAxis(appearance, digitWidth);
|
|
81
|
+
// A native import probes a few metrics. Bound retained axes for a sheet with mixed producers.
|
|
82
|
+
if (widths.size >= 8) widths.delete(widths.keys().next().value!);
|
|
83
|
+
widths.set(digitWidth, column);
|
|
84
|
+
}
|
|
85
|
+
const col = column;
|
|
86
|
+
/** @param x - Native x position. @param y - Native y position. @returns A pair of cell offsets. */
|
|
87
|
+
function marker(x: number, y: number): WorkbookDrawingPoint {
|
|
88
|
+
const [column, localX] = col.marker(x), [rowIndex, localY] = row.marker(y);
|
|
89
|
+
return { row: rowIndex, column, x: localX, y: localY };
|
|
90
|
+
}
|
|
91
|
+
return {
|
|
92
|
+
bounds({ from, to }) {
|
|
93
|
+
const x = col.offset(from.column) + Math.round(from.x * emuPerCssPixel);
|
|
94
|
+
const y = row.offset(from.row) + Math.round(from.y * emuPerCssPixel);
|
|
95
|
+
return { x, y, width: col.offset(to.column) + Math.round(to.x * emuPerCssPixel) - x,
|
|
96
|
+
height: row.offset(to.row) + Math.round(to.y * emuPerCssPixel) - y };
|
|
97
|
+
},
|
|
98
|
+
anchor(sheetId, { x, y, width, height }) { return { sheetId, from: marker(x, y), to: marker(x + width, y + height) }; }
|
|
99
|
+
};
|
|
100
|
+
};
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
/** @param worksheet - Final worksheet with dimensions, outline and filter visibility already written.
|
|
104
|
+
* @param sheetId - Worksheet identity. @returns Native coordinate projection for the saved XML. */
|
|
105
|
+
export function readXlsxDrawingLayout(worksheet: Element, sheetId: string): XlsxDrawingLayout {
|
|
106
|
+
const rows = new Map<number, NonNullable<ReturnType<typeof readRowAppearance>>>();
|
|
107
|
+
const data = child(worksheet, "sheetData");
|
|
108
|
+
for (const element of data ? children(data, "row") : []) {
|
|
109
|
+
const row = readIndex(element, "r"), layout = readRowAppearance(element);
|
|
110
|
+
if (row && row <= workbookRows && layout) rows.set(row - 1, layout);
|
|
111
|
+
}
|
|
112
|
+
return createXlsxDrawingLayout(readSheetAppearance(worksheet, sheetId, rows, {}));
|
|
113
|
+
}
|
|
@@ -0,0 +1,16 @@
|
|
|
1
|
+
import type { Element } from "@xmldom/xmldom";
|
|
2
|
+
import { workbookColumns, workbookRows, type WorkbookDrawingPoint } from "@quirekit/workbook";
|
|
3
|
+
import { child } from "../../opc/xml";
|
|
4
|
+
import { emuPerCssPixel } from "../namespaces";
|
|
5
|
+
|
|
6
|
+
/** @param node - Drawing part's cell anchor. @returns Safe zero-based cell and 96-DPI offsets. */
|
|
7
|
+
export function readDrawingMarker(node: Element | undefined): WorkbookDrawingPoint | null {
|
|
8
|
+
if (!node) return null;
|
|
9
|
+
const [row, column, x, y] = ["row", "col", "colOff", "rowOff"].map(name => {
|
|
10
|
+
const value = child(node, name)?.textContent;
|
|
11
|
+
return value && /^[+-]?\d+$/u.test(value.trim()) ? Number(value) : NaN;
|
|
12
|
+
});
|
|
13
|
+
if (row === undefined || column === undefined || x === undefined || y === undefined
|
|
14
|
+
|| ![row, column, x, y].every(Number.isSafeInteger) || row < 0 || column < 0 || row >= workbookRows || column >= workbookColumns) return null;
|
|
15
|
+
return { row, column, x: x / emuPerCssPixel, y: y / emuPerCssPixel };
|
|
16
|
+
}
|
|
@@ -0,0 +1,132 @@
|
|
|
1
|
+
import type { WorkbookDrawingAnchor } from "@quirekit/workbook";
|
|
2
|
+
import type { Element } from "@xmldom/xmldom";
|
|
3
|
+
import { drawingElement, readDrawingAnchor } from "./anchor";
|
|
4
|
+
import { emuPerCssPixel } from "../namespaces";
|
|
5
|
+
import { defaultXlsxDrawingDigitWidth } from "./axes";
|
|
6
|
+
import type { XlsxDrawingLayout, XlsxDrawingAxes, XlsxDrawingRect } from "./types";
|
|
7
|
+
|
|
8
|
+
const unitsPerDegree = 60_000;
|
|
9
|
+
const unitsPerTurn = unitsPerDegree * 360;
|
|
10
|
+
|
|
11
|
+
/** @param transform - Optional individual DrawingML transform. @returns An angle in degrees, or null for an invalid native attribute. */
|
|
12
|
+
export function readDrawingRotation(transform: Element | undefined): number | null {
|
|
13
|
+
if (!transform?.hasAttribute("rot")) return 0;
|
|
14
|
+
const raw = transform.getAttribute("rot")!.trim();
|
|
15
|
+
const units = Number(raw);
|
|
16
|
+
if (!/^[+-]?\d+$/u.test(raw) || !Number.isInteger(units) || units < -2_147_483_648 || units > 2_147_483_647) return null;
|
|
17
|
+
return ((units % unitsPerTurn + unitsPerTurn) % unitsPerTurn) / unitsPerDegree;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
/** @param rotation - Canonical clockwise angle. @returns Whether the native anchors describe a quarter-turned frame. */
|
|
21
|
+
export function xlsxDrawingUsesSwappedAxes(rotation = 0): boolean {
|
|
22
|
+
return rotation >= 45 && rotation < 135 || rotation >= 225 && rotation < 315;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** @param rect - Shape or native position. @returns A rectangle of exchanged dimensions around the same center. */
|
|
26
|
+
function swapDrawingAxes({ x, y, width, height }: XlsxDrawingRect): XlsxDrawingRect {
|
|
27
|
+
// Truncating the signed half shift makes the native conversion reversible at integer EMU precision.
|
|
28
|
+
const shift = Math.trunc((width - height) / 2);
|
|
29
|
+
return { x: x + shift, y: y - shift, width: height, height: width };
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** @param frame - Native frame. @returns A frame whose leading corner is in the worksheet. */
|
|
33
|
+
function keepDrawingAtSheetOrigin(frame: XlsxDrawingRect): XlsxDrawingRect {
|
|
34
|
+
return frame.x < 0 || frame.y < 0 ? { ...frame, x: Math.max(frame.x, 0), y: Math.max(frame.y, 0) } : frame;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** @param left - Saved native frame. @param right - Corresponding transform frame. @returns Whether both encode the same geometry. */
|
|
38
|
+
function sameDrawingRect(left: XlsxDrawingRect, right: XlsxDrawingRect): boolean {
|
|
39
|
+
return left.x === right.x && left.y === right.y && left.width === right.width && left.height === right.height;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/** @param transform - Native 2D transform. @param allowFlat - Permit a connector extent with one zero axis.
|
|
43
|
+
* @returns A complete physical geometry hint, if provided by the producer. */
|
|
44
|
+
function explicitFrame(transform: Element | undefined, allowFlat: boolean): XlsxDrawingRect | undefined {
|
|
45
|
+
const point = drawingElement(transform, "off"), size = drawingElement(transform, "ext");
|
|
46
|
+
const attributes = [point?.getAttribute("x"), point?.getAttribute("y"), size?.getAttribute("cx"), size?.getAttribute("cy")];
|
|
47
|
+
if (!attributes.every(value => typeof value === "string" && /^[+-]?\d+$/u.test(value.trim()))) return;
|
|
48
|
+
const [x, y, width, height] = attributes.map(Number) as [number, number, number, number];
|
|
49
|
+
if ([x, y, width, height].every(Number.isSafeInteger) && hasExtent(width, height, allowFlat)) return { x, y, width, height };
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
/** @param width - Native horizontal extent. @param height - Native vertical extent. @param allowFlat - Whether a line may have one zero axis.
|
|
53
|
+
* @returns Whether the supported object has nonempty geometry. */
|
|
54
|
+
function hasExtent(width: number, height: number, allowFlat: boolean): boolean {
|
|
55
|
+
return allowFlat ? width >= 0 && height >= 0 && width + height > 0 : width > 0 && height > 0;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** @param layout - Worksheet axis resolver. @param anchor - Native marker pair. @param expected - Native frame inferred from complete transform data.
|
|
59
|
+
* @param fixed - Whether extent comes from the transform and only the start marker can calibrate a font width.
|
|
60
|
+
* @returns A deterministic column metric, preferring geometry corroborated by both the transform and the markers. */
|
|
61
|
+
function compatibleDrawingAxes(layout: XlsxDrawingLayout, anchor: WorkbookDrawingAnchor,
|
|
62
|
+
expected: XlsxDrawingRect | undefined, fixed: boolean): XlsxDrawingAxes {
|
|
63
|
+
const defaults = layout();
|
|
64
|
+
if (!expected) return defaults;
|
|
65
|
+
const { from, to } = anchor;
|
|
66
|
+
const baseline = defaults.bounds(anchor);
|
|
67
|
+
const point = Math.round(from.x * emuPerCssPixel), span = Math.round(to.x * emuPerCssPixel) - point;
|
|
68
|
+
const candidates = new Set<number>([defaultXlsxDrawingDigitWidth]);
|
|
69
|
+
for (const [old, target] of [[baseline.x - point, expected.x - point],
|
|
70
|
+
[fixed ? 0 : baseline.width - span, expected.width - span]]) {
|
|
71
|
+
if (!old || old < 0 || !target || target < 0) continue;
|
|
72
|
+
const width = Math.round(defaultXlsxDrawingDigitWidth * target / old);
|
|
73
|
+
for (const value of [width, width - 1, width + 1]) if (value >= 1 && value <= 256) candidates.add(value);
|
|
74
|
+
}
|
|
75
|
+
let best = defaults, error = Infinity;
|
|
76
|
+
for (const width of candidates) {
|
|
77
|
+
const guess = layout(width), measured = guess.bounds(anchor);
|
|
78
|
+
const difference = Math.abs(expected.x - measured.x) + (fixed ? 0 : Math.abs(expected.width - measured.width));
|
|
79
|
+
if (difference < error) { error = difference; best = guess; }
|
|
80
|
+
if (error === 0) break;
|
|
81
|
+
}
|
|
82
|
+
return error <= 2 * emuPerCssPixel ? best : defaults;
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
/** @param node - Native worksheet anchor. @param transform - Individual object transform. @param sheetId - Worksheet ID.
|
|
86
|
+
* @param rotation - Clockwise angle. @param layout - Saved worksheet dimensions.
|
|
87
|
+
* @param allowFlat - Whether this connector can be horizontal or vertical. @param allowPoint - Whether an attached line can coincide.
|
|
88
|
+
* @returns Model placement before the rotation, regardless of the native anchor convention. */
|
|
89
|
+
export function readXlsxDrawingPlacement(node: Element, transform: Element | undefined, sheetId: string, rotation: number,
|
|
90
|
+
layout: XlsxDrawingLayout, allowFlat = false, allowPoint = false): WorkbookDrawingAnchor | undefined {
|
|
91
|
+
const anchor = readDrawingAnchor(node, transform, sheetId, allowFlat, allowPoint);
|
|
92
|
+
if (!anchor || !xlsxDrawingUsesSwappedAxes(rotation)) return anchor;
|
|
93
|
+
const complete = explicitFrame(transform, allowFlat), behavior = node.getAttribute("editAs");
|
|
94
|
+
if (node.localName === "twoCellAnchor" && behavior === "absolute" && complete) return anchor;
|
|
95
|
+
const fixed = node.localName === "twoCellAnchor" && behavior === "oneCell" && complete !== undefined;
|
|
96
|
+
const expected = complete && swapDrawingAxes(complete);
|
|
97
|
+
const origin = expected && keepDrawingAtSheetOrigin(expected);
|
|
98
|
+
const from = anchor.from;
|
|
99
|
+
const adjusted = !fixed && origin && origin !== expected &&
|
|
100
|
+
(origin.x === expected!.x || from.column === 0 && from.x === 0)
|
|
101
|
+
&& (origin.y === expected!.y || from.row === 0 && from.y === 0);
|
|
102
|
+
const axes = compatibleDrawingAxes(layout, anchor, adjusted ? origin : expected, fixed);
|
|
103
|
+
const position = axes.bounds(anchor);
|
|
104
|
+
const frame = fixed ? { ...position, width: complete!.height, height: complete!.width } : position;
|
|
105
|
+
if (!hasExtent(frame.width, frame.height, allowFlat)) return anchor;
|
|
106
|
+
// The saved transform recovers the authoring frame only when the markers exactly encode the origin adjustment.
|
|
107
|
+
const local = adjusted && sameDrawingRect(frame, origin) ? complete! : swapDrawingAxes(frame);
|
|
108
|
+
return axes.anchor(sheetId, local);
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
/** @param anchor - Unrotated model placement. @param rotation - Clockwise angle. @param axes - Final worksheet dimensions.
|
|
112
|
+
* @param allowFlat - Lines carry an explicit transform even when upright and permit one zero axis.
|
|
113
|
+
* @returns Native cell markers and original frame geometry for the transform. */
|
|
114
|
+
export function writeXlsxDrawingPlacement(anchor: WorkbookDrawingAnchor, rotation: number | undefined, axes?: XlsxDrawingAxes, allowFlat = false):
|
|
115
|
+
{ anchor: WorkbookDrawingAnchor; frame?: XlsxDrawingRect } {
|
|
116
|
+
if (!axes || !rotation && !allowFlat) return { anchor };
|
|
117
|
+
const frame = axes.bounds(anchor);
|
|
118
|
+
// A frame wholly covered by hidden rows or columns remains anchored to its cells.
|
|
119
|
+
if (!hasExtent(frame.width, frame.height, allowFlat)) return { anchor };
|
|
120
|
+
const written = xlsxDrawingUsesSwappedAxes(rotation) ? axes.anchor(anchor.sheetId, keepDrawingAtSheetOrigin(swapDrawingAxes(frame))) : anchor;
|
|
121
|
+
return { anchor: written, frame };
|
|
122
|
+
}
|
|
123
|
+
|
|
124
|
+
/** @param rotation - Canonical clockwise degrees. @param frame - Explicit unrotated frame when available.
|
|
125
|
+
* @param flipHorizontal - Native horizontal mirror. @param flipVertical - Native vertical mirror.
|
|
126
|
+
* @returns Native transform when the frame has an explicit change. */
|
|
127
|
+
export function drawingTransformXml(rotation: number | undefined, frame?: XlsxDrawingRect, flipHorizontal = false, flipVertical = false): string {
|
|
128
|
+
if (!rotation && !frame && !flipHorizontal && !flipVertical) return "";
|
|
129
|
+
const attributes = `${rotation ? ` rot="${Math.round(rotation * unitsPerDegree)}"` : ""}${flipHorizontal ? ' flipH="1"' : ""}${flipVertical ? ' flipV="1"' : ""}`;
|
|
130
|
+
return frame ? `<a:xfrm${attributes}><a:off x="${frame.x}" y="${frame.y}"/><a:ext cx="${frame.width}" cy="${frame.height}"/></a:xfrm>`
|
|
131
|
+
: `<a:xfrm${attributes}/>`;
|
|
132
|
+
}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import type { WorkbookDrawingAnchor } from "@quirekit/workbook";
|
|
2
|
+
|
|
3
|
+
/** A transformed or untransformed drawing rectangle in integer EMU coordinates. */
|
|
4
|
+
export interface XlsxDrawingRect {
|
|
5
|
+
/** Horizontal position from the worksheet origin. */ readonly x: number;
|
|
6
|
+
/** Vertical position from the worksheet origin. */ readonly y: number;
|
|
7
|
+
/** Horizontal size in EMUs. */ readonly width: number;
|
|
8
|
+
/** Vertical size in EMUs. */ readonly height: number;
|
|
9
|
+
}
|
|
10
|
+
|
|
11
|
+
/** Native conversion between absolute coordinates and cell markers. */
|
|
12
|
+
export interface XlsxDrawingAxes {
|
|
13
|
+
/** @param anchor - Two worksheet markers. @returns The same rectangle in absolute EMUs. */
|
|
14
|
+
bounds(anchor: WorkbookDrawingAnchor): XlsxDrawingRect;
|
|
15
|
+
/** @param sheetId - Workbench sheet ID. @param rect - Physical frame. @returns Cell markers at the same position. */
|
|
16
|
+
anchor(sheetId: string, rect: XlsxDrawingRect): WorkbookDrawingAnchor;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
/** @param digitWidth - Optional Normal font measurement in pixels. @returns Native geometry using these column metrics. */
|
|
20
|
+
export type XlsxDrawingLayout = (digitWidth?: number) => XlsxDrawingAxes;
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
import type { ChartPreviewAxis, ChartPreviewNumberFormat } from "@quirekit/chart";
|
|
2
|
+
import type { Element } from "@xmldom/xmldom";
|
|
3
|
+
import { children, isTrue, readIndex } from "../../../opc/xml";
|
|
4
|
+
import { chartNamespace } from "../../namespaces";
|
|
5
|
+
import { chartChild, chartPosition, chartValue } from "../properties";
|
|
6
|
+
import type { CartesianAxisPair } from "./types";
|
|
7
|
+
|
|
8
|
+
/** @param axis - A supported axis declaration. @returns Whether its coordinates are discrete categories. */
|
|
9
|
+
function isCategory(axis: Element): boolean {
|
|
10
|
+
return axis.localName === "catAx" || axis.localName === "dateAx";
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/** @param area - Native plot area. @param plots - Supported groups in source order.
|
|
14
|
+
* @returns Their exact category and value axis pairs, or null if the binding is ambiguous. */
|
|
15
|
+
export function readCartesianAxisPairs(area: Element, plots: readonly Element[]): readonly CartesianAxisPair[] | null {
|
|
16
|
+
const axes = children(area).filter(node => node.namespaceURI === chartNamespace && (isCategory(node) || node.localName === "valAx"));
|
|
17
|
+
if (plots.length === 1 && !chartChild(plots[0], "axId")) {
|
|
18
|
+
const categories = axes.filter(isCategory), values = axes.filter(axis => !isCategory(axis));
|
|
19
|
+
return categories.length <= 1 && values.length <= 1 ? [{ category: categories[0], value: values[0] }] : null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// IDs identify the coordinate system independently of the order of definitions in the part.
|
|
23
|
+
const byId = new Map<number, Element>();
|
|
24
|
+
for (const axis of axes) {
|
|
25
|
+
const id = readIndex(chartChild(axis, "axId"), "val");
|
|
26
|
+
if (id === undefined || byId.has(id)) return null;
|
|
27
|
+
byId.set(id, axis);
|
|
28
|
+
}
|
|
29
|
+
const pairs: CartesianAxisPair[] = [];
|
|
30
|
+
for (const plot of plots) {
|
|
31
|
+
const ids = children(plot, "axId").filter(node => node.namespaceURI === chartNamespace);
|
|
32
|
+
const bound = ids.map(node => byId.get(readIndex(node, "val") ?? -1));
|
|
33
|
+
const category = bound.find(axis => axis && isCategory(axis));
|
|
34
|
+
const value = bound.find(axis => axis?.localName === "valAx");
|
|
35
|
+
if (ids.length !== 2 || !category || !value) return null;
|
|
36
|
+
if (plots.length > 1 && [category, value].some(axis => {
|
|
37
|
+
const cross = chartChild(axis, "crossAx");
|
|
38
|
+
if (!cross) return false;
|
|
39
|
+
const other = byId.get(readIndex(cross, "val") ?? -1);
|
|
40
|
+
return !other || isCategory(other) === isCategory(axis);
|
|
41
|
+
})) return null;
|
|
42
|
+
pairs.push({ category, value });
|
|
43
|
+
}
|
|
44
|
+
return pairs;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** @param nodes - Axis nodes in order of first use. @param horizontal - Direction of the axis.
|
|
48
|
+
* @returns A side for each axis, separating simultaneous labels when producers reuse one position. */
|
|
49
|
+
export function chartAxisPositions(nodes: readonly (Element | undefined)[], horizontal: boolean): ChartPreviewAxis["position"][] {
|
|
50
|
+
const first = horizontal ? "bottom" : "left", second = horizontal ? "top" : "right";
|
|
51
|
+
const positions = nodes.map(node => chartPosition(node, "axPos"));
|
|
52
|
+
if (nodes.length < 2) return positions;
|
|
53
|
+
const explicit = positions.map(position => position === first || position === second ? position : undefined);
|
|
54
|
+
const [leading, trailing] = explicit;
|
|
55
|
+
if (leading && trailing && leading !== trailing) return explicit;
|
|
56
|
+
if (!leading && trailing) return [trailing === first ? second : first, trailing];
|
|
57
|
+
if (leading && !trailing) return [leading, leading === first ? second : first];
|
|
58
|
+
|
|
59
|
+
const atMax = nodes.map(node => chartValue(node, "crosses") === "max");
|
|
60
|
+
return atMax[0] && !atMax[1] ? [second, first] : [first, second];
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/** @param node - Value holder. @param name - Numeric property. @returns Finite native value if specified. */
|
|
64
|
+
function finiteValue(node: Element | undefined, name: string): number | undefined {
|
|
65
|
+
const value = chartValue(node, name)?.trim();
|
|
66
|
+
return value && Number.isFinite(Number(value)) ? Number(value) : undefined;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** @param source - Source tick format. @returns Representable labels with no change to their data units. */
|
|
70
|
+
function numberFormat(source: string | null | undefined): ChartPreviewNumberFormat | undefined {
|
|
71
|
+
const match = /^(0|#,##0)(?:\.(0{1,8}))?(%)?$/u.exec(source ?? "");
|
|
72
|
+
if (!match) return;
|
|
73
|
+
return { decimals: match[2]?.length ?? 0, useGrouping: match[1] === "#,##0", ...(match[3] && { percent: true }) };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** @param node - Native axis declaration. @param position - Resolved placement.
|
|
77
|
+
* @param categories - Data labels for a discrete scale. @param stackedPercent - Whether the renderer uses normalized percent units.
|
|
78
|
+
* @param combination - Whether independent scales should use separate plot edges.
|
|
79
|
+
* @returns Static preview with axis-local visibility, geometry and numeric presentation. */
|
|
80
|
+
export function readCartesianAxis(node: Element | undefined, position: ChartPreviewAxis["position"],
|
|
81
|
+
categories: readonly string[] | undefined, stackedPercent: boolean, combination: boolean): ChartPreviewAxis {
|
|
82
|
+
const scaling = chartChild(node, "scaling");
|
|
83
|
+
const deleted = isTrue(chartValue(node, "delete"));
|
|
84
|
+
const min = finiteValue(scaling, "min"), max = finiteValue(scaling, "max");
|
|
85
|
+
const step = finiteValue(node, "majorUnit");
|
|
86
|
+
const multiplier = stackedPercent ? 100 : 1;
|
|
87
|
+
const format = categories === undefined ? numberFormat(chartChild(node, "numFmt")?.getAttribute("formatCode")) : undefined;
|
|
88
|
+
// Only pass explicit intervals when both endpoints bound the amount of renderer work.
|
|
89
|
+
const boundsFit = min === undefined || max === undefined || (min < max && Number.isFinite((max - min) * multiplier));
|
|
90
|
+
const bounded = boundsFit && min !== undefined && max !== undefined && step !== undefined
|
|
91
|
+
&& step > 0 && Number.isFinite(step * multiplier) && max - step < max && (max - min) / step <= 64;
|
|
92
|
+
return {
|
|
93
|
+
...(categories && { categories }), ...(position && { position }),
|
|
94
|
+
...(combination && { atEdge: true }),
|
|
95
|
+
visible: !deleted && chartValue(node, "tickLblPos") !== "none",
|
|
96
|
+
gridlines: !deleted && !!chartChild(node, "majorGridlines"),
|
|
97
|
+
reversed: chartValue(scaling, "orientation") === "maxMin",
|
|
98
|
+
...(min !== undefined && Number.isFinite(min * multiplier) && boundsFit && { min: min * multiplier }),
|
|
99
|
+
...(max !== undefined && Number.isFinite(max * multiplier) && boundsFit && { max: max * multiplier }),
|
|
100
|
+
...(bounded && { interval: step * multiplier }),
|
|
101
|
+
...(stackedPercent && { percent: true }), ...(format && { numberFormat: format })
|
|
102
|
+
};
|
|
103
|
+
}
|